answer
stringlengths 17
10.2M
|
|---|
package io.rong;
import io.rong.models.ChatroomInfo;
import io.rong.models.FormatType;
import io.rong.models.GroupInfo;
import io.rong.models.Message;
import io.rong.models.SdkHttpResult;
import io.rong.util.HttpUtil;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.List;
public class ApiHttpClient {
private static final String RONGCLOUDURI = "http://api.cn.ronghub.com";
private static final String UTF8 = "UTF-8";
// token
public static SdkHttpResult getToken(String appKey, String appSecret,
String userId, String userName, String portraitUri,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/user/getToken." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&name=").append(URLEncoder.encode(userName==null?"":userName, UTF8));
sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri==null?"":portraitUri, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult checkOnline(String appKey, String appSecret,
String userId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/checkOnline." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult refreshUser(String appKey, String appSecret,
String userId, String userName, String portraitUri,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/user/refresh." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
if (userName != null) {
sb.append("&name=").append(URLEncoder.encode(userName, UTF8));
}
if (portraitUri != null) {
sb.append("&portraitUri=").append(
URLEncoder.encode(portraitUri, UTF8));
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult blockUser(String appKey, String appSecret,
String userId, int minute, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/user/block." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&minute=").append(
URLEncoder.encode(String.valueOf(minute), UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult unblockUser(String appKey, String appSecret,
String userId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/user/unblock." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult queryBlockUsers(String appKey,
String appSecret, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/block/query." + format.toString());
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult blackUser(String appKey, String appSecret,
String userId, List<String> blackUserIds, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/blacklist/add." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
if (blackUserIds != null) {
for (String blackId : blackUserIds) {
sb.append("&blackUserId=").append(
URLEncoder.encode(blackId, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult unblackUser(String appKey, String appSecret,
String userId, List<String> blackUserIds, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/blacklist/remove." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
if (blackUserIds != null) {
for (String blackId : blackUserIds) {
sb.append("&blackUserId=").append(
URLEncoder.encode(blackId, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult QueryblackUser(String appKey, String appSecret,
String userId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/user/blacklist/query." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult createGroup(String appKey, String appSecret,
List<String> userIds, String groupId, String groupName,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/create." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8));
sb.append("&groupName=").append(URLEncoder.encode(groupName==null?"":groupName, UTF8));
if (userIds != null) {
for (String id : userIds) {
sb.append("&userId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult joinGroup(String appKey, String appSecret,
String userId, String groupId, String groupName, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/join." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&groupId=").append(URLEncoder.encode(groupId, UTF8));
sb.append("&groupName=").append(URLEncoder.encode(groupName==null?"":groupName, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult joinGroupBatch(String appKey, String appSecret,
List<String> userIds, String groupId, String groupName,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/join." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8));
sb.append("&groupName=").append(URLEncoder.encode(groupName==null?"":groupName, UTF8));
if (userIds != null) {
for (String id : userIds) {
sb.append("&userId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult quitGroup(String appKey, String appSecret,
String userId, String groupId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/quit." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&groupId=").append(URLEncoder.encode(groupId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult quitGroupBatch(String appKey, String appSecret,
List<String> userIds, String groupId, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/quit." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8));
if (userIds != null) {
for (String id : userIds) {
sb.append("&userId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult dismissGroup(String appKey, String appSecret,
String userId, String groupId, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/group/dismiss." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
sb.append("&groupId=").append(URLEncoder.encode(groupId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult syncGroup(String appKey, String appSecret,
String userId, List<GroupInfo> groups, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret, RONGCLOUDURI + "/group/sync." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
if (groups != null) {
for (GroupInfo info : groups) {
if (info != null) {
sb.append(
String.format("&group[%s]=",
URLEncoder.encode(info.getId(), UTF8)))
.append(URLEncoder.encode(info.getName(), UTF8));
}
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult refreshGroupInfo(String appKey,
String appSecret, String groupId, String groupName,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/group/refresh." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8));
sb.append("&groupName=").append(URLEncoder.encode(groupName==null?"":groupName, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult refreshGroupInfo(String appKey,
String appSecret, GroupInfo group, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/group/refresh." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(URLEncoder.encode(group.getId(), UTF8));
sb.append("&groupName=").append(
URLEncoder.encode(group.getName(), UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishMessage(String appKey, String appSecret,
String fromUserId, List<String> toUserIds, Message msg,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/private/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toUserIds != null) {
for (int i = 0; i < toUserIds.size(); i++) {
sb.append("&toUserId=").append(
URLEncoder.encode(toUserIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishMessage(String appKey, String appSecret,
String fromUserId, List<String> toUserIds, Message msg,
String pushContent, String pushData, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toUserIds != null) {
for (int i = 0; i < toUserIds.size(); i++) {
sb.append("&toUserId=").append(
URLEncoder.encode(toUserIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
if (pushContent != null) {
sb.append("&pushContent=").append(
URLEncoder.encode(pushContent==null?"":pushContent, UTF8));
}
if (pushData != null) {
sb.append("&pushData=").append(URLEncoder.encode(pushData==null?"":pushData, UTF8));
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishSystemMessage(String appKey,
String appSecret, String fromUserId, List<String> toUserIds,
Message msg, String pushContent, String pushData, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/system/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toUserIds != null) {
for (int i = 0; i < toUserIds.size(); i++) {
sb.append("&toUserId=").append(
URLEncoder.encode(toUserIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
if (pushContent != null) {
sb.append("&pushContent=").append(
URLEncoder.encode(pushContent==null?"":pushContent, UTF8));
}
if (pushData != null) {
sb.append("&pushData=").append(URLEncoder.encode(pushData==null?"":pushData, UTF8));
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishGroupMessage(String appKey,
String appSecret, String fromUserId, List<String> toGroupIds,
Message msg, String pushContent, String pushData, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/group/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toGroupIds != null) {
for (int i = 0; i < toGroupIds.size(); i++) {
sb.append("&toGroupId=").append(
URLEncoder.encode(toGroupIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
if (pushContent != null) {
sb.append("&pushContent=").append(
URLEncoder.encode(pushContent==null?"":pushContent, UTF8));
}
if (pushData != null) {
sb.append("&pushData=").append(URLEncoder.encode(pushData==null?"":pushData, UTF8));
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult publishChatroomMessage(String appKey,
String appSecret, String fromUserId, List<String> toChatroomIds,
Message msg, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil
.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
+ "/message/chatroom/publish." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
if (toChatroomIds != null) {
for (int i = 0; i < toChatroomIds.size(); i++) {
sb.append("&toChatroomId=").append(
URLEncoder.encode(toChatroomIds.get(i), UTF8));
}
}
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult broadcastMessage(String appKey, String appSecret,
String fromUserId, Message msg,String pushContent, String pushData, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/broadcast." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8));
sb.append("&objectName=")
.append(URLEncoder.encode(msg.getType(), UTF8));
sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8));
if (pushContent != null) {
sb.append("&pushContent=").append(
URLEncoder.encode(pushContent==null?"":pushContent, UTF8));
}
if (pushData != null) {
sb.append("&pushData=").append(URLEncoder.encode(pushData==null?"":pushData, UTF8));
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult createChatroom(String appKey, String appSecret,
List<ChatroomInfo> chatrooms, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/chatroom/create." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("1=1");
if (chatrooms != null) {
for (ChatroomInfo info : chatrooms) {
if (info != null) {
sb.append(
String.format("&chatroom[%s]=",
URLEncoder.encode(info.getId(), UTF8)))
.append(URLEncoder.encode(info.getName(), UTF8));
}
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult destroyChatroom(String appKey,
String appSecret, List<String> chatroomIds, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/chatroom/destroy." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("1=1");
if (chatroomIds != null) {
for (String id : chatroomIds) {
sb.append("&chatroomId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult queryChatroom(String appKey, String appSecret,
List<String> chatroomIds, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/chatroom/query." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("1=1");
if (chatroomIds != null) {
for (String id : chatroomIds) {
sb.append("&chatroomId=").append(URLEncoder.encode(id, UTF8));
}
}
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult getMessageHistoryUrl(String appKey,
String appSecret, String date, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/history." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("date=").append(URLEncoder.encode(date, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult deleteMessageHistory(String appKey,
String appSecret, String date, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/message/history/delete." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("date=").append(URLEncoder.encode(date, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult queryGroupUserList(String appKey,
String appSecret, String groupId, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/group/user/query." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(
URLEncoder.encode(groupId == null ? "" : groupId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult groupUserGagAdd(String appKey,
String appSecret, String groupId, String userId, long minute,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/group/user/gag/add." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(
URLEncoder.encode(groupId == null ? "" : groupId, UTF8));
sb.append("userId=").append(
URLEncoder.encode(userId == null ? "" : userId, UTF8));
sb.append("minute=").append(
URLEncoder.encode(String.valueOf(minute), UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult groupUserGagRollback(String appKey,
String appSecret, String groupId, String userId, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/group/user/gag/rollback." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(
URLEncoder.encode(groupId == null ? "" : groupId, UTF8));
sb.append("userId=").append(
URLEncoder.encode(userId == null ? "" : userId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult groupUserGagList(String appKey,
String appSecret, String groupId, FormatType format)
throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/group/user/gag/list." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("groupId=").append(
URLEncoder.encode(groupId == null ? "" : groupId, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult wordFilterAdd(String appKey, String appSecret,
String word, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/wordfilter/add." + format.toString());
if (word == null || word.length() == 0) {
throw new Exception("word is not null or empty.");
}
StringBuilder sb = new StringBuilder();
sb.append("word=").append(
URLEncoder.encode(word == null ? "" : word, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult wordFilterDelete(String appKey,
String appSecret, String word, FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/wordfilter/delete." + format.toString());
if (word == null || word.length() == 0) {
throw new Exception("word is not null or empty.");
}
StringBuilder sb = new StringBuilder();
sb.append("word=").append(
URLEncoder.encode(word == null ? "" : word, UTF8));
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
public static SdkHttpResult wordFilterList(String appKey, String appSecret,
FormatType format) throws Exception {
HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey,
appSecret,
RONGCLOUDURI + "/wordfilter/delete." + format.toString());
StringBuilder sb = new StringBuilder();
sb.append("1=1");
HttpUtil.setBodyParameter(sb, conn);
return HttpUtil.returnResult(conn);
}
}
|
package tinyrs;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Scanner;
import java.util.Set;
public enum GlobalProperty {
SCREENSHOT_FORMAT("png"),
DEFAULT_WORLD(2),
CONFIRM_CLOSE(false),
ALWAYS_ON_TOP(false),
REMEMBER_WINDOW_BOUNDS(false),
LAST_WINDOW_X(0),
LAST_WINDOW_Y(0),
LAST_WINDOW_WIDTH(765),
LAST_WINDOW_HEIGHT(503);
private static final Set<GlobalProperty> PROPERTIES = Collections.unmodifiableSet(EnumSet.allOf(GlobalProperty.class));
private final Object defaultValue;
private volatile Object value;
GlobalProperty(final Object defaultValue) {
this.defaultValue = defaultValue;
value = defaultValue;
}
@SuppressWarnings("unchecked")
public <T> T get(final Class<T> type) {
assertCompatibleType(type);
return (T) value;
}
public String get() {
return get(Object.class).toString();
}
@SuppressWarnings("unchecked")
public <T> T getDefault(final Class<T> type) {
assertCompatibleType(type);
return (T) defaultValue;
}
public String getDefault() {
return getDefault(Object.class).toString();
}
public void set(final Object value) {
assertCompatibleType(value.getClass());
this.value = value;
}
public void setDefault() {
value = defaultValue;
}
private void assertCompatibleType(final Class<?> type) {
final Class<?> thisType = defaultValue.getClass();
if (!(type == Object.class
|| (thisType == Integer.class && type == int.class)
|| (thisType == Boolean.class && type == boolean.class)
|| type.isAssignableFrom(thisType))) {
throw new IllegalArgumentException("The provided type is incompatible with this property's.");
}
}
public static void readAll(final InputStream inputStream) {
final Scanner scanner = new Scanner(inputStream);
try {
while (scanner.hasNextLine()) {
final String line = scanner.nextLine().trim();
if (line.startsWith("
continue;
}
final int equalsIndex = line.indexOf('=');
if (equalsIndex == -1) {
continue;
}
try {
getProperty(line.substring(0, equalsIndex)).set(convertFromString(line.substring(equalsIndex + 1)));
} catch (final IllegalArgumentException e) {
e.printStackTrace();
}
}
} finally {
scanner.close();
}
}
public static void writeAll(final OutputStream outputStream) {
final PrintWriter printWriter = new PrintWriter(outputStream);
try {
for (final GlobalProperty property : PROPERTIES) {
printWriter.println(property.toString() + '=' + property.get());
}
printWriter.println();
} finally {
printWriter.close();
}
}
private static GlobalProperty getProperty(final String name) {
for (final GlobalProperty property : PROPERTIES) {
if (property.name().equalsIgnoreCase(name)) {
return property;
}
}
throw new IllegalArgumentException(String.format("There is no global property with the name \"%s\".", name));
}
private static Object convertFromString(final String value) {
try {
return Integer.parseInt(value);
} catch (final NumberFormatException expected) {
}
if ("true".equalsIgnoreCase(value)) {
return true;
} else if ("false".equalsIgnoreCase(value)) {
return false;
}
return value;
}
}
|
package io.spire.api;
import io.spire.api.Api.ApiDescriptionModel.ApiSchemaModel;
import io.spire.request.Request.RequestType;
import io.spire.request.Request;
import io.spire.request.RequestData;
import io.spire.request.RequestFactory;
import io.spire.request.Response;
import io.spire.request.ResponseException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
/**
* General abstraction of Api resources
*
* @since 1.0
* @author Jorge Gonzalez
*
*/
public abstract class Resource {
/** Holds the internal resource data */
protected ResourceModel model;
/** Holds descriptions of all Api resource schemas */
protected ApiSchemaModel schema;
/**
* Default constructor
*/
public Resource() {
this.model = new ResourceModel(new HashMap<String, Object>());
}
/**
* Initialize a resource with the Api resource schemas
*
* @param schema {@link ApiSchemaModel}
*/
public Resource(ApiSchemaModel schema) {
this();
this.schema = schema;
}
/**
* Initialize a resource model and Api resource schemas
*
* @param model
* @param schema
*/
public Resource(ResourceModel model, ApiSchemaModel schema) {
this.schema = schema;
this.model = model;
this.initialize();
}
/**
* This is called automatically by the resource constructor
* to initialize any other internal properties.
* Derived classes should override this method adding any
* custom initialization needed by the class
*/
protected abstract void initialize();
/**
* Access resources from the internal resource model
*
* @param resourceName
* @return {@link ResourceModel}
*/
@SuppressWarnings("unchecked")
protected ResourceModel getResourceModel(String resourceName){
Map<String, Object> rawModel = model.getProperty(resourceName, Map.class);
if(rawModel == null){
rawModel = new HashMap<String, Object>();
model.setProperty(resourceName, rawModel);
}
return new ResourceModel(rawModel);
}
/**
* Updates the underlying resource model when GET/UPDATE a resource
* Subclasses would want to override this method if any special operations
* need to done in regards of how the model should be updated
*
* @param rawModel is a representation of the raw model as a Map<String, Object>
*/
protected void updateModel(Map<String, Object> rawModel){
model.rawModel = rawModel;
this.initialize();
}
/**
* Set the internal resource model
*
* @param rawModel
*/
protected abstract void addModel(Map<String, Object> rawModel);
/**
* Wrapper for the resource model internal data
*
* @since 1.0
* @author Jorge Gonzalez
*
*/
public static class ResourceModel implements ResourceModelInterface {
private Map<String, Object> rawModel;
/**
* Default constructor
*
* @param data Map object representing the resource
*/
public ResourceModel(Map<String, Object> data){
this.rawModel = data;
if(this.rawModel == null){
this.rawModel = new HashMap<String, Object>();
}
}
@Override
public <T>T getProperty(String propertyName, Class<T> type){
T t = null;
try{
t = type.cast(rawModel.get(propertyName));
}catch (Exception e) {
//e.printStackTrace();
}
return t;
}
@Override
public void setProperty(String propertyName, Object data){
rawModel.put(propertyName, data);
}
@SuppressWarnings("unchecked")
public ResourceModel getResourceMapCollection(String resourceName){
HashMap<String, Object> rawModelCollection = new HashMap<String, Object>();
Map<String, Object> resources = this.getProperty(resourceName, Map.class);
for (Map.Entry<String, Object> resource : resources.entrySet()) {
String name = (String)resource.getKey();
Map<String, Object> rawData = (Map<String, Object>)resource.getValue();
ResourceModel rawModel = new ResourceModel(rawData);
rawModelCollection.put(name, rawModel);
}
return new ResourceModel(rawModelCollection);
}
@SuppressWarnings("unchecked")
public <T> Map<String, T> getMapCollection(String resourceName, Class<T> T, ApiSchemaModel schema) throws RuntimeException{
HashMap<String, T> mapCollection = new HashMap<String, T>();
Constructor<T> constructorT;
try {
constructorT = T.getConstructor(ResourceModel.class, ApiSchemaModel.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
return null;
}
Map<String, Object> resources = this.getProperty(resourceName, Map.class);
if(resources == null)
return mapCollection;
for (Map.Entry<String, Object> resource : resources.entrySet()) {
String name = (String)resource.getKey();
Map<String, Object> rawData = (Map<String, Object>)resource.getValue();
ResourceModel rawModel = new ResourceModel(rawData);
try{
T t = constructorT.newInstance(rawModel, schema);
mapCollection.put(name, t);
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
return mapCollection;
}
}
/**
* Gets the resource url
*
* @return {@link String}
*/
public String getUrl(){
return model.getProperty("url", String.class);
}
/**
* Sets the resource url
*
* @param url
*/
public void setUrl(String url){
model.setProperty("url", url);
}
/**
* Gets the resource name
* Should be defined by each derived class
*
* @return {@link String}
*/
public abstract String getResourceName();
/**
* Gets the resource media type
*
* @return {@link String}
*/
public String getMediaType(){
String resourceName = this.getResourceName();
return schema.getMediaType(resourceName);
}
/**
* Gets the resource capability
*
* @return {@link String}
*/
public String getCapability(){
return model.getProperty("capability", String.class);
}
/**
* Sets the resource capability
*
* @param capability
*/
public void setCapability(String capability){
model.setProperty("capability", capability);
}
/**
* Gets the resource key
*
* @return {@link String}
*/
public String getKey(){
return model.getProperty("key", String.class);
}
/**
* Gets the resource type
*
* @return {@link String}
*/
public String getType(){
return model.getProperty("type", String.class);
}
/**
* Gets the name assigned to this resource instance
*
* @return {@link String}
*/
public String getName(){
return model.getProperty("name", String.class);
}
/**
* Sets the name for this resource instance
*
* @param name
*/
public void setName(String name){
model.setProperty("name", name);
}
/**
* Gets resource model data
*
* @return {@link ResourceModel}
*/
public ResourceModel getInnerModel(){
return model;
}
/**
* Sets resource model data
*
* @param model
*/
public void setInnerModel(ResourceModel model){
this.model = model;
}
/**
* Copy the resource model
*
* @param resource
*/
protected void copy(Resource resource){
this.model = resource.model;
this.initialize();
}
/**
* Knows how to build a request {@link RequestData} object, describing
* the HTTP request operation to be executed (GET/PUT/DELETE/POST)
*
* @param methodType
* @param content
* @param headers
* @return RequestData
*/
protected RequestData createRequestData(RequestType methodType, Map<String, Object> queryParams, Map<String, Object> content, Map<String, String> headers){
RequestData data = RequestFactory.createRequestData();
data.method = methodType;
data.url = model.getProperty("url", String.class);
data.queryParams = queryParams;
data.headers.put("Authorization", "Capability " + model.getProperty("capability", String.class));
data.headers.put("Accept", this.getMediaType());
if(methodType != RequestType.HTTP_GET){
data.headers.put("Content-Type", this.getMediaType());
}
if(headers != null && !headers.isEmpty()){
for (Map.Entry<String, String> header : headers.entrySet()) {
data.headers.put(header.getKey(), header.getValue());
}
}
if(methodType == RequestType.HTTP_PUT || methodType == RequestType.HTTP_POST){
data.body = content;
}
return data;
}
/**
* Sends HTTP GET request to the underlying resource
*
* @throws ResponseException
* @throws IOException
*/
public void get() throws ResponseException, IOException{
this.get(null, null);
}
public Map<String, Object> get(Map<String, Object> queryParams, Map<String, String> headers) throws ResponseException, IOException{
RequestData data = this.createRequestData(RequestType.HTTP_GET, queryParams, null, headers);
Map<String, Object> rawModel = this.sendRequest(data);
updateModel(rawModel);
return rawModel;
}
/**
* Sends HTTP PUT request to the underlying resource
*
* @throws ResponseException
* @throws IOException
*/
@SuppressWarnings("unchecked")
public void update() throws ResponseException, IOException{
RequestData data = RequestFactory.createRequestData();
data.method = RequestType.HTTP_PUT;
data.url = model.getProperty("url", String.class);
data.headers.put("Authorization", "Capability " + model.getProperty("capability", String.class));
data.headers.put("Accept", this.getMediaType());
data.headers.put("Content-Type", this.getMediaType());
data.body = model.rawModel;
Request request = RequestFactory.createRequest(data);
Response response = request.send();
if(!response.isSuccessStatusCode())
throw new ResponseException(response, "Error updating " + getResourceName());
Map<String, Object> rawModel = response.parseAs(HashMap.class);
updateModel(rawModel);
}
/**
* Sends HTTP DELETE request to the underlying resource
*
* @throws ResponseException
* @throws IOException
*/
public void delete() throws ResponseException, IOException{
RequestData data = RequestFactory.createRequestData();
data.method = RequestType.HTTP_DELETE;
data.url = model.getProperty("url", String.class);
data.headers.put("Authorization", "Capability " + model.getProperty("capability", String.class));
data.headers.put("Accept", this.getMediaType());
data.headers.put("Content-Type", this.getMediaType());
Request request = RequestFactory.createRequest(data);
Response response = request.send();
if(!response.isSuccessStatusCode())
throw new ResponseException(response, "Error deleting " + getResourceName());
}
/**
* Sends HTTP POST request to the underlying resource
*
* @param content
* @return {@link Map}
* @throws ResponseException
* @throws IOException
*/
public Map<String, Object> post(Map<String, Object> content) throws ResponseException, IOException{
RequestData data = this.createRequestData(RequestType.HTTP_POST, null, content, null);
return this.post(data);
}
/**
* Sends HTTP POST request to the underlying resource
*
* @param content
* @param headers
* @return {@link Map}
* @throws ResponseException
* @throws IOException
*/
public Map<String, Object> post(Map<String, Object> content, Map<String, String> headers) throws ResponseException, IOException{
RequestData data = this.createRequestData(RequestType.HTTP_POST, null, content, headers);
return this.post(data);
}
/**
* Sends HTTP POST request to the underlying resource
*
* @param data
* @return {@link Map}
* @throws ResponseException
* @throws IOException
*/
public Map<String, Object> post(RequestData data) throws ResponseException, IOException{
Map<String, Object> rawModel = this.sendRequest(data);
addModel(rawModel);
return rawModel;
}
/**
* Sends HTTP request based on the data described by {@link RequestData} data
*
* @param data describes the HTTP request to send out
* @return {@link Map}
* @throws ResponseException
* @throws IOException
*/
@SuppressWarnings("unchecked")
public Map<String, Object> sendRequest(RequestData data) throws ResponseException, IOException{
Request request = RequestFactory.createRequest(data);
Response response = request.send();
if(!response.isSuccessStatusCode())
throw new ResponseException(response, "Error " + data.method.name().toLowerCase() + "ing" + getResourceName());
Map<String, Object> rawModel = response.parseAs(HashMap.class);
return rawModel;
}
}
|
package net.sf.ardengine.dialogs.gui;
import javafx.scene.control.TextArea;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputDialog;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import net.sf.ardengine.dialogs.Dialog;
import net.sf.ardengine.dialogs.Event;
import net.sf.ardengine.dialogs.Execute;
import net.sf.ardengine.dialogs.Response;
import net.sf.ardengine.dialogs.cache.LoadedDocument;
import net.sf.ardengine.dialogs.functions.FunctionAttributes;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
/**
* FXML Controller class
*
* @author Kuba
*/
public class FXMLmainController implements Initializable {
@FXML
TextArea taQuestion, taAnswer;
@FXML
AnchorPane ap;
@FXML
ScrollPane spAttributes;
@FXML
TextField tfConditionL, tfConditionR;
@FXML
ChoiceBox chbCondition;
@FXML
ComboBox cbFunctions, cbSource;
@FXML
MenuButton mbTarget;
@FXML
ListView<Dialog> lvDialogs;
@FXML
ListView<Response> lvAnswers;
@FXML
ListView<Execute> lvExecute;
@FXML
TabPane tp1, tp2, tp3;
@FXML
Label lFile, lDialog;
@FXML
Tab tabChosenDialog, tabDialogs, tabFile;
@FXML
Pane pAnswer, pAttr;
LoadedDocument document;
Document configXML;
Dialog actualDialog;
Response actualResponse;
String fileName, target, projectFolder, filePath;
ObservableList<Dialog> dialogs;
ObservableList<Response> answers;
ObservableList<Condition> functions, conditions;
SAXBuilder jdomBuilder;
@Override
public void initialize(URL url, ResourceBundle rb) {
conditions = FXCollections.observableArrayList();
functions = FXCollections.observableArrayList();
conditions.add(new Condition("", "Žádná", false));
conditions.add(new Condition("EQUALS", "==", false));
conditions.add(new Condition("EQUALS", "!=", true));
conditions.add(new Condition("GREATER_THAN", ">", false));
conditions.add(new Condition("LOWER_THAN", "<", false));
conditions.add(new Condition("LOWER_THAN", ">=", true));
conditions.add(new Condition("GREATER_THAN", "<=", true));
chbCondition.setItems(conditions);
chbCondition.getSelectionModel().selectFirst();
jdomBuilder = new SAXBuilder();
}
private void refreshDialogs() {
dialogs = FXCollections.observableArrayList();
document.getAllDialogs().forEach((dialog) -> {
dialogs.add(dialog);
});
lvDialogs.setItems(dialogs);
}
private void refreshAnswers() {
if (actualDialog != null) {
answers = FXCollections.observableArrayList();
answers.addAll(actualDialog.getAllResponsesArray());
lvAnswers.setItems(answers);
taQuestion.setText(actualDialog.getEvent().getRawText());
}
}
private void refreshAns() {
if (actualResponse == null) {
pAnswer.setDisable(true);
} else {
pAnswer.setDisable(false);
taAnswer.setText(actualResponse.getRawText());
//condition = ans.getIfToken();
/* if (condition.startsWith("#")) {
chbCondition.setDisable(false);
for (AnswerToken answerstoken : answerstokens) {
if (answerstoken.getContent().equals(condition)) {
mbCondition.setText(answerstoken.getName());
break;
}
}
if (condition.startsWith("#!")) {
chbCondition.getSelectionModel().selectLast();
} else {
chbCondition.getSelectionModel().selectFirst();
}
} else {
chbCondition.setDisable(true);
}*/
FunctionAttributes attrs = actualResponse.getFunctionAttributes();
tfConditionL.setText(attrs.getAttributeValue("value1"));
tfConditionR.setText(attrs.getAttributeValue("value2"));
if (attrs.getAttributeValue(Response.ATTR_CONDITION) != null) {
switch (attrs.getAttributeValue(Response.ATTR_CONDITION)) {
case "EQUALS":
if (attrs.getAttributeValue("negate").equals("true")) {
chbCondition.getSelectionModel().select(2);
} else {
chbCondition.getSelectionModel().select(1);
}
break;
case "GREATER_THAN":
if (attrs.getAttributeValue("negate").equals("true")) {
chbCondition.getSelectionModel().select(6);
} else {
chbCondition.getSelectionModel().select(3);
}
break;
case "LOWER_THAN":
if (attrs.getAttributeValue("negate").equals("true")) {
chbCondition.getSelectionModel().select(5);
} else {
chbCondition.getSelectionModel().select(4);
}
break;
default:
chbCondition.getSelectionModel().select(0);
tfConditionL.setText("");
tfConditionR.setText("");
break;
}
} else {
chbCondition.getSelectionModel().select(0);
tfConditionL.setText("");
tfConditionR.setText("");
}
target = actualResponse.getTarget();
mbTarget.setText(target);
}
}
private String dialogWindow(String dotaz) {
TextInputDialog dialog = new TextInputDialog("");
dialog.setHeaderText(null);
dialog.setContentText(dotaz);
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
return result.get();
}
return "0";
}
private void dialogWarning(String text) {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Warning Dialog");
alert.setHeaderText("Varování!");
alert.setContentText(text);
alert.showAndWait();
}
public void openProject() {
DirectoryChooser chooser = new DirectoryChooser();
chooser.setTitle("JavaFX Projects");
File defaultDirectory = new File(System.getProperty("user.home"));
chooser.setInitialDirectory(defaultDirectory);
projectFolder = (chooser.showDialog((Stage) (ap.getScene().getWindow()))).getAbsolutePath();
tabDialogs.setDisable(false);
tabFile.setDisable(false);
System.out.println(projectFolder);
File configFile = new File(projectFolder + File.separator+".configuration"+File.separator+"functions.xml");
File sourcesFile = new File(projectFolder + File.separator +".configuration"+File.separator+"sources.xml");
Document sourcesXML;
try {
configXML = jdomBuilder.build(configFile);
sourcesXML = jdomBuilder.build(sourcesFile);
ObservableList<String> sources = FXCollections.observableArrayList();
sourcesXML.getRootElement().getChildren().forEach((s) -> {
sources.add(s.getAttributeValue("name"));
});
cbSource.setItems(sources);
} catch (JDOMException | IOException ex) {
Logger.getLogger(FXMLmainController.class.getName()).log(Level.SEVERE, null, ex);
//throw some cool exception
}
functions.clear();
configXML.getRootElement().getChildren().forEach((func) -> {
Condition con = new Condition(func.getAttributeValue("name"), func.getChildText("description"), false);
func.getChild("compulsory").getChildren().forEach((arg) -> {
con.addArgument(new Argument(arg.getAttributeValue("name"), arg.getChildText("description"), false));
});
func.getChild("optional").getChildren().forEach((arg) -> {
con.addArgument(new Argument(arg.getAttributeValue("name"), arg.getChildText("description"), true));
});
functions.add(con);
});
/* for (int i = 3; i < functions.size(); i++) {
conditions.add(functions.get(i));
}*/
cbFunctions.setItems(functions);
cbFunctions.getSelectionModel().select(0);
tp1.getSelectionModel().select(1);
}
public void openFile() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Otevřít dialogový soubor.");
File directory = new File(projectFolder);
fileChooser.setInitialDirectory(directory);
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("XML", "*.xml"));
File file = fileChooser.showOpenDialog((Stage) (ap.getScene().getWindow()));
try {
document = new LoadedDocument(file, jdomBuilder.build(file));
} catch (JDOMException | IOException ex) {
Logger.getLogger(FXMLmainController.class.getName()).log(Level.SEVERE, null, ex);
//throw some cool exception
}
refreshDialogs();
refreshAnswers();
refreshAns();
filePath = file.getAbsolutePath();
fileName = file.getAbsolutePath().replace(directory.getAbsolutePath() + File.separator, "");
lFile.setText(fileName);
fillTargets();
tp1.getSelectionModel().select(2);
}
public void newFile() {
fileName = dialogWindow("Zadejte název souboru: "); //TODO cesta
lFile.setText(fileName + ".xml");
document = new LoadedDocument(new File(projectFolder + File.separator + fileName + ".xml"), new Document(new Element("root")));
filePath = document.source.getAbsolutePath();
filePath = filePath.substring(0, filePath.length() - 4);
fillTargets();
refreshDialogs();
refreshAnswers();
refreshAns();
tp1.getSelectionModel().select(2);
}
public void saveFile() {
if (actualDialog!=null) {
document.addOrRefreshDialog(actualDialog);
}
document.save(new XMLOutputter(Format.getPrettyFormat()), document.source);
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Info");
alert.setHeaderText(null);
alert.setContentText("Soubor " + fileName + " uložen.");
alert.showAndWait();
}
public void newDialog() {
String id = dialogWindow("Zadejte id dialogu:");
lDialog.setText(id);
addDialogToMenu(id);
actualResponse = null;
actualDialog = new Dialog(id, new Event("", "Undefined"), new ArrayList<>());
tabChosenDialog.setDisable(false);
document.addOrRefreshDialog(actualDialog);
// tp2.getSelectionModel().select(2);
refreshDialogs();
refreshAnswers();
refreshAns();
refreshExecutes();
}
public void editDialog() {
actualDialog = lvDialogs.getSelectionModel().getSelectedItem();
lDialog.setText(actualDialog.getDialogID());
cbSource.getSelectionModel().select(actualDialog.getEvent().getSourceID());
actualResponse = null;
refreshExecutes();
refreshAnswers();
refreshAns();
tabChosenDialog.setDisable(false);
}
public void deleteDialog() {
String id = lvDialogs.getSelectionModel().getSelectedItem().getDialogID();
removeDialogFromMenu(id);
document.removeDialog(id);
refreshDialogs();
refreshAnswers();
refreshAns();
}
public void saveQuestion() { //saveEvent
actualDialog.getEvent().setSourceID((String) cbSource.getSelectionModel().getSelectedItem());
actualDialog.getEvent().setRawText(taQuestion.getText());
tp3.getSelectionModel().select(2);
document.addOrRefreshDialog(actualDialog);
}
public void saveAnswer() { //saveResponse
actualResponse.setRawText(taAnswer.getText());
//not gonna work anymore..
FunctionAttributes attrs = actualResponse.getFunctionAttributes();
if (!chbCondition.getSelectionModel().isSelected(0)) {
Condition selected = (Condition) chbCondition.getSelectionModel().getSelectedItem();
attrs.setAttribute(Response.ATTR_CONDITION, selected.functionName);
attrs.setAttribute("value1", tfConditionL.getText());
attrs.setAttribute("value2", tfConditionR.getText());
attrs.setAttribute("negate", selected.negate ? "true" : "false");
} else if (attrs.getAttributeValue(Response.ATTR_CONDITION) != null) {
attrs.setAttribute(Response.ATTR_CONDITION, "");
}
actualResponse.setTarget(target);
document.addOrRefreshDialog(actualDialog);
refreshAnswers();
refreshAns();
}
public void newAnswer() { //newResponse
actualResponse = new Response("...");
mbTarget.setText("Konec");
chbCondition.getSelectionModel().selectFirst();
tfConditionL.setText("");
tfConditionR.setText("");
target = "exit()";
//cbTokenRemember.setSelected(false);
actualDialog.addResponse(actualResponse);
refreshAnswers();
refreshAns();
}
public void editAnswer() {
actualResponse = lvAnswers.getSelectionModel().getSelectedItem();
refreshAnswers();
refreshAns();
}
public void deleteAnswer() {
actualDialog.removeResponse(lvAnswers.getSelectionModel().getSelectedItem());
refreshAnswers();
refreshAns();
}
public void fillTargets() {
mbTarget.getItems().get(0).setOnAction((ActionEvent t) -> {
mbTarget.setText("Konec");
target = "exit()";
});
Menu subMenu = (Menu) mbTarget.getItems().get(1);
boolean exists = false;
MenuItem[] menuArray = subMenu.getItems().toArray(new MenuItem[0]);
for (MenuItem menu : menuArray) {
if (menu.getText().equals(filePath)) {
exists = true;
}
}
if (!exists) {
Menu newFileMenu = new Menu(filePath);
document.getAllDialogsIDs().forEach((String id) -> {
MenuItem item = new MenuItem(id);
item.setOnAction((ActionEvent t) -> {
mbTarget.setText(id);
target = filePath.replace(projectFolder + File.separator, "");
target = target.replace(".xml", ":" + id);
});
newFileMenu.getItems().add(item);
});
subMenu.getItems().add(newFileMenu);
}
}
/**
* Add dialog to menu of avilible targets under the correct file.
*
* @param id - Dialog ID added to avilible targets
*/
public void addDialogToMenu(String id) {
MenuItem item = new MenuItem(id);
item.setOnAction((ActionEvent t) -> {
mbTarget.setText(id);
target = filePath.replace(projectFolder + File.separator, "");
target = target.replace(".xml", ":" + id);
});
((Menu) mbTarget.getItems().get(1)).getItems().forEach((MenuItem subMenu) -> {
if (subMenu.getText().equals(filePath)) {
((Menu) subMenu).getItems().add(item);
}
});
}
/**
* Remove dialog from menu of avilible targets.
*
* @param id - Dialog ID removed from avilible targets
*/
public void removeDialogFromMenu(String id) {
((Menu) mbTarget.getItems().get(1)).getItems().forEach((MenuItem subMenu) -> {
if (subMenu.getText().equals(filePath)) {
((Menu) subMenu).getItems().forEach((MenuItem item) -> {
if (item.getText().equals(id)) {
((Menu) subMenu).getItems().remove(item);
}
});
}
});
}
public void addExecute() {
if (actualDialog != null) {
Condition con = (Condition) cbFunctions.getSelectionModel().getSelectedItem();
pAttr.getChildren().clear();
List<Argument> arguments = con.getArgumentList();
for(int i=0; i < arguments.size(); i++){
createArgumentComponents(arguments.get(i), i);
}
} else {
dialogWarning("Není zvolen dialog. Upravte existující nebo vytvořte nový.");
}
}
private void createArgumentComponents(Argument arg, int offset){
Label label = new Label(arg.name + (arg.optional ? "" : "*"));
label.setLayoutY(offset * 25);
label.setId("");
pAttr.getChildren().add(label);
TextField text = new TextField();
text.setId(arg.name);
text.promptTextProperty().setValue(arg.desc);
text.setLayoutX(80);
text.setPrefWidth(320);
text.setLayoutY(offset * 25);
offset++;
pAttr.getChildren().add(text);
}
public void saveExecute() {
if (actualDialog != null) {
Execute exe = new Execute(((Condition) cbFunctions.getSelectionModel().getSelectedItem()).functionName);
pAttr.getChildren().forEach((node) -> {
if (!node.idProperty().getValue().isEmpty()) {
TextField text = (TextField) node;
if (!text.getText().isEmpty()) {
exe.getFunctionAttributes().setAttribute(text.getId(), text.getText());
}
}
});
actualDialog.getEvent().addExecute(exe);
document.addOrRefreshDialog(actualDialog);
refreshExecutes();
} else {
dialogWarning("Není zvolen dialog. Upravte existující nebo vytvořte nový.");
}
}
public void deleteExecute() {
if (lvExecute.getSelectionModel().getSelectedItem() != null) {
actualDialog.getEvent().removeExecute(lvExecute.getSelectionModel().getSelectedItem());
lvExecute.getItems().remove(lvExecute.getSelectionModel().getSelectedItem());
} else {
dialogWarning("Není vybrán žádný execute.");
}
}
private void refreshExecutes() {
pAttr.getChildren().clear();
ObservableList<Execute> executes = FXCollections.observableArrayList();
actualDialog.getEvent().getAllExecutes().forEach((t) -> {
executes.add(t);
});
lvExecute.setItems(executes);
}
private class Condition {
String desc, functionName;
List<Argument> list;
boolean negate;
Condition(String name, String desc, boolean negate) {
this.functionName = name;
this.desc = desc;
this.negate = negate;
list = new ArrayList<>();
}
public void addArgument(Argument a) {
list.add(a);
}
public List<Argument> getArgumentList() {
return list;
}
public boolean isBasicCondition() {
return list.isEmpty();
}
@Override
public String toString() {
if (isBasicCondition()) {
return desc;
}else{
return functionName;
}
}
}
private class Argument {
String name, desc;
boolean optional;
Argument(String name, String desc, boolean optional) {
this.name = name;
this.desc = desc;
this.optional = optional;
}
@Override
public String toString() {
return desc;
}
}
}
|
package jade.core;
import jade.util.leap.Properties;
import jade.util.leap.List;
import jade.util.leap.ArrayList;
import jade.util.leap.Iterator;
//#MIDP_EXCLUDE_BEGIN
import java.net.*;
//#MIDP_EXCLUDE_END
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
/**
* This class allows the JADE core to retrieve configuration-dependent classes
* and boot parameters.
* <p>
* Take care of using different instances of this class when launching
* different containers/main-containers on the same JVM otherwise
* they would conflict!
*
* @author Federico Bergenti
* @author Giovanni Rimassa - Universita' di Parma
* @author Giovanni Caire - TILAB
*
* @version 1.0, 22/11/00
*
*/
public class ProfileImpl extends Profile {
private Properties props = null;
// Keys to retrieve the implementation classes for configurable
// functionalities among the bootstrap properties.
private static final String RESOURCE = "resource";
private static final String IMTP = "imtp";
//#APIDOC_EXCLUDE_BEGIN
public static final int DEFAULT_PORT = 1099;
//#APIDOC_EXCLUDE_END
//#ALL_EXCLUDE_BEGIN
private static final String DEFAULT_IMTPMANAGER_CLASS = "jade.imtp.rmi.RMIIMTPManager";
//#ALL_EXCLUDE_END
/*#ALL_INCLUDE_BEGIN
private static final String DEFAULT_IMTPMANAGER_CLASS = "jade.imtp.leap.LEAPIMTPManager";
#ALL_INCLUDE_END*/
//#MIDP_EXCLUDE_BEGIN
private MainContainerImpl myMain = null;
//#MIDP_EXCLUDE_END
private PlatformManager myPlatformManager = null;
private ServiceManager myServiceManager = null;
private CommandProcessor myCommandProcessor = null;
private IMTPManager myIMTPManager = null;
private ResourceManager myResourceManager = null;
/**
Creates a Profile implementation using the given properties to
configure the platform startup process.
@param aProp The names and values of the configuration properties
to use.
*/
public ProfileImpl(Properties aProp) {
props = aProp;
init();
}
/**
* Creates a Profile implementation with the following default configuration:
* <br> if isMain is true, then the profile is configured to launch
* a main-container on the localhost,
* RMI internal Message Transport Protocol, port number 1099,
* iiop MTP.
* <br> if isMain is false, then the profile is configured to launch
* a remote container on the localhost, connecting to the main-container
* on the localhost through
* RMI internal Message Transport Protocol, port number 1099.
*/
public ProfileImpl(boolean isMain) {
//#ALL_EXCLUDE_BEGIN
props = new jade.util.BasicProperties();
//#ALL_EXCLUDE_END
/*#ALL_INCLUDE_BEGIN
props = new Properties();
#ALL_INCLUDE_END*/
props.setProperty(Profile.MAIN, (new Boolean(isMain)).toString()); // set to a main/non-main container
init();
}
/**
* Create a Profile object initialized with the settings specified
* in a given property file
*/
public ProfileImpl(String fileName) throws ProfileException {
props = new Properties();
if (fileName != null) {
try {
props.load(fileName);
}
catch (IOException ioe) {
throw new ProfileException("Can't load properties: "+ioe.getMessage());
}
}
init();
}
/**
* This constructor creates a default Profile for launching a platform.
* @param host is the name of the host where the main-container should
* be listen to. A null value means use the default (i.e. localhost)
* @param port is the port number where the main-container should be
* listen
* for other containers. A negative value should be used for using
* the default port number.
* @param platformID is the synbolic name of the platform, if
* different from default. A null value means use the default
* (i.e. localhost)
**/
public ProfileImpl(String host, int port, String platformID) {
// create the object props
//#ALL_EXCLUDE_BEGIN
props = new jade.util.BasicProperties();
//#ALL_EXCLUDE_END
/*#ALL_INCLUDE_BEGIN
props = new Properties();
#ALL_INCLUDE_END*/
// set the passed properties
if(host != null)
props.setProperty(MAIN_HOST, host);
if(port > 0)
setIntProperty(MAIN_PORT, port);
if(platformID != null)
props.setProperty(PLATFORM_ID, platformID);
// calls the method init to adjust all the other parameters
init();
}
private void init() {
// Set JVM parameter if not set
if(props.getProperty(JVM) == null) {
//#PJAVA_EXCLUDE_BEGIN
props.setProperty(JVM, J2SE);
//#PJAVA_EXCLUDE_END
/*#PJAVA_INCLUDE_BEGIN
props.setProperty(JVM, PJAVA);
#PJAVA_INCLUDE_END*/
/*#MIDP_INCLUDE_BEGIN
props.setProperty(JVM, MIDP);
props.setProperty(MAIN, "false");
#MIDP_INCLUDE_END*/
}
// Set default values
setPropertyIfNot(MAIN, "true");
String host = props.getProperty(MAIN_HOST);
if(host == null) {
host = getDefaultNetworkName();
props.setProperty(MAIN_HOST, host);
}
String p = props.getProperty(MAIN_PORT);
if(p == null) {
String localPort = props.getProperty(LOCAL_PORT);
// Default for a sole main container: use the local port, or
// the default port if also the local port is null.
if(isFirstMain()) {
if(localPort != null) {
p = localPort;
}
else {
p = Integer.toString(DEFAULT_PORT);
}
}
else {
// All other cases: use the default port.
p = Integer.toString(DEFAULT_PORT);
}
props.setProperty(MAIN_PORT, p);
}
String localHost = props.getProperty(LOCAL_HOST);
if(localHost == null) {
if(isFirstMain()) {
// Default for a sole main container: use the MAIN_HOST property
localHost = host;
}
else {
// Default for a peripheral container or an added main container: use the local host
localHost = getDefaultNetworkName();
}
props.setProperty(LOCAL_HOST, localHost);
}
String lp = props.getProperty(LOCAL_PORT);
if(lp == null) {
if(isFirstMain()) {
// Default for a sole main container: use the MAIN_PORT property
lp = p;
}
else {
// Default for a peripheral container or an added main container: use the default port
lp = Integer.toString(DEFAULT_PORT);
}
props.setProperty(LOCAL_PORT, lp);
}
setPropertyIfNot(SERVICES, DEFAULT_SERVICES);
//#MIDP_EXCLUDE_BEGIN
// Set agents as a list to handle the "gui" option
try {
List agents = getSpecifiers(AGENTS);
String isGui = props.getProperty("gui");
if (isGui != null && CaseInsensitiveString.equalsIgnoreCase(isGui, "true")) {
Specifier s = new Specifier();
s.setName("rma");
s.setClassName("jade.tools.rma.rma");
agents.add(0, s);
props.put(AGENTS, agents);
}
}
catch(ProfileException pe) {
// FIXME: Should throw?
pe.printStackTrace();
}
//#MIDP_EXCLUDE_END
//#J2ME_EXCLUDE_BEGIN
// If this is a Main Container and the '-nomtp' option is not
// given, activate the default IIOP MTP (unless some MTPs have
// been directly provided).
if(isMain() && !getBooleanProperty("nomtp", false) && (props.getProperty(MTPS) == null)) {
Specifier s = new Specifier();
s.setClassName("jade.mtp.iiop.MessageTransportProtocol");
List l = new ArrayList(1);
l.add(s);
props.put(MTPS, l);
}
//#J2ME_EXCLUDE_END
}
/**
* Return the underlying properties collection.
* @return Properties The properties collection.
*/
public Properties getProperties() {
return props;
}
/**
* Assign the given value to the given property name.
*
* @param key is the property name
* @param value is the property value
*/
public void setParameter(String key, String value) {
props.setProperty(key, value);
}
/**
* Assign the given property value to the given property name
*
* @param key is the property name
* @param value is the property value
*/
public void setSpecifiers(String key, List value) {
//#MIDP_EXCLUDE_BEGIN
props.put(key, value);
//#MIDP_EXCLUDE_END
}
/**
* Retrieve a String value from the configuration properties.
* If no parameter corresponding to the specified key is found,
* <code>aDefault</code> is returned.
* @param key The key identifying the parameter to be retrieved
* among the configuration properties.
* @param aDefault The value that is returned if the specified
* key is not found
*/
public String getParameter(String key, String aDefault) {
String v = props.getProperty(key);
return (v != null ? v.trim() : aDefault);
}
/**
* Retrieve a boolean value for a configuration property. If no
* corresponding property is found or if its string value cannot
* be converted to a boolean one, a default value is returned.
* @param key The key identifying the parameter to be retrieved
* among the configuration properties.
* @param aDefault The value to return when there is no property
* set for the given key, or its value cannot be converted to a
* boolean value.
*
public boolean getParameter(String key, boolean aDefault) {
String v = props.getProperty(key);
if(v == null) {
return aDefault;
}
else {
if(CaseInsensitiveString.equalsIgnoreCase(v, "true")) {
return true;
}
else if(CaseInsensitiveString.equalsIgnoreCase(v, "false")) {
return false;
}
else {
return aDefault;
}
}
}*/
/**
* Retrieve a list of Specifiers from the configuration properties.
* Agents, MTPs and other items are specified among the configuration
* properties in this way.
* If no list of Specifiers corresponding to the specified key is found,
* an empty list is returned.
* @param key The key identifying the list of Specifires to be retrieved
* among the configuration properties.
*/
public List getSpecifiers(String key) throws ProfileException {
//#MIDP_EXCLUDE_BEGIN
// Check if the list of specs is already in the properties as a list
List l = null;
try {
l = (List) props.get(key);
}
catch (ClassCastException cce) {
}
if (l != null) {
return l;
}
//#MIDP_EXCLUDE_END
// The list should be present as a string --> parse it
String specsLine = getParameter(key, null);
try {
Vector v = Specifier.parseSpecifierList(specsLine);
// convert the vector into an arraylist (notice that using the vector allows to avoid class loading of ArrayList)
List l1 = new ArrayList(v.size());
for (int i=0; i<v.size(); i++)
l1.add(v.elementAt(i));
return l1;
}
catch (Exception e) {
throw new ProfileException("Error parsing specifier list "+specsLine+".", e);
}
}
/**
* Retrieve a boolean value for a configuration property. If no
* corresponding property is found or if its string value cannot
* be converted to a boolean one, a default value is returned.
* @param key The key identifying the parameter to be retrieved
* among the configuration properties.
* @param aDefault The value to return when there is no property
* set for the given key, or its value cannot be converted to a
* boolean value.
*/
public boolean getBooleanProperty(String aKey, boolean aDefault) {
String v = props.getProperty(aKey);
if(v == null) {
return aDefault;
}
else {
if(CaseInsensitiveString.equalsIgnoreCase(v, "true")) {
return true;
}
else if(CaseInsensitiveString.equalsIgnoreCase(v, "false")) {
return false;
}
else {
return aDefault;
}
}
}
/**
Creates a string representation of this profile. The returned
string has the format
<p><code>(profile name1=value1 name2=value2 ... )</code></p>
@return A string containing a readable representation of this
profile object.
*/
public String toString() {
StringBuffer str = new StringBuffer("(Profile");
String[] properties = propsToStringArray();
if (properties != null)
for (int i=0; i<properties.length; i++)
str.append(" "+properties[i]);
str.append(")");
return str.toString();
}
//#APIDOC_EXCLUDE_BEGIN
protected PlatformManager getPlatformManager() throws ProfileException {
if (myPlatformManager == null) {
createPlatformManager();
}
return myPlatformManager;
}
/**
Access the platform service manager.
@return The platform service manager, either the real
implementation or a remote proxy object.
@throws ProfileException If some needed information is wrong or
missing from the profile.
*/
protected ServiceManager getServiceManager() throws ProfileException {
if(myServiceManager == null) {
myServiceManager = new ServiceManagerImpl(this, getPlatformManager());
}
return myServiceManager;
}
/**
Access the platform service finder.
@return The platform service finder, either the real
implementation or a remote proxy object.
@throws ProfileException If some needed information is wrong or
missing from the profile.
*/
protected ServiceFinder getServiceFinder() throws ProfileException {
return (ServiceFinder) getServiceManager();
}
protected CommandProcessor getCommandProcessor() throws ProfileException {
if(myCommandProcessor == null) {
myCommandProcessor = new CommandProcessor();
}
return myCommandProcessor;
}
//#MIDP_EXCLUDE_BEGIN
protected MainContainerImpl getMain() throws ProfileException {
return myMain;
}
//#MIDP_EXCLUDE_END
protected IMTPManager getIMTPManager() throws ProfileException {
if (myIMTPManager == null) {
createIMTPManager();
}
return myIMTPManager;
}
public ResourceManager getResourceManager() throws ProfileException {
if (myResourceManager == null) {
createResourceManager();
}
return myResourceManager;
}
//#APIDOC_EXCLUDE_END
private void createPlatformManager() throws ProfileException {
try {
myIMTPManager = getIMTPManager();
//#MIDP_EXCLUDE_BEGIN
if(isMain()) {
// This is a main container: create a real PlatformManager,
// export it and get the MainContainer.
PlatformManagerImpl pm = new PlatformManagerImpl(this);
myIMTPManager.exportPlatformManager(pm);
myMain = pm.getMain();
myPlatformManager = pm;
return;
}
//#MIDP_EXCLUDE_END
// This is a peripheral container: create a proxy to the PlatformManager
myPlatformManager = myIMTPManager.getPlatformManagerProxy();
}
catch(IMTPException imtpe) {
throw new ProfileException("Can't get a proxy to the Platform Manager", imtpe);
}
}
private void createIMTPManager() throws ProfileException {
String className = getParameter(IMTP, DEFAULT_IMTPMANAGER_CLASS);
try {
myIMTPManager = (IMTPManager) Class.forName(className).newInstance();
}
catch (Exception e) {
throw new ProfileException("Error loading IMTPManager class "+className);
}
}
private void createResourceManager() throws ProfileException {
//#ALL_EXCLUDE_BEGIN
String className = getParameter(RESOURCE, "jade.core.FullResourceManager");
//#ALL_EXCLUDE_END
/*#ALL_INCLUDE_BEGIN
String className = getParameter(RESOURCE, "jade.core.LightResourceManager");
#ALL_INCLUDE_END*/
try {
myResourceManager = (ResourceManager) Class.forName(className).newInstance();
}
catch (Exception e) {
throw new ProfileException("Error loading ResourceManager class "+className);
}
}
private void setPropertyIfNot(String key, String value) {
String old = props.getProperty(key);
if(old == null) {
props.setProperty(key, value);
}
}
private void setIntProperty(String aKey, int aValue) {
props.setProperty(aKey, Integer.toString(aValue));
}
private String[] propsToStringArray() {
String[] result = new String[props.size()];
int i = 0;
for(Enumeration e = props.keys(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
String value = props.getProperty(key);
if (value != null) {
result[i++] = key + "=" + value;
}
else {
result[i++] = key + "=";
}
}
return result;
}
//#APIDOC_EXCLUDE_BEGIN
protected boolean isMain() {
return getBooleanProperty(MAIN, false);
}
// True if this is a Main Container and the LOCAL_SERVICE_MANAGER
// option is set to false or not set
protected boolean isFirstMain() {
return isMain() && !getBooleanProperty(LOCAL_SERVICE_MANAGER, false);
}
//#APIDOC_EXCLUDE_END
}
|
package com.aspose.words.examples.linq;
import com.aspose.words.*;
import com.aspose.words.examples.Utils;
public class InTableRow {
/**
* The main entry point for the application.
*/
public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = Utils.getDataDir(InTableRow.class);
String fileName = "InTableRow.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
// engine.getKnownTypes().add(DateUtil.class);
engine.buildReport(doc, Common.GetContracts(), "ds");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
System.out.println("\nIn-Table row template document is populated with the data about managers.\nFile saved at " + dataDir);
}
}
|
package jade.core;
import jade.util.leap.Properties;
import jade.util.leap.List;
import jade.util.leap.ArrayList;
//#MIDP_EXCLUDE_BEGIN
import java.net.*;
//#MIDP_EXCLUDE_END
import java.io.IOException;
import java.util.Vector;
import java.util.Enumeration;
/**
* This class allows the JADE core to retrieve configuration-dependent classes
* and boot parameters.
* <p>
* Take care of using different instances of this class when launching
* different containers/main-containers on the same JVM otherwise
* they would conflict!
*
* @author Federico Bergenti
* @author Giovanni Rimassa - Universita' di Parma
* @author Giovanni Caire - TILAB
*
* @version 1.0, 22/11/00
*
*/
public class ProfileImpl extends Profile {
private Properties props = null;
// Keys to retrieve the implementation classes for configurable
// functionalities among the bootstrap properties.
private static final String RESOURCE = "resource";
//#APIDOC_EXCLUDE_BEGIN
public static final int DEFAULT_PORT = 1099;
//#APIDOC_EXCLUDE_END
//#ALL_EXCLUDE_BEGIN
private static final String DEFAULT_IMTPMANAGER_CLASS = "jade.imtp.rmi.RMIIMTPManager";
//#ALL_EXCLUDE_END
/*#ALL_INCLUDE_BEGIN
private static final String DEFAULT_IMTPMANAGER_CLASS = "jade.imtp.leap.LEAPIMTPManager";
#ALL_INCLUDE_END*/
//#MIDP_EXCLUDE_BEGIN
private MainContainerImpl myMain = null;
//#MIDP_EXCLUDE_END
private PlatformManager myPlatformManager = null;
private ServiceManager myServiceManager = null;
private CommandProcessor myCommandProcessor = null;
private IMTPManager myIMTPManager = null;
private ResourceManager myResourceManager = null;
private boolean udpMonitoring;
private int udpMonitoringPort;
private int udpMonitoringPingDelay;
private int udpMonitoringTimeLimit;
/**
Creates a Profile implementation using the given properties to
configure the platform startup process.
@param aProp The names and values of the configuration properties
to use.
*/
public ProfileImpl(Properties aProp) {
props = aProp;
init();
}
/**
* Creates a Profile implementation with the following default configuration:
* <br> if isMain is true, then the profile is configured to launch
* a main-container on the localhost,
* RMI internal Message Transport Protocol, port number 1099,
* HTTP MTP.
* <br> if isMain is false, then the profile is configured to launch
* a remote container on the localhost, connecting to the main-container
* on the localhost through
* RMI internal Message Transport Protocol, port number 1099.
*/
public ProfileImpl(boolean isMain) {
//#ALL_EXCLUDE_BEGIN
props = new jade.util.BasicProperties();
//#ALL_EXCLUDE_END
/*#ALL_INCLUDE_BEGIN
props = new Properties();
#ALL_INCLUDE_END*/
props.setProperty(Profile.MAIN, (new Boolean(isMain)).toString()); // set to a main/non-main container
init();
}
/**
This is equivalent to <code>ProfileImpl(true)</code>
*/
public ProfileImpl() {
this(true);
}
/**
* Create a Profile object initialized with the settings specified
* in a given property file
*/
public ProfileImpl(String fileName) throws ProfileException {
props = new Properties();
if (fileName != null) {
try {
props.load(fileName);
}
catch (IOException ioe) {
throw new ProfileException("Can't load properties: "+ioe.getMessage());
}
}
init();
}
/**
* This constructor creates a default Profile for launching a platform (<b>i.e. a main container!!</b>).
* @param host is the name of the host where the main-container should
* be listen to. A null value means use the default (i.e. localhost)
* @param port is the port number where the main-container should be
* listen
* for other containers. A negative value should be used for using
* the default port number.
* @param platformID is the symbolic name of the platform, if
* different from default. A null value means use the default
* (i.e. localhost)
**/
public ProfileImpl(String host, int port, String platformID) {
this(host, port, platformID, true);
}
/**
* This constructor creates a default Profile for launching a main (or non-main) container
* (depending on the value of <code>isMain</code>)
* @param host is the name of the host where the main-container should
* be listen to. A null value means use the default (i.e. localhost)
* @param port is the port number where the main-container should be
* listen
* for other containers. A negative value should be used for using
* the default port number.
* @param platformID is the symbolic name of the platform, if
* different from default. A null value means use the default
* (i.e. localhost)
* @param isMain if isMain is false, then the profile is configured to launch
* a remote container, if true a main-container
**/
public ProfileImpl(String host, int port, String platformID, boolean isMain) {
// create the object props
//#ALL_EXCLUDE_BEGIN
props = new jade.util.BasicProperties();
//#ALL_EXCLUDE_END
/*#ALL_INCLUDE_BEGIN
props = new Properties();
#ALL_INCLUDE_END*/
// set the passed properties
props.setProperty(Profile.MAIN, (new Boolean(isMain)).toString()); // set to a main/non-main container
if(host != null)
props.setProperty(MAIN_HOST, host);
if(port > 0)
setIntProperty(MAIN_PORT, port);
if(platformID != null)
props.setProperty(PLATFORM_ID, platformID);
// calls the method init to adjust all the other parameters
init();
}
private void init() {
// Set JVM parameter if not set
if(props.getProperty(JVM) == null) {
//#PJAVA_EXCLUDE_BEGIN
props.setProperty(JVM, J2SE);
//#PJAVA_EXCLUDE_END
/*#PJAVA_INCLUDE_BEGIN
props.setProperty(JVM, PJAVA);
#PJAVA_INCLUDE_END*/
/*#MIDP_INCLUDE_BEGIN
props.setProperty(JVM, MIDP);
props.setProperty(MAIN, "false");
#MIDP_INCLUDE_END*/
}
// Set default values
setPropertyIfNot(MAIN, "true");
String host = props.getProperty(MAIN_HOST);
if(host == null) {
host = getDefaultNetworkName();
props.setProperty(MAIN_HOST, host);
}
String p = props.getProperty(MAIN_PORT);
if(p == null) {
String localPort = props.getProperty(LOCAL_PORT);
// Default for a sole main container: use the local port, or
// the default port if also the local port is null.
if(isFirstMain()) {
if(localPort != null) {
p = localPort;
}
else {
p = Integer.toString(DEFAULT_PORT);
}
}
else {
// All other cases: use the default port.
p = Integer.toString(DEFAULT_PORT);
}
props.setProperty(MAIN_PORT, p);
}
String localHost = props.getProperty(LOCAL_HOST);
if(localHost == null) {
if(isFirstMain()) {
// Default for a sole main container: use the MAIN_HOST property
localHost = host;
}
else {
// Default for a peripheral container or an added main container: use the local host
localHost = getDefaultNetworkName();
}
props.setProperty(LOCAL_HOST, localHost);
}
String lp = props.getProperty(LOCAL_PORT);
if(lp == null) {
if(isFirstMain()) {
// Default for a sole main container: use the MAIN_PORT property
lp = p;
}
else {
// Default for a peripheral container or an added main container: use the default port
lp = Integer.toString(DEFAULT_PORT);
}
props.setProperty(LOCAL_PORT, lp);
}
setPropertyIfNot(SERVICES, DEFAULT_SERVICES);
//#MIDP_EXCLUDE_BEGIN
// Set agents as a list to handle the "gui" option
try {
List agents = getSpecifiers(AGENTS);
String isGui = props.getProperty("gui");
if (isGui != null && CaseInsensitiveString.equalsIgnoreCase(isGui, "true")) {
Specifier s = new Specifier();
s.setName("rma");
s.setClassName("jade.tools.rma.rma");
agents.add(0, s);
props.put(AGENTS, agents);
}
}
catch(ProfileException pe) {
// FIXME: Should throw?
pe.printStackTrace();
}
//#MIDP_EXCLUDE_END
//#J2ME_EXCLUDE_BEGIN
// If this is a Main Container and the '-nomtp' option is not
// given, activate the default HTTP MTP (unless some MTPs have
// been directly provided).
if(isMain() && !getBooleanProperty("nomtp", false) && (props.getProperty(MTPS) == null)) {
Specifier s = new Specifier();
s.setClassName("jade.mtp.http.MessageTransportProtocol");
List l = new ArrayList(1);
l.add(s);
props.put(MTPS, l);
}
//#J2ME_EXCLUDE_END
}
/**
* Return the underlying properties collection.
* @return Properties The properties collection.
*/
public Properties getProperties() {
return props;
}
/**
* Assign the given value to the given property name.
*
* @param key is the property name
* @param value is the property value
*/
public void setParameter(String key, String value) {
props.setProperty(key, value);
}
/**
* Assign the given property value to the given property name
*
* @param key is the property name
* @param value is the property value
*/
public void setSpecifiers(String key, List value) {
//#MIDP_EXCLUDE_BEGIN
props.put(key, value);
//#MIDP_EXCLUDE_END
}
/**
* Retrieve a String value from the configuration properties.
* If no parameter corresponding to the specified key is found,
* <code>aDefault</code> is returned.
* @param key The key identifying the parameter to be retrieved
* among the configuration properties.
* @param aDefault The value that is returned if the specified
* key is not found
*/
public String getParameter(String key, String aDefault) {
String v = props.getProperty(key);
if (v==null) {
String dottedKey = key.replace('_', '.');
v = props.getProperty( dottedKey );
}
if (v==null) {
String underscoredKey = key.replace('.', '_');
v = props.getProperty( underscoredKey );
}
return (v != null ? v.trim() : aDefault);
}
/**
* Retrieve a boolean value for a configuration property. If no
* corresponding property is found or if its string value cannot
* be converted to a boolean one, a default value is returned.
* @param key The key identifying the parameter to be retrieved
* among the configuration properties.
* @param aDefault The value to return when there is no property
* set for the given key, or its value cannot be converted to a
* boolean value.
*
public boolean getParameter(String key, boolean aDefault) {
String v = props.getProperty(key);
if(v == null) {
return aDefault;
}
else {
if(CaseInsensitiveString.equalsIgnoreCase(v, "true")) {
return true;
}
else if(CaseInsensitiveString.equalsIgnoreCase(v, "false")) {
return false;
}
else {
return aDefault;
}
}
}*/
/**
* Retrieve a list of Specifiers from the configuration properties.
* Agents, MTPs and other items are specified among the configuration
* properties in this way.
* If no list of Specifiers corresponding to the specified key is found,
* an empty list is returned.
* @param key The key identifying the list of Specifires to be retrieved
* among the configuration properties.
*/
public List getSpecifiers(String key) throws ProfileException {
//#MIDP_EXCLUDE_BEGIN
// Check if the list of specs is already in the properties as a list
List l = null;
try {
l = (List) props.get(key);
}
catch (ClassCastException cce) {
}
if (l != null) {
return l;
}
//#MIDP_EXCLUDE_END
// The list should be present as a string --> parse it
String specsLine = getParameter(key, null);
try {
Vector v = Specifier.parseSpecifierList(specsLine);
// convert the vector into an arraylist (notice that using the vector allows to avoid class loading of ArrayList)
List l1 = new ArrayList(v.size());
for (int i=0; i<v.size(); i++)
l1.add(v.elementAt(i));
return l1;
}
catch (Exception e) {
throw new ProfileException("Error parsing specifier list "+specsLine+".", e);
}
}
/**
* Retrieve a boolean value for a configuration property. If no
* corresponding property is found or if its string value cannot
* be converted to a boolean one, a default value is returned.
* @param key The key identifying the parameter to be retrieved
* among the configuration properties.
* @param aDefault The value to return when there is no property
* set for the given key, or its value cannot be converted to a
* boolean value.
*/
public boolean getBooleanProperty(String aKey, boolean aDefault) {
String v = props.getProperty(aKey);
if(v == null) {
return aDefault;
}
else {
if(CaseInsensitiveString.equalsIgnoreCase(v, "true")) {
return true;
}
else if(CaseInsensitiveString.equalsIgnoreCase(v, "false")) {
return false;
}
else {
return aDefault;
}
}
}
/**
Creates a string representation of this profile. The returned
string has the format
<p><code>(profile name1=value1 name2=value2 ... )</code></p>
@return A string containing a readable representation of this
profile object.
*/
public String toString() {
StringBuffer str = new StringBuffer("(Profile");
String[] properties = propsToStringArray();
if (properties != null)
for (int i=0; i<properties.length; i++)
str.append(" "+properties[i]);
str.append(")");
return str.toString();
}
//#APIDOC_EXCLUDE_BEGIN
protected PlatformManager getPlatformManager() throws ProfileException {
if (myPlatformManager == null) {
createPlatformManager();
}
return myPlatformManager;
}
/**
Access the platform service manager.
@return The platform service manager, either the real
implementation or a remote proxy object.
@throws ProfileException If some needed information is wrong or
missing from the profile.
*/
protected ServiceManager getServiceManager() throws ProfileException {
if(myServiceManager == null) {
myServiceManager = new ServiceManagerImpl(this, getPlatformManager());
}
return myServiceManager;
}
/**
Access the platform service finder.
@return The platform service finder, either the real
implementation or a remote proxy object.
@throws ProfileException If some needed information is wrong or
missing from the profile.
*/
protected ServiceFinder getServiceFinder() throws ProfileException {
return (ServiceFinder) getServiceManager();
}
protected CommandProcessor getCommandProcessor() throws ProfileException {
if(myCommandProcessor == null) {
myCommandProcessor = new CommandProcessor();
}
return myCommandProcessor;
}
//#MIDP_EXCLUDE_BEGIN
protected MainContainerImpl getMain() throws ProfileException {
return myMain;
}
//#MIDP_EXCLUDE_END
protected IMTPManager getIMTPManager() throws ProfileException {
if (myIMTPManager == null) {
createIMTPManager();
}
return myIMTPManager;
}
public ResourceManager getResourceManager() throws ProfileException {
if (myResourceManager == null) {
createResourceManager();
}
return myResourceManager;
}
//#APIDOC_EXCLUDE_END
private void createPlatformManager() throws ProfileException {
try {
myIMTPManager = getIMTPManager();
//#MIDP_EXCLUDE_BEGIN
if(isMain()) {
// This is a main container: create a real PlatformManager,
// export it and get the MainContainer.
PlatformManagerImpl pm = new PlatformManagerImpl(this);
myIMTPManager.exportPlatformManager(pm);
myMain = pm.getMain();
myPlatformManager = pm;
return;
}
//#MIDP_EXCLUDE_END
// This is a peripheral container: create a proxy to the PlatformManager
myPlatformManager = myIMTPManager.getPlatformManagerProxy();
}
catch(IMTPException imtpe) {
throw new ProfileException("Can't get a proxy to the Platform Manager", imtpe);
}
}
private void createIMTPManager() throws ProfileException {
String className = getParameter(IMTP, DEFAULT_IMTPMANAGER_CLASS);
try {
myIMTPManager = (IMTPManager) Class.forName(className).newInstance();
}
catch (Exception e) {
throw new ProfileException("Error loading IMTPManager class "+className);
}
}
private void createResourceManager() throws ProfileException {
//#J2ME_EXCLUDE_BEGIN
String className = getParameter(RESOURCE, "jade.core.FullResourceManager");
//#J2ME_EXCLUDE_END
/*#J2ME_INCLUDE_BEGIN
String className = getParameter(RESOURCE, "jade.core.LightResourceManager");
#J2ME_INCLUDE_END*/
try {
myResourceManager = (ResourceManager) Class.forName(className).newInstance();
}
catch (Exception e) {
throw new ProfileException("Error loading ResourceManager class "+className);
}
}
private void setPropertyIfNot(String key, String value) {
Object old = props.get(key);
if(old == null) {
props.put(key, value);
}
}
private void setIntProperty(String aKey, int aValue) {
props.setProperty(aKey, Integer.toString(aValue));
}
private String[] propsToStringArray() {
String[] result = new String[props.size()];
int i = 0;
for(Enumeration e = props.keys(); e.hasMoreElements(); ) {
String key = (String) e.nextElement();
String value = props.getProperty(key);
if (value != null) {
result[i++] = key + "=" + value;
}
else {
result[i++] = key + "=";
}
}
return result;
}
//#APIDOC_EXCLUDE_BEGIN
protected boolean isMain() {
return getBooleanProperty(MAIN, false);
}
// True if this is a Main Container and the LOCAL_SERVICE_MANAGER
// option is set to false or not set
protected boolean isFirstMain() {
return isMain() && !getBooleanProperty(LOCAL_SERVICE_MANAGER, false);
}
//#APIDOC_EXCLUDE_END
}
|
package nxt.util;
import nxt.Constants;
import nxt.NxtException;
import nxt.crypto.Crypto;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Arrays;
public final class Convert {
private static final char[] hexChars = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
private static final long[] multipliers = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
public static final BigInteger two64 = new BigInteger("18446744073709551616");
public static int counter;
private Convert() {} //never
public static byte[] parseHexString(String hex) {
if (hex == null) {
return null;
}
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
int char1 = hex.charAt(i * 2);
char1 = char1 > 0x60 ? char1 - 0x57 : char1 - 0x30;
int char2 = hex.charAt(i * 2 + 1);
char2 = char2 > 0x60 ? char2 - 0x57 : char2 - 0x30;
if (char1 < 0 || char2 < 0 || char1 > 15 || char2 > 15) {
throw new NumberFormatException("Invalid hex number: " + hex);
}
bytes[i] = (byte)((char1 << 4) + char2);
}
return bytes;
}
public static String toHexString(byte[] bytes) {
if (bytes == null) {
return null;
}
char[] chars = new char[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
chars[i * 2] = hexChars[((bytes[i] >> 4) & 0xF)];
chars[i * 2 + 1] = hexChars[(bytes[i] & 0xF)];
}
return String.valueOf(chars);
}
public static String toUnsignedLong(long objectId) {
if (objectId >= 0) {
return String.valueOf(objectId);
}
BigInteger id = BigInteger.valueOf(objectId).add(two64);
return id.toString();
}
public static long parseUnsignedLong(String number) {
if (number == null) {
return 0;
}
BigInteger bigInt = new BigInteger(number.trim());
if (bigInt.signum() < 0 || bigInt.compareTo(two64) != -1) {
throw new IllegalArgumentException("overflow: " + number);
}
return bigInt.longValue();
}
public static long parseLong(Object o) {
if (o == null) {
return 0;
} else if (o instanceof Long) {
return ((Long)o);
} else if (o instanceof String) {
return Long.parseLong((String)o);
} else {
throw new IllegalArgumentException("Not a long: " + o);
}
}
public static long parseAccountId(String account) {
if (account == null) {
return 0;
}
account = account.toUpperCase();
if (account.startsWith("NXT-")) {
return Crypto.rsDecode(account.substring(4));
} else {
return parseUnsignedLong(account);
}
}
public static String rsAccount(long accountId) {
return "NXT-" + Crypto.rsEncode(accountId);
}
public static long fullHashToId(byte[] hash) {
if (hash == null || hash.length < 8) {
throw new IllegalArgumentException("Invalid hash: " + Arrays.toString(hash));
}
BigInteger bigInteger = new BigInteger(1, new byte[] {hash[7], hash[6], hash[5], hash[4], hash[3], hash[2], hash[1], hash[0]});
return bigInteger.longValue();
}
public static long fullHashToId(String hash) {
if (hash == null) {
return 0;
}
return fullHashToId(Convert.parseHexString(hash));
}
public static long fromEpochTime(int epochTime) {
return epochTime * 1000L + Constants.EPOCH_BEGINNING - 500L;
}
public static String emptyToNull(String s) {
return s == null || s.length() == 0 ? null : s;
}
public static String nullToEmpty(String s) {
return s == null ? "" : s;
}
public static byte[] emptyToNull(byte[] bytes) {
if (bytes == null) {
return null;
}
for (byte b : bytes) {
if (b != 0) {
return bytes;
}
}
return null;
}
public static byte[] toBytes(String s) {
try {
return s.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.toString(), e);
}
}
public static String toString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.toString(), e);
}
}
public static String readString(ByteBuffer buffer, int numBytes, int maxLength) throws NxtException.NotValidException {
if (numBytes > 3 * maxLength) {
throw new NxtException.NotValidException("Max parameter length exceeded");
}
byte[] bytes = new byte[numBytes];
buffer.get(bytes);
return Convert.toString(bytes);
}
public static String truncate(String s, String replaceNull, int limit, boolean dots) {
return s == null ? replaceNull : s.length() > limit ? (s.substring(0, dots ? limit - 3 : limit) + (dots ? "..." : "")) : s;
}
public static long parseNXT(String nxt) {
return parseStringFraction(nxt, 8, Constants.MAX_BALANCE_NXT);
}
private static long parseStringFraction(String value, int decimals, long maxValue) {
String[] s = value.trim().split("\\.");
if (s.length == 0 || s.length > 2) {
throw new NumberFormatException("Invalid number: " + value);
}
long wholePart = Long.parseLong(s[0]);
if (wholePart > maxValue) {
throw new IllegalArgumentException("Whole part of value exceeds maximum possible");
}
if (s.length == 1) {
return wholePart * multipliers[decimals];
}
long fractionalPart = Long.parseLong(s[1]);
if (fractionalPart >= multipliers[decimals] || s[1].length() > decimals) {
throw new IllegalArgumentException("Fractional part exceeds maximum allowed divisibility");
}
for (int i = s[1].length(); i < decimals; i++) {
fractionalPart *= 10;
}
return wholePart * multipliers[decimals] + fractionalPart;
}
public static long safeAdd(long left, long right)
throws ArithmeticException {
if (right > 0 ? left > Long.MAX_VALUE - right
: left < Long.MIN_VALUE - right) {
throw new ArithmeticException("Integer overflow");
}
return left + right;
}
public static long safeSubtract(long left, long right)
throws ArithmeticException {
if (right > 0 ? left < Long.MIN_VALUE + right
: left > Long.MAX_VALUE + right) {
throw new ArithmeticException("Integer overflow");
}
return left - right;
}
public static long safeMultiply(long left, long right)
throws ArithmeticException {
if (right > 0 ? left > Long.MAX_VALUE/right
|| left < Long.MIN_VALUE/right
: (right < -1 ? left > Long.MIN_VALUE/right
|| left < Long.MAX_VALUE/right
: right == -1
&& left == Long.MIN_VALUE) ) {
throw new ArithmeticException("Integer overflow");
}
return left * right;
}
public static long safeDivide(long left, long right)
throws ArithmeticException {
if ((left == Long.MIN_VALUE) && (right == -1)) {
throw new ArithmeticException("Integer overflow");
}
return left / right;
}
public static long safeNegate(long a) throws ArithmeticException {
if (a == Long.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return -a;
}
public static long safeAbs(long a) throws ArithmeticException {
if (a == Long.MIN_VALUE) {
throw new ArithmeticException("Integer overflow");
}
return Math.abs(a);
}
}
|
package org.waterforpeople.mapping.app.web;
import com.gallatinsystems.common.domain.UploadStatusContainer;
import com.gallatinsystems.common.util.S3Util;
import com.gallatinsystems.common.util.ZipUtil;
import com.gallatinsystems.framework.rest.AbstractRestApiServlet;
import com.gallatinsystems.framework.rest.RestRequest;
import com.gallatinsystems.framework.rest.RestResponse;
import com.gallatinsystems.operations.dao.ProcessingStatusDao;
import com.gallatinsystems.operations.domain.ProcessingStatus;
import com.gallatinsystems.survey.dao.*;
import com.gallatinsystems.survey.domain.*;
import com.gallatinsystems.survey.domain.Survey;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.utils.SystemProperty;
import org.akvo.flow.dao.MessageDao;
import org.akvo.flow.domain.Message;
import org.akvo.flow.xml.PublishedForm;
import org.akvo.flow.xml.XmlForm;
import org.apache.log4j.Logger;
import org.waterforpeople.mapping.app.web.dto.SurveyAssemblyRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;
public class SurveyAssemblyServlet extends AbstractRestApiServlet {
private static final Logger log = Logger
.getLogger(SurveyAssemblyServlet.class.getName());
private static final long serialVersionUID = -6044156962558183224L;
public static final String FREE_QUESTION_TYPE = "free";
public static final String OPTION_QUESTION_TYPE = "option";
public static final String GEO_QUESTION_TYPE = "geo";
public static final String VIDEO_QUESTION_TYPE = "video";
public static final String PHOTO_QUESTION_TYPE = "photo";
public static final String SCAN_QUESTION_TYPE = "scan";
public static final String STRENGTH_QUESTION_TYPE = "strength";
public static final String DATE_QUESTION_TYPE = "date";
public static final String CASCADE_QUESTION_TYPE = "cascade";
public static final String GEOSHAPE_QUESTION_TYPE = "geoshape";
public static final String SIGNATURE_QUESTION_TYPE = "signature";
public static final String CADDISFLY_QUESTION_TYPE = "caddisfly";
private static final String SURVEY_UPLOAD_URL = "surveyuploadurl";
private static final String SURVEY_UPLOAD_DIR = "surveyuploaddir";
private static final String FORM_PUB_STATUS_KEY = "formPublication";
private Random randomNumber = new Random();
@Override
protected RestRequest convertRequest() throws Exception {
HttpServletRequest req = getRequest();
RestRequest restRequest = new SurveyAssemblyRequest();
restRequest.populateFromHttpRequest(req);
return restRequest;
}
@Override
protected RestResponse handleRequest(RestRequest req) throws Exception {
RestResponse response = new RestResponse();
SurveyAssemblyRequest importReq = (SurveyAssemblyRequest) req;
if (SurveyAssemblyRequest.ASSEMBLE_SURVEY.equalsIgnoreCase(importReq.getAction())) {
Date start = new Date();
Long id = importReq.getSurveyId();
//Instrumentation
ProcessingStatusDao statusDao = new ProcessingStatusDao();
ProcessingStatus status = statusDao.getStatusByCode(
FORM_PUB_STATUS_KEY + (id != null ? ":" + id : ""));
if (status == null) {
status = new ProcessingStatus();
status.setCode(FORM_PUB_STATUS_KEY + (id != null ? ":" + id : ""));
status.setMaxDurationMs(0L);
}
status.setLastEventDate(start);
Long maxDuration = status.getMaxDurationMs();
if (maxDuration == null) {
maxDuration = 0L;
}
status.setInError(true); //In case it never saves an end sts
status.setValue("inProgress");
statusDao.save(status);
//Need to keep this shorter than task queue limit (600 seconds)
boolean ok = assembleFormWithJackson(importReq.getSurveyId());
//Clear caches
List<Long> ids = new ArrayList<Long>();
ids.add(id);
SurveyUtils.notifyReportService(ids, "invalidate");
// now update the status
status.setInError(ok);
status.setValue("finished");
Long duration = new Date().getTime() - start.getTime();
if (duration > maxDuration) {
status.setMaxDurationMs(duration);
status.setMaxDurationDate(start);
}
statusDao.save(status);
}
return response;
}
// Manual triggering of publication should start here
static public void runAsTask(Long surveyId) {
log.info("Forking to task for long assembly");
TaskOptions options = TaskOptions.Builder
.withUrl("/app_worker/surveyassembly")
.param(SurveyAssemblyRequest.ACTION_PARAM,
SurveyAssemblyRequest.ASSEMBLE_SURVEY)
.param(SurveyAssemblyRequest.SURVEY_ID_PARAM, surveyId.toString());
Queue queue = QueueFactory.getQueue("surveyAssembly");
queue.add(options);
Survey s = new SurveyDAO().getById(surveyId);
SurveyGroup sg = s != null ? new SurveyGroupDAO().getByKey(s.getSurveyGroupId()) : null;
if (sg != null && sg.getNewLocaleSurveyId() != null &&
sg.getNewLocaleSurveyId().longValue() == surveyId.longValue()) {
// This is the registration form. Schedule datapoint name re-assembly
DataProcessorRestServlet.scheduleDatapointNameAssembly(sg.getKey().getId(), null);
}
}
@Override
protected void writeOkResponse(RestResponse resp) throws Exception {
HttpServletResponse httpResp = getResponse();
httpResp.setStatus(HttpServletResponse.SC_OK);
// httpResp.setContentType("text/plain");
httpResp.getWriter().print("OK");
httpResp.flushBuffer();
}
/*
* NEW! Assembly through Jackson classes.
*
*/
private boolean assembleFormWithJackson(Long formId) {
log.debug("Starting Jackson assembly of form " + formId);
SurveyDAO surveyDao = new SurveyDAO();
Survey form = surveyDao.loadFullForm(formId);
SurveyGroupDAO surveyGroupDao = new SurveyGroupDAO();
QuestionDao questionDao = new QuestionDao();
SurveyGroup survey = surveyGroupDao.getByKey(form.getSurveyGroupId());
Long transactionId = randomNumber.nextLong();
XmlForm jacksonForm = new XmlForm(form, survey, SystemProperty.applicationId.get());
String formXML;
try {
formXML = PublishedForm.generate(jacksonForm);
} catch (IOException e) {
log.error("Failed to convert form to XML: "+ e.getMessage());
return false;
}
boolean uploadOk = false;
log.debug("Uploading " + formId);
UploadStatusContainer uc = uploadFormXML(
Long.toString(formId), //latest version in plain filename
Long.toString(formId) + "v" + form.getVersion(), //archive copy
formXML.toString());
Message message = new Message();
message.setActionAbout("surveyAssembly");
message.setObjectId(formId);
message.setObjectTitle(survey.getCode() + " / " + form.getName());
if (uc.getUploadedZip1() && uc.getUploadedZip2()) {
log.debug("Finishing assembly of " + formId);
form.setStatus(Survey.Status.PUBLISHED);
if (form.getWebForm()){
boolean webForm = WebForm.validWebForm(surveyGroupDao.getByKey(form.getObjectId()), form, questionDao.listQuestionsBySurvey(form.getObjectId()));
form.setWebForm(webForm);
}
surveyDao.save(form); //remember PUBLISHED status
String messageText = "Published. Please check: " + uc.getUrl();
message.setShortMessage(messageText);
message.setTransactionUUID(transactionId.toString());
MessageDao messageDao = new MessageDao();
messageDao.save(message);
uploadOk = true;
//invalidate any cached reports in flow-services
List<Long> ids = new ArrayList<Long>();
ids.add(formId);
SurveyUtils.notifyReportService(ids, "invalidate");
} else {
String messageText = "Failed to publish: " + formId + "\n" + uc.getMessage();
message.setTransactionUUID(transactionId.toString());
message.setShortMessage(messageText);
MessageDao messageDao = new MessageDao();
messageDao.save(message);
log.warn("Failed to upload assembled form, id " + formId + "\n"
+ uc.getMessage());
}
log.debug("Completed form assembly for " + formId);
return uploadOk;
}
/** Upload a zipped form file twice to S3 under different filenames.
* @param fileName1
* @param fileName2
* @param formXML
* @return
*/
public UploadStatusContainer uploadFormXML(String fileName1, String fileName2, String formXML) {
Properties props = System.getProperties();
String bucketName = props.getProperty("s3bucket");
String directory = props.getProperty(SURVEY_UPLOAD_DIR);
UploadStatusContainer uc = new UploadStatusContainer();
uc.setUploadedZip1(uploadZippedXml(formXML, bucketName, directory, fileName1));
uc.setUploadedZip2(uploadZippedXml(formXML, bucketName, directory, fileName2));
uc.setUrl(props.getProperty(SURVEY_UPLOAD_URL)
+ props.getProperty(SURVEY_UPLOAD_DIR)
+ "/" + fileName1 + ".zip");
return uc;
}
private boolean uploadZippedXml(String content, String bucketName, String directory, String fileName) {
ByteArrayOutputStream os2 = ZipUtil.generateZip(content, fileName + ".xml");
try {
return S3Util.put(bucketName,
directory + "/" + fileName + ".zip",
os2.toByteArray(),
"application/zip",
true);
} catch (IOException e) {
log.error("Error uploading zipfile: " + e.getMessage(), e);
return false;
}
}
}
|
package org.opensim.view;
import java.util.Vector;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.actions.CallableSystemAction;
import org.opensim.view.nodes.OneComponentNode;
import org.opensim.view.nodes.OpenSimObjectNode;
import org.opensim.view.nodes.OpenSimObjectNode.displayOption;
import org.opensim.view.nodes.OpenSimObjectSetNode;
public final class ObjectDisplayOpacityAction extends CallableSystemAction {
public void performAction() {
Vector<OneComponentNode> objects = CollectAffectedComponentNodes();
ObjectDisplayOpacityPanel.showDialog(objects);
}
protected Vector<OneComponentNode> CollectAffectedComponentNodes() {
Vector<OneComponentNode> objects = new Vector<OneComponentNode>();
Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes();
for(int i=0; i<selected.length; i++) {
if(selected[i] instanceof OneComponentNode)
collectDescendentNodes((OneComponentNode)selected[i], objects);
else if (selected[i] instanceof OpenSimObjectSetNode){
// Get children nd descend if instanceof OneComponentNode
Children ch = ((OpenSimObjectSetNode) selected[i]).getChildren();
for (int chNum=0; chNum < ch.getNodesCount(); chNum++){
if (ch.getNodeAt(chNum) instanceof OneComponentNode)
collectDescendentNodes((OneComponentNode)ch.getNodeAt(chNum), objects);
}
}
}
return objects;
}
// node could be a Group or a list of objects not backed by OpenSim objects
protected void collectDescendentNodes(OpenSimObjectNode node, Vector<OneComponentNode> descendents) {
if (node instanceof OneComponentNode) {
descendents.add((OneComponentNode)node);
}
Children ch = node.getChildren();
// process children
for (Node childNode : ch.getNodes()) {
if (childNode instanceof OpenSimObjectNode) {
collectDescendentNodes((OpenSimObjectNode) childNode, descendents);
}
}
}
public String getName() {
return NbBundle.getMessage(ObjectDisplayOpacityAction.class, "CTL_ObjectDisplayOpacityAction");
}
protected void initialize() {
super.initialize();
// see org.openide.util.actions.SystemAction.iconResource() javadoc for more details
putValue("noIconInMenu", Boolean.TRUE);
}
public HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
protected boolean asynchronous() {
return false;
}
// Make it available only if selected objects have representation and belong to same model
public boolean isEnabled() {
// The "hide" option is enabled unless every selected node is hidden.
Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes();
boolean isColorable=true;
for(int i=0; i<selected.length && isColorable; i++){
isColorable = (selected[i] instanceof OpenSimObjectNode);
if (isColorable){
OpenSimObjectNode objectNode = (OpenSimObjectNode) selected[i];
isColorable=objectNode.getValidDisplayOptions().contains(displayOption.Colorable);
}
}
return isColorable;
}
}
|
package org.opensim.view;
import java.util.Vector;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.actions.CallableSystemAction;
import org.opensim.modeling.OpenSimObject;
import org.opensim.view.nodes.OneComponentNode;
import org.opensim.view.nodes.OneGeometryNode;
import org.opensim.view.nodes.OpenSimObjectNode;
import org.opensim.view.nodes.OpenSimObjectNode.displayOption;
public final class ObjectDisplayOpacityAction extends CallableSystemAction {
public void performAction() {
Vector<OneComponentNode> objects = new Vector<OneComponentNode>();
Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes();
for(int i=0; i<selected.length; i++) {
if(selected[i] instanceof OneComponentNode)
collectDescendentNodes((OneComponentNode)selected[i], objects);
}
ObjectDisplayOpacityPanel.showDialog(objects);
}
// node could be a Group or a list of objects not backed by OpenSim objects
public void collectDescendentNodes(OpenSimObjectNode node, Vector<OneComponentNode> descendents) {
if (node instanceof OneComponentNode) {
descendents.add((OneComponentNode)node);
}
Children ch = node.getChildren();
// process children
for (Node childNode : ch.getNodes()) {
if (childNode instanceof OpenSimObjectNode) {
collectDescendentNodes((OpenSimObjectNode) childNode, descendents);
}
}
}
public String getName() {
return NbBundle.getMessage(ObjectDisplayOpacityAction.class, "CTL_ObjectDisplayOpacityAction");
}
protected void initialize() {
super.initialize();
// see org.openide.util.actions.SystemAction.iconResource() javadoc for more details
putValue("noIconInMenu", Boolean.TRUE);
}
public HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
protected boolean asynchronous() {
return false;
}
// Make it available only if selected objects have representation and belong to same model
public boolean isEnabled() {
// The "hide" option is enabled unless every selected node is hidden.
Node[] selected = ExplorerTopComponent.findInstance().getExplorerManager().getSelectedNodes();
boolean isColorable=true;
for(int i=0; i<selected.length && isColorable; i++){
isColorable = (selected[i] instanceof OpenSimObjectNode);
if (isColorable){
OpenSimObjectNode objectNode = (OpenSimObjectNode) selected[i];
isColorable=objectNode.getValidDisplayOptions().contains(displayOption.Colorable);
}
}
return isColorable;
}
}
|
package alma.acs.container;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.omg.PortableServer.Servant;
import alma.ACS.ACSComponentOperations;
import alma.JavaContainerError.wrappers.AcsJJavaComponentHelperEx;
import alma.acs.component.ComponentLifecycle;
import alma.acs.component.dynwrapper.DynamicProxyFactory;
import alma.acs.logging.ClientLogManager;
import alma.maciErrType.wrappers.AcsJComponentCreationEx;
/**
* Base class for component helper classes that must be provided
* by the component developers (for example by copying the template file that gets
* generated with the <code>COMPONENT_HELPERS=on</code> Makefile setting).
* <p>
* The method implementations in this class perform checks on the data returned
* from the subclass methods (framework-style design). In that sense, <code>ComponentHelper</code>
* is part of the container, whereas its subclass belongs to the component.
* <p>
* The methods that return a <code>Class</code>
* object should be implemented like <code>return XxxPOATie.class;</code> so that the absence
* of this class can be discovered at compile time.
* (Therefore don't use <code>classForName</code> which evades compile time checking.)
*
* @author hsommer
*/
public abstract class ComponentHelper
{
private ComponentLifecycle m_componentImpl;
// must be private since any subclass should get a different logger ("forComponent")
private final Logger m_containerLogger;
protected String componentInstanceName;
/**
* Subclasses must override and call this constructor ("<code>super(containerLogger)</code>").
* @param containerLogger logger used by this base class.
*/
public ComponentHelper(Logger containerLogger)
{
m_containerLogger = containerLogger;
}
/**
* Allows the container to set the component instance name.
* This name is used for the component logger and may also be useful in other ways.
* <p>
* Note that in a better design this name should be given in the constructor,
* but was added here as a separate method to avoid modifying existing component helper classes.
* @param name the component instance name (CURL).
* @since ACS 5.0
*/
final void setComponentInstanceName(String name) {
componentInstanceName = name;
}
/**
* Gets the component logger.
* @return the logger to be used by subclasses if they have to log anything.
*/
protected final Logger getComponentLogger() {
String loggerName = ( componentInstanceName != null ? componentInstanceName : "ComponentHelper" );
return ClientLogManager.getAcsLogManager().getLoggerForComponent(loggerName);
}
/**
* Gets the component implementation.
* Must be the same object that also implements the functional interface
* obtained from <code>getInternalInterface</code>.
*
* @return The component implementation class that implements <code>ComponentLifecycle</code>
* and the functional interface.
* @throws AcsJJavaComponentHelperEx if the component implementation construction failed or
* if the component does not implement its declared functional interface.
*/
protected final synchronized ComponentLifecycle getComponentImpl() throws AcsJComponentCreationEx, AcsJJavaComponentHelperEx
{
if (m_componentImpl== null)
{
Class<?> internalIF = null;
try {
m_componentImpl = _createComponentImpl();
internalIF = getInternalInterface();
}
catch (AcsJComponentCreationEx ex) {
throw ex;
}
catch (AcsJJavaComponentHelperEx ex) {
throw ex;
}
catch (Throwable thr) {
// the ex type is slightly misleading if an overloaded 'getInternalInterface' throws something other than
// the declared AcsJJavaComponentHelperEx
throw new AcsJComponentCreationEx(thr);
}
if (m_componentImpl == null) {
AcsJComponentCreationEx ex = new AcsJComponentCreationEx();
ex.setReason("_createComponentImpl() returned null.");
throw ex;
}
if (!internalIF.isInstance(m_componentImpl)) {
AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx();
ex.setContextInfo("component impl class '" + m_componentImpl.getClass().getName() +
"' does not implement the specified functional IF " + internalIF.getName());
throw ex;
}
else if (!ACSComponentOperations.class.isInstance(m_componentImpl))
{
AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx();
ex.setContextInfo("component impl class '" + m_componentImpl.getClass().getName() +
"' does not implement the mandatory IF " + ACSComponentOperations.class.getName() +
". Check the IDL interface definition, and add ': ACS::ACSComponent'.");
throw ex;
}
m_containerLogger.finer("component '" + componentInstanceName + "' (class '" + m_componentImpl.getClass().getName() + "') instantiated.");
}
return m_componentImpl;
}
/**
* Method _createComponentImpl to be provided by subclasses.
* Must return the same object that also implements the functional component interface.
*
* @return ComponentLifecycle The component impl class that implements the ComponentLifecycle interface.
* @throws AcsJComponentCreationEx if the component implementation class could not be instantiated
*/
abstract protected ComponentLifecycle _createComponentImpl() throws AcsJComponentCreationEx;
/**
* Gets the <code>Class</code> object for the POA tie skeleton class.
* The POA tie class is generated by the IDL compiler and must have
* a constructor that takes the operations interface as its only parameter.
*
* @return the tie class.
*/
final Class<? extends Servant> getPOATieClass() throws AcsJJavaComponentHelperEx
{
Class<? extends Servant> poaTieClass = null;
try {
poaTieClass = _getPOATieClass();
}
catch (Throwable thr) {
AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx(thr);
ex.setContextInfo("failed to obtain the POATie class from component helper.");
throw ex;
}
if (poaTieClass == null) {
AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx();
ex.setContextInfo("received null as the POATie class from the component helper.");
throw ex;
}
// check inheritance stuff (Servant should be checked by compiler under JDK 1.5, but operations IF is unknown at ACS compile time)
if (!Servant.class.isAssignableFrom(poaTieClass)) {
AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx();
ex.setContextInfo("received invalid POATie class that is not a subclass of org.omg.PortableServer.Servant");
throw ex;
}
if (!getOperationsInterface().isAssignableFrom(poaTieClass)) {
AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx();
ex.setContextInfo("POATie class '" + poaTieClass + "' does not implement the declared operations interface '" + getOperationsInterface().getName() + "'.");
throw ex;
}
return poaTieClass;
}
/**
* This method must be provided by the component helper class.
* It must return the Class of the IDL-generated POA-Tie Servant, as in <br>
* <code>return DummyComponentPOATie.class;</code>.
*/
protected abstract Class<? extends Servant> _getPOATieClass();
/**
* Gets the xxOperations interface as generated by the IDL compiler by calling {@link #_getOperationsInterface()}.
* @throws AcsJJavaComponentHelperEx if the subclass methdod throws something or returns <code>null</code>.
*/
public final Class<? extends ACSComponentOperations> getOperationsInterface() throws AcsJJavaComponentHelperEx
{
Class<? extends ACSComponentOperations> opIF = null;
try {
opIF = _getOperationsInterface();
}
catch (Throwable thr) {
AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx(thr);
ex.setContextInfo("failed to retrieve 'operations' interface from component helper");
throw ex;
}
if (opIF == null) {
AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx();
ex.setContextInfo("received null as the 'operations' IF class from the component helper.");
throw ex;
}
return opIF;
}
/**
* Gets the xxOperations interface as generated by the IDL compiler.
*
* This method must be provided by the component helper class.
*
* @return the <code>Class</code> object associated with the operations interface.
*/
protected abstract Class<? extends ACSComponentOperations> _getOperationsInterface();
/**
* Gets the component's implemented functional IF.
* For instance, the method signatures can be the same as in the operations interface,
* except that the internal interface uses xml binding classes
* where the IDL-generated operations interface only contains stringified XML.
* <p>
* To be overridden by the component helper class only if the InternalInterface differs from
* the OperationsInterface.
*
* @return Class the Java Class of the internal interface.
*/
protected Class<?> getInternalInterface() throws AcsJJavaComponentHelperEx {
return getOperationsInterface();
}
/**
* Method getInterfaceTranslator. Called by the container framework.
* @return Object
* @throws AcsJJavaComponentHelperEx
*/
final Object getInterfaceTranslator()
throws AcsJJavaComponentHelperEx
{
Object interfaceTranslator = null;
// the dynamic proxy is the default interface translator
Object defaultInterfaceTranslator = null;
try {
defaultInterfaceTranslator =
DynamicProxyFactory.getDynamicProxyFactory(m_containerLogger).createServerProxy(
getOperationsInterface(), m_componentImpl, getInternalInterface());
}
catch (Throwable thr) {
throw new AcsJJavaComponentHelperEx(thr);
}
try {
interfaceTranslator = _getInterfaceTranslator(defaultInterfaceTranslator);
}
catch (Throwable thr) {
AcsJJavaComponentHelperEx ex = new AcsJJavaComponentHelperEx(thr);
ex.setContextInfo("failed to obtain the custom interface translator.");
throw ex;
}
if (interfaceTranslator == null) {
// use default translator
interfaceTranslator = defaultInterfaceTranslator;
}
return interfaceTranslator;
}
/**
* To be overridden by subclass only if it wants its own interface translator to be used.
* <p>
* The returned interface translator must implement the component's operations interface,
* and must take care of translating <code>in</code>, <code>inout</code> parameters,
* forwarding the call to the respective method in the component implementation,
* and then translating <code>out</code>, <code>inout</code> parameters, and the return value.
* <p>
* It is foreseen that the necessary translations for most methods will be done
* automatically by the dynamic proxy classes. Some methods may require manual translation,
* e.g. if an expression that involves xml entity classes is too complex for the
* dynamic proxy.
* <br>
* On the other end of the spectrum, a manual implementation may
* choose to <emph>not</emph> unmarshal a marshalled binding object that
* it receives as an <code>in</code> parameter, because the binding object
* will only be routed through to another component, so first unmarshalling
* and later marshalling it would be an unnecessary performance loss.
* In that case, the manual interface translator could call an additional
* method in the component implementation which expects the marshalled xml
* rather than the binding object.
* <p>
* To facilitate the implementation of a manual interface translator,
* the <code>defaultInterfaceTranslator</code> is provided; it is a dynamic
* proxy object that implements the component's operations interface and
* forwards all calls to the component implementation created in
* <code>_createComponentImpl</code>, performing type translations in between.
* The methods that should be handled automatically can then be directly
* delegated to that proxy object, and only those methods that require
* special care need to be implemented by hand.
*
* @param defaultInterfaceTranslator the default translator that the custon translator may
* use to delegate some or all method invocations to.
* @return the custom translator, or null if the default translator should be used.
*/
protected Object _getInterfaceTranslator(Object defaultInterfaceTranslator) throws AcsJJavaComponentHelperEx {
return null;
}
/**
* @see #_getComponentMethodsExcludedFromInvocationLogging
*/
final String[] getComponentMethodsExcludedFromInvocationLogging() {
String[] ret = null;
try {
ret = _getComponentMethodsExcludedFromInvocationLogging();
}
catch (Exception ex) {
m_containerLogger.log(Level.WARNING, "failed to obtain the list of component methods to exclude from automatic logging.", ex);
}
return ret;
}
/**
* Tells the container to not automatically log calls to certain component interface methods.
* This method may be overridden by helper subclasses, since the default behavior is
* for the container to log all component method invocations except <code>ACSComponentOperations#componentState()</code>.
* <p>
* Dealing with OffShoots: offshoots that follow the Corba Tie-approach enjoy automatic method invocation logging
* just like components do. In the rare event that you explicitly activate offshoots from your component,
* and want to suppress automatic logging for certain methods, return <code>String</code>(s) in the
* following format: <code>OFFSHOOT::<offshootinterfacename>#<methodname></code>.
* Example for ALMA archive: "OFFSHOOT::Operational#retrieveFragment".
* <p>
* Note that returning <code>String</code>s is fine (compared with more sophisticated <code>Method</code> objects)
* because the functional component interface methods cannot have parameter polymorphism thanks to IDL limitations.
* Thus there is no ambiguity in the method names.
*
* @return names of component methods for which the call-intercepting container should not log anything.
* Can be null.
* @since ACS 5.0
*/
protected String[] _getComponentMethodsExcludedFromInvocationLogging() {
return null;
}
/**
* <strong>Do not overwrite this method unless you absolutely need to
* (currently only for the archive logger component!)</strong>
* <p>
* If <code>true</code> then the ORB logger will not send any log messages to the central (remote) Log service
* after activation of this component, regardless of any kind (env var, CDB, dynamic) log level settings.
* Local stdout logging by the ORB is not affected.
* Currently the ORB log suppression is not reversible: even when the component which requested this
* is unloaded, the ORB logger will not resume sending remote log messages.
* This may change in the future though.
* <p>
* Note that <code>getComponentMethodsExcludedFromInvocationLogging</code> can switch off automatic logging
* done by the container on behalf of the component. However, the ORB does not use a logger-per-component
* concept, and thus can't be told selectively to not log anything for a particualar component.
* The entire process (container and all components) are affected by suppressing the ORB's remote logging.
* <p>
* This method addresses the special problem of an infrastructural component that receives log messages
* from the Log service and writes them to the archive.
* Any message logged by the ORB on the receiver side would go back to the Log service and be received
* by the infrastructural component, with positive feedback leading to an explosion of log messages.
* Therefore we can't rely on log level settings and must categorically rule out such feedback loops.
* <p>
* @since ACS 7.0 when JacORB logs get sent to the Log service by default.
* @return
*/
protected boolean requiresOrbCentralLogSuppression() {
return false;
}
}
|
package ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
import model.Model;
import model.TurboLabel;
public class ManageLabelsDialog implements Dialog<String> {
public static final String UNGROUPED_NAME = "<Ungrouped>";
public static final String ROOT_NAME = "root";
private final Stage parentStage;
private final Model model;
private CompletableFuture<String> response;
public ManageLabelsDialog(Stage parentStage, Model model) {
this.parentStage = parentStage;
this.model = model;
response = new CompletableFuture<>();
}
public CompletableFuture<String> show() {
showDialog();
return response;
}
private void showDialog() {
HBox layout = new HBox();
layout.setPadding(new Insets(15));
layout.setSpacing(10);
Scene scene = new Scene(layout, 330, 400);
Stage stage = new Stage();
stage.setTitle("Manage Labels");
stage.setScene(scene);
Platform.runLater(() -> stage.requestFocus());
TreeView<LabelTreeItem> treeView = createTreeView(stage);
layout.getChildren().addAll(treeView, createButtons(treeView, stage));
stage.initOwner(parentStage);
// secondStage.initModality(Modality.APPLICATION_MODAL);
stage.setX(parentStage.getX());
stage.setY(parentStage.getY());
stage.show();
}
private Node createButtons(TreeView<LabelTreeItem> treeView, Stage stage) {
VBox container = new VBox();
container.setSpacing(5);
Button newGroup = new Button("New Group");
newGroup.setOnAction(e -> {
(new GroupDialog(stage, "newgroup" + getUniqueId(), false))
.setExclusiveCheckboxVisible(true)
.show().thenApply(response -> {
assert response.getValue() != null;
if (response.getValue().isEmpty()) {
return false;
}
TreeItem<LabelTreeItem> item = new TreeItem<>(response);
treeView.getRoot().getChildren().add(item);
return true;
});
});
Button close = new Button("Close");
close.setOnAction(e -> {
stage.close();
});
container.getChildren().addAll(newGroup, close);
return container;
}
private TreeView<LabelTreeItem> createTreeView(Stage stage) {
final TreeItem<LabelTreeItem> treeRoot = new TreeItem<>(new TurboLabelGroup(ROOT_NAME));
populateTree(treeRoot);
final TreeView<LabelTreeItem> treeView = new TreeView<>();
treeView.setRoot(treeRoot);
treeView.setShowRoot(false);
treeView.setPrefWidth(180);
treeRoot.setExpanded(true);
treeRoot.getChildren().forEach(child -> child.setExpanded(true));
treeView.setCellFactory(new Callback<TreeView<LabelTreeItem>, TreeCell<LabelTreeItem>>() {
@Override
public TreeCell<LabelTreeItem> call(TreeView<LabelTreeItem> stringTreeView) {
return new ManageLabelsTreeCell<LabelTreeItem>(stage, model);
}
});
return treeView;
}
public static HashMap<String, ArrayList<TurboLabel>> groupLabels(List<TurboLabel> labels) {
HashMap<String, ArrayList<TurboLabel>> groups = new HashMap<>();
for (TurboLabel l : labels) {
String groupName = l.getGroup() == null ? UNGROUPED_NAME : l.getGroup();
if (groups.get(groupName) == null) {
groups.put(groupName, new ArrayList<TurboLabel>());
}
groups.get(groupName).add(l);
}
return groups;
}
private void populateTree(TreeItem<LabelTreeItem> treeRoot) {
for (TurboLabel l : model.getLabels()) {
assert l.getGroup() == null || !l.getGroup().equals(UNGROUPED_NAME);
}
// Hash all labels by group
HashMap<String, ArrayList<TurboLabel>> labels = groupLabels(model.getLabels());
ArrayList<TurboLabel> ungrouped = labels.get(UNGROUPED_NAME);
if (ungrouped == null) ungrouped = new ArrayList<>();
labels.remove(UNGROUPED_NAME);
// Add labels with a group into the tree
for (String groupName : labels.keySet()) {
TurboLabelGroup group = new TurboLabelGroup(groupName);
TreeItem<LabelTreeItem> groupItem = new TreeItem<>(group);
treeRoot.getChildren().add(groupItem);
boolean exclusive = true;
for (TurboLabel l : labels.get(group.getValue())) {
group.addLabel(l);
TreeItem<LabelTreeItem> labelItem = new TreeItem<>(l);
groupItem.getChildren().add(labelItem);
exclusive = exclusive && l.isExclusive();
}
// Set exclusivity status
group.setExclusive(exclusive);
}
// Do the same for ungrouped labels
TurboLabelGroup ungroupedGroup = new TurboLabelGroup(UNGROUPED_NAME);
TreeItem<LabelTreeItem> ungroupedItem = new TreeItem<>(ungroupedGroup);
treeRoot.getChildren().add(ungroupedItem);
for (TurboLabel l : ungrouped) {
ungroupedGroup.addLabel(l);
TreeItem<LabelTreeItem> labelItem = new TreeItem<>(l);
ungroupedItem.getChildren().add(labelItem);
}
}
public static String getUniqueId() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
}
|
package uqac.sma.project;
import uqac.sma.project.core.*;
import uqac.sma.project.strategies.*;
import uqac.sma.project.agent.*;
public class Test {
public static void main(String[] args) {
Agent agentA = new Agent(new AllC());
Agent agentB = new Agent(new AllD());
int it = 10000;
int sA, sB, tA = 0, tB = 0, vA = 0, vB = 0;
for (int i = 0; i< it; i++){
Match m = new Match(agentA,agentB);
m.fight();
sA = agentA.getScore();
sB = agentB.getScore();
System.out.println("A = "+sA+" || B = "+sB);
tA += sA;
tB += sB;
if(sA > sB) vA += 1;
if(sB > sA) vB += 1;
}
System.out.println("Agent A : score moyen = "+tA/it+"; probabilit de victoire = "+vA*100/it);
System.out.println("Agent A : score moyen = "+tB/it+"; probabilit de victoire = "+vB*100/it);
}
}
|
package us.kbase.userandjobstate.test.kbase;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.File;
import java.net.URL;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import org.ini4j.Ini;
import org.ini4j.Profile.Section;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import us.kbase.common.service.ServerException;
import us.kbase.common.service.Tuple2;
import us.kbase.common.service.UObject;
import us.kbase.common.test.controllers.mongo.MongoController;
import us.kbase.userandjobstate.InitProgress;
import us.kbase.userandjobstate.Result;
import us.kbase.userandjobstate.Results;
import us.kbase.userandjobstate.UserAndJobStateClient;
import us.kbase.userandjobstate.UserAndJobStateServer;
import us.kbase.userandjobstate.jobstate.JobResults;
import us.kbase.userandjobstate.test.FakeJob;
import us.kbase.userandjobstate.test.UserJobStateTestCommon;
/*
* These tests are specifically for testing the JSON-RPC communications between
* the client, up to the invocation of the {@link us.kbase.userandjobstate.userstate.UserState}
* and {@link us.kbase.userandjobstate.jobstate.JobState}
* methods. As such they do not test the full functionality of the methods;
* {@link us.kbase.userandjobstate.userstate.test.UserStateTests} and
* {@link us.kbase.userandjobstate.jobstate.test.JobStateTests} handles that.
*/
public class JSONRPCLayerTest extends JSONRPCLayerTestUtils {
private static UserAndJobStateServer SERVER = null;
private static UserAndJobStateClient CLIENT1 = null;
private static String USER1 = null;
private static UserAndJobStateClient CLIENT2 = null;
private static String USER2 = null;
private static String TOKEN1;
private static String TOKEN2;
private static MongoController mongo;
@BeforeClass
public static void setUpClass() throws Exception {
USER1 = System.getProperty("test.user1");
USER2 = System.getProperty("test.user2");
String p1 = System.getProperty("test.pwd1");
String p2 = System.getProperty("test.pwd2");
mongo = new MongoController(
UserJobStateTestCommon.getMongoExe(),
Paths.get(UserJobStateTestCommon.getTempDir()));
System.out.println("Using Mongo temp dir " + mongo.getTempDir());
//write the server config file:
File iniFile = File.createTempFile("test", ".cfg", new File("./"));
iniFile.deleteOnExit();
System.out.println("Created temporary config file: " + iniFile.getAbsolutePath());
Ini ini = new Ini();
Section ws = ini.add("UserAndJobState");
ws.add("mongodb-host", "localhost:" + mongo.getServerPort());
ws.add("mongodb-database", "JSONRPCLayerTest_DB");
ws.add("mongodb-user", "foo");
ws.add("mongodb-pwd", "foo");
ws.add("kbase-admin-user", USER1);
ws.add("kbase-admin-pwd", p1);
ini.store(iniFile);
//set up env
Map<String, String> env = getenv();
env.put("KB_DEPLOYMENT_CONFIG", iniFile.getAbsolutePath());
env.put("KB_SERVICE_NAME", "UserAndJobState");
SERVER = new UserAndJobStateServer();
new ServerThread(SERVER).start();
System.out.println("Main thread waiting for server to start up");
while(SERVER.getServerPort() == null) {
Thread.sleep(1000);
}
int port = SERVER.getServerPort();
System.out.println("Started test server on port " + port);
System.out.println("Starting tests");
CLIENT1 = new UserAndJobStateClient(new URL("http://localhost:" + port), USER1, p1);
CLIENT2 = new UserAndJobStateClient(new URL("http://localhost:" + port), USER2, p2);
CLIENT1.setIsInsecureHttpConnectionAllowed(true);
CLIENT2.setIsInsecureHttpConnectionAllowed(true);
TOKEN1 = CLIENT1.getToken().toString();
TOKEN2 = CLIENT2.getToken().toString();
}
@AfterClass
public static void tearDownClass() throws Exception {
if (SERVER != null) {
System.out.print("Killing server... ");
SERVER.stopServer();
System.out.println("Done");
}
if (mongo != null) {
mongo.destroy(UserJobStateTestCommon.getDeleteTempFiles());
}
}
@Test
public void ver() throws Exception {
assertThat("got correct version", CLIENT1.ver(), is("0.1.2"));
}
@Test
public void unicode() throws Exception {
int[] char1 = {11614};
String uni = new String(char1, 0, 1);
CLIENT1.setState("uni", "key", new UObject(uni));
assertThat("get unicode back",
CLIENT1.getState("uni", "key", 0L)
.asClassInstance(Object.class),
is((Object) uni));
CLIENT1.removeState("uni", "key");
}
@Test
public void getSetListStateService() throws Exception {
List<Integer> data = Arrays.asList(1, 2, 3, 5, 8, 13);
List<Integer> data2 = Arrays.asList(42);
CLIENT1.setState("serv1", "key1", new UObject(data));
CLIENT2.setState("serv1", "2key1", new UObject(data2));
CLIENT1.setStateAuth(TOKEN2, "akey1", new UObject(data));
CLIENT2.setStateAuth(TOKEN1, "2akey1", new UObject(data2));
succeedGetHasState(CLIENT1, "serv1", "key1", 0L, data);
succeedGetHasState(CLIENT2, "serv1", "2key1", 0L, data2);
succeedGetHasState(CLIENT1, USER2, "akey1", 1L, data);
succeedGetHasState(CLIENT2, USER1, "2akey1", 1L, data2);
CLIENT1.setState("serv1", "key2", new UObject(data));
CLIENT1.setState("serv2", "key", new UObject(data));
CLIENT1.setStateAuth(TOKEN2, "akey2", new UObject(data));
CLIENT1.setStateAuth(TOKEN1, "akey", new UObject(data));
assertThat("get correct keys",
new HashSet<String>(CLIENT1.listState("serv1", 0L)),
is(new HashSet<String>(Arrays.asList("key1", "key2"))));
assertThat("get correct keys",
new HashSet<String>(CLIENT1.listState("serv2", 0L)),
is(new HashSet<String>(Arrays.asList("key"))));
assertThat("get correct keys",
new HashSet<String>(CLIENT1.listState(USER2, 1L)),
is(new HashSet<String>(Arrays.asList("akey1", "akey2"))));
assertThat("get correct keys",
new HashSet<String>(CLIENT1.listState(USER1, 1L)),
is(new HashSet<String>(Arrays.asList("akey"))));
assertThat("get correct services",
new HashSet<String>(CLIENT1.listStateServices(0L)),
is(new HashSet<String>(Arrays.asList("serv1", "serv2"))));
assertThat("get correct services",
new HashSet<String>(CLIENT1.listStateServices(1L)),
is(new HashSet<String>(Arrays.asList(USER1, USER2))));
CLIENT1.removeState("serv1", "key1");
CLIENT1.removeStateAuth(TOKEN2, "akey1");
failGetHasState(CLIENT1, "serv1", "key1", 0L);
failGetHasState(CLIENT1, USER2, "akey1", 1L);
}
private void failGetHasState(UserAndJobStateClient client, String service,
String key, long auth) throws Exception {
String exp = String.format("There is no key %s for the %sauthorized service %s",
key, auth == 1 ? "" : "un", service);
try {
client.getState(service, key, auth);
fail("got deleted state");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exp));
}
Tuple2<Long, UObject> t2 = client.getHasState(service, key, auth);
assertThat("key does not exist", t2.getE1(), is(0L));
assertThat("null value", t2.getE2(),
is((Object) null));
assertThat("has key returns false", client.hasState(service, key, auth),
is(0L));
}
private void succeedGetHasState(UserAndJobStateClient client, String service,
String key, long auth, Object data) throws Exception {
assertThat("get correct data back",
client.getState(service, key, auth).asClassInstance(Object.class),
is(data));
Tuple2<Long, UObject> t2 = client.getHasState(service, key, auth);
assertThat("key exists", t2.getE1(), is(1L));
assertThat("correct value", t2.getE2().asClassInstance(Object.class),
is(data));
assertThat("has key returns true", client.hasState(service, key, auth),
is(1L));
}
@Test
public void badToken() throws Exception {
try {
CLIENT1.setStateAuth(null, "key", new UObject("foo"));
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token cannot be null or the empty string"));
}
try {
CLIENT1.setStateAuth("", "key", new UObject("foo"));
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token cannot be null or the empty string"));
}
try {
CLIENT1.setStateAuth("boogabooga", "key", new UObject("foo"));
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Auth token is in the incorrect format, near 'boogabooga'"));
}
try {
CLIENT1.setStateAuth(TOKEN2 + "a", "key", new UObject("foo"));
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token is invalid"));
}
try {
CLIENT1.removeStateAuth(null, "key");
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token cannot be null or the empty string"));
}
try {
CLIENT1.removeStateAuth("", "key");
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token cannot be null or the empty string"));
}
try {
CLIENT1.removeStateAuth("boogabooga", "key");
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Auth token is in the incorrect format, near 'boogabooga'"));
}
try {
CLIENT1.removeStateAuth(TOKEN2 + "a", "key");
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token is invalid"));
}
}
private String[] getNearbyTimes() {
SimpleDateFormat dateform =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
SimpleDateFormat dateformutc =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
dateformutc.setTimeZone(TimeZone.getTimeZone("UTC"));
Date nf = new Date(new Date().getTime() + 10000);
Date np = new Date(new Date().getTime() - 10);
String[] nearfuture = new String[3];
nearfuture[0] = dateform.format(nf);
nearfuture[1] = dateformutc.format(nf);
nearfuture[2] = dateform.format(np);
return nearfuture;
}
@Test
public void createAndStartJob() throws Exception {
String[] nearfuture = getNearbyTimes();
String jobid = CLIENT1.createJob();
checkJob(CLIENT1, jobid, "created",null, null, null, null,
null, null, null, null, null, null, null);
CLIENT1.startJob(jobid, TOKEN2, "new stat", "ne desc",
new InitProgress().withPtype("none"), null);
checkJob(CLIENT1, jobid, "started", "new stat", USER2,
"ne desc", "none", null, null, null, 0L, 0L, null, null);
jobid = CLIENT1.createJob();
CLIENT1.startJob(jobid, TOKEN2, "new stat2", "ne desc2",
new InitProgress().withPtype("percent"), nearfuture[0]);
checkJob(CLIENT1, jobid, "started", "new stat2", USER2,
"ne desc2", "percent", 0L, 100L, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createJob();
CLIENT1.startJob(jobid, TOKEN2, "new stat3", "ne desc3",
new InitProgress().withPtype("task").withMax(5L), null);
checkJob(CLIENT1, jobid, "started", "new stat3", USER2,
"ne desc3", "task", 0L, 5L, null, 0L, 0L, null, null);
startJobBadArgs(null, TOKEN2, "s", "d", new InitProgress().withPtype("none"),
null, "id cannot be null or the empty string", true);
startJobBadArgs("", TOKEN2, "s", "d", new InitProgress().withPtype("none"),
null, "id cannot be null or the empty string", true);
startJobBadArgs("aaaaaaaaaaaaaaaaaaaa", TOKEN2, "s", "d",
new InitProgress().withPtype("none"),
null, "Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID", true);
jobid = CLIENT1.createJob();
startJobBadArgs(jobid, null, "s", "d", new InitProgress().withPtype("none"),
null, "Service token cannot be null or the empty string");
startJobBadArgs(jobid, "foo", "s", "d", new InitProgress().withPtype("none"),
null, "Auth token is in the incorrect format, near 'foo'");
startJobBadArgs(jobid, TOKEN2 + "a", "s", "d", new InitProgress().withPtype("none"),
null, "Service token is invalid");
startJobBadArgs(jobid, TOKEN2, "s", "d",
new InitProgress().withPtype("none"),
nearfuture[2], "The estimated completion date must be in the future", true);
startJobBadArgs(jobid, TOKEN2, "s", "d",
new InitProgress().withPtype("none"),
"2200-12-30T23:30:54-8000",
"Unparseable date: Invalid format: \"2200-12-30T23:30:54-8000\" is malformed at \"8000\"", true);
startJobBadArgs(jobid, TOKEN2, "s", "d",
new InitProgress().withPtype("none"),
"2200-12-30T123:30:54-0800",
"Unparseable date: Invalid format: \"2200-12-30T123:30:54-0800\" is malformed at \"3:30:54-0800\"", true);
startJobBadArgs(jobid, TOKEN2, "s", "d", null,
null, "InitProgress cannot be null");
InitProgress ip = new InitProgress().withPtype("none");
ip.setAdditionalProperties("foo", "bar");
startJobBadArgs(jobid, TOKEN2, "s", "d", ip,
null, "Unexpected arguments in InitProgress: foo");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype(null),
null, "Progress type cannot be null");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype("foo"),
null, "No such progress type: foo");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype("task")
.withMax(null),
null, "Max progress cannot be null for task based progress");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype("task")
.withMax(-1L),
null, "The maximum progress for the job must be > 0");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype("task")
.withMax(((long) Integer.MAX_VALUE) + 1),
null, "Max progress can be no greater than " + Integer.MAX_VALUE);
jobid = CLIENT1.createAndStartJob(TOKEN2, "cs stat", "cs desc",
new InitProgress().withPtype("none"), nearfuture[0]);
checkJob(CLIENT1, jobid, "started", "cs stat", USER2,
"cs desc", "none", null, null, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "cs stat2", "cs desc2",
new InitProgress().withPtype("percent"), null);
checkJob(CLIENT1, jobid, "started", "cs stat2", USER2,
"cs desc2", "percent", 0L, 100L, null, 0L, 0L, null, null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "cs stat3", "cs desc3",
new InitProgress().withPtype("task").withMax(5L), null);
checkJob(CLIENT1, jobid, "started", "cs stat3", USER2,
"cs desc3", "task", 0L, 5L, null, 0L, 0L, null, null);
}
private void startJobBadArgs(String jobid, String token, String stat, String desc,
InitProgress prog, String estCompl, String exception) throws Exception {
startJobBadArgs(jobid, token, stat, desc, prog, estCompl, exception, false);
}
private void startJobBadArgs(String jobid, String token, String stat, String desc,
InitProgress prog, String estCompl, String exception, boolean badid)
throws Exception {
try {
CLIENT1.startJob(jobid, token, stat, desc, prog, estCompl);
fail("started job w/ bad args");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
if (badid) {
return;
}
try {
CLIENT1.createAndStartJob(token, stat, desc, prog, estCompl);
fail("started job w/ bad args");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
@Test
public void getJobInfoBadArgs() throws Exception {
failGetJob(CLIENT1, null, "id cannot be null or the empty string");
failGetJob(CLIENT1, "", "id cannot be null or the empty string");
failGetJob(CLIENT1, "foo", "Job ID foo is not a legal ID");
String jobid = CLIENT1.createJob();
if (jobid.charAt(0) == 'a') {
jobid = "b" + jobid.substring(1);
} else {
jobid = "a" + jobid.substring(1);
}
failGetJob(CLIENT1, jobid, String.format(
"There is no job %s viewable by user %s", jobid, USER1));
}
@Test
public void updateJob() throws Exception {
String[] nearfuture = getNearbyTimes();
String jobid = CLIENT1.createAndStartJob(TOKEN2, "up stat", "up desc",
new InitProgress().withPtype("none"), null);
CLIENT1.updateJob(jobid, TOKEN2, "up stat2", null);
checkJob(CLIENT1, jobid, "started", "up stat2", USER2,
"up desc", "none", null, null, null, 0L, 0L, null, null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up stat3", 40L, null);
checkJob(CLIENT1, jobid, "started", "up stat3", USER2,
"up desc", "none", null, null, null, 0L, 0L, null, null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up stat3", null, nearfuture[0]);
checkJob(CLIENT1, jobid, "started", "up stat3", USER2,
"up desc", "none", null, null, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "up2 stat", "up2 desc",
new InitProgress().withPtype("percent"), null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up2 stat2", 40L, null);
checkJob(CLIENT1, jobid, "started", "up2 stat2", USER2,
"up2 desc", "percent", 40L, 100L, null, 0L, 0L, null, null);
CLIENT1.updateJob(jobid, TOKEN2, "up2 stat3", nearfuture[0]);
checkJob(CLIENT1, jobid, "started", "up2 stat3", USER2,
"up2 desc", "percent", 40L, 100L, nearfuture[1], 0L, 0L, null,
null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up2 stat4", 70L, null);
checkJob(CLIENT1, jobid, "started", "up2 stat4", USER2,
"up2 desc", "percent", 100L, 100L, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "up3 stat", "up3 desc",
new InitProgress().withPtype("task").withMax(42L), null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up3 stat2", 30L, nearfuture[0]);
checkJob(CLIENT1, jobid, "started", "up3 stat2", USER2,
"up3 desc", "task", 30L, 42L, nearfuture[1], 0L, 0L, null, null);
CLIENT1.updateJob(jobid, TOKEN2, "up3 stat3", null);
checkJob(CLIENT1, jobid, "started", "up3 stat3", USER2,
"up3 desc", "task", 30L, 42L, nearfuture[1], 0L, 0L, null,
null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up3 stat4", 15L, null);
checkJob(CLIENT1, jobid, "started", "up3 stat4", USER2,
"up3 desc", "task", 42L, 42L, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "up4 stat", "up4 desc",
new InitProgress().withPtype("none"), null);
updateJobBadArgs(jobid, TOKEN2, "up4 stat2", -1L, null, "progress cannot be negative");
updateJobBadArgs(jobid, TOKEN2, "up4 stat2",
(long) Integer.MAX_VALUE + 1, null,
"Max progress can be no greater than " + Integer.MAX_VALUE);
updateJobBadArgs(null, TOKEN2, "s", null,
"id cannot be null or the empty string");
updateJobBadArgs("", TOKEN2, "s", null,
"id cannot be null or the empty string");
updateJobBadArgs("aaaaaaaaaaaaaaaaaaaa", TOKEN2, "s", null,
"Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID");
//test a few bad times
updateJobBadArgs(jobid, TOKEN2, "s", nearfuture[2],
"The estimated completion date must be in the future");
updateJobBadArgs(jobid, TOKEN2, "s", "2200-12-30T123:30:54-0800",
"Unparseable date: Invalid format: \"2200-12-30T123:30:54-0800\" is malformed at \"3:30:54-0800\"");
updateJobBadArgs(jobid, TOKEN2, "s", "2013-04-26T25:52:06-0800",
"Unparseable date: Cannot parse \"2013-04-26T25:52:06-0800\": Value 25 for hourOfDay must be in the range [0,23]");
updateJobBadArgs(jobid, TOKEN2, "s", "2013-04-26T23:52:06-8000",
"Unparseable date: Invalid format: \"2013-04-26T23:52:06-8000\" is malformed at \"8000\"");
updateJobBadArgs(jobid, TOKEN2, "s", "2013-04-35T23:52:06-0800",
"Unparseable date: Cannot parse \"2013-04-35T23:52:06-0800\": Value 35 for dayOfMonth must be in the range [1,30]");
updateJobBadArgs(jobid, TOKEN2, "s", "2013-13-26T23:52:06-0800",
"Unparseable date: Cannot parse \"2013-13-26T23:52:06-0800\": Value 13 for monthOfYear must be in the range [1,12]");
updateJobBadArgs(jobid, TOKEN2, "s", "2013-13-26T23:52:06.1111-0800",
"Unparseable date: Invalid format: \"2013-13-26T23:52:06.1111-0800\" is malformed at \"1-0800\"");
updateJobBadArgs(jobid, TOKEN2, "s", "2013-13-26T23:52:06.-0800",
"Unparseable date: Invalid format: \"2013-13-26T23:52:06.-0800\" is malformed at \".-0800\"");
updateJobBadArgs(jobid, TOKEN2, "s", "2013-12-26T23:52:06.55",
"Unparseable date: Invalid format: \"2013-12-26T23:52:06.55\" is too short");
updateJobBadArgs(jobid, TOKEN2, "s", "2013-12-26T23:52-0800",
"Unparseable date: Invalid format: \"2013-12-26T23:52-0800\" is malformed at \"-0800\"");
updateJobBadArgs(jobid, null, "s", null,
"Service token cannot be null or the empty string");
updateJobBadArgs(jobid, "foo", "s", null,
"Auth token is in the incorrect format, near 'foo'");
updateJobBadArgs(jobid, TOKEN1, "s", null, String.format(
"There is no uncompleted job %s for user %s started by service %s",
jobid, USER1, USER1));
updateJobBadArgs(jobid, TOKEN2 + "a", "s", null,
"Service token is invalid");
}
private void updateJobBadArgs(String jobid, String token, String status,
Long prog, String estCompl, String exception) throws Exception {
try {
CLIENT1.updateJobProgress(jobid, token, status, prog, estCompl);
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
private void updateJobBadArgs(String jobid, String token, String status,
String estCompl, String exception) throws Exception {
try {
CLIENT1.updateJob(jobid, token, status, estCompl);
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
try {
CLIENT1.updateJobProgress(jobid, token, status, 1L, estCompl);
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
@Test
public void completeJob() throws Exception {
String[] nearfuture = getNearbyTimes();
String jobid = CLIENT1.createAndStartJob(TOKEN2, "c stat", "c desc",
new InitProgress().withPtype("none"), null);
CLIENT1.completeJob(jobid, TOKEN2, "c stat2", null, null);
checkJob(CLIENT1, jobid, "complete", "c stat2", USER2, "c desc", "none", null,
null, null, 1L, 0L, null, null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "c2 stat", "c2 desc",
new InitProgress().withPtype("percent"), null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "c2 stat2", 40L, null);
CLIENT1.completeJob(jobid, TOKEN2, "c2 stat3", "omg err",
new Results());
checkJob(CLIENT1, jobid, "error", "c2 stat3", USER2, "c2 desc", "percent",
100L, 100L, null, 1L, 1L, "omg err", new Results());
jobid = CLIENT1.createAndStartJob(TOKEN2, "c3 stat", "c3 desc",
new InitProgress().withPtype("task").withMax(37L), null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "c3 stat2", 15L, nearfuture[0]);
List<Result> r = new LinkedList<Result>();
r.add(new Result().withUrl("some url").withServerType("server")
.withId("an id").withDescription("desc"));
Results res = new Results()
.withShocknodes(Arrays.asList("node1", "node3"))
.withShockurl("surl")
.withWorkspaceids(Arrays.asList("ws1", "ws3"))
.withWorkspaceurl("wurl")
.withResults(r);
CLIENT1.completeJob(jobid, TOKEN2, "c3 stat3", null, res);
checkJob(CLIENT1, jobid, "complete", "c3 stat3", USER2, "c3 desc", "task",
37L, 37L, nearfuture[1], 1L, 0L, null, res);
failCompleteJob(null, TOKEN2, "s", null, null,
"id cannot be null or the empty string");
failCompleteJob("", TOKEN2, "s", null, null,
"id cannot be null or the empty string");
failCompleteJob("aaaaaaaaaaaaaaaaaaaa", TOKEN2, "s", null, null,
"Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID");
failCompleteJob(jobid, null, "s", null, null,
"Service token cannot be null or the empty string");
failCompleteJob(jobid, "foo", "s", null, null,
"Auth token is in the incorrect format, near 'foo'");
failCompleteJob(jobid, TOKEN2 + "w", "s", null, null,
"Service token is invalid");
failCompleteJob(jobid, TOKEN1, "s", null, null, String.format(
"There is no uncompleted job %s for user %s started by service %s",
jobid, USER1, USER1));
Results badres = new Results();
badres.setAdditionalProperties("foo", "bar");
failCompleteJob(jobid, TOKEN1, "s", null, badres,
"Unexpected arguments in Results: foo");
jobid = CLIENT1.createAndStartJob(TOKEN2, "bad res stat",
"bad res desc", new InitProgress().withPtype("none"), null);
Results res2 = new Results().withShockurl("");
failCompleteJob(jobid, TOKEN2, "foo", "bar", res2, "shockurl cannot be the empty string");
failCompleteJob(jobid, TOKEN2, "foo", "bar", res.withShockurl(null).withWorkspaceurl(""),
"workspaceurl cannot be the empty string");
failCompleteJob(jobid, TOKEN2, "foo", "bar", res.withWorkspaceurl(null)
.withShocknodes(Arrays.asList("")),
"shocknode cannot be null or the empty string");
failCompleteJob(jobid, TOKEN2, "foo", "bar", res.withShocknodes(null)
.withWorkspaceids(Arrays.asList("")),
"workspaceid cannot be null or the empty string");
Result r2 = new Result();
r2.setAdditionalProperties("foo", "bar");
List<Result> rl = new LinkedList<Result>();
rl.add(r2);
failCompleteJob(jobid, TOKEN2, "foo", "bar", res.withWorkspaceids(null)
.withResults(rl), "Unexpected arguments in Result: foo");
r2 = new Result().withServerType(null).withId("id").withUrl("url");
rl.clear();
rl.add(r2);
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"servertype cannot be null or the empty string");
r2.withServerType("");
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"servertype cannot be null or the empty string");
r2.withServerType(CHAR101);
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"servertype exceeds the maximum length of 100");
r2.withServerType("serv");
r2.withId(null);
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"id cannot be null or the empty string");
r2.withId("");
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"id cannot be null or the empty string");
r2.withId(CHAR1001);
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"id exceeds the maximum length of 1000");
r2.withId("id");
r2.withUrl(null);
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"url cannot be null or the empty string");
r2.withUrl("");
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"url cannot be null or the empty string");
r2.withUrl(CHAR1001);
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"url exceeds the maximum length of 1000");
r2.withUrl("url");
r2.withDescription(CHAR1001);
failCompleteJob(jobid, TOKEN2, "foo", "bar", res,
"description exceeds the maximum length of 1000");
}
private void failCompleteJob(String jobid, String token, String status,
String error, Results res, String exception) throws Exception {
try {
CLIENT1.completeJob(jobid, token, status, error, res);
fail("Completed job with bad input");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
@Test
public void deleteJob() throws Exception {
String nojob = "There is no job %s viewable by user %s";
InitProgress noprog = new InitProgress().withPtype("none");
String jobid = CLIENT1.createAndStartJob(TOKEN2, "d stat", "d desc", noprog, null);
CLIENT1.completeJob(jobid, TOKEN2, "d stat2", null, null);
CLIENT1.deleteJob(jobid);
failGetJob(CLIENT1, jobid, String.format(nojob, jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "e stat", "e desc", noprog, null);
CLIENT1.completeJob(jobid, TOKEN2, "e stat2", "err", null);
CLIENT1.deleteJob(jobid);
failGetJob(CLIENT1, jobid, String.format(nojob, jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "d2 stat", "d2 desc", noprog, null);
CLIENT1.forceDeleteJob(TOKEN2, jobid);
failGetJob(CLIENT1, jobid, String.format(nojob, jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "d3 stat", "d3 desc", noprog, null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "d3 stat2", 3L, null);
CLIENT1.forceDeleteJob(TOKEN2, jobid);
failGetJob(CLIENT1, jobid, String.format(nojob, jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "d4 stat", "d4 desc", noprog, null);
CLIENT1.completeJob(jobid, TOKEN2, "d4 stat2", null, null);
CLIENT1.forceDeleteJob(TOKEN2, jobid);
failGetJob(CLIENT1, jobid, String.format(nojob, jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "d5 stat", "d5 desc", noprog, null);
CLIENT1.completeJob(jobid, TOKEN2, "d5 stat2", "err", null);
CLIENT1.forceDeleteJob(TOKEN2, jobid);
failGetJob(CLIENT1, jobid, String.format(nojob, jobid, USER1));
jobid = CLIENT1.createJob();
failToDeleteJob(jobid, String.format(
"There is no completed job %s for user %s", jobid, USER1));
failToDeleteJob(jobid, TOKEN2, String.format(
"There is no job %s for user %s and service %s",
jobid, USER1, USER2));
CLIENT1.startJob(jobid, TOKEN2, "d6 stat", "d6 desc", noprog, null);
failToDeleteJob(jobid, String.format(
"There is no completed job %s for user %s", jobid, USER1));
CLIENT1.updateJobProgress(jobid, TOKEN2, "d6 stat2", 3L, null);
failToDeleteJob(jobid, String.format(
"There is no completed job %s for user %s", jobid, USER1));
failToDeleteJob(null, "id cannot be null or the empty string");
failToDeleteJob("", "id cannot be null or the empty string");
failToDeleteJob("aaaaaaaaaaaaaaaaaaaa",
"Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID");
failToDeleteJob(null, TOKEN2,
"id cannot be null or the empty string");
failToDeleteJob("", TOKEN2,
"id cannot be null or the empty string");
failToDeleteJob("aaaaaaaaaaaaaaaaaaaa", TOKEN2,
"Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID");
failToDeleteJob(jobid, null,
"Service token cannot be null or the empty string", true);
failToDeleteJob(jobid, "foo",
"Auth token is in the incorrect format, near 'foo'");
failToDeleteJob(jobid, TOKEN2 + 'w',
"Service token is invalid");
failToDeleteJob(jobid, TOKEN1, String.format(
"There is no job %s for user %s and service %s",
jobid, USER1, USER1));
}
private void failToDeleteJob(String jobid, String exception)
throws Exception {
failToDeleteJob(jobid, null, exception, false);
}
private void failToDeleteJob(String jobid, String token, String exception)
throws Exception {
failToDeleteJob(jobid, token, exception, false);
}
private void failToDeleteJob(String jobid, String token, String exception,
boolean usenulltoken)
throws Exception {
try {
if (!usenulltoken && token == null) {
CLIENT1.deleteJob(jobid);
} else {
CLIENT1.forceDeleteJob(token, jobid);
}
fail("deleted job with bad args");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
@Test
public void listServices() throws Exception {
checkListServices(CLIENT2, new HashSet<String>());
InitProgress noprog = new InitProgress().withPtype("none");
String jobid1 = CLIENT1.createAndStartJob(TOKEN2, "ls stat", "ls desc",
noprog, null);
checkListServices(CLIENT1, new HashSet<String>(Arrays.asList(USER2)));
String jobid2 = CLIENT1.createAndStartJob(TOKEN1, "ls2 stat",
"ls2 desc", noprog, null);
checkListServices(CLIENT1, new HashSet<String>(Arrays.asList(USER1, USER2)));
checkListServices(CLIENT2, new HashSet<String>());
CLIENT1.shareJob(jobid2, Arrays.asList(USER2));
checkListServices(CLIENT2, new HashSet<String>(Arrays.asList(USER1)));
CLIENT1.shareJob(jobid1, Arrays.asList(USER2));
checkListServices(CLIENT2, new HashSet<String>(Arrays.asList(USER1, USER2)));
CLIENT1.unshareJob(jobid2, Arrays.asList(USER2));
checkListServices(CLIENT2, new HashSet<String>(Arrays.asList(USER2)));
CLIENT1.forceDeleteJob(TOKEN1, jobid2);
CLIENT1.forceDeleteJob(TOKEN2, jobid1);
}
private void checkListServices(UserAndJobStateClient client,
Set<String> service) throws Exception {
assertThat("got correct services", new HashSet<String>(client.listJobServices()),
is(service));
}
@Test
public void listJobs() throws Exception {
//NOTE: all jobs must be deleted from CLIENT2 or other tests may fail
InitProgress noprog = new InitProgress().withPtype("none");
Set<FakeJob> empty = new HashSet<FakeJob>();
checkListJobs(CLIENT2, USER1, null, empty);
checkListJobs(CLIENT2, USER1, "", empty);
checkListJobs(CLIENT2, USER1, "S", empty);
checkListJobs(CLIENT2, USER1, "R", empty);
checkListJobs(CLIENT2, USER1, "RS", empty);
checkListJobs(CLIENT2, USER1, "C", empty);
checkListJobs(CLIENT2, USER1, "CS", empty);
checkListJobs(CLIENT2, USER1, "E", empty);
checkListJobs(CLIENT2, USER1, "ES", empty);
checkListJobs(CLIENT2, USER1, "RC", empty);
checkListJobs(CLIENT2, USER1, "RCS", empty);
checkListJobs(CLIENT2, USER1, "CE", empty);
checkListJobs(CLIENT2, USER1, "CES", empty);
checkListJobs(CLIENT2, USER1, "RE", empty);
checkListJobs(CLIENT2, USER1, "RES", empty);
checkListJobs(CLIENT2, USER1, "RCE", empty);
checkListJobs(CLIENT2, USER1, "RCES", empty);
checkListJobs(CLIENT2, USER1, "RCEX", empty);
checkListJobs(CLIENT2, USER1, "RCEXS", empty);
String jobid = CLIENT1.createAndStartJob(TOKEN1, "ljs stat", "ljs desc", noprog, null);
FakeJob shared = new FakeJob(jobid, null, USER1, "started", null, "ljs desc",
"none", null, null, "ljs stat", false, false, null, null);
CLIENT1.shareJob(jobid, Arrays.asList(USER2));
Set<FakeJob> setsharedonly = new HashSet<FakeJob>(Arrays.asList(shared));
checkListJobs(CLIENT2, USER1, null, empty);
checkListJobs(CLIENT2, USER1, "", empty);
checkListJobs(CLIENT2, USER1, "S", setsharedonly);
checkListJobs(CLIENT2, USER1, "R", empty);
checkListJobs(CLIENT2, USER1, "RS", setsharedonly);
checkListJobs(CLIENT2, USER1, "C", empty);
checkListJobs(CLIENT2, USER1, "CS", empty);
checkListJobs(CLIENT2, USER1, "E", empty);
checkListJobs(CLIENT2, USER1, "ES", empty);
checkListJobs(CLIENT2, USER1, "RC", empty);
checkListJobs(CLIENT2, USER1, "RCS", setsharedonly);
checkListJobs(CLIENT2, USER1, "CE", empty);
checkListJobs(CLIENT2, USER1, "CES", empty);
checkListJobs(CLIENT2, USER1, "RE", empty);
checkListJobs(CLIENT2, USER1, "RES", setsharedonly);
checkListJobs(CLIENT2, USER1, "RCE", empty);
checkListJobs(CLIENT2, USER1, "RCES", setsharedonly);
checkListJobs(CLIENT2, USER1, "RCEX", empty);
checkListJobs(CLIENT2, USER1, "RCEXS", setsharedonly);
jobid = CLIENT2.createJob();
checkListJobs(CLIENT2, USER1, null, empty);
checkListJobs(CLIENT2, USER1, "", empty);
checkListJobs(CLIENT2, USER1, "R", empty);
checkListJobs(CLIENT2, USER1, "C", empty);
checkListJobs(CLIENT2, USER1, "E", empty);
checkListJobs(CLIENT2, USER1, "RC", empty);
checkListJobs(CLIENT2, USER1, "CE", empty);
checkListJobs(CLIENT2, USER1, "RE", empty);
checkListJobs(CLIENT2, USER1, "RCE", empty);
checkListJobs(CLIENT2, USER1, "RXCE", empty);
CLIENT2.startJob(jobid, TOKEN1, "lj stat", "lj desc", noprog, null);
FakeJob started = new FakeJob(jobid, null, USER1, "started", null, "lj desc",
"none", null, null, "lj stat", false, false, null, null);
Set<FakeJob> setstarted = new HashSet<FakeJob>(Arrays.asList(started));
Set<FakeJob> setstartshare = new HashSet<FakeJob>(setstarted);
setstartshare.add(shared);
checkListJobs(CLIENT2, USER1, null, setstarted);
checkListJobs(CLIENT2, USER1, "", setstarted);
checkListJobs(CLIENT2, USER1, "S", setstartshare);
checkListJobs(CLIENT2, USER1, "R", setstarted);
checkListJobs(CLIENT2, USER1, "RS", setstartshare);
checkListJobs(CLIENT2, USER1, "C", empty);
checkListJobs(CLIENT2, USER1, "CS", empty);
checkListJobs(CLIENT2, USER1, "E", empty);
checkListJobs(CLIENT2, USER1, "ES", empty);
checkListJobs(CLIENT2, USER1, "RC", setstarted);
checkListJobs(CLIENT2, USER1, "RCS", setstartshare);
checkListJobs(CLIENT2, USER1, "CE", empty);
checkListJobs(CLIENT2, USER1, "CES", empty);
checkListJobs(CLIENT2, USER1, "RE", setstarted);
checkListJobs(CLIENT2, USER1, "RES", setstartshare);
checkListJobs(CLIENT2, USER1, "RCE", setstarted);
checkListJobs(CLIENT2, USER1, "RCES", setstartshare);
checkListJobs(CLIENT2, USER1, "!RCE", setstarted);
checkListJobs(CLIENT2, USER1, "!RCES", setstartshare);
jobid = CLIENT2.createAndStartJob(TOKEN1, "lj2 stat", "lj2 desc",
new InitProgress().withPtype("percent"), null);
CLIENT2.updateJobProgress(jobid, TOKEN1, "lj2 stat2", 42L, null);
FakeJob started2 = new FakeJob(jobid, null, USER1, "started", null,
"lj2 desc", "percent", 42, 100, "lj2 stat2", false, false, null,
null);
setstarted.add(started2);
checkListJobs(CLIENT2, USER1, null, setstarted);
checkListJobs(CLIENT2, USER1, "", setstarted);
checkListJobs(CLIENT2, USER1, "R", setstarted);
checkListJobs(CLIENT2, USER1, "C", empty);
checkListJobs(CLIENT2, USER1, "E", empty);
checkListJobs(CLIENT2, USER1, "RC", setstarted);
checkListJobs(CLIENT2, USER1, "CE", empty);
checkListJobs(CLIENT2, USER1, "RE", setstarted);
checkListJobs(CLIENT2, USER1, "RCE", setstarted);
checkListJobs(CLIENT2, USER1, "RCwE", setstarted);
CLIENT2.completeJob(jobid, TOKEN1, "lj2 stat3", null,
new Results().withShocknodes(Arrays.asList("node1", "node2")));
setstarted.remove(started2);
started2 = null;
JobResults res = new JobResults(null, null, null, null,
Arrays.asList("node1", "node2"));
FakeJob complete = new FakeJob(jobid, null, USER1, "complete", null,
"lj2 desc", "percent", 100, 100, "lj2 stat3", true, false,
null, res);
Set<FakeJob> setcomplete = new HashSet<FakeJob>(Arrays.asList(complete));
Set<FakeJob> setstartcomp = new HashSet<FakeJob>();
setstartcomp.addAll(setstarted);
setstartcomp.addAll(setcomplete);
Set<FakeJob> setstartcompshare = new HashSet<FakeJob>(setstartcomp);
setstartcompshare.add(shared);
checkListJobs(CLIENT2, USER1, null, setstartcomp);
checkListJobs(CLIENT2, USER1, "", setstartcomp);
checkListJobs(CLIENT2, USER1, "S", setstartcompshare);
checkListJobs(CLIENT2, USER1, "R", setstarted);
checkListJobs(CLIENT2, USER1, "RS", setstartshare);
checkListJobs(CLIENT2, USER1, "C", setcomplete);
checkListJobs(CLIENT2, USER1, "CS", setcomplete);
checkListJobs(CLIENT2, USER1, "C0", setcomplete);
checkListJobs(CLIENT2, USER1, "C0S", setcomplete);
checkListJobs(CLIENT2, USER1, "E", empty);
checkListJobs(CLIENT2, USER1, "ES", empty);
checkListJobs(CLIENT2, USER1, "RC", setstartcomp);
checkListJobs(CLIENT2, USER1, "RCS", setstartcompshare);
checkListJobs(CLIENT2, USER1, "CE", setcomplete);
checkListJobs(CLIENT2, USER1, "CES", setcomplete);
checkListJobs(CLIENT2, USER1, "RE", setstarted);
checkListJobs(CLIENT2, USER1, "RES", setstartshare);
checkListJobs(CLIENT2, USER1, "RCE", setstartcomp);
checkListJobs(CLIENT2, USER1, "RCES", setstartcompshare);
jobid = CLIENT2.createAndStartJob(TOKEN1, "lj3 stat", "lj3 desc",
new InitProgress().withPtype("task").withMax(55L), null);
CLIENT2.updateJobProgress(jobid, TOKEN1, "lj3 stat2", 40L, null);
started2 = new FakeJob(jobid, null, USER1, "started", null,
"lj3 desc", "task", 40, 55, "lj3 stat2", false, false, null,
null);
setstarted.add(started2);
setstartcomp.add(started2);
checkListJobs(CLIENT2, USER1, null, setstartcomp);
checkListJobs(CLIENT2, USER1, "", setstartcomp);
checkListJobs(CLIENT2, USER1, "R", setstarted);
checkListJobs(CLIENT2, USER1, "C", setcomplete);
checkListJobs(CLIENT2, USER1, "E", empty);
checkListJobs(CLIENT2, USER1, "RC", setstartcomp);
checkListJobs(CLIENT2, USER1, "CE", setcomplete);
checkListJobs(CLIENT2, USER1, "C#E", setcomplete);
checkListJobs(CLIENT2, USER1, "RE", setstarted);
checkListJobs(CLIENT2, USER1, "RCE", setstartcomp);
CLIENT2.completeJob(jobid, TOKEN1, "lj3 stat3", "omg err",
new Results().withWorkspaceids(Arrays.asList("wss1", "wss2")));
setstarted.remove(started2);
setstartcomp.remove(started2);
started2 = null;
JobResults res2 = new JobResults(null, null,
Arrays.asList("wss1", "wss2"), null, null);
FakeJob error = new FakeJob(jobid, null, USER1, "error", null,
"lj3 desc", "task", 55, 55, "lj3 stat3", true, true, null,
res2);
Set<FakeJob> seterr = new HashSet<FakeJob>(Arrays.asList(error));
Set<FakeJob> all = new HashSet<FakeJob>(
Arrays.asList(started, complete, error));
checkListJobs(CLIENT2, USER1, null, all);
checkListJobs(CLIENT2, USER1, "", all);
checkListJobs(CLIENT2, USER1, "x", all);
checkListJobs(CLIENT2, USER1, "R", setstarted);
checkListJobs(CLIENT2, USER1, "C", setcomplete);
checkListJobs(CLIENT2, USER1, "E", seterr);
checkListJobs(CLIENT2, USER1, "RC", setstartcomp);
checkListJobs(CLIENT2, USER1, "CE", new HashSet<FakeJob>(
Arrays.asList(complete, error)));
checkListJobs(CLIENT2, USER1, "RE", new HashSet<FakeJob>(
Arrays.asList(started, error)));
checkListJobs(CLIENT2, USER1, "RCE", all);
CLIENT2.forceDeleteJob(TOKEN1, started.getID());
all.remove(started);
checkListJobs(CLIENT2, USER1, null, all);
checkListJobs(CLIENT2, USER1, "", all);
checkListJobs(CLIENT2, USER1, "goodness this is odd input", all);
checkListJobs(CLIENT2, USER1, "R", empty);
checkListJobs(CLIENT2, USER1, "C", setcomplete);
checkListJobs(CLIENT2, USER1, "E", seterr);
checkListJobs(CLIENT2, USER1, "cE", seterr);
checkListJobs(CLIENT2, USER1, "RC", setcomplete);
checkListJobs(CLIENT2, USER1, "CE", new HashSet<FakeJob>(
Arrays.asList(complete, error)));
checkListJobs(CLIENT2, USER1, "RE", seterr);
checkListJobs(CLIENT2, USER1, "RCE", all);
CLIENT2.deleteJob(complete.getID());
checkListJobs(CLIENT2, USER1, null, seterr);
checkListJobs(CLIENT2, USER1, "", seterr);
checkListJobs(CLIENT2, USER1, "R", empty);
checkListJobs(CLIENT2, USER1, "C", empty);
checkListJobs(CLIENT2, USER1, "E", seterr);
checkListJobs(CLIENT2, USER1, "e", seterr);
checkListJobs(CLIENT2, USER1, "RC", empty);
checkListJobs(CLIENT2, USER1, "CE", seterr);
checkListJobs(CLIENT2, USER1, "RE", seterr);
checkListJobs(CLIENT2, USER1, "RCE", seterr);
CLIENT2.deleteJob(error.getID());
checkListJobs(CLIENT2, USER1, null, empty);
checkListJobs(CLIENT2, USER1, "", empty);
checkListJobs(CLIENT2, USER1, "R", empty);
checkListJobs(CLIENT2, USER1, "C", empty);
checkListJobs(CLIENT2, USER1, "E", empty);
checkListJobs(CLIENT2, USER1, "RC", empty);
checkListJobs(CLIENT2, USER1, "CE", empty);
checkListJobs(CLIENT2, USER1, "RE", empty);
checkListJobs(CLIENT2, USER1, "RCE", empty);
testListJobsWithBadArgs(CLIENT2, null,
"service cannot be null or the empty string");
testListJobsWithBadArgs(CLIENT2, "",
"service cannot be null or the empty string");
testListJobsWithBadArgs(CLIENT2, "abcdefghijklmnopqrst" + "abcdefghijklmnopqrst"
+ "abcdefghijklmnopqrst" + "abcdefghijklmnopqrst" +
"abcdefghijklmnopqrst" + "a",
"service exceeds the maximum length of 100");
}
@Test
public void sharing() throws Exception {
InitProgress noprog = new InitProgress().withPtype("none");
String jobid = CLIENT2.createAndStartJob(TOKEN1, "sh stat", "sh desc", noprog, null);
CLIENT2.shareJob(jobid, Arrays.asList(USER1));
//next line ensures that all job read functions are accessible to client 1
checkJob(CLIENT1, jobid, "started", "sh stat", USER1, "sh desc", "none", null, null, null, 0L, 0L, null, null);
failShareJob(CLIENT1, jobid, Arrays.asList(USER2), String.format(
"There is no job %s owned by user %s", jobid, USER1));
assertThat("shared list ok", CLIENT2.getJobShared(jobid), is(Arrays.asList(USER1)));
failGetJobShared(jobid, String.format("User %s may not access the sharing list of job %s", USER1, jobid));
assertThat("owner ok", CLIENT1.getJobOwner(jobid), is(USER2));
assertThat("owner ok", CLIENT2.getJobOwner(jobid), is(USER2));
CLIENT2.unshareJob(jobid, Arrays.asList(USER1));
failGetJob(CLIENT1, jobid, String.format("There is no job %s viewable by user %s", jobid, USER1));
failGetJobOwner(jobid, String.format("There is no job %s viewable by user %s", jobid, USER1));
failGetJobShared(jobid, String.format("There is no job %s viewable by user %s", jobid, USER1));
CLIENT2.shareJob(jobid, Arrays.asList(USER1));
failUnshareJob(CLIENT1, jobid, Arrays.asList(USER2), String.format(
"User %s may only stop sharing job %s for themselves", USER1, jobid));
CLIENT1.unshareJob(jobid, Arrays.asList(USER1));
failGetJob(CLIENT1, jobid, String.format("There is no job %s viewable by user %s", jobid, USER1));
String jobid2 = CLIENT1.createAndStartJob(TOKEN1, "sh stat2", "sh desc2", noprog, null);
failShareUnshareJob(CLIENT1, jobid2, Arrays.asList("thishadbetterbeafakeuserorthistestwillfail"),
"User thishadbetterbeafakeuserorthistestwillfail is not a valid user");
failShareUnshareJob(CLIENT1, jobid2, null, "The user list may not be null or empty");
failShareUnshareJob(CLIENT1, jobid2, new ArrayList<String>(), "The user list may not be null or empty");
}
private void failGetJobOwner(String id, String exception) throws Exception {
try {
CLIENT1.getJobOwner(id);
fail("got job owner w/ bad args");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
private void failGetJobShared(String id, String exception) throws Exception {
try {
CLIENT1.getJobShared(id);
fail("got job shared list w/ bad args");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
}
|
package kademlia;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.NoSuchElementException;
import java.util.Timer;
import java.util.TimerTask;
import kademlia.core.DefaultConfiguration;
import kademlia.dht.GetParameter;
import kademlia.core.KadConfiguration;
import kademlia.core.KadServer;
import kademlia.dht.DHT;
import kademlia.dht.GetParameterFUC;
import kademlia.dht.KadContent;
import kademlia.dht.StorageEntry;
import kademlia.exceptions.ContentNotFoundException;
import kademlia.exceptions.RoutingException;
import kademlia.exceptions.UpToDateContentException;
import kademlia.message.MessageFactory;
import kademlia.node.Node;
import kademlia.node.NodeId;
import kademlia.operation.ConnectOperation;
import kademlia.operation.ContentLookupOperation;
import kademlia.operation.ContentLookupOperationFUC;
import kademlia.operation.Operation;
import kademlia.operation.KadRefreshOperation;
import kademlia.operation.StoreOperation;
import kademlia.routing.SocialKadRoutingTable;
import kademlia.routing.SocialKadRoutingTableImpl;
import kademlia.util.serializer.JsonDHTSerializer;
import kademlia.util.serializer.JsonSerializer;
import kademlia.util.serializer.JsonSocialKadRoutingTableSerializer;
/**
* The main Kademlia Node on the network, this node manages everything for this local system.
*
* @author Joshua Kissoon
* @since 20140215
*
* @todo When we receive a store message - if we have a newer version of the content, re-send this newer version to that node so as to update their version
* @todo Handle IPv6 Addresses
*
*/
public class KademliaNode
{
/* Kademlia Attributes */
private final String ownerId;
/* Objects to be used */
private final transient Node localNode;
private final transient KadServer server;
private final transient DHT dht;
private transient SocialKadRoutingTable routingTable;
private final int udpPort;
private transient KadConfiguration config;
/* Timer used to execute refresh operations */
private transient Timer refreshOperationTimer;
private transient TimerTask refreshOperationTTask;
/* Factories */
private final transient MessageFactory messageFactory;
/* Statistics */
private final transient SocialKadStatistician statistician;
{
statistician = new Statistician();
}
/**
* Creates a Kademlia DistributedMap using the specified name as filename base.
* If the id cannot be read from disk the specified defaultId is used.
* The instance is bootstraped to an existing network by specifying the
* address of a bootstrap node in the network.
*
* @param ownerId The Name of this node used for storage
* @param localNode The Local Node for this Kad instance
* @param udpPort The UDP port to use for routing messages
* @param dht The DHT for this instance
* @param config
* @param routingTable
*
* @throws IOException If an error occurred while reading id or local map
* from disk <i>or</i> a network error occurred while
* attempting to bootstrap to the network
* */
public KademliaNode(String ownerId, Node localNode, int udpPort, DHT dht, SocialKadRoutingTable routingTable, KadConfiguration config) throws IOException
{
this.ownerId = ownerId;
this.udpPort = udpPort;
this.localNode = localNode;
this.dht = dht;
this.config = config;
this.routingTable = routingTable;
this.messageFactory = new MessageFactory(this, this.dht, this.config);
this.server = new KadServer(udpPort, this.messageFactory, this.localNode, this.config, this.statistician);
this.startRefreshOperation();
}
/**
* Schedule the recurring refresh operation
*/
public final void startRefreshOperation()
{
this.refreshOperationTimer = new Timer(true);
refreshOperationTTask = new TimerTask()
{
@Override
public void run()
{
try
{
/* Runs a DHT RefreshOperation */
KademliaNode.this.refresh();
}
catch (IOException e)
{
System.err.println("Refresh Operation Failed; Message: " + e.getMessage());
}
}
};
refreshOperationTimer.schedule(refreshOperationTTask, this.config.restoreInterval(), this.config.restoreInterval());
}
public final void stopRefreshOperation()
{
/* Close off the timer tasks */
this.refreshOperationTTask.cancel();
this.refreshOperationTimer.cancel();
this.refreshOperationTimer.purge();
}
public KademliaNode(String ownerId, Node node, int udpPort, SocialKadRoutingTable routingTable, KadConfiguration config) throws IOException
{
this(
ownerId,
node,
udpPort,
new DHT(ownerId, config),
routingTable,
config
);
}
public KademliaNode(String ownerId, Node node, int udpPort, KadConfiguration config) throws IOException
{
this(
ownerId,
node,
udpPort,
new SocialKadRoutingTableImpl(node, config),
config
);
}
public KademliaNode(String ownerId, NodeId defaultId, int udpPort) throws IOException
{
this(
ownerId,
new Node(defaultId, InetAddress.getLocalHost(), udpPort),
udpPort,
new DefaultConfiguration()
);
}
/**
* Load Stored state using default configuration
*
* @param ownerId The ID of the owner for the stored state
*
* @return A Kademlia instance loaded from a stored state in a file
*
* @throws java.io.FileNotFoundException
* @throws java.lang.ClassNotFoundException
*/
public static KademliaNode loadFromFile(String ownerId) throws FileNotFoundException, IOException, ClassNotFoundException
{
return KademliaNode.loadFromFile(ownerId, new DefaultConfiguration());
}
/**
* Load Stored state
*
* @param ownerId The ID of the owner for the stored state
* @param iconfig Configuration information to work with
*
* @return A Kademlia instance loaded from a stored state in a file
*
* @throws java.io.FileNotFoundException
* @throws java.lang.ClassNotFoundException
*/
public static KademliaNode loadFromFile(String ownerId, KadConfiguration iconfig) throws FileNotFoundException, IOException, ClassNotFoundException
{
DataInputStream din;
/**
* @section Read Basic Kad data
*/
din = new DataInputStream(new FileInputStream(getStateStorageFolderName(ownerId, iconfig) + File.separator + "kad.kns"));
KademliaNode ikad = new JsonSerializer<KademliaNode>().read(din);
/**
* @section Read the routing table
*/
din = new DataInputStream(new FileInputStream(getStateStorageFolderName(ownerId, iconfig) + File.separator + "routingtable.kns"));
SocialKadRoutingTable irtbl = new JsonSocialKadRoutingTableSerializer(iconfig).read(din);
/**
* @section Read the node state
*/
din = new DataInputStream(new FileInputStream(getStateStorageFolderName(ownerId, iconfig) + File.separator + "node.kns"));
Node inode = new JsonSerializer<Node>().read(din);
/**
* @section Read the DHT
*/
din = new DataInputStream(new FileInputStream(getStateStorageFolderName(ownerId, iconfig) + File.separator + "dht.kns"));
DHT idht = new JsonDHTSerializer().read(din);
idht.setConfiguration(iconfig);
return new KademliaNode(ownerId, inode, ikad.getPort(), idht, irtbl, iconfig);
}
/**
* @return Node The local node for this system
*/
public Node getNode()
{
return this.localNode;
}
/**
* @return The KadServer used to send/receive messages
*/
public KadServer getServer()
{
return this.server;
}
/**
* @return The DHT for this kad instance
*/
public DHT getDHT()
{
return this.dht;
}
/**
* @return The current KadConfiguration object being used
*/
public KadConfiguration getCurrentConfiguration()
{
return this.config;
}
public synchronized final void bootstrap(Node n) throws IOException, RoutingException
{
long startTime = System.nanoTime();
Operation op = new ConnectOperation(this.server, this, n, this.config);
op.execute();
long endTime = System.nanoTime();
this.statistician.setBootstrapTime(endTime - startTime);
}
/**
* Stores the specified value under the given key
* This value is stored on K nodes on the network, or all nodes if there are > K total nodes in the network
*
* @param content The content to put onto the DHT
*
* @return Integer How many nodes the content was stored on
*
* @throws java.io.IOException
*
*/
public synchronized int put(KadContent content) throws IOException
{
StoreOperation sop = new StoreOperation(this.server, this, content, this.dht, this.config);
sop.execute();
/* Return how many nodes the content was stored on */
return sop.numNodesStoredAt();
}
/**
* Put the data on the network and also cache a copy locally
*
* @param content The content to store
*
* @return How many nodes the content has been stored at excluding the local node.
*
* @throws java.io.IOException
*/
public synchronized int putAndCache(KadContent content) throws IOException
{
this.cache(content);
return this.put(content);
}
/**
* Store a content on the local node's DHT
*
* @param content The content to put on the DHT
*
* @throws java.io.IOException
*/
public synchronized void putLocally(KadContent content) throws IOException
{
this.dht.store(content);
}
/**
* Stores the specified value under the given key locally;
* This content is permanently stored locally and will not be deleted unless the cache is cleared.
*
* @param content The content to put onto the local DHT
*
* @throws java.io.IOException
*
*/
public synchronized void cache(KadContent content) throws IOException
{
this.dht.cache(content);
}
private synchronized void cache(StorageEntry entry) throws IOException
{
this.dht.cache(entry);
}
/**
* Get some content cached locally on the DHT.
*
* @param param The parameters used to search for the content
*
* @return DHTContent The content
*
* @throws java.io.IOException
*/
public StorageEntry getCachedContent(GetParameter param) throws NoSuchElementException, IOException
{
return this.dht.get(param);
}
/**
* Method called to do an updated of a content in the local storage; this method updates both cached and un-cached content.
*
* @param param The parameters of the content to update
*
* @return StorageEntry with the updated content
*
* @throws java.io.IOException
* @throws kademlia.exceptions.UpToDateContentException
*/
public StorageEntry updateContentLocally(GetParameterFUC param) throws IOException, UpToDateContentException, NoSuchElementException
{
if (this.dht.contains(param))
{
return this.getUpdated(param);
}
else
{
throw new NoSuchElementException("KademliaNode.updateContentLocally(): This content is not a part of the DHT. ");
}
}
/**
* Get some content stored on the DHT
*
* @param param The parameters used to search for the content
*
* @return DHTContent The content
*
* @throws java.io.IOException
* @throws kademlia.exceptions.ContentNotFoundException
*/
public StorageEntry get(GetParameter param) throws NoSuchElementException, IOException, ContentNotFoundException
{
if (this.dht.contains(param))
{
/* The content is on our DHT */
StorageEntry e = this.dht.get(param);
if (e.getContentMetadata().isCached())
{
/**
* If it's cached, we check for an updated version
*
* @note Here we don't log the statistic because the getUpdated will log for us
*/
GetParameterFUC gpf = new GetParameterFUC(e.getContentMetadata());
try
{
/* Get and return an updated version of the content */
return this.getUpdated(gpf);
}
catch (UpToDateContentException ex)
{
/* well the version we have is the latest, lets just return that */
return e;
}
}
else
{
/* If it's not cached, we just return it since our node is one of the K-Closest */
return e;
}
}
/* Seems like it doesn't exist in our DHT, get it from other Nodes */
long startTime = System.nanoTime();
ContentLookupOperation clo = new ContentLookupOperation(server, this, param, this.config);
clo.execute();
long endTime = System.nanoTime();
this.statistician.addContentLookup(endTime - startTime, clo.routeLength());
return clo.getContentFound();
}
/**
* Get a content and cache it.
*
* @param gp
*
* @return The StorageEntry with the content
*
* @throws java.io.IOException
* @throws kademlia.exceptions.ContentNotFoundException
*/
public StorageEntry getAndCache(final GetParameter gp) throws IOException, ContentNotFoundException
{
StorageEntry e = this.get(gp);
this.cache(e);
return e;
}
/**
* Get some content stored on the DHT if there is a newer version than our current version.
*
* @param param The parameters used to search for the content
*
* @return StorageEntry The content
*
* @throws java.io.IOException
* @throws kademlia.exceptions.UpToDateContentException
*/
public StorageEntry getUpdated(GetParameterFUC param) throws IOException, UpToDateContentException
{
/* Seems like it doesn't exist in our DHT, get it from other Nodes */
long startTime = System.nanoTime();
ContentLookupOperationFUC clo = new ContentLookupOperationFUC(server, this, param, this.config);
clo.execute();
long endTime = System.nanoTime();
this.statistician.addContentLookupFUC(endTime - startTime, clo.routeLength(), clo.newerContentExist());
StorageEntry latest = clo.getContentFound();
/* If we have this content locally, lets update it too */
try
{
this.dht.update(latest);
}
catch (NoSuchElementException ex)
{
/* Any exception here will be if we don't have the content... just ignore it */
}
return latest;
}
/**
* Allow the user of the System to call refresh even out of the normal Kad refresh timing
*
* @throws java.io.IOException
*/
public void refresh() throws IOException
{
new KadRefreshOperation(this.server, this, this.dht, this.config).execute();
}
/**
* @return String The ID of the owner of this local network
*/
public String getOwnerId()
{
return this.ownerId;
}
/**
* @return Integer The port on which this kad instance is running
*/
public int getPort()
{
return this.udpPort;
}
/**
* Here we handle properly shutting down the Kademlia instance
*
* @param saveState Whether to save the application state or not
*
* @throws java.io.FileNotFoundException
*/
public void shutdown(final boolean saveState) throws IOException
{
/* Shut down the server */
this.server.shutdown();
this.stopRefreshOperation();
/* Save this Kademlia instance's state if required */
if (saveState)
{
/* Save the system state */
this.saveKadState();
}
}
/**
* Saves the node state to a text file
*
* @throws java.io.FileNotFoundException
*/
private void saveKadState() throws IOException
{
DataOutputStream dout;
/**
* @section Store Basic Kad data
*/
dout = new DataOutputStream(new FileOutputStream(getStateStorageFolderName(this.ownerId, this.config) + File.separator + "kad.kns"));
new JsonSerializer<KademliaNode>().write(this, dout);
/**
* @section Save the node state
*/
dout = new DataOutputStream(new FileOutputStream(getStateStorageFolderName(this.ownerId, this.config) + File.separator + "node.kns"));
new JsonSerializer<Node>().write(this.localNode, dout);
/**
* @section Save the routing table
* We need to save the routing table separate from the node since the routing table will contain the node and the node will contain the routing table
* This will cause a serialization recursion, and in turn a Stack Overflow
*/
dout = new DataOutputStream(new FileOutputStream(getStateStorageFolderName(this.ownerId, this.config) + File.separator + "routingtable.kns"));
new JsonSocialKadRoutingTableSerializer(this.config).write(this.getRoutingTable(), dout);
/**
* @section Save the DHT
*/
dout = new DataOutputStream(new FileOutputStream(getStateStorageFolderName(this.ownerId, this.config) + File.separator + "dht.kns"));
new JsonDHTSerializer().write(this.dht, dout);
}
/**
* Get the name of the folder for which a content should be stored
*
* @return String The name of the folder to store node states
*/
private static String getStateStorageFolderName(String ownerId, KadConfiguration iconfig)
{
/* Setup the nodes storage folder if it doesn't exist */
String path = iconfig.getNodeDataFolder(ownerId) + File.separator + "nodeState";
File nodeStateFolder = new File(path);
if (!nodeStateFolder.isDirectory())
{
nodeStateFolder.mkdir();
}
return nodeStateFolder.toString();
}
/**
* @return The routing table for this node.
*/
public SocialKadRoutingTable getRoutingTable()
{
return this.routingTable;
}
/**
* @return The statistician that manages all statistics
*/
public SocialKadStatistician getStatistician()
{
return this.statistician;
}
/**
* Creates a string containing all data about this Kademlia instance
*
* @return The string representation of this Kad instance
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder("\n\nPrinting Kad State for instance with owner: ");
sb.append(this.ownerId);
sb.append("\n\n");
sb.append("\n");
sb.append("Local Node");
sb.append(this.localNode);
sb.append("\n");
sb.append("\n");
sb.append("Routing Table: ");
sb.append(this.getRoutingTable());
sb.append("\n");
sb.append("\n");
sb.append("DHT: ");
sb.append(this.dht);
sb.append("\n");
sb.append("\n\n\n");
return sb.toString();
}
}
|
package com.github.miachm.SODS.spreadsheet;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.fail;
public class RangeTest {
@Test
public void testClear() throws Exception {
Sheet sheet = new Sheet("A");
Range range = sheet.getDataRange();
range.setValue(1);
range.clear();
assertNull(range.getValue());
sheet.insertColumnAfter(0);
sheet.insertRowAfter(0);
range = sheet.getDataRange();
range.setValues(1,2,3,4);
range.clear();
Object[][] values = range.getValues();
for (Object[] row : values)
for (Object value : row)
assertNull(value);
}
@Test
public void testCopyTo() throws Exception {
Sheet sheet = new Sheet("A");
sheet.insertColumnsAfter(0,3);
sheet.insertRowAfter(0);
Range range = sheet.getDataRange();
range.setValues(1,2,3,4,5,6,7,8);
Range origin = sheet.getRange(0,0,2,2);
Range dest = sheet.getRange(0,2,2,2);
origin.copyTo(dest);
Object[][] values = dest.getValues();
assertEquals(values[0][0],1);
assertEquals(values[1][0],5);
assertEquals(values[0][1],2);
assertEquals(values[1][1],6);
}
@Test
public void testGetCell() throws Exception {
Sheet sheet = new Sheet("A");
sheet.insertColumnsAfter(0,2);
sheet.insertRowAfter(0);
Range range = sheet.getDataRange();
range.setValues(1,2,3,4,5,6);
assertEquals(sheet.getCell(0,0).getValue(),1);
assertEquals(sheet.getCell(0,1).getValue(),2);
assertEquals(sheet.getCell(0,2).getValue(),3);
assertEquals(sheet.getCell(1,0).getValue(),4);
assertEquals(sheet.getCell(1,1).getValue(),5);
assertEquals(sheet.getCell(1,2).getValue(),6);
}
@Test
public void testGetColumn() throws Exception {
Sheet sheet = new Sheet("A");
sheet.appendRows(10);
sheet.appendColumns(10);
for (int i = 0;i < sheet.getMaxRows()/2;i++) {
for (int j = 0; j < sheet.getMaxColumns()/2; j++) {
Range range = sheet.getRange(i,j,2,2);
assertEquals(range.getColumn(),j);
}
}
}
@Test
public void testGetFormula() throws Exception {
fail("Not implemented");
}
@Test
public void testGetFormulas() throws Exception {
fail("Not implemented");
}
@Test
public void testGetLastColumn() throws Exception {
Sheet sheet = new Sheet("A");
sheet.appendRows(10);
sheet.appendColumns(10);
for (int i = 0;i < sheet.getMaxRows()/2;i++) {
for (int j = 0; j < sheet.getMaxColumns()/2; j++) {
Range range = sheet.getRange(i,j,2,2);
assertEquals(range.getLastColumn(),j+1);
}
}
}
@Test
public void testGetLastRow() throws Exception {
Sheet sheet = new Sheet("A");
sheet.appendRows(10);
sheet.appendColumns(10);
for (int i = 0;i < sheet.getMaxRows()/2;i++) {
for (int j = 0; j < sheet.getMaxColumns()/2; j++) {
Range range = sheet.getRange(i,j,2,2);
assertEquals(range.getLastRow(),i+1);
}
}
}
@Test
public void testGetNumColumns() throws Exception {
Sheet sheet = new Sheet("A");
sheet.appendRows(10);
sheet.appendColumns(10);
for (int i = 0;i < sheet.getMaxRows()/2;i++) {
for (int j = 0; j < sheet.getMaxColumns()/2; j++) {
Range range = sheet.getRange(i,j,3,2);
assertEquals(range.getNumColumns(),2);
}
}
}
@Test
public void testGetNumRows() throws Exception {
Sheet sheet = new Sheet("A");
sheet.appendRows(10);
sheet.appendColumns(10);
for (int i = 0;i < sheet.getMaxRows()/2;i++) {
for (int j = 0; j < sheet.getMaxColumns()/2; j++) {
Range range = sheet.getRange(i,j,3,2);
assertEquals(range.getNumRows(),3);
}
}
}
@Test
public void testGetRow() throws Exception {
Sheet sheet = new Sheet("A");
sheet.appendRows(10);
sheet.appendColumns(10);
for (int i = 0;i < sheet.getMaxRows()/2;i++) {
for (int j = 0; j < sheet.getMaxColumns() / 2; j++) {
Range range = sheet.getRange(i, j, 2, 2);
assertEquals(range.getRow(), i);
}
}
}
@Test
public void testGetSheet() throws Exception {
Sheet sheet = new Sheet("A");
Range range = sheet.getDataRange();
Sheet parent = range.getSheet();
assertEquals(sheet,parent);
}
@Test
public void testGetValue() throws Exception {
Sheet sheet = new Sheet("A");
sheet.appendRow();
sheet.appendColumn();
Range range = sheet.getDataRange();
range.setValues(1,2,3,4);
assertEquals(range.getValue(),1);
range = sheet.getRange(1,1);
assertEquals(range.getValue(),4);
}
@Test
public void testGetValues() throws Exception {
Sheet sheet = new Sheet("A");
sheet.appendRow();
sheet.appendColumn();
Range range = sheet.getDataRange();
range.setValues(1,2,3,4);
Object[][] arr = range.getValues();
assertEquals(arr[0][0],1);
assertEquals(arr[0][1],2);
assertEquals(arr[1][0],3);
assertEquals(arr[1][1],4);
}
@Test
public void testGetNumValues() throws Exception {
}
@Test
public void testSetValue() throws Exception {
}
@Test
public void testSetValues() throws Exception {
}
@Test
public void testSetValues1() throws Exception {
}
}
|
package learn;
import gcm2sbml.parser.GCMFile;
import lhpn2sbml.parser.LHPNFile;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.prefs.Preferences;
import javax.swing.*;
import org.sbml.libsbml.*;
import biomodelsim.*;
/**
* This class creates a GUI for the Learn program. It implements the
* ActionListener class. This allows the GUI to perform actions when menu items
* and buttons are selected.
*
* @author Curtis Madsen
*/
public class LearnLHPN extends JPanel implements ActionListener, Runnable {
private static final long serialVersionUID = -5806315070287184299L;
private JButton save, run, viewLhpn, saveLhpn, viewLog; // the run button
private JComboBox debug; // debug combo box
private JTextField iteration;
// private JTextField windowRising, windowSize;
private JComboBox numBins;
private JCheckBox basicFBP;
private ArrayList<ArrayList<Component>> variables;
private JPanel variablesPanel;
private JRadioButton user, auto, range, points;
private JButton suggest;
private String directory, lrnFile;
private JLabel numBinsLabel;
private Log log;
private String separator;
private BioSim biosim;
private String learnFile, binFile, lhpnFile;
private boolean change;
private ArrayList<String> variablesList;
private boolean firstRead;
/**
* This is the constructor for the Learn class. It initializes all the input
* fields, puts them on panels, adds the panels to the frame, and then
* displays the frame.
*/
public LearnLHPN(String directory, Log log, BioSim biosim) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
this.biosim = biosim;
this.log = log;
this.directory = directory;
String[] getFilename = directory.split(separator);
lrnFile = getFilename[getFilename.length - 1] + ".lrn";
binFile = getFilename[getFilename.length - 1] + ".bins";
lhpnFile = getFilename[getFilename.length - 1] + ".g";
Preferences biosimrc = Preferences.userRoot();
// Sets up the encodings area
JPanel radioPanel = new JPanel(new BorderLayout());
JPanel selection1 = new JPanel();
JPanel selection2 = new JPanel();
JPanel selection = new JPanel(new BorderLayout());
/*
* spacing = new JRadioButton("Equal Spacing Of Bins"); data = new
* JRadioButton("Equal Data Per Bins");
*/
range = new JRadioButton("Minimize Range of Rates");
points = new JRadioButton("Equalize Points Per Bin");
user = new JRadioButton("Use User Generated Levels");
auto = new JRadioButton("Use Auto Generated Levels");
suggest = new JButton("Suggest Levels");
ButtonGroup select = new ButtonGroup();
select.add(auto);
select.add(user);
ButtonGroup select2 = new ButtonGroup();
select2.add(range);
select2.add(points);
// if (biosimrc.get("biosim.learn.autolevels", "").equals("Auto")) {
// auto.setSelected(true);
// else {
// user.setSelected(true);
user.addActionListener(this);
range.addActionListener(this);
auto.addActionListener(this);
suggest.addActionListener(this);
// if (biosimrc.get("biosim.learn.equaldata", "").equals("Equal Data Per
// Bins")) {
// data.setSelected(true);
// else {
range.setSelected(true);
points.addActionListener(this);
selection1.add(points);
selection1.add(range);
selection2.add(auto);
selection2.add(user);
selection2.add(suggest);
auto.setSelected(true);
selection.add(selection1, "North");
selection.add(selection2, "Center");
suggest.setEnabled(false);
JPanel encodingPanel = new JPanel(new BorderLayout());
variablesPanel = new JPanel();
JPanel sP = new JPanel();
((FlowLayout) sP.getLayout()).setAlignment(FlowLayout.LEFT);
sP.add(variablesPanel);
JLabel encodingsLabel = new JLabel("Variable Levels:");
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(260, 200));
scroll2.setPreferredSize(new Dimension(276, 132));
scroll2.setViewportView(sP);
radioPanel.add(selection, "North");
radioPanel.add(encodingPanel, "Center");
encodingPanel.add(encodingsLabel, "North");
encodingPanel.add(scroll2, "Center");
// Sets up initial network and experiments text fields
// JPanel initNet = new JPanel();
// JLabel initNetLabel = new JLabel("Background Knowledge Network:");
// browseInit = new JButton("Browse");
// browseInit.addActionListener(this);
// initNetwork = new JTextField(39);
// initNet.add(initNetLabel);
// initNet.add(initNetwork);
// initNet.add(browseInit);
// Sets up the thresholds area
JPanel thresholdPanel2 = new JPanel(new GridLayout(8, 2));
JPanel thresholdPanel1 = new JPanel(new GridLayout(4, 2));
JLabel backgroundLabel = new JLabel("Linked Background file:");
JTextField backgroundField = new JTextField(lhpnFile);
backgroundField.setEditable(false);
thresholdPanel1.add(backgroundLabel);
thresholdPanel1.add(backgroundField);
JLabel iterationLabel = new JLabel("Iterations of Optimization Algorithm");
iteration = new JTextField("10000");
thresholdPanel1.add(iterationLabel);
thresholdPanel1.add(iteration);
/*
* JLabel activationLabel = new JLabel("Ratio For Activation (Ta):");
* thresholdPanel2.add(activationLabel); activation = new
* JTextField(biosimrc.get("biosim.learn.ta", "")); //
* activation.addActionListener(this); thresholdPanel2.add(activation);
* JLabel repressionLabel = new JLabel("Ratio For Repression (Tr):");
* thresholdPanel2.add(repressionLabel); repression = new
* JTextField(biosimrc.get("biosim.learn.tr", "")); //
* repression.addActionListener(this); thresholdPanel2.add(repression);
* JLabel influenceLevelLabel = new JLabel("Merge Influence Vectors
* Delta (Tm):"); thresholdPanel2.add(influenceLevelLabel);
* influenceLevel = new JTextField(biosimrc.get("biosim.learn.tm", "")); //
* influenceLevel.addActionListener(this);
* thresholdPanel2.add(influenceLevel); JLabel letNThroughLabel = new
* JLabel("Minimum Number Of Initial Vectors (Tn): ");
* thresholdPanel1.add(letNThroughLabel); letNThrough = new
* JTextField(biosimrc.get("biosim.learn.tn", "")); //
* letNThrough.addActionListener(this);
* thresholdPanel1.add(letNThrough); JLabel maxVectorSizeLabel = new
* JLabel("Maximum Influence Vector Size (Tj):");
* thresholdPanel1.add(maxVectorSizeLabel); maxVectorSize = new
* JTextField(biosimrc.get("biosim.learn.tj", "")); //
* maxVectorSize.addActionListener(this);
* thresholdPanel1.add(maxVectorSize); JLabel parentLabel = new
* JLabel("Score For Empty Influence Vector (Ti):");
* thresholdPanel1.add(parentLabel); parent = new
* JTextField(biosimrc.get("biosim.learn.ti", ""));
* parent.addActionListener(this); thresholdPanel1.add(parent); JLabel
* relaxIPDeltaLabel = new JLabel("Relax Thresholds Delta (Tt):");
* thresholdPanel2.add(relaxIPDeltaLabel); relaxIPDelta = new
* JTextField(biosimrc.get("biosim.learn.tt", "")); //
* relaxIPDelta.addActionListener(this);
* thresholdPanel2.add(relaxIPDelta);
*/
numBinsLabel = new JLabel("Number of Bins:");
String[] bins = { "2", "3", "4", "5", "6", "7", "8", "9" };
numBins = new JComboBox(bins);
numBins.setSelectedItem(biosimrc.get("biosim.learn.bins", ""));
numBins.addActionListener(this);
numBins.setActionCommand("text");
thresholdPanel1.add(numBinsLabel);
thresholdPanel1.add(numBins);
JPanel thresholdPanelHold1 = new JPanel();
thresholdPanelHold1.add(thresholdPanel1);
JLabel debugLabel = new JLabel("Debug Level:");
String[] options = new String[4];
options[0] = "0";
options[1] = "1";
options[2] = "2";
options[3] = "3";
debug = new JComboBox(options);
// debug.setSelectedItem(biosimrc.get("biosim.learn.debug", ""));
debug.addActionListener(this);
thresholdPanel2.add(debugLabel);
thresholdPanel2.add(debug);
// succ = new JRadioButton("Successors");
// pred = new JRadioButton("Predecessors");
// both = new JRadioButton("Both");
// if (biosimrc.get("biosim.learn.succpred", "").equals("Successors")) {
// succ.setSelected(true);
// else if (biosimrc.get("biosim.learn.succpred",
// "").equals("Predecessors")) {
// pred.setSelected(true);
// else {
// both.setSelected(true);
// succ.addActionListener(this);
// pred.addActionListener(this);
// both.addActionListener(this);
basicFBP = new JCheckBox("Basic FindBaseProb");
// if (biosimrc.get("biosim.learn.findbaseprob", "").equals("True")) {
// basicFBP.setSelected(true);
// else {
basicFBP.setSelected(false);
basicFBP.addActionListener(this);
// ButtonGroup succOrPred = new ButtonGroup();
// succOrPred.add(succ);
// succOrPred.add(pred);
// succOrPred.add(both);
JPanel three = new JPanel();
// three.add(succ);
// three.add(pred);
// three.add(both);
((FlowLayout) three.getLayout()).setAlignment(FlowLayout.LEFT);
thresholdPanel2.add(three);
thresholdPanel2.add(new JPanel());
thresholdPanel2.add(basicFBP);
thresholdPanel2.add(new JPanel());
// JPanel thresholdPanelHold2 = new JPanel();
// thresholdPanelHold2.add(thresholdPanel2);
/*
* JLabel windowRisingLabel = new JLabel("Window Rising Amount:");
* windowRising = new JTextField("1");
* thresholdPanel2.add(windowRisingLabel);
* thresholdPanel2.add(windowRising); JLabel windowSizeLabel = new
* JLabel("Window Size:"); windowSize = new JTextField("1");
* thresholdPanel2.add(windowSizeLabel);
* thresholdPanel2.add(windowSize); harshenBoundsOnTie = new
* JCheckBox("Harshen Bounds On Tie");
* harshenBoundsOnTie.setSelected(true); donotInvertSortOrder = new
* JCheckBox("Do Not Invert Sort Order");
* donotInvertSortOrder.setSelected(true); seedParents = new
* JCheckBox("Parents Should Be Ranked By Score");
* seedParents.setSelected(true); mustNotWinMajority = new
* JCheckBox("Must Not Win Majority");
* mustNotWinMajority.setSelected(true); donotTossSingleRatioParents =
* new JCheckBox("Single Ratio Parents Should Be Kept");
* donotTossChangedInfluenceSingleParents = new JCheckBox( "Parents That
* Change Influence Should Not Be Tossed");
* thresholdPanel2.add(harshenBoundsOnTie);
* thresholdPanel2.add(donotInvertSortOrder);
* thresholdPanel2.add(seedParents);
* thresholdPanel2.add(mustNotWinMajority);
* thresholdPanel2.add(donotTossSingleRatioParents);
* thresholdPanel2.add(donotTossChangedInfluenceSingleParents);
*/
// load parameters
Properties load = new Properties();
learnFile = "";
try {
FileInputStream in = new FileInputStream(new File(directory + separator + lrnFile));
load.load(in);
in.close();
if (load.containsKey("learn.file")) {
String[] getProp = load.getProperty("learn.file").split(separator);
learnFile = directory.substring(0, directory.length()
- getFilename[getFilename.length - 1].length())
+ separator + getProp[getProp.length - 1];
backgroundField.setText(getProp[getProp.length - 1]);
}
if (load.containsKey("learn.iter")) {
iteration.setText(load.getProperty("learn.iter"));
}
if (load.containsKey("learn.bins")) {
numBins.setSelectedItem(load.getProperty("learn.bins"));
}
if (load.containsKey("learn.equal")) {
if (load.getProperty("learn.equal").equals("range")) {
range.setSelected(true);
}
else {
points.setSelected(true);
}
}
if (load.containsKey("learn.use")) {
if (load.getProperty("learn.use").equals("auto")) {
auto.setSelected(true);
}
else if (load.getProperty("learn.use").equals("user")) {
user.setSelected(true);
}
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
variablesList = new ArrayList<String>();
LHPNFile lhpn = new LHPNFile(log);
lhpn.load(learnFile);
HashMap<String, Properties> variablesMap = lhpn.getVariables();
for (String s : variablesMap.keySet()) {
variablesList.add(s);
}
try {
FileWriter write = new FileWriter(new File(directory + separator + "background.g"));
BufferedReader input = new BufferedReader(new FileReader(new File(learnFile)));
String line = null;
while ((line = input.readLine()) != null) {
write.write(line + "\n");
}
write.close();
input.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to create background file!",
"Error Writing Background", JOptionPane.ERROR_MESSAGE);
}
// sortSpecies();
JPanel runHolder = new JPanel();
autogen(false);
if (auto.isSelected()) {
auto.doClick();
}
else {
user.doClick();
}
// Creates the run button
run = new JButton("Save and Learn");
runHolder.add(run);
run.addActionListener(this);
run.setMnemonic(KeyEvent.VK_L);
// Creates the run button
save = new JButton("Save Parameters");
runHolder.add(save);
save.addActionListener(this);
save.setMnemonic(KeyEvent.VK_S);
// Creates the view circuit button
viewLhpn = new JButton("View Circuit");
runHolder.add(viewLhpn);
viewLhpn.addActionListener(this);
viewLhpn.setMnemonic(KeyEvent.VK_V);
// Creates the save circuit button
saveLhpn = new JButton("Save Circuit");
runHolder.add(saveLhpn);
saveLhpn.addActionListener(this);
saveLhpn.setMnemonic(KeyEvent.VK_C);
// Creates the view circuit button
viewLog = new JButton("View Run Log");
runHolder.add(viewLog);
viewLog.addActionListener(this);
viewLog.setMnemonic(KeyEvent.VK_R);
if (!(new File(directory + separator + lhpnFile).exists())) {
viewLhpn.setEnabled(false);
saveLhpn.setEnabled(false);
}
if (!(new File(directory + separator + "run.log").exists())) {
viewLog.setEnabled(false);
}
// Creates the main panel
this.setLayout(new BorderLayout());
JPanel middlePanel = new JPanel(new BorderLayout());
JPanel firstTab = new JPanel(new BorderLayout());
JPanel firstTab1 = new JPanel(new BorderLayout());
// JPanel secondTab = new JPanel(new BorderLayout());
middlePanel.add(radioPanel, "Center");
// firstTab1.add(initNet, "North");
firstTab1.add(thresholdPanelHold1, "Center");
firstTab.add(firstTab1, "North");
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, middlePanel, null);
splitPane.setDividerSize(0);
// secondTab.add(thresholdPanelHold2, "North");
firstTab.add(splitPane, "Center");
// JTabbedPane tab = new JTabbedPane();
// tab.addTab("Basic Options", firstTab);
// tab.addTab("Advanced Options", secondTab);
// this.add(tab, "Center");
this.add(firstTab, "Center");
// this.add(runHolder, "South");
firstRead = true;
// if (user.isSelected()) {
// auto.doClick();
// user.doClick();
// else {
// user.doClick();
// auto.doClick();
firstRead = false;
change = false;
}
/**
* This method performs different functions depending on what menu items or
* buttons are selected.
*/
public void actionPerformed(ActionEvent e) {
/*
* if (e.getActionCommand().contains("box")) { int num =
* Integer.parseInt(e.getActionCommand().substring(3)) - 1; if
* (!((JCheckBox) this.species.get(num).get(0)).isSelected()) {
* ((JComboBox) this.species.get(num).get(2)).setSelectedItem("0");
* editText(num); speciesPanel.revalidate(); speciesPanel.repaint(); for
* (int i = 1; i < this.species.get(num).size(); i++) {
* this.species.get(num).get(i).setEnabled(false); } } else {
* this.species.get(num).get(1).setEnabled(true); if (user.isSelected()) {
* for (int i = 2; i < this.species.get(num).size(); i++) {
* this.species.get(num).get(i).setEnabled(true); } } } } else
*/
change = true;
if (e.getActionCommand().contains("text")) {
// int num = Integer.parseInt(e.getActionCommand().substring(4)) -
if (variables != null && user.isSelected()) {
for (int i = 0; i < variables.size(); i++) {
editText(i);
}
}
variablesPanel.revalidate();
variablesPanel.repaint();
biosim.setGlassPane(true);
}
else if (e.getSource() == numBins || e.getSource() == debug) {
biosim.setGlassPane(true);
}
else if (e.getSource() == user) {
if (!firstRead) {
try {
FileWriter write = new FileWriter(new File(directory + separator + binFile));
// write.write("time 0\n");
for (int i = 0; i < variables.size(); i++) {
if (((JTextField) variables.get(i).get(0)).getText().trim().equals("")) {
write.write("?");
}
else {
write.write(((JTextField) variables.get(i).get(0)).getText().trim());
}
// write.write(" " + ((JComboBox)
// variables.get(i).get(1)).getSelectedItem());
for (int j = 2; j < variables.get(i).size(); j++) {
if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) {
write.write(" ?");
}
else {
write.write(" "
+ ((JTextField) variables.get(i).get(j)).getText().trim());
}
}
write.write("\n");
}
write.close();
}
catch (Exception e1) {
}
}
numBinsLabel.setEnabled(false);
numBins.setEnabled(false);
suggest.setEnabled(true);
// levelsBin();
variablesPanel.revalidate();
variablesPanel.repaint();
levels();
}
else if (e.getSource() == auto) {
numBinsLabel.setEnabled(true);
numBins.setEnabled(true);
suggest.setEnabled(false);
for (Component c : variablesPanel.getComponents()) {
for (int i = 1; i < ((JPanel) c).getComponentCount(); i++) {
((JPanel) c).getComponent(i).setEnabled(false);
}
}
}
else if (e.getSource() == suggest) {
autogen(false);
variablesPanel.revalidate();
variablesPanel.repaint();
}
// if the browse initial network button is clicked
// else if (e.getSource() == browseInit) {
// Buttons.browse(this, new File(initNetwork.getText().trim()),
// initNetwork,
// JFileChooser.FILES_ONLY, "Open");
// if the run button is selected
else if (e.getSource() == run) {
save();
new Thread(this).start();
}
else if (e.getSource() == save) {
save();
}
else if (e.getSource() == viewLhpn) {
viewLhpn();
}
else if (e.getSource() == viewLog) {
viewLog();
}
else if (e.getSource() == saveLhpn) {
saveLhpn();
}
}
private void autogen(boolean readfile) {
try {
if (!readfile) {
FileWriter write = new FileWriter(new File(directory + separator + binFile));
// write.write("time 0\n");
for (int i = 0; i < variables.size(); i++) {
if (((JTextField) variables.get(i).get(0)).getText().trim().equals("")) {
write.write("?");
}
else {
write.write(((JTextField) variables.get(i).get(0)).getText().trim());
}
// write.write(" " + ((JComboBox)
// variables.get(i).get(1)).getSelectedItem());
for (int j = 3; j < variables.get(i).size(); j++) {
if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) {
write.write(" ?");
}
else {
write.write(" "
+ ((JTextField) variables.get(i).get(j)).getText().trim());
}
}
write.write("\n");
}
write.close();
// Integer numThresh =
// Integer.parseInt(numBins.getSelectedItem().toString()) - 1;
// Thread myThread = new Thread(this);
new Thread(this).start();
}
}
catch (Exception e1) {
levels();
}
}
private void levels() {
ArrayList<String> str = null;
try {
Scanner f = new Scanner(new File(directory + separator + binFile));
str = new ArrayList<String>();
while (f.hasNextLine()) {
str.add(f.nextLine());
}
}
catch (Exception e1) {
}
if (!directory.equals("")) {
if (true) {
variablesPanel.removeAll();
this.variables = new ArrayList<ArrayList<Component>>();
variablesPanel.setLayout(new GridLayout(variablesList.size() + 1, 1));
int max = 0;
if (str != null) {
for (String st : str) {
String[] getString = st.split("\\s");
max = Math.max(max, getString.length + 1);
}
}
JPanel label = new JPanel(new GridLayout());
// label.add(new JLabel("Use"));
label.add(new JLabel("Variables"));
label.add(new JLabel("DMV"));
label.add(new JLabel("Number Of Bins"));
for (int i = 0; i < max - 3; i++) {
label.add(new JLabel("Level " + (i + 1)));
}
variablesPanel.add(label);
int j = 0;
for (String s : variablesList) {
j++;
JPanel sp = new JPanel(new GridLayout());
ArrayList<Component> specs = new ArrayList<Component>();
// JCheckBox check = new JCheckBox();
// check.setSelected(true);
// specs.add(check);
specs.add(new JTextField(s));
String[] options = { "2", "3", "4", "5", "6", "7", "8", "9" };
JComboBox combo = new JComboBox(options);
String[] dmvOptions = { "", "Yes", "No" };
JComboBox dmv = new JComboBox(dmvOptions);
dmv.setSelectedIndex(0);
combo.setSelectedItem(numBins.getSelectedItem());
specs.add(dmv);
specs.add(combo);
((JTextField) specs.get(0)).setEditable(false);
// sp.add(specs.get(0));
// ((JCheckBox) specs.get(0)).addActionListener(this);
// ((JCheckBox) specs.get(0)).setActionCommand("box" + j);
sp.add(specs.get(0));
sp.add(specs.get(1));
sp.add(specs.get(2));
((JComboBox) specs.get(2)).addActionListener(this);
((JComboBox) specs.get(2)).setActionCommand("text" + j);
this.variables.add(specs);
if (str != null) {
boolean found = false;
for (String st : str) {
String[] getString = st.split(" ");
if (getString[0].trim().equals(".dmvc")) {
for (int i = 1; i < getString.length; i++) {
if (getString[i].equals(s)) {
((JComboBox) specs.get(1)).setSelectedItem("Yes");
break;
}
}
}
else if (getString[0].trim().equals(s)) {
found = true;
if (getString.length >= 1) {
((JComboBox) specs.get(2))
.setSelectedItem(getString.length - 1);
for (int i = 0; i < Integer
.parseInt((String) ((JComboBox) specs.get(2))
.getSelectedItem()) - 1; i++) {
if (getString[i + 1].trim().equals("?")) {
specs.add(new JTextField(""));
}
else {
specs.add(new JTextField(getString[i + 1].trim()));
}
sp.add(specs.get(i + 3));
}
for (int i = Integer.parseInt((String) ((JComboBox) specs
.get(2)).getSelectedItem()) - 1; i < max - 3; i++) {
sp.add(new JLabel());
}
}
}
if (((JComboBox) specs.get(1)).getSelectedItem().equals("")) {
((JComboBox) specs.get(1)).setSelectedItem("No");
}
}
if (!found) {
for (int i = 0; i < Integer
.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem()) - 1; i++) {
specs.add(new JTextField(""));
sp.add(specs.get(i + 3));
}
for (int i = Integer.parseInt((String) ((JComboBox) specs.get(2))
.getSelectedItem()) - 1; i < max - 3; i++) {
sp.add(new JLabel());
}
}
}
else {
for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(2))
.getSelectedItem()) - 1; i++) {
specs.add(new JTextField(""));
sp.add(specs.get(i + 3));
}
}
variablesPanel.add(sp);
}
}
}
editText(0);
}
/*
* private void levelsBin() { if (!directory.equals("")) { // File n = null; //
* for (File f : new File(directory).listFiles()) { // if
* (f.getAbsolutePath().contains(".tsd")) { // n = f; // } // } if (true) { //
* if (n != null) { // ArrayList<String> species = new ArrayList<String>(); //
* try { // InputStream input = new FileInputStream(n); // boolean reading =
* true; // char cha; // while (reading) { // String word = ""; // boolean
* readWord = true; // while (readWord) { // int read = input.read(); // if
* (read == -1) { // reading = false; // readWord = false; // } // cha =
* (char) read; // if (Character.isWhitespace(cha)) { // word += cha; // } //
* else if (cha == ',' || cha == ':' || cha == ';' || cha == '\"' || cha // ==
* '\'' // || cha == '(' || cha == ')' || cha == '[' || cha == ']') { // if
* (!word.equals("") && !word.equals("time")) { // try { //
* Double.parseDouble(word); // } // catch (Exception e2) { //
* species.add(word); // } // } // word = ""; // } // else if (read != -1) { //
* word += cha; // } // } // } // input.close(); // } // catch (Exception
* e1) { // } speciesPanel.removeAll(); this.species = new ArrayList<ArrayList<Component>>();
* speciesPanel.setLayout(new GridLayout(speciesList.size() + 1, 1)); JPanel
* label = new JPanel(new GridLayout()); // label.add(new JLabel("Use"));
* label.add(new JLabel("Species")); label.add(new JLabel("Number Of
* Bins")); for (int i = 0; i < Integer.parseInt((String)
* numBins.getSelectedItem()) - 1; i++) { label.add(new JLabel("Level " + (i +
* 1))); } speciesPanel.add(label); int j = 0; for (String s : speciesList) {
* j++; JPanel sp = new JPanel(new GridLayout()); ArrayList<Component>
* specs = new ArrayList<Component>(); // JCheckBox check = new
* JCheckBox(); // check.setSelected(true); // specs.add(check);
* specs.add(new JTextField(s)); String[] options = { "0", "1", "2", "3",
* "4", "5", "6", "7", "8", "9" }; JComboBox combo = new JComboBox(options);
* combo.setSelectedItem(numBins.getSelectedItem()); specs.add(combo);
* ((JTextField) specs.get(0)).setEditable(false); // sp.add(specs.get(0)); //
* ((JCheckBox) specs.get(0)).addActionListener(this); // ((JCheckBox)
* specs.get(0)).setActionCommand("box" + j); sp.add(specs.get(0));
* sp.add(specs.get(1)); ((JComboBox) specs.get(1)).addActionListener(this);
* ((JComboBox) specs.get(1)).setActionCommand("text" + j);
* this.species.add(specs); for (int i = 0; i < Integer.parseInt((String)
* ((JComboBox) specs.get(1)) .getSelectedItem()) - 1; i++) { specs.add(new
* JTextField("")); sp.add(specs.get(i + 2)); } speciesPanel.add(sp); } } } }
*/
private void editText(int num) {
try {
ArrayList<Component> specs = variables.get(num);
Component[] panels = variablesPanel.getComponents();
int boxes = Integer.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem());
if ((specs.size() - 3) < boxes) {
for (int i = 0; i < boxes - 1; i++) {
try {
specs.get(i + 3);
}
catch (Exception e1) {
JTextField temp = new JTextField("");
((JPanel) panels[num + 1]).add(temp);
specs.add(temp);
}
}
}
else {
try {
if (boxes > 0) {
while (true) {
specs.remove(boxes + 2);
((JPanel) panels[num + 1]).remove(boxes + 2);
}
}
else if (boxes == 0) {
while (true) {
specs.remove(2);
((JPanel) panels[num + 1]).remove(2);
}
}
}
catch (Exception e1) {
}
}
int max = 0;
for (int i = 0; i < this.variables.size(); i++) {
max = Math.max(max, variables.get(i).size());
}
if (((JPanel) panels[0]).getComponentCount() < max) {
for (int i = 0; i < max - 2; i++) {
try {
((JPanel) panels[0]).getComponent(i + 2);
}
catch (Exception e) {
((JPanel) panels[0]).add(new JLabel("Level " + (i)));
}
}
}
else {
try {
while (true) {
((JPanel) panels[0]).remove(max);
}
}
catch (Exception e) {
}
}
for (int i = 1; i < panels.length; i++) {
JPanel sp = (JPanel) panels[i];
for (int j = sp.getComponentCount() - 1; j >= 2; j
if (sp.getComponent(j) instanceof JLabel) {
sp.remove(j);
}
}
if (max > sp.getComponentCount()) {
for (int j = sp.getComponentCount(); j < max; j++) {
sp.add(new JLabel());
}
}
else {
for (int j = sp.getComponentCount() - 2; j >= max; j
sp.remove(j);
}
}
}
}
catch (Exception e) {
}
}
public void saveLhpn() {
try {
if (true) {// (new File(directory + separator +
// "method.gcm").exists()) {
String copy = JOptionPane.showInputDialog(biosim.frame(), "Enter Circuit Name:",
"Save Circuit", JOptionPane.PLAIN_MESSAGE);
if (copy != null) {
copy = copy.trim();
}
else {
return;
}
if (!copy.equals("")) {
if (copy.length() > 1) {
if (!copy.substring(copy.length() - 2).equals(".g")) {
copy += ".g";
}
}
else {
copy += ".g";
}
}
biosim.saveLhpn(copy, directory + separator + lhpnFile);
}
else {
JOptionPane.showMessageDialog(biosim.frame(), "No circuit has been generated yet.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to save circuit.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewLhpn() {
try {
File work = new File(directory);
if (new File(directory + separator + lhpnFile).exists()) {
String dotFile = lhpnFile.replace(".lhpn", ".dot");
File dot = new File(directory + separator + dotFile);
dot.delete();
String command = "open " + dotFile;
log.addText("Executing:\n" + "open " + directory + separator + dotFile + "\n");
Runtime exec = Runtime.getRuntime();
Process load = exec.exec("atacs -cPllodpl " + lhpnFile + " " + dotFile, null, work);
load.waitFor();
if (dot.exists()) {
exec.exec(command, null, work);
}
else {
File log = new File(directory + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(biosim.frame(), "No circuit has been generated yet.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to view circuit.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewLog() {
try {
if (new File(directory + separator + "run.log").exists()) {
File log = new File(directory + separator + "run.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Run Log",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(biosim.frame(), "No run log exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to view run log.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void save() {
try {
Properties prop = new Properties();
FileInputStream in = new FileInputStream(new File(directory + separator + lrnFile));
prop.load(in);
in.close();
prop.setProperty("learn.file", learnFile);
prop.setProperty("learn.iter", this.iteration.getText().trim());
prop.setProperty("learn.bins", (String) this.numBins.getSelectedItem());
if (range.isSelected()) {
prop.setProperty("learn.equal", "range");
}
else {
prop.setProperty("learn.equal", "points");
}
if (auto.isSelected()) {
prop.setProperty("learn.use", "auto");
}
else {
prop.setProperty("learn.use", "user");
}
log.addText("Saving learn parameters to file:\n" + directory + separator + lrnFile
+ "\n");
FileOutputStream out = new FileOutputStream(new File(directory + separator + lrnFile));
prop.store(out, learnFile);
out.close();
String[] tempBin = lrnFile.split("\\.");
String binFile = tempBin[0] + ".bins";
FileWriter write = new FileWriter(new File(directory + separator + binFile));
boolean flag = false;
for (int i = 0; i < variables.size(); i++) {
if (((JComboBox) variables.get(i).get(1)).getSelectedItem().equals("Yes")) {
if (!flag) {
write.write(".dmvc ");
flag = true;
}
write.write(((JTextField) variables.get(i).get(0)).getText().trim() + " ");
}
if (flag) {
// write.write("\n");
}
}
for (int i = 0; i < variables.size(); i++) {
if (((JTextField) variables.get(i).get(0)).getText().trim().equals("")) {
write.write("?");
}
else {
write.write(((JTextField) variables.get(i).get(0)).getText().trim());
}
// write.write(", " + ((JComboBox)
// variables.get(i).get(1)).getSelectedItem());
for (int j = 3; j < variables.get(i).size(); j++) {
if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) {
write.write(" ?");
}
else {
write.write(" " + ((JTextField) variables.get(i).get(j)).getText().trim());
}
}
write.write("\n");
}
write.close();
log.addText("Creating levels file:\n" + directory + separator + binFile + "\n");
// String command = "autogenT.py -b" + binFile + " -t"
// + numBins.getSelectedItem().toString() + " -i" +
// iteration.getText();
// if (range.isSelected()) {
// command = command + " -cr";
// File work = new File(directory);
// Runtime.getRuntime().exec(command, null, work);
change = false;
}
catch (Exception e1) {
// e1.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(), "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
}
public void learn() {
try {
if (auto.isSelected()) {
FileWriter write = new FileWriter(new File(directory + separator + binFile));
for (int i = 0; i < variables.size(); i++) {
if (((JTextField) variables.get(i).get(0)).getText().trim().equals("")) {
write.write("?");
}
else {
write.write(((JTextField) variables.get(i).get(0)).getText().trim());
}
// write.write(", " + ((JComboBox)
// variables.get(i).get(1)).getSelectedItem());
for (int j = 3; j < variables.get(i).size(); j++) {
write.write(" ?");
}
write.write("\n");
}
write.close();
// bins.waitFor();
}
new Thread(this).start();
String command = "data2lhpn.py -b" + binFile + " -l" + lhpnFile;
log.addText("Executing:\n" + command + " " + directory + "\n");
File work = new File(directory);
Process run = Runtime.getRuntime().exec(command, null, work);
run.waitFor();
command = "atacs -lloddl " + lhpnFile;
Runtime.getRuntime().exec(command, null, work);
}
catch (Exception e) {
}
}
public void run() {
try {
File work = new File(directory);
final JFrame running = new JFrame("Progress");
String makeBin = "autogenT.py -b" + binFile + " -i" + iteration.getText();
if (range.isSelected()) {
makeBin = makeBin + " -cr";
}
log.addText(makeBin);
// log.addText("Creating levels file:\n" + directory + separator
// + binFile + "\n");
final Process bins = Runtime.getRuntime().exec(makeBin, null, work);
final JButton cancel = new JButton("Cancel");
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
cancel.doClick();
running.dispose();
}
public void windowOpened(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowActivated(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
};
running.addWindowListener(w);
JPanel text = new JPanel();
JPanel progBar = new JPanel();
JPanel button = new JPanel();
JPanel all = new JPanel(new BorderLayout());
JLabel label = new JLabel("Running...");
JProgressBar progress = new JProgressBar(0, Integer.parseInt(iteration.getText()));
progress.setStringPainted(true);
// progress.setString("");
progress.setValue(0);
text.add(label);
progBar.add(progress);
button.add(cancel);
all.add(text, "North");
all.add(progBar, "Center");
all.add(button, "South");
running.setContentPane(all);
running.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = running.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
running.setLocation(x, y);
running.setVisible(true);
running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
cancel.setActionCommand("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bins.destroy();
running.setCursor(null);
running.dispose();
}
});
biosim.getExitButton().setActionCommand("Exit program");
biosim.getExitButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bins.destroy();
running.setCursor(null);
running.dispose();
}
});
try {
String output = "";
InputStream reb = bins.getInputStream();
InputStreamReader isr = new InputStreamReader(reb);
BufferedReader br = new BufferedReader(isr);
FileWriter out = new FileWriter(new File(directory + separator + "run.log"));
int count = 0;
while ((output = br.readLine()) != null) {
if (output.matches("\\d+/\\d+")) {
// log.addText(output);
count += 500;
progress.setValue(count);
}
out.write(output);
out.write("\n");
}
br.close();
isr.close();
reb.close();
out.close();
viewLog.setEnabled(true);
}
catch (Exception e) {
}
int exitValue = bins.waitFor();
if (exitValue == 143) {
JOptionPane.showMessageDialog(biosim.frame(), "Learning was"
+ " canceled by the user.", "Canceled Learning", JOptionPane.ERROR_MESSAGE);
}
running.setCursor(null);
running.dispose();
levels();
}
catch (Exception e1) {
}
}
public boolean hasChanged() {
return change;
}
public boolean isComboSelected() {
if (debug.isFocusOwner() || numBins.isFocusOwner()) {
return true;
}
if (variables == null) {
return false;
}
for (int i = 0; i < variables.size(); i++) {
if (((JComboBox) variables.get(i).get(1)).isFocusOwner()
|| ((JComboBox) variables.get(i).get(2)).isFocusOwner()) {
return true;
}
}
return false;
}
public boolean getViewLhpnEnabled() {
return viewLhpn.isEnabled();
}
public boolean getSaveLhpnEnabled() {
return saveLhpn.isEnabled();
}
public boolean getViewLogEnabled() {
return viewLog.isEnabled();
}
public void updateSpecies(String newLearnFile) {
learnFile = newLearnFile;
variablesList = new ArrayList<String>();
if ((learnFile.contains(".sbml")) || (learnFile.contains(".xml"))) {
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(learnFile);
Model model = document.getModel();
ListOf ids = model.getListOfSpecies();
try {
FileWriter write = new FileWriter(
new File(directory + separator + "background.gcm"));
write.write("digraph G {\n");
for (int i = 0; i < model.getNumSpecies(); i++) {
variablesList.add(((Species) ids.get(i)).getId());
write.write("s" + i + " [shape=ellipse,color=black,label=\""
+ ((Species) ids.get(i)).getId() + "\"" + "];\n");
}
write.write("}\n");
write.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to create background file!",
"Error Writing Background", JOptionPane.ERROR_MESSAGE);
}
}
else {
GCMFile gcm = new GCMFile();
gcm.load(learnFile);
HashMap<String, Properties> speciesMap = gcm.getSpecies();
for (String s : speciesMap.keySet()) {
variablesList.add(s);
}
try {
FileWriter write = new FileWriter(
new File(directory + separator + "background.gcm"));
BufferedReader input = new BufferedReader(new FileReader(new File(learnFile)));
String line = null;
while ((line = input.readLine()) != null) {
write.write(line + "\n");
}
write.close();
input.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to create background file!",
"Error Writing Background", JOptionPane.ERROR_MESSAGE);
}
}
sortVariables();
if (user.isSelected()) {
auto.doClick();
user.doClick();
}
else {
user.doClick();
auto.doClick();
}
}
private void sortVariables() {
int i, j;
String index;
for (i = 1; i < variablesList.size(); i++) {
index = variablesList.get(i);
j = i;
while ((j > 0) && variablesList.get(j - 1).compareToIgnoreCase(index) > 0) {
variablesList.set(j, variablesList.get(j - 1));
j = j - 1;
}
variablesList.set(j, index);
}
}
public void setDirectory(String directory) {
this.directory = directory;
String[] getFilename = directory.split(separator);
lrnFile = getFilename[getFilename.length - 1] + ".lrn";
}
}
|
package learn;
//import gcm2sbml.parser.GCMFile;
import lhpn2sbml.parser.LhpnFile;
import lhpn2sbml.parser.Lpn2verilog;
import parser.*;
import java.awt.*;
import java.awt.List;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.prefs.Preferences;
import java.util.regex.*;
//import java.util.regex.Pattern;
import javax.swing.*;
//import org.sbml.libsbml.*;
import biomodelsim.*;
import org.jdesktop.layout.*;
/**
* This class creates a GUI for the Learn program. It implements the
* ActionListener class. This allows the GUI to perform actions when menu items
* and buttons are selected.
*
* @author Curtis Madsen
*/
public class LearnLHPN extends JPanel implements ActionListener, Runnable, ItemListener { // added ItemListener SB
private static final long serialVersionUID = -5806315070287184299L;
private JButton save, run, viewLhpn, saveLhpn, viewLog; // the run button
private JButton viewCoverage;
private JButton viewVHDL,viewVerilog;
private JComboBox debug; // debug combo box
private JTextField iteration, backgroundField, propertyG;
// private JTextField windowRising, windowSize;
private JComboBox numBins;
private JCheckBox basicFBP;
private ArrayList<ArrayList<Component>> variables;
private JPanel variablesPanel; //, basicOpt, advancedOpt;
private JRadioButton user, auto, range, points;
private JButton suggest;
private String directory, lrnFile;
private JLabel numBinsLabel;
private Log log;
private String separator;
private BioSim biosim;
private String learnFile, lhpnFile;
private boolean change, fail;
private ArrayList<String> variablesList;
private boolean firstRead, generate, execute;
private ArrayList<Variable> reqdVarsL;
private ArrayList<Integer> reqdVarIndices;
private ArrayList<ArrayList<Double>> data;
private ArrayList<String> varNames;
private int[][] bins;
private ArrayList<ArrayList<Double>> divisionsL;
private HashMap<String, ArrayList<Double>> thresholds;
private Double[][] rates;
private Double[] duration;
private int dmvcCnt = 0;
private int pathLength ; //= 7 ;// intFixed 25 pd 7 integrator 15;
private int rateSampling ; //= -1 ; //intFixed 250; 20; //-1;
private boolean placeRates = true;
private LhpnFile g;
private Integer numPlaces = 0;
private Integer numTransitions = 0;
HashMap<String, Properties> placeInfo;
HashMap<String, Properties> transitionInfo;
HashMap<String, Properties> cvgInfo;
/*
* public enum PType { RATE, DMVC, PROP, ASGN, TRACE }
*/
private Double minDelayVal = 10.0;
private Double minRateVal = 10.0;
private Double minDivisionVal = 100.0;
// private String decPercent;
// private boolean limitExists;
private Double delayScaleFactor = 1.0;
private Double varScaleFactor = 1.0;
BufferedWriter out;
File logFile;
// Threshold parameters
private double epsilon ;//= 0.1; // What is the +/- epsilon where signals are considered to be equivalent
private int runLength ; //= 15; // the number of time points that a value must persist to be considered constant
private double runTime ; // = 5e-12; // 10e-6 for intFixed; 5e-6 for integrator. 5e-12 for pd;// the amount of time that must pass to be considered constant when using absoluteTime
private boolean absoluteTime ; // = true; // true for intfixed //false; true for pd; false for integrator// when False time points are used to determine DMVC and when true absolutime time is used to determine DMVC
private double percent ; // = 0.8; // a decimal value representing the percent of the total trace that must be constant to qualify to become a DMVC var
private JTextField epsilonG;
private JTextField percentG;
private JCheckBox absTimeG;
private JTextField pathLengthG;
private JTextField rateSamplingG;
private JTextField runTimeG;
private JTextField runLengthG;
private boolean suggestIsSource = false;
private Double[] lowerLimit;
private Double[] upperLimit;
private String[] transEnablingsVHDL;
private String[][] transIntAssignVHDL;
private String[] transDelayAssignVHDL;
private String[] transEnablingsVAMS;
private String[] transConditionalsVAMS;
private String[][] transIntAssignVAMS;
private String[] transDelayAssignVAMS;
private String failPropVHDL;
private HashMap<String, Properties> transientNetPlaces;
private HashMap<String, Properties> transientNetTransitions;
private ArrayList<String> ratePlaces;
private ArrayList<String> dmvcInputPlaces;
private ArrayList<String> propPlaces;
private boolean vamsRandom = false;
private ArrayList<String> allVars;
private Thread LearnThread;
// private int[] numValuesL;// the number of constant values for each variable...-1 indicates that the variable isn't considered a DMVC variable
// private double vaRateUpdateInterval = 1e-6;// how often the rate is added
// to the continuous variable in the Verilog-A model output
// Pattern lParenR = Pattern.compile("\\(+"); //SB
//Pattern floatingPointNum = Pattern.compile(">=(-*[0-9]+\\.*[0-9]*)"); //SB
// Pattern absoluteTimeR = Pattern.compile(".absoluteTime"); //SB
// Pattern falseR = Pattern.compile("false",Pattern.CASE_INSENSITIVE); //pass the I flag to be case insensitive
/**
* This is the constructor for the Learn class. It initializes all the input
* fields, puts them on panels, adds the panels to the frame, and then
* displays the frame.
*/
public LearnLHPN(String directory, Log log, BioSim biosim) {
if (File.separator.equals("\\")) {
separator = "\\\\";
} else {
separator = File.separator;
}
this.biosim = biosim;
this.log = log;
this.directory = directory;
String[] getFilename = directory.split(separator);
lrnFile = getFilename[getFilename.length - 1] + ".lrn";
// binFile = getFilename[getFilename.length - 1] + ".bins";
// newBinFile = getFilename[getFilename.length - 1] + "_NEW" + ".bins";
lhpnFile = getFilename[getFilename.length - 1] + ".lpn";
Preferences biosimrc = Preferences.userRoot();
// Sets up the encodings area
JPanel radioPanel = new JPanel(new BorderLayout());
JPanel selection1 = new JPanel();
JPanel selection2 = new JPanel();
JPanel selection = new JPanel(new BorderLayout());
/*
* spacing = new JRadioButton("Equal Spacing Of Bins"); data = new
* JRadioButton("Equal Data Per Bins");
*/
range = new JRadioButton("Minimize Range of Rates");
points = new JRadioButton("Equalize Points Per Bin");
user = new JRadioButton("Use User Generated Levels");
auto = new JRadioButton("Use Auto Generated Levels");
suggest = new JButton("Suggest Levels");
ButtonGroup select = new ButtonGroup();
select.add(auto);
select.add(user);
ButtonGroup select2 = new ButtonGroup();
select2.add(range);
select2.add(points);
// if (biosimrc.get("biosim.learn.autolevels", "").equals("Auto")) {
// auto.setSelected(true);
// else {
// user.setSelected(true);
user.addActionListener(this);
range.addActionListener(this);
auto.addActionListener(this);
suggest.addActionListener(this);
// if (biosimrc.get("biosim.learn.equaldata", "").equals("Equal Data Per
// Bins")) {
// data.setSelected(true);
// else {
range.setSelected(true);
points.addActionListener(this);
selection1.add(points);
selection1.add(range);
selection2.add(auto);
selection2.add(user);
selection2.add(suggest);
auto.setSelected(true);
selection.add(selection1, "North");
selection.add(selection2, "Center");
suggest.setEnabled(false);
JPanel encodingPanel = new JPanel(new BorderLayout());
variablesPanel = new JPanel();
JPanel sP = new JPanel();
((FlowLayout) sP.getLayout()).setAlignment(FlowLayout.LEFT);
sP.add(variablesPanel);
JLabel encodingsLabel = new JLabel("Variable Levels:");
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(260, 200));
scroll2.setPreferredSize(new Dimension(276, 132));
scroll2.setViewportView(sP);
radioPanel.add(selection, "North");
radioPanel.add(encodingPanel, "Center");
encodingPanel.add(encodingsLabel, "North");
encodingPanel.add(scroll2, "Center");
// Sets up initial network and experiments text fields
// JPanel initNet = new JPanel();
// JLabel initNetLabel = new JLabel("Background Knowledge Network:");
// browseInit = new JButton("Browse");
// browseInit.addActionListener(this);
// initNetwork = new JTextField(39);
// initNet.add(initNetLabel);
// initNet.add(initNetwork);
// initNet.add(browseInit);
// Sets up the thresholds area
JPanel thresholdPanel2 = new JPanel(new GridLayout(8, 2));
JPanel thresholdPanel1 = new JPanel(new GridLayout(4, 2));
JLabel backgroundLabel = new JLabel("Model File:");
backgroundField = new JTextField(lhpnFile);
backgroundField.setEditable(false);
thresholdPanel1.add(backgroundLabel);
thresholdPanel1.add(backgroundField);
JLabel iterationLabel = new JLabel("Iterations of Optimization Algorithm");
iteration = new JTextField("10");
thresholdPanel1.add(iterationLabel);
thresholdPanel1.add(iteration);
JLabel rateLabel = new JLabel("Rate calculation parameters");
JLabel epsilonLabel = new JLabel("Epsilon");
epsilonG = new JTextField("0.1");
JLabel pathLengthLabel = new JLabel("Minimum Pathlength");//("Pathlength");
pathLengthG = new JTextField("0");
JLabel rateSamplingLabel = new JLabel("Window Size");//("Rate Sampling");
rateSamplingG = new JTextField("-1");
JLabel dmvcLabel = new JLabel("DMV determination parameters");
JLabel absTimeLabel = new JLabel("Absolute Time");
absTimeG = new JCheckBox();
absTimeG.setSelected(false);
absTimeG.addItemListener(this);
JLabel percentLabel = new JLabel("Fraction");
percentG = new JTextField("0.8");
JLabel runTimeLabel = new JLabel("DMV Run Time");
runTimeG = new JTextField("5e-6");
runTimeG.setEnabled(false);
JLabel runLengthLabel = new JLabel("DMV Run Length");
runLengthG = new JTextField("2");
runLengthG.setEnabled(true);
epsilonG.addActionListener(this);
pathLengthG.addActionListener(this);
rateSamplingG.addActionListener(this);
percentG.addActionListener(this);
runTimeG.addActionListener(this);
runLengthG.addActionListener(this);
JPanel newPanel = new JPanel();
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(epsilonLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 85, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 104, Short.MAX_VALUE)
.add(epsilonG, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE))
.add(jPanel1Layout.createSequentialGroup()
.add(rateSamplingLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(129, 129, 129)
.add(rateSamplingG, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE))
.add(jPanel1Layout.createSequentialGroup()
.add(pathLengthLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
.add(68, 68, 68)
.add(pathLengthG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 81, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
.add(jPanel1Layout.createSequentialGroup()
.add(60, 60, 60)
.add(rateLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 186, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel1Layout.linkSize(new java.awt.Component[] {epsilonG, pathLengthG, rateSamplingG}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(rateLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(51, 51, 51)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(epsilonLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(epsilonG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(rateSamplingLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(rateSamplingG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(pathLengthLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(pathLengthG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(35, 35, 35))
);
jPanel1Layout.linkSize(new java.awt.Component[] {epsilonG, epsilonLabel, pathLengthG, pathLengthLabel, rateSamplingG, rateSamplingLabel}, org.jdesktop.layout.GroupLayout.VERTICAL);
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel2Layout.createSequentialGroup()
.addContainerGap(140, Short.MAX_VALUE)
.add(dmvcLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 206, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(85, 85, 85))
.add(jPanel2Layout.createSequentialGroup()
.add(83, 83, 83)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel2Layout.createSequentialGroup()
.add(percentLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 112, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(percentG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.add(jPanel2Layout.createSequentialGroup()
.add(absTimeLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 85, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(31, 31, 31)
.add(absTimeG)
.add(30, 30, 30))))
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
.add(73, 73, 73)
.add(runTimeLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(runTimeG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(73, Short.MAX_VALUE)
.add(runLengthLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 103, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(runLengthG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 81, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel2Layout.linkSize(new java.awt.Component[] {percentG, runLengthG, runTimeG}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
jPanel2Layout.linkSize(new java.awt.Component[] {absTimeLabel, percentLabel, runLengthLabel, runTimeLabel}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
.add(53, 53, 53)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jPanel2Layout.createSequentialGroup()
.add(dmvcLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(35, 35, 35)
.add(absTimeLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(absTimeG))
.add(18, 18, 18)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, percentLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, percentG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, runTimeLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, runTimeG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, runLengthLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 17, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, runLengthG, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(63, 63, 63))
);
jPanel2Layout.linkSize(new java.awt.Component[] {absTimeLabel, percentG, percentLabel, runLengthG, runLengthLabel, runTimeG, runTimeLabel}, org.jdesktop.layout.GroupLayout.VERTICAL);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(newPanel);
newPanel.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(72, 72, 72)
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 256, Short.MAX_VALUE)
.add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(157, 157, 157))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.add(layout.createSequentialGroup()
.add(56, 56, 56)
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
// divisionsL = new ArrayList<ArrayList<Double>>(); // SB
thresholds = new HashMap<String, ArrayList<Double>>();
reqdVarsL = new ArrayList<Variable>();
/*
* JLabel activationLabel = new JLabel("Ratio For Activation (Ta):");
* thresholdPanel2.add(activationLabel); activation = new
* JTextField(biosimrc.get("biosim.learn.ta", "")); //
* activation.addActionListener(this); thresholdPanel2.add(activation);
* JLabel repressionLabel = new JLabel("Ratio For Repression (Tr):");
* thresholdPanel2.add(repressionLabel); repression = new
* JTextField(biosimrc.get("biosim.learn.tr", "")); //
* repression.addActionListener(this); thresholdPanel2.add(repression);
* JLabel influenceLevelLabel = new JLabel("Merge Influence Vectors
* Delta (Tm):"); thresholdPanel2.add(influenceLevelLabel);
* influenceLevel = new JTextField(biosimrc.get("biosim.learn.tm", "")); //
* influenceLevel.addActionListener(this);
* thresholdPanel2.add(influenceLevel); JLabel letNThroughLabel = new
* JLabel("Minimum Number Of Initial Vectors (Tn): ");
* thresholdPanel1.add(letNThroughLabel); letNThrough = new
* JTextField(biosimrc.get("biosim.learn.tn", "")); //
* letNThrough.addActionListener(this);
* thresholdPanel1.add(letNThrough); JLabel maxVectorSizeLabel = new
* JLabel("Maximum Influence Vector Size (Tj):");
* thresholdPanel1.add(maxVectorSizeLabel); maxVectorSize = new
* JTextField(biosimrc.get("biosim.learn.tj", "")); //
* maxVectorSize.addActionListener(this);
* thresholdPanel1.add(maxVectorSize); JLabel parentLabel = new
* JLabel("Score For Empty Influence Vector (Ti):");
* thresholdPanel1.add(parentLabel); parent = new
* JTextField(biosimrc.get("biosim.learn.ti", ""));
* parent.addActionListener(this); thresholdPanel1.add(parent); JLabel
* relaxIPDeltaLabel = new JLabel("Relax Thresholds Delta (Tt):");
* thresholdPanel2.add(relaxIPDeltaLabel); relaxIPDelta = new
* JTextField(biosimrc.get("biosim.learn.tt", "")); //
* relaxIPDelta.addActionListener(this);
* thresholdPanel2.add(relaxIPDelta);
*/
numBinsLabel = new JLabel("Number of Bins:");
String[] bins = { "0", "2", "3", "4", "5", "6", "7", "8", "16", "32"};//, "10", "11", "12", "13", "14", "15", "16", "17", "33", "65", "129", "257" };
numBins = new JComboBox(bins);
numBins.setSelectedItem(biosimrc.get("biosim.learn.bins", ""));
numBins.addActionListener(this);
numBins.setActionCommand("text");
thresholdPanel1.add(numBinsLabel);
thresholdPanel1.add(numBins);
JLabel propertyLabel = new JLabel("Assertion to be Verified");
propertyG = new JTextField("");
thresholdPanel1.add(propertyLabel);
thresholdPanel1.add(propertyG);
JPanel thresholdPanelHold1 = new JPanel();
thresholdPanelHold1.add(thresholdPanel1);
JLabel debugLabel = new JLabel("Debug Level:");
String[] options = new String[4];
options[0] = "0";
options[1] = "1";
options[2] = "2";
options[3] = "3";
debug = new JComboBox(options);
// debug.setSelectedItem(biosimrc.get("biosim.learn.debug", ""));
debug.addActionListener(this);
thresholdPanel2.add(debugLabel);
thresholdPanel2.add(debug);
// succ = new JRadioButton("Successors");
// pred = new JRadioButton("Predecessors");
// both = new JRadioButton("Both");
// if (biosimrc.get("biosim.learn.succpred", "").equals("Successors")) {
// succ.setSelected(true);
// else if (biosimrc.get("biosim.learn.succpred",
// "").equals("Predecessors")) {
// pred.setSelected(true);
// else {
// both.setSelected(true);
// succ.addActionListener(this);
// pred.addActionListener(this);
// both.addActionListener(this);
basicFBP = new JCheckBox("Basic FindBaseProb");
// if (biosimrc.get("biosim.learn.findbaseprob", "").equals("True")) {
// basicFBP.setSelected(true);
// else {
basicFBP.setSelected(false);
basicFBP.addActionListener(this);
// ButtonGroup succOrPred = new ButtonGroup();
// succOrPred.add(succ);
// succOrPred.add(pred);
// succOrPred.add(both);
JPanel three = new JPanel();
// three.add(succ);
// three.add(pred);
// three.add(both);
((FlowLayout) three.getLayout()).setAlignment(FlowLayout.LEFT);
thresholdPanel2.add(three);
thresholdPanel2.add(new JPanel());
thresholdPanel2.add(basicFBP);
thresholdPanel2.add(new JPanel());
// JPanel thresholdPanelHold2 = new JPanel();
// thresholdPanelHold2.add(thresholdPanel2);
/*
* JLabel windowRisingLabel = new JLabel("Window Rising Amount:");
* windowRising = new JTextField("1");
* thresholdPanel2.add(windowRisingLabel);
* thresholdPanel2.add(windowRising); JLabel windowSizeLabel = new
* JLabel("Window Size:"); windowSize = new JTextField("1");
* thresholdPanel2.add(windowSizeLabel);
* thresholdPanel2.add(windowSize); harshenBoundsOnTie = new
* JCheckBox("Harshen Bounds On Tie");
* harshenBoundsOnTie.setSelected(true); donotInvertSortOrder = new
* JCheckBox("Do Not Invert Sort Order");
* donotInvertSortOrder.setSelected(true); seedParents = new
* JCheckBox("Parents Should Be Ranked By Score");
* seedParents.setSelected(true); mustNotWinMajority = new
* JCheckBox("Must Not Win Majority");
* mustNotWinMajority.setSelected(true); donotTossSingleRatioParents =
* new JCheckBox("Single Ratio Parents Should Be Kept");
* donotTossChangedInfluenceSingleParents = new JCheckBox( "Parents That
* Change Influence Should Not Be Tossed");
* thresholdPanel2.add(harshenBoundsOnTie);
* thresholdPanel2.add(donotInvertSortOrder);
* thresholdPanel2.add(seedParents);
* thresholdPanel2.add(mustNotWinMajority);
* thresholdPanel2.add(donotTossSingleRatioParents);
* thresholdPanel2.add(donotTossChangedInfluenceSingleParents);
*/
// load parameters
// reading lrnFile twice. On the first read, only learnFile (the initial lpn) is processed.
// In the gap b/w these reads, reqdVarsL is created based on the learnFile
Properties load = new Properties();
learnFile = "";
//int i = 1;
TSDParser extractVars;
ArrayList<String> datFileVars = new ArrayList<String>();
allVars = new ArrayList<String>();
Boolean varPresent = false;
//Finding the intersection of all the variables present in all data files.
for (int i = 1; (new File(directory + separator + "run-" + i + ".tsd")).exists(); i++) {
Properties cProp = new Properties();
extractVars = new TSDParser(directory + separator + "run-" + i + ".tsd", biosim,false);
datFileVars = extractVars.getSpecies();
if (i == 1){
allVars.addAll(datFileVars);
}
for (String s : allVars){
varPresent = false;
for (String t : datFileVars){
if (s.equalsIgnoreCase(t)){
varPresent = true;
break;
}
}
if (!varPresent){
allVars.remove(s);
}
}
}
if (allVars.size() != 0){
if (allVars.get(0).toLowerCase(Locale.ENGLISH).contains("time")){
allVars.remove(0);
}
else{
JOptionPane.showMessageDialog(biosim.frame(),
"Error!",
"AllVars doesnot have time at zeroeth element. Something wrong. Please check time variable", JOptionPane.ERROR_MESSAGE);
}
}
//System.out.println("All variables are : ");
//for (String s : allVars){
// System.out.print(s + " ");
try {
FileInputStream in = new FileInputStream(new File(directory
+ separator + lrnFile));
load.load(in);
in.close();
if (load.containsKey("learn.file")) {
String[] getProp = load.getProperty("learn.file").split(
separator);
learnFile = directory.substring(0, directory.length()
- getFilename[getFilename.length - 1].length())
+ separator + getProp[getProp.length - 1];
backgroundField.setText(getProp[getProp.length - 1]);
}
} catch (IOException e) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
variablesList = new ArrayList<String>();
LhpnFile lhpn = new LhpnFile(log);
// log.addText(learnFile);
lhpn.load(learnFile);
HashMap<String, Properties> variablesMap = lhpn.getContinuous();
for (String s : variablesMap.keySet()) {
variablesList.add(s);
reqdVarsL.add(new Variable(s));
thresholds.put(s, new ArrayList<Double>());
}
// System.out.println(variablesList);
try {
FileInputStream in = new FileInputStream(new File(directory
+ separator + lrnFile));
load.load(in);
in.close();
if (load.containsKey("learn.iter")) {
iteration.setText(load.getProperty("learn.iter"));
}
if (load.containsKey("learn.bins")) {
numBins.setSelectedItem(load.getProperty("learn.bins"));
}
if (load.containsKey("learn.prop")) {
propertyG.setText(load.getProperty("learn.prop"));
}
if (load.containsKey("learn.equal")) {
if (load.getProperty("learn.equal").equals("range")) {
range.setSelected(true);
} else {
points.setSelected(true);
}
}
if (load.containsKey("learn.use")) {
if (load.getProperty("learn.use").equals("auto")) {
auto.setSelected(true);
} else if (load.getProperty("learn.use").equals("user")) {
user.setSelected(true);
}
}
if (load.containsKey("learn.epsilon")){
epsilonG.setText(load.getProperty("learn.epsilon"));
}
if (load.containsKey("learn.rateSampling")){
rateSamplingG.setText(load.getProperty("learn.rateSampling"));
}
if (load.containsKey("learn.pathLength")){
pathLengthG.setText(load.getProperty("learn.pathLength"));
}
if (load.containsKey("learn.percent")){
percentG.setText(load.getProperty("learn.percent"));
}
if (load.containsKey("learn.absTime")){
absTimeG.setSelected(Boolean.parseBoolean(load.getProperty("learn.absTime")));
}
if (load.containsKey("learn.runTime")){
runTimeG.setText(load.getProperty("learn.runTime"));
}
if (load.containsKey("learn.runLength")){
runLengthG.setText(load.getProperty("learn.runLength"));
}
int j = 0;
//levels();
/*while (load.containsKey("learn.bins"+j)){
String s = load.getProperty("learn.bins" + j);
String[] savedBins = s.split("\\s");
//divisionsL.add(new ArrayList<Double>());
//variablesList.add(savedBins[0]);
// ((JComboBox)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(2))).setSelectedItem(savedBins[1]);
for (int i = 2; i < savedBins.length ; i++){
// ((JTextField)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(i+1))).setText(savedBins[i]);
if (j < variablesMap.size()) {
divisionsL.get(j).add(Double.parseDouble(savedBins[i]));
}
}
j++;
}*/
String[] varsList = null;
if (load.containsKey("learn.varsList")){
String varsListString = load.getProperty("learn.varsList");
varsList = varsListString.split("\\s");
for (String st1 : varsList){
boolean varFound = false;
String s = load.getProperty("learn.bins" + st1);
String[] savedBins = null;
if (s != null){
savedBins = s.split("\\s");
}
for (String st2 :variablesList){
if (st1.equalsIgnoreCase(st2)){
varFound = true;
break;
}
}
if (varFound){
if (savedBins != null){
for (int i = 2; i < savedBins.length ; i++){
thresholds.get(st1).add(Double.parseDouble(savedBins[i]));
}
}
}
else{
variablesList.add(st1);
reqdVarsL.add(new Variable(st1));
thresholds.put(st1, new ArrayList<Double>());
if (savedBins != null){
for (int i = 2; i < savedBins.length ; i++){
thresholds.get(st1).add(Double.parseDouble(savedBins[i]));
}
}
}
}
ArrayList<Variable> removeVars = new ArrayList<Variable>();
for (Variable v : reqdVarsL){
boolean varFound = false;
String st1 = v.getName();
for (String st2 : varsList){
if (st1.equalsIgnoreCase(st2)){
varFound = true;
}
}
if (!varFound){
variablesList.remove(st1);
removeVars.add(v);
//reqdVarsL.remove(v); not allowed. concurrent modification exception
thresholds.remove(st1);
}
}
for (Variable v : removeVars){
reqdVarsL.remove(v);
}
/* for (String st1 : varsList){
String s = load.getProperty("learn.bins" + st1);
if (s != null){
String[] savedBins = s.split("\\s");
//divisionsL.add(new ArrayList<Double>());
//variablesList.add(savedBins[0]);
// ((JComboBox)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(2))).setSelectedItem(savedBins[1]);
boolean varFound = false;
if (noLpn){
variablesList.add(st1);
reqdVarsL.add(new Variable(st1));
thresholds.put(st1, new ArrayList<Double>());
}
for (String st2 :variablesList){
if (st1.equalsIgnoreCase(st2)){
varFound = true;
break;
}
}
if (!varFound){
continue;
}
else{
for (int i = 2; i < savedBins.length ; i++){
// ((JTextField)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(i+1))).setText(savedBins[i]);
if (j < variablesMap.size()) {
// divisionsL.get(j).add(Double.parseDouble(savedBins[i]));
thresholds.get(st1).add(Double.parseDouble(savedBins[i]));
}
}
j++;
}
}
}*/
}
// else{ Doing this will clear the selects even first time when created from lpn
// variablesList.clear();
// reqdVarsL.clear();
// thresholds.clear();
if (load.containsKey("learn.inputs")){
String s = load.getProperty("learn.inputs");
String[] savedInputs = s.split("\\s");
for (String st1 : savedInputs){
for (int i = 0; i < reqdVarsL.size(); i++){
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setInput(true);
}
}
}
}
} catch (IOException e) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
try {
FileWriter write = new FileWriter(new File(directory + separator + "background.lpn"));
BufferedReader input = new BufferedReader(new FileReader(new File(learnFile)));
String line = null;
while ((line = input.readLine()) != null) {
write.write(line + "\n");
}
write.close();
input.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to create background file!",
"Error Writing Background", JOptionPane.ERROR_MESSAGE);
}
// sortSpecies();
JPanel runHolder = new JPanel();
autogen(false);
if (auto.isSelected()) {
auto.doClick();
} else {
user.doClick();
}
// Creates the run button
run = new JButton("Save and Learn");
runHolder.add(run);
run.addActionListener(this);
run.setMnemonic(KeyEvent.VK_L);
// Creates the run button
save = new JButton("Save Parameters");
runHolder.add(save);
save.addActionListener(this);
save.setMnemonic(KeyEvent.VK_S);
// Creates the view circuit button
viewLhpn = new JButton("View Circuit");
runHolder.add(viewLhpn);
viewLhpn.addActionListener(this);
viewLhpn.setMnemonic(KeyEvent.VK_V);
// Creates the save circuit button
saveLhpn = new JButton("Save Circuit");
runHolder.add(saveLhpn);
saveLhpn.addActionListener(this);
saveLhpn.setMnemonic(KeyEvent.VK_C);
// Creates the view circuit button
viewLog = new JButton("View Run Log");
runHolder.add(viewLog);
viewLog.addActionListener(this);
viewLog.setMnemonic(KeyEvent.VK_R);
if (!(new File(directory + separator + lhpnFile).exists())) {
viewLhpn.setEnabled(false);
saveLhpn.setEnabled(false);
}
else{
viewLhpn.setEnabled(true);
saveLhpn.setEnabled(true);
}
if (!(new File(directory + separator + "run.log").exists())) {
viewLog.setEnabled(false);
}
viewCoverage = new JButton("View Coverage Report");
viewVHDL = new JButton("View VHDL-AMS Model");
viewVerilog = new JButton("View Verilog-AMS Model");
runHolder.add(viewCoverage);
runHolder.add(viewVHDL);
viewCoverage.addActionListener(this);
viewVHDL.addActionListener(this);
// viewCoverage.setMnemonic(KeyEvent.VK_R);
if (!(new File(directory + separator + "run.cvg").exists())) {
viewCoverage.setEnabled(false);
}
else{
viewCoverage.setEnabled(true);
}
String vhdFile = lhpnFile.replace(".lpn",".vhd");
if (!(new File(directory + separator + vhdFile).exists())) {
viewVHDL.setEnabled(false);
}
else{
viewVHDL.setEnabled(true);
}
// Creates the main panel
this.setLayout(new BorderLayout());
JPanel middlePanel = new JPanel(new BorderLayout());
JPanel firstTab = new JPanel(new BorderLayout());
JPanel firstTab1 = new JPanel(new BorderLayout());
JPanel secondTab = new JPanel(new BorderLayout()); // SB uncommented
middlePanel.add(radioPanel, "Center");
// firstTab1.add(initNet, "North");
firstTab1.add(thresholdPanelHold1, "Center");
firstTab.add(firstTab1, "North");
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
middlePanel, null);
splitPane.setDividerSize(0);
// secondTab.add(thresholdPanelHold2, "North");
// JPanel binsFileHoldPanel = new JPanel();
// binsFileHoldPanel.add(binsFilePanel);
//binsFileHoldPanel.setMinimumSize(new Dimension(10000,16000));
//binsFileHoldPanel.setPreferredSize(getPreferredSize());
//secondTab.add(binsFileHoldPanel, "Center");
secondTab.add(newPanel,"Center");
firstTab.add(splitPane, "Center");
JTabbedPane tab = new JTabbedPane();
tab.addTab("Basic Options", firstTab);
tab.addTab("Advanced Options", secondTab);
this.add(tab, "Center");
//this.addTab("Basic", (JComponent)firstTab);
//this.addTab("Advanced", (JComponent)firstTab);
// this.add(runHolder, "South");
firstRead = true;
// if (user.isSelected()) {
// auto.doClick();
// user.doClick();
// else {
// user.doClick();
// auto.doClick();
firstRead = false;
change = false;
}
/**
* This method performs different functions depending on what menu items or
* buttons are selected.
*/
public void actionPerformed(ActionEvent e) {
/*
* if (e.getActionCommand().contains("box")) { int num =
* Integer.parseInt(e.getActionCommand().substring(3)) - 1; if
* (!((JCheckBox) this.species.get(num).get(0)).isSelected()) {
* ((JComboBox) this.species.get(num).get(2)).setSelectedItem("0");
* editText(num); speciesPanel.revalidate(); speciesPanel.repaint(); for
* (int i = 1; i < this.species.get(num).size(); i++) {
* this.species.get(num).get(i).setEnabled(false); } } else {
* this.species.get(num).get(1).setEnabled(true); if (user.isSelected()) {
* for (int i = 2; i < this.species.get(num).size(); i++) {
* this.species.get(num).get(i).setEnabled(true); } } } } else
*/
change = true;
if (e.getActionCommand().contains("text")) {
// int num = Integer.parseInt(e.getActionCommand().substring(4)) -
if (variables != null && user.isSelected()) { // action source is any of the variables' combobox
for (int i = 0; i < variables.size(); i++) {
editText(i);
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
if (findReqdVarslIndex(currentVar) != -1){ // condition added after adding allVars
int combox_selected = Integer.parseInt((String) ((JComboBox) variables.get(i).get(3)).getSelectedItem()); // changed 2 to 3 after required
/*if (divisionsL.get(i).size() >= combox_selected){
for (int j = divisionsL.get(i).size() - 1; j >= (combox_selected-1) ; j--){
divisionsL.get(i).remove(j); //combox_selected);
}
}*/
//Added for replacing divisionsL by thresholds
ArrayList<Double> iThresholds = thresholds.get(currentVar);
if (combox_selected != 0){
if ((iThresholds != null) && ( iThresholds.size() >= combox_selected)){
for (int j = iThresholds.size() - 1; j >= (combox_selected-1) ; j
thresholds.get(currentVar).remove(j);
}
}
}
else{ // if 0 selected, then remove all the stored thresholds
if ((iThresholds != null) && ( iThresholds.size() >= 1)){
for (int j = iThresholds.size() - 1; j >= 0 ; j
thresholds.get(currentVar).remove(j);
}
}
}
}
}
}
else if ( auto.isSelected()) { // variables != null // action source is numBins on top
int combox_selected = Integer.parseInt((String) numBins.getSelectedItem());
//for (int i = 0; i < variablesList.size(); i++) {//commented after adding allVars
for (int i = 0; i < allVars.size(); i++) {
editText(i); //editText not required??
/*if (divisionsL.get(i).size() >= combox_selected){
for (int j = divisionsL.get(i).size() - 1; j >= (combox_selected-1) ; j--){
divisionsL.get(i).remove(j); //combox_selected);
//thresholds.get(variablesList.get(i)).remove(j); TODO:COULD USE THIS BELOW?
}
}*/
//Added for replacing divisionsL by thresholds
// String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
// int iThresholds = thresholds.get(currentVar).size(); // GIVING EXCEPTION BCOz variables is null when called first;
//String currentVar = variablesList.get(i); //commented after adding allVars
String currentVar = allVars.get(i);
if (findReqdVarslIndex(currentVar) != -1){ // condition added after adding allVars
//int iThresholds = thresholds.get(variablesList.get(i)).size(); //commented after adding allVars
ArrayList<Double> iThresholds = thresholds.get(currentVar);
if (combox_selected != 0){
if ((iThresholds != null) && (iThresholds.size() >= combox_selected)){
for (int j = iThresholds.size() - 1; j >= (combox_selected-1) ; j
thresholds.get(currentVar).remove(j);
}
}
}
else{
if ((iThresholds != null) && ( iThresholds.size() >= 1)){
for (int j = iThresholds.size() - 1; j >= 0; j
thresholds.get(currentVar).remove(j);
}
}
}
}
}
}
variablesPanel.revalidate();
variablesPanel.repaint();
int j = 0;
for (Component c : variablesPanel.getComponents()) {
if (j == 0){ // recheck .. SB
j++;
continue;
}
String s = ((JTextField)((JPanel) c).getComponent(0)).getText().trim();
if (findReqdVarslIndex(s) != -1) { // condition added after adding allVars
((JCheckBox)((JPanel) c).getComponent(1)).setSelected(true); // added after adding allVars
((JCheckBox)((JPanel) c).getComponent(2)).setEnabled(true);// added after adding allVars
// for (int i = 3; i < ((JPanel) c).getComponentCount(); i++) { // added after allVars
// ((JPanel) c).getComponent(i).setEnabled(true); // added after adding allVars
//if (reqdVarsL.get(j-1).isInput()){ changed after adding allVars
if (reqdVarsL.get(findReqdVarslIndex(s)).isInput()){
((JCheckBox)((JPanel) c).getComponent(2)).setSelected(true); // // changed 1 to 2 after required
}
//for (Variable v : reqdVarsL){ //SB after required
// if ((v.getName()).equalsIgnoreCase(((JTextField)((JPanel) c).getComponent(0)).toString())){
// ((JCheckBox)((JPanel) c).getComponent(1)).setSelected(true); // for required
}
else{ // added after adding allVars
((JCheckBox)((JPanel) c).getComponent(1)).setSelected(false);
((JCheckBox)((JPanel) c).getComponent(2)).setEnabled(false);
//((JComboBox)((JPanel) c).getComponent(3)).setEnabled(false);
for (int i = 3; i < ((JPanel) c).getComponentCount(); i++) { // added after allVars
((JPanel) c).getComponent(i).setEnabled(false); // added after adding allVars
}
}
j++;
}
biosim.setGlassPane(true);
} else if (e.getSource() == numBins || e.getSource() == debug) {
biosim.setGlassPane(true);
} else if (e.getActionCommand().contains("dmv")) {
int num = Integer.parseInt(e.getActionCommand().substring(3)) - 1;
editText(num);
} else if (e.getActionCommand().contains("input")) {
//int num = Integer.parseInt(e.getActionCommand().substring(5)); // -1; ??
//reqdVarsL.get(num).setInput(!reqdVarsL.get(num).isInput());
String var = e.getActionCommand().substring(5,e.getActionCommand().length());
/*for (int i = 0; i < reqdVarsL.size() ; i++){ // COMMENTED after adding required
if (var.equalsIgnoreCase(reqdVarsL.get(i).getName())){
reqdVarsL.get(i).setInput(!reqdVarsL.get(i).isInput());
break;
}
}*/
for (int i = 0 ; i < variables.size(); i++){
if ((((JTextField) variables.get(i).get(0)).getText().trim()).equalsIgnoreCase(var)){
if (((JCheckBox) variables.get(i).get(1)).isSelected()){
reqdVarsL.get(findReqdVarslIndex(((JTextField) variables.get(i).get(0)).getText().trim())).setInput(((JCheckBox) variables.get(i).get(2)).isSelected());
}
}
}
}
else if (e.getActionCommand().contains("required")) {
//int num = Integer.parseInt(e.getActionCommand().substring(5)); // -1; ??
//reqdVarsL.get(num).setInput(!reqdVarsL.get(num).isInput());
String var = e.getActionCommand().substring(8,e.getActionCommand().length());
for (int i = 0 ; i < variables.size(); i++){
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
if ((currentVar).equalsIgnoreCase(var)){
if (((JCheckBox) variables.get(i).get(1)).isSelected()){
((JCheckBox) variables.get(i).get(2)).setEnabled(true);
if ( auto.isSelected()) {
//TODO:could disable the comboboxes & thresholds though
// they would already be disabled here.
}
else{
for (int j = 3; j < variables.get(i).size(); j++) { // added after allVars
variables.get(i).get(j).setEnabled(true); // added after adding allVars
}
}
if (findReqdVarslIndex(var) == -1){
reqdVarsL.add(new Variable(var));
}
}
else{
((JCheckBox) variables.get(i).get(2)).setEnabled(false);
for (int j = 3; j < variables.get(i).size(); j++) { // added after allVars
variables.get(i).get(j).setEnabled(false); // added after adding allVars
}
int ind = findReqdVarslIndex(var);
if (ind != -1){
reqdVarsL.remove(ind);
//TODO: Should keep updating reqdVarsIndices all the times??
}
}
}
}
//for (int i = 0; i < reqdVarsL.size() ; i++){
// if (var.equalsIgnoreCase(reqdVarsL.get(i).getName())){
// reqdVarsL.get(i).setInput(!reqdVarsL.get(i).isInput());
// break;
}
else if (e.getSource() == user) {
if (!firstRead) {
try {
for (int i = 0; i < variables.size(); i++) {
/*if (divisionsL.get(i).size() == 0){ // This condition added later.. This ensures that when you switch from auto to user, the options of auto are written to the textboxes. SB.. rechk
for (int j = 4; j < variables.get(i).size(); j++) { // changed 2 to 3 SB
if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) {
//divisionsL.get(i).set(j-3,null);
// if (divisionsL.get(i).size() < (j-3)){
// divisionsL.get(i).set(j-3,null);
// }
// else{
// divisionsL.get(i).add(null);
// }
} else {
//divisionsL.get(i).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
if (divisionsL.get(i).size() <= (j-4)){ // changed 3 to 4 after required
divisionsL.get(i).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
//thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}
else{
divisionsL.get(i).set(j-4,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); // changed 3 to 4 after required
//thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}
}
}
}*/
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
if (findReqdVarslIndex(currentVar) != -1){
((JCheckBox) variables.get(i).get(2)).setEnabled(true);
((JComboBox) variables.get(i).get(3)).setEnabled(true);
ArrayList<Double> iThresholds = thresholds.get(currentVar);
if ((iThresholds == null) || ( iThresholds.size() == 0)){ // This condition added later.. This ensures that when you switch from auto to user, the options of auto are written to the textboxes. SB.. rechk
for (int j = 4; j < variables.get(i).size(); j++) { // changed 2 to 3 SB
if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) {
//divisionsL.get(i).set(j-3,null);
/* if (divisionsL.get(i).size() < (j-3)){
divisionsL.get(i).set(j-3,null);
}
else{
divisionsL.get(i).add(null);
} */
} else {
//divisionsL.get(i).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
if ((iThresholds == null) || (iThresholds.size() <= (j-4))){ // changed 3 to 4 after required
thresholds.get(currentVar).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}
else{
thresholds.get(currentVar).set(j-4,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); // changed 3 to 4 after required
}
}
}
}
}
else{
((JCheckBox) variables.get(i).get(2)).setEnabled(false);
((JComboBox) variables.get(i).get(3)).setEnabled(false);
}
// write.write("\n");
}
// write.close();
} catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to save thresholds!",
"Error saving thresholds", JOptionPane.ERROR_MESSAGE);
}
}
numBinsLabel.setEnabled(false);
numBins.setEnabled(false);
suggest.setEnabled(true);
// levelsBin();
variablesPanel.revalidate();
variablesPanel.repaint();
levels(); // To be added later? if the scaled divisions are not supposed to be shown after auto to user switching, then should have something like divsB4scaling which should be passed as a parameter to levels()
} else if (e.getSource() == auto) {
numBinsLabel.setEnabled(true);
numBins.setEnabled(true);
suggest.setEnabled(false);
//int j = 0; // recheck .. SB
for (Component c : variablesPanel.getComponents()) {
for (int i = 3; i < ((JPanel) c).getComponentCount(); i++) { // changed 1 to 2 SB
((JPanel) c).getComponent(i).setEnabled(false);
}
/* if (j == 0){ // recheck .. SB
j++; // SB
continue; // SB
} //SB
((JCheckBox)((JPanel) c).getComponent(1)).addActionListener(this); // SB
((JCheckBox)((JPanel) c).getComponent(1)).setActionCommand("input" + j); // SB */
}
} else if (e.getSource() == suggest) {
suggestIsSource = true;
autogen(false);
variablesPanel.revalidate();
variablesPanel.repaint();
int j = 0;
for (Component c : variablesPanel.getComponents()) {
if (j == 0){ // recheck .. SB
j++;
continue;
}
String currentVar = ((JTextField)((JPanel) c).getComponent(0)).getText().trim();
int ind = findReqdVarslIndex(currentVar);
if (ind != -1){ //this code shouldn't be required ideally.
if (reqdVarsL.get(ind).isInput()){ //tempPorts.get(j-1)){
((JCheckBox)((JPanel) c).getComponent(2)).setSelected(true); // SB // changed 1 to 2 after required
}
}
j++;
}
}
// if the browse initial network button is clicked
// else if (e.getSource() == browseInit) {
// Buttons.browse(this, new File(initNetwork.getText().trim()),
// initNetwork,
// JFileChooser.FILES_ONLY, "Open");
// if the run button is selected
else if (e.getSource() == run) {
if (!auto.isSelected()){
save();
learn();
}
else{
learn();
}
} else if (e.getSource() == save) {
save();
} else if (e.getSource() == viewLhpn) {
viewLhpn();
} else if (e.getSource() == viewLog) {
viewLog();
} else if (e.getSource() == saveLhpn) {
saveLhpn();
} else if (e.getSource() == viewCoverage) {
viewCoverage();
} else if (e.getSource() == viewVHDL) {
viewVHDL();
} else if (e.getSource() == viewVerilog) {
viewVerilog();
}
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == absTimeG) {
absoluteTime = !absoluteTime;
if (e.getStateChange() == ItemEvent.DESELECTED){
absTimeG.setSelected(false);
runTimeG.setEnabled(false);
runLengthG.setEnabled(true);
}
else{
absTimeG.setSelected(true);
runTimeG.setEnabled(true);
runLengthG.setEnabled(false);
}
}
}
private void autogen(boolean readfile) {
try {
if (!readfile) {
// FileWriter write = new FileWriter(new File(directory + separator + binFile));
// FileWriter writeNew = new FileWriter(new File(directory + separator + newBinFile));
// write.write("time 0\n");
// boolean flag = false;
// for (int i = 0; i < variables.size(); i++) {
// if (((JCheckBox) variables.get(i).get(1)).isSelected()) {
// if (!flag) {
// write.write(".dmvc ");
// writeNew.write(".dmvc ");
// flag = true;
// write.write(((JTextField)
// variables.get(i).get(0)).getText().trim() + " ");
// writeNew.write(((JTextField)
// variables.get(i).get(0)).getText().trim()
// if (flag) {
// write.write("\n");
// writeNew.write("\n");
for (int i = 0; i < variables.size(); i++) {
// if (!((JCheckBox) variables.get(i).get(1)).isSelected())
// if (((JTextField) variables.get(i).get(0)).getText().trim().equals("")) {
// write.write("?");
// writeNew.write("?");
// } else {
// write.write(((JTextField) variables.get(i).get(0)).getText().trim());
// writeNew.write(((JTextField) variables.get(i).get(0)).getText().trim());
// write.write(" " + ((JComboBox)
// variables.get(i).get(1)).getSelectedItem());
for (int j = 4; j < variables.get(i).size(); j++) { // changed 2 to 3 SB
if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) {
// write.write(" ?");
// writeNew.write(" ?");
// divisionsL.get(i).set(j-3,null);
} else {
// write.write(" " + ((JTextField) variables.get(i).get(j)).getText().trim());
// writeNew.write(" " + ((JTextField) variables.get(i).get(j)).getText().trim());
// divisionsL.get(i).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
/* if (divisionsL.get(i).size() <= (j-4)){ // changed 3 to 4 after required
divisionsL.get(i).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}
else{
divisionsL.get(i).set(j-4,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); // changed 3 to 4 after required
//thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}*/
if (thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).size() <= (j-4)){ // changed 3 to 4 after required
thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}
else{
thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).set(j-4,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); // changed 3 to 4 after required
}
}
}
// write.write("\n");
// writeNew.write("\n");
}
// write.close();
// writeNew.close();
// Integer numThresh =
// Integer.parseInt(numBins.getSelectedItem().toString()) - 1;
// Thread myThread = new Thread(this);
generate = true;
execute = false;
LearnThread = new Thread(this);
LearnThread.start();
}
} catch (Exception e1) {
// e1.printStackTrace();
levels();
}
}
private void levels() { // based on the current data, create/update the variablesPanel???
/* ArrayList<String> str = null;
try {
Scanner f = new Scanner(new File(directory + separator + binFile));
// log.addText(directory + separator + binFile);
str = new ArrayList<String>();
str.add(f.nextLine());
while (f.hasNextLine()) {
str.add(f.nextLine());
}
f.close();
// System.out.println("here " + str.toString());
} catch (Exception e1) {
} */
if (!directory.equals("")) {
if (true) {
// System.out.println(str.toString());
variablesPanel.removeAll();
this.variables = new ArrayList<ArrayList<Component>>();
//variablesPanel.setLayout(new GridLayout(variablesList.size() + 1, 1)); //commented after adding allVars
variablesPanel.setLayout(new GridLayout(allVars.size() + 1, 1));
int max = 0;
/*if (!divisionsL.isEmpty()){
for (int i = 0; i < divisionsL.size(); i++){
if (divisionsL.get(i) != null) {
max = Math.max(max, divisionsL.get(i).size()+2);
}
}
}*/
//Added for replacing divisionsL by thresholds
if (!thresholds.isEmpty()){
for (String s : thresholds.keySet()){
if (thresholds.get(s) != null) {
max = Math.max(max, thresholds.get(s).size()+2);
}
}
}
JPanel label = new JPanel(new GridLayout());
label.add(new JLabel("Variables"));
// label.add(new JLabel("DMV"));
label.add(new JLabel("Use"));
label.add(new JLabel("Input"));
label.add(new JLabel("Number Of Bins"));
for (int i = 0; i < max - 2; i++) {
label.add(new JLabel("Level " + (i + 1)));
}
variablesPanel.add(label);
int j = 0;
//for (String s : variablesList) {// commented after adding allVars
for (String s : allVars) {
j++;
JPanel sp = new JPanel(new GridLayout());
ArrayList<Component> specs = new ArrayList<Component>();
// JCheckBox check = new JCheckBox();
// check.setSelected(true);
// specs.add(check);
specs.add(new JTextField(s));
String[] options = { "0", "2", "3", "4", "5", "6", "7", "8", "16", "32"};//, "10", "11", "12", "13", "14", "15", "16", "17", "33", "65", "129", "257" };
JComboBox combo = new JComboBox(options);
// String[] dmvOptions = { "", "Yes", "No" };
// JComboBox dmv = new JComboBox(dmvOptions);
// JCheckBox dmv = new JCheckBox();
JCheckBox required = new JCheckBox();
JCheckBox input = new JCheckBox();
// dmv.setSelectedIndex(0);
// dmv.addActionListener(this);
input.addActionListener(this);
required.addActionListener(this);
// dmv.setActionCommand("dmv" + j);
// required.setActionCommand("required" + variablesList.get(j-1)); // SB commented after adding allVars
// input.setActionCommand("input" + variablesList.get(j-1)); // SB commented after adding allVars
required.setActionCommand("required" + s);
input.setActionCommand("input" + s);
combo.setSelectedItem(numBins.getSelectedItem());
// specs.add(dmv);
specs.add(required);
specs.add(input);
specs.add(combo);
((JTextField) specs.get(0)).setEditable(false);
// sp.add(specs.get(0));
// ((JCheckBox) specs.get(0)).addActionListener(this);
// ((JCheckBox) specs.get(0)).setActionCommand("box" + j);
sp.add(specs.get(0));
sp.add(specs.get(1));
sp.add(specs.get(2)); // Uncommented SB
sp.add(specs.get(3)); // after required SB
/*if ((j-1) < reqdVarsL.size() && reqdVarsL.get(j-1).isInput()){ // changed after adding required.
((JCheckBox) specs.get(2)).setSelected(true); // changed 1 to 2 after required
}
else{
((JCheckBox) specs.get(2)).setSelected(false); // changed 1 to 2 after required
}*/
//if ((j-1) < reqdVarsL.size() && reqdVarsL.get(j-1).isInput()){ // changed after adding allVars
if (findReqdVarslIndex(s) != -1){
((JCheckBox) specs.get(1)).setSelected(true); // changed 1 to 2 after required
((JCheckBox) specs.get(2)).setEnabled(true); // added after allVars
((JComboBox) specs.get(3)).setEnabled(true); // added after allVars
/*for (int i = 3; i < specs.size(); i++) { // added after allVars
specs.get(i).setEnabled(true);
}*/
if (reqdVarsL.get(findReqdVarslIndex(s)).isInput()){
((JCheckBox) specs.get(2)).setSelected(true);
}
else{
((JCheckBox) specs.get(2)).setSelected(false);
}
}
else{ // variable not required
((JCheckBox) specs.get(1)).setSelected(false); // changed 1 to 2 after required
((JCheckBox) specs.get(2)).setEnabled(false); // added after allVars
((JComboBox) specs.get(3)).setEnabled(false); // added after allVars
/*for (int i = 3; i < specs.size(); i++) { // added after allVars
specs.get(i).setEnabled(false);
}*/
}
((JComboBox) specs.get(3)).addActionListener(this); // changed 1 to 2 SB
((JComboBox) specs.get(3)).setActionCommand("text" + j);// changed 1 to 2 SB
//TODO: BETTER BE THIS ((JComboBox) specs.get(3)).setActionCommand("text" + variablesList.get(j-1));// changed 1 to 2 SB
this.variables.add(specs);
//if (!divisionsL.isEmpty()) {
if (!thresholds.isEmpty()) { //Replacing divisionsL by thresholds
boolean found = false;
// if ((j-1) < divisionsL.size()) { COMMENTED BY SB
// divisionsL.add(null);
// ArrayList<Double> div = divisionsL.get(j-1);
//ArrayList<Double> div = thresholds.get(variablesList.get(j-1)); //Replacing divisionsL by thresholds; commented after adding allVars
if (findReqdVarslIndex(s) != -1){ //This condition added after adding allvarsL
ArrayList<Double> div = thresholds.get(s);
// log.addText(s + " here " + st); String[] getString = st.split(" "); log.addText(getString[0] + s);
//found = true; //moved this down after adding allVars
// if (getString.length >= 1) {
if ((div != null) && (div.size() > 0)){ //changed >= to >
//((JComboBox) specs.get(2)).setSelectedItem("div.size()+1");// Treats div.size() as string & doesn't work.. changed 1 to 2 SB
found = true;
((JComboBox) specs.get(3)).setSelectedItem(String.valueOf(div.size()+1));// changed 1 to 2 SB
for (int i = 0; i < (Integer.parseInt((String) ((JComboBox) specs.get(3)).getSelectedItem()) - 1); i++) {// changed 1 to 2 SB
if (div.isEmpty() || div.size() < i) {
specs.add(new JTextField(""));
} else {
// log.addText(getString[i+1]);
specs.add(new JTextField(div.get(i).toString()));
}
// if (((JCheckBox) specs.get(1)).isSelected()) {
// log.addText("here");
// ((JTextField) specs.get(i + 2)).setEditable(false);
sp.add(specs.get(i + 4)); // changed 2 to 3 SB
}
for (int i = Integer.parseInt((String) ((JComboBox) specs.get(3)).getSelectedItem()) - 1; i < max - 2; i++) {// changed 1 to 2 SB
sp.add(new JLabel());
}
}
else{ // if (!found){
for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(3)).getSelectedItem()) - 1; i++) {// changed 1 to 2 SB
specs.add(new JTextField(""));
sp.add(specs.get(i + 4));// changed 1 to 2 SB // changed to 4 expecting a bug
}
for (int i = Integer.parseInt((String) ((JComboBox) specs.get(3)).getSelectedItem()) - 1; i < max - 2; i++) {// changed 1 to 2 SB
sp.add(new JLabel());
}
}
for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(3)).getSelectedItem()) - 1; i++) {
((JTextField) specs.get(i + 4)).setEnabled(true);
}
((JCheckBox) specs.get(1)).setSelected(true);
((JCheckBox) specs.get(2)).setEnabled(true);
((JComboBox) specs.get(3)).setEnabled(true);
if (reqdVarsL.get(findReqdVarslIndex(s)).isInput()){
((JCheckBox) specs.get(2)).setSelected(true);
}
}
else{
((JCheckBox) specs.get(1)).setSelected(false);
((JCheckBox) specs.get(2)).setEnabled(false);
((JComboBox) specs.get(3)).setEnabled(false);
//for (int k = 1; k < variables.size(); k++){
// if ((((JTextField) variables.get(k).get(0)).getText().trim()).equalsIgnoreCase(s)){
for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(3)).getSelectedItem()) - 1; i++) {
if ((specs.size() -4) < Integer.parseInt((String) ((JComboBox) specs.get(3)).getSelectedItem()) - 1){
specs.add(new JTextField(""));
sp.add(specs.get(i + 4));
((JTextField) specs.get(i + 4)).setEnabled(false);
}
else{
((JTextField) specs.get(i + 4)).setEnabled(false);
}
}
}
} else {
if (findReqdVarslIndex(((JTextField) sp.getComponent(0)).getText().trim()) != -1){
((JCheckBox) specs.get(1)).setSelected(true);
((JCheckBox) specs.get(2)).setEnabled(true);
((JComboBox) specs.get(3)).setEnabled(true);
if (reqdVarsL.get(findReqdVarslIndex(s)).isInput()){
((JCheckBox) specs.get(2)).setSelected(true);
}
}
else{
((JCheckBox) specs.get(1)).setSelected(false);
((JCheckBox) specs.get(2)).setEnabled(false);
((JComboBox) specs.get(3)).setEnabled(false);
}
for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(3)).getSelectedItem()) - 1; i++) {// changed 1 to 2 SB
specs.add(new JTextField(""));
sp.add(specs.get(i + 4));// changed 1 to 2 SB //changed to 4 bcoz of a bug
if (findReqdVarslIndex(((JTextField) sp.getComponent(0)).getText().trim()) != -1){
((JTextField) specs.get(i + 4)).setEnabled(true);
}
else{
((JTextField) specs.get(i + 4)).setEnabled(false);
}
}
}
variablesPanel.add(sp);
}
}
}
editText(0);
}
private void editText(int num) { // adjusts number of boxes for thresholds
try {
ArrayList<Component> specs = variables.get(num);
Component[] panels = variablesPanel.getComponents();
int boxes = Integer.parseInt((String) ((JComboBox) specs.get(3)).getSelectedItem()); //changed 1 to 2 SB
if ((specs.size() - 4) < boxes) { // changed 2 to 3 SB
for (int i = 0; i < boxes - 1; i++) {
try {
specs.get(i + 4); // changed 2 to 3 SB
} catch (Exception e1) {
JTextField temp = new JTextField("");
((JPanel) panels[num + 1]).add(temp);
specs.add(temp);
}
}
} else {
try {
if (boxes > 0) {
while (true) {
specs.remove(boxes + 3); // changed 1 to 2 SB
((JPanel) panels[num + 1]).remove(boxes + 3); // changed 1 to 2 SB
}
} else if (boxes == 0) {
while (true) {
specs.remove(4); // changed 2 to 3 SB
((JPanel) panels[num + 1]).remove(4); // changed 2 to 3 SB
}
}
} catch (Exception e1) {
}
}
int max = 0;
for (int i = 0; i < this.variables.size(); i++) {
max = Math.max(max, variables.get(i).size());
}
if (((JPanel) panels[0]).getComponentCount() < max) {
for (int i = 0; i < max - 4; i++) { //changed 2 to 3 SB
try {
((JPanel) panels[0]).getComponent(i + 4); //changed 2 to 3 SB
} catch (Exception e) {
((JPanel) panels[0]).add(new JLabel("Level " + (i + 1)));
}
}
} else {
try {
while (true) {
((JPanel) panels[0]).remove(max);
}
} catch (Exception e) {
}
}
for (int i = 1; i < panels.length; i++) {
JPanel sp = (JPanel) panels[i];
for (int j = sp.getComponentCount() - 1; j >= 4; j--) {//changed 2 to 3 SB
if (sp.getComponent(j) instanceof JLabel) {
sp.remove(j);
}
}
if (max > sp.getComponentCount()) {
for (int j = sp.getComponentCount(); j < max; j++) {
sp.add(new JLabel());
}
} else {
for (int j = sp.getComponentCount() - 3; j >= max; j--) {//changed 2 to 3 SB .. not sure??
sp.remove(j);
}
}
}
} catch (Exception e) {
}
}
private int findReqdVarslIndex(String s) {
for (int i = 0; i < reqdVarsL.size() ; i++){
if (s.equalsIgnoreCase(reqdVarsL.get(i).getName())){
return i;
}
}
return -1;
}
public void saveLhpn() {
try {
if (true) {// (new File(directory + separator +
// "method.gcm").exists()) {
String copy = JOptionPane.showInputDialog(biosim.frame(),
"Enter Circuit Name:", "Save Circuit",
JOptionPane.PLAIN_MESSAGE);
if (copy != null) {
copy = copy.trim();
} else {
return;
}
if (!copy.equals("")) {
if (copy.length() > 1) {
if (copy.length() < 4 || !copy.substring(copy.length() - 4).equals(".lpn")) {
copy += ".lpn";
}
} else {
copy += ".lpn";
}
}
biosim.saveLhpn(copy, directory + separator + lhpnFile);
} else {
JOptionPane.showMessageDialog(biosim.frame(),
"No circuit has been generated yet.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to save model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewLhpn() {
try {
File work = new File(directory);
if (new File(directory + separator + lhpnFile).exists()) {
String dotFile = lhpnFile.replace(".lpn", ".dot");
File dot = new File(directory + separator + dotFile);
dot.delete();
log.addText("Executing:\n" + "atacs -cPllodpl " + lhpnFile);
Runtime exec = Runtime.getRuntime();
Process load = exec.exec("atacs -cPllodpl " + lhpnFile, null,
work);
load.waitFor();
if (dot.exists()) {
viewLhpn.setEnabled(true);
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open " + dotFile;
log.addText("gnome-open " + directory + separator
+ dotFile + "\n");
} else {
command = "open " + dotFile;
log.addText("open " + directory + separator + dotFile
+ "\n");
}
exec.exec(command, null, work);
} else {
File log = new File(directory + separator + "atacs.log");
BufferedReader input = new BufferedReader(new FileReader(
log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea
.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls,
"Log", JOptionPane.INFORMATION_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(biosim.frame(),
"No circuit has been generated yet.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to view LPN Model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewLog() {
try {
if (new File(directory + separator + "run.log").exists()) {
File log = new File(directory + separator + "run.log");
BufferedReader input = new BufferedReader(new FileReader(log));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls,
"Run Log", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(biosim.frame(),
"No run log exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to view run log.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewLearnComplete() {
JFrame learnComplete = new JFrame("LEMA");
learnComplete.setResizable(false);
JPanel all = new JPanel(new BorderLayout());
JLabel label = new JLabel("<html><b>Learning Completed</b></html>",SwingConstants.CENTER);
all.add(label, BorderLayout.CENTER);
Dimension screenSize;
learnComplete.setContentPane(all);
learnComplete.setMinimumSize(new Dimension(300,140));
learnComplete.pack();
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
} catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = learnComplete.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
learnComplete.setLocation(x, y);
learnComplete.setVisible(true);
// learnComplete.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
public void viewCoverage() {
try {
if (new File(directory + separator + "run.cvg").exists()) {
File cvgRpt = new File(directory + separator + "run.cvg");
BufferedReader input = new BufferedReader(new FileReader(cvgRpt));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(500, 500));
scrolls.setPreferredSize(new Dimension(500, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls,
"Coverage Report", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(biosim.frame(),
"No Coverage Report exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to view Coverage Report.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewVHDL() {
try {
String vhdFile = lhpnFile.replace(".lpn", ".vhd");
if (new File(directory + separator + vhdFile).exists()) {
File vhdlAmsFile = new File(directory + separator + vhdFile);
BufferedReader input = new BufferedReader(new FileReader(vhdlAmsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls,
"VHDL-AMS Model", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(biosim.frame(),
"VHDL-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to view VHDL-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void viewVerilog() {
try {
String vamsFileName = lhpnFile.replace(".lpn", ".sv");
if (new File(directory + separator + vamsFileName).exists()) {
File vamsFile = new File(directory + separator + vamsFileName);
BufferedReader input = new BufferedReader(new FileReader(vamsFile));
String line = null;
JTextArea messageArea = new JTextArea();
while ((line = input.readLine()) != null) {
messageArea.append(line);
messageArea.append(System.getProperty("line.separator"));
}
input.close();
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(800, 500));
scrolls.setPreferredSize(new Dimension(800, 500));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls,
"Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(biosim.frame(),
"Verilog-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to view Verilog-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void save() {
try {
Properties prop = new Properties();
FileInputStream in = new FileInputStream(new File(directory + separator + lrnFile));
prop.load(in);
in.close();
prop.setProperty("learn.file", learnFile);
prop.setProperty("learn.iter", this.iteration.getText().trim());
prop.setProperty("learn.bins", (String) this.numBins.getSelectedItem());
prop.setProperty("learn.prop", (String) this.propertyG.getText().trim());
String varsList = null;
if (range.isSelected()) {
prop.setProperty("learn.equal", "range");
} else {
prop.setProperty("learn.equal", "points");
}
if (auto.isSelected()) {
prop.setProperty("learn.use", "auto");
int k = 0; // added later .. so that the exact divisions are stored to file when auto is selected. & not the divisions in the textboxes
int inputCount = 0;
String ip = null;
int numOfBins = Integer.parseInt(this.numBins.getSelectedItem().toString());
//int numThresholds = numOfBins -1;
for (Component c : variablesPanel.getComponents()) {
if (k == 0){
k++;
continue;
}
if (((JCheckBox)((JPanel)c).getComponent(1)).isSelected()){ // added after required
if (varsList == null){
varsList = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
varsList += " "+ ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
String currentVar = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
String s = currentVar + " " + numOfBins;
/*if ((divisionsL != null) && (divisionsL.size() != 0)){
for (int i = 0; i < (numOfBins -1); i++){
if ((divisionsL.get(k-1)!= null) && (divisionsL.get(k-1).size() > i)){
s += " ";
s += divisionsL.get(k-1).get(i);
}
}
} COMMENTED ABOVE FOR REPLACING divisionsL by threholds */
if ((thresholds != null) && (thresholds.size() != 0)){ //Added for replacing divisionsL by thresholds
for (int i = 0; i < (numOfBins -1); i++){
if ((thresholds.get(currentVar)!= null) && (thresholds.get(currentVar).size() > i)){
s += " ";
s += thresholds.get(currentVar).get(i);
}
}
}
prop.setProperty("learn.bins"+ currentVar, s);
if (((JCheckBox)((JPanel)c).getComponent(2)).isSelected()){ // changed 1 to 2 after required
if (inputCount == 0){
inputCount++;
ip = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
ip = ip + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
}
k++;
}
if (inputCount != 0){
prop.setProperty("learn.inputs", ip);
}
else{
prop.remove("learn.inputs");
}
} else {
prop.setProperty("learn.use", "user");
int k = 0;
int inputCount = 0;
String ip = null;
for (Component c : variablesPanel.getComponents()) {
if (k == 0){
k++;
continue;
}
if (((JCheckBox)((JPanel)c).getComponent(1)).isSelected()){
if (varsList == null) { //(k == 1){
varsList = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
varsList += " "+ ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
String s = ((JTextField)((JPanel)c).getComponent(0)).getText().trim() + " " + (String)((JComboBox)((JPanel)c).getComponent(3)).getSelectedItem(); // changed to 3 after required
int numOfBins = Integer.parseInt((String)((JComboBox)((JPanel)c).getComponent(3)).getSelectedItem())-1; // changed to 3 after required
for (int i = 0; i < numOfBins; i++){
s += " ";
s += ((JTextField)(((JPanel)c).getComponent(i+4))).getText().trim();// changed to 4 after required
}
prop.setProperty("learn.bins"+ ((JTextField)((JPanel)c).getComponent(0)).getText().trim(), s);
if (((JCheckBox)((JPanel)c).getComponent(2)).isSelected()){ // changed to 2 after required
if (inputCount == 0){
inputCount++;
ip = ((JTextField)((JPanel)c).getComponent(0)).getText().trim();//((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
else{
ip = ip + " " + ((JTextField)((JPanel)c).getComponent(0)).getText().trim();
}
}
}
k++;
}
if (inputCount != 0){
prop.setProperty("learn.inputs", ip);
}
else{
prop.remove("learn.inputs");
}
}
prop.setProperty("learn.epsilon", this.epsilonG.getText().trim());
prop.setProperty("learn.pathLength", this.pathLengthG.getText().trim());
prop.setProperty("learn.rateSampling", this.rateSamplingG.getText().trim());
prop.setProperty("learn.percent", this.percentG.getText().trim());
prop.setProperty("learn.absTime",String.valueOf(this.absTimeG.isSelected()));
prop.setProperty("learn.runTime",this.runTimeG.getText().trim());
prop.setProperty("learn.runLength",this.runLengthG.getText().trim());
if (varsList != null){
prop.setProperty("learn.varsList",varsList);
}
else{
prop.remove("learn.varsList");
}
log.addText("Saving learn parameters to file:\n" + directory
+ separator + lrnFile + "\n");
FileOutputStream out = new FileOutputStream(new File(directory + separator + lrnFile));
prop.store(out, learnFile);
out.close();
// log.addText("Creating levels file:\n" + directory + separator +
// binFile + "\n");
// String command = "autogenT.py -b" + binFile + " -t"
// + numBins.getSelectedItem().toString() + " -i" +
// iteration.getText();
// if (range.isSelected()) {
// command = command + " -cr";
// File work = new File(directory);
// Runtime.getRuntime().exec(command, null, work);
change = false;
} catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to save parameter file!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
}
}
public void reload(String newname) {
// try {
// Properties prop = new Properties();
// FileInputStream in = new FileInputStream(new File(directory +
// separator + lrnFile));
// prop.load(in);
// in.close();
// prop.setProperty("learn.file", newname);
// prop.setProperty("learn.iter", this.iteration.getText().trim());
// prop.setProperty("learn.bins", (String)
// this.numBins.getSelectedItem());
// if (range.isSelected()) {
// prop.setProperty("learn.equal", "range");
// else {
// prop.setProperty("learn.equal", "points");
// if (auto.isSelected()) {
// prop.setProperty("learn.use", "auto");
// else {
// prop.setProperty("learn.use", "user");
// log.addText("Saving learn parameters to file:\n" + directory +
// separator + lrnFile
// FileOutputStream out = new FileOutputStream(new File(directory +
// separator + lrnFile));
// prop.store(out, learnFile);
// out.close();
// catch (Exception e1) {
// //e1.printStackTrace();
// JOptionPane.showMessageDialog(biosim.frame(), "Unable to save
// parameter file!",
// "Error Saving File", JOptionPane.ERROR_MESSAGE);
backgroundField.setText(newname);
}
public void learn() {
try {
if (auto.isSelected()) {
for (int i = 0; i < variables.size(); i++) {
for (int j = 4; j < variables.get(i).size(); j++) { // changed to 4 after required
if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) {
} else {
/*if (divisionsL.get(i).size() <= (j-4)){ // changed to 4 after required
divisionsL.get(i).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}
else{
divisionsL.get(i).set(j-4,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); // changed to 4 after required
//thresholds.get(((JTextField) variables.get(i).get(0)).getText().trim()).set(j-3,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}*/
//Added for replacing divisionsL by thresholds
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
if (thresholds.get(currentVar).size() <= (j-4)){ // changed to 4 after required
thresholds.get(currentVar).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}
else{
thresholds.get(currentVar).set(j-4,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); // changed to 4 after required
}
}
}
}
generate = true;
} else {
for (int i = 0; i < variables.size(); i++) {
for (int j = 4; j < variables.get(i).size(); j++) { // changed 2 to 3 SB
if (((JTextField) variables.get(i).get(j)).getText().trim().equals("")) {
} else {
/*if (divisionsL.get(i).size() <= (j-4)){ // changed to 4 after required
divisionsL.get(i).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}
else{
divisionsL.get(i).set(j-4,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); // changed to 4 after required
}*/
//Added for replacing divisionsL by thresholds
String currentVar = ((JTextField) variables.get(i).get(0)).getText().trim();
if (thresholds.get(currentVar).size() <= (j-4)){ // changed to 4 after required
thresholds.get(currentVar).add(Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim()));
}
else{
thresholds.get(currentVar).set(j-4,Double.parseDouble(((JTextField) variables.get(i).get(j)).getText().trim())); // changed to 4 after required
}
}
}
}
generate = false;
}
execute = true;
LearnThread = new Thread(this);
LearnThread.start();
}
catch (NullPointerException e1) {
e1.printStackTrace();
System.out.println("Some problem with thresholds hashmap");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Some problem");
}
}
public void run() {
new File(directory + separator + lhpnFile).delete();
fail = false;
try {
//File work = new File(directory);
final JFrame running = new JFrame("Progress");
//running.setUndecorated(true);
final JButton cancel = new JButton("Cancel");
running.setResizable(false);
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
running.dispose();
}
public void windowOpened(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowActivated(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
};
running.addWindowListener(w);
JPanel text = new JPanel();
JPanel progBar = new JPanel();
JPanel button = new JPanel();
JPanel all = new JPanel(new BorderLayout());
JLabel label = new JLabel("Running...");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
// progress.setStringPainted(true);
// progress.setString("");
progress.setValue(0);
text.add(label);
progBar.add(progress);
button.add(cancel);
all.add(text, "North");
all.add(progBar, "Center");
all.add(button, "South");
running.setContentPane(all);
running.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
} catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = running.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
running.setLocation(x, y);
running.setVisible(true);
running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
logFile = new File(directory + separator + "run.log");
logFile.createNewFile();
out = new BufferedWriter(new FileWriter(logFile));
cancel.setActionCommand("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
running.setCursor(null);
running.dispose();
if (LearnThread != null) {
LearnThread.stop();
}
//throw new RuntimeException();
//TODO: Need to kill thread somehow???
}
});
if (generate) {
out.write("Running autoGenT\n");
thresholds = autoGenT(running);
if (!execute) {
levels();
}
else{ //added later.. for saving the autogenerated thresholds into learn file after generating thresholds & before running data2lhpn
save();
}
}
if (execute && !fail) {
File lhpn = new File(directory + separator + lhpnFile);
lhpn.delete();
dataToLHPN(running);
viewLog.setEnabled(true);
if (new File(directory + separator + lhpnFile).exists()) {
viewVHDL.setEnabled(true);
viewVerilog.setEnabled(true);
viewLhpn.setEnabled(true);
viewCoverage.setEnabled(true);
saveLhpn.setEnabled(true);
//viewLearnComplete(); // SB
JFrame learnComplete = new JFrame();
JOptionPane.showMessageDialog(learnComplete,
"Learning Complete.",
"LEMA",
JOptionPane.PLAIN_MESSAGE);
//viewLhpn();
biosim.updateMenu(true,true);
} else {
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLhpn.setEnabled(false);
viewCoverage.setEnabled(false);
saveLhpn.setEnabled(false);
fail = true;
biosim.updateMenu(true,false);
}
}
running.setCursor(null);
running.dispose();
if (fail) {
viewLog();
}
} catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to create log file.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
/*catch (RuntimeException e1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Learning was" + " canceled by the user.",
"Canceled Learning", JOptionPane.ERROR_MESSAGE);
} */
}
public boolean hasChanged() {
return change;
}
public boolean isComboSelected() {
if (debug.isFocusOwner() || numBins.isFocusOwner()) {
return true;
}
if (variables == null) {
return false;
}
for (int i = 0; i < variables.size(); i++) {
if (((JComboBox) variables.get(i).get(3)).isFocusOwner()) { // changed 1 to 2 SB
return true;
}
}
return false;
}
public boolean getViewLhpnEnabled() {
return viewLhpn.isEnabled();
}
public boolean getSaveLhpnEnabled() {
return saveLhpn.isEnabled();
}
public boolean getViewLogEnabled() {
return viewLog.isEnabled();
}
public boolean getViewCoverageEnabled() {
return viewCoverage.isEnabled();
}
public boolean getViewVHDLEnabled() {
return viewVHDL.isEnabled();
}
public boolean getViewVerilogEnabled() {
return viewVerilog.isEnabled();
}
public void updateSpecies(String newLearnFile) {
learnFile = newLearnFile;
variablesList = new ArrayList<String>();
* learnFile); Set<String> ids = lhpn.getVariables().keySet(); /*try {
* FileWriter write = new FileWriter( new File(directory + separator +
* "background.g")); write.write("digraph G {\n"); for (String s : ids) {
* variablesList.add(s); write.write("s" + s + "
* [shape=ellipse,color=black,label=\"" + (s) + "\"" + "];\n"); }
* write.write("}\n"); write.close(); } catch (Exception e) {
* JOptionPane.showMessageDialog(biosim.frame(), "Unable to create
* background file!", "Error Writing Background",
* JOptionPane.ERROR_MESSAGE); } } else {
*/
thresholds = new HashMap<String, ArrayList<Double>>();
reqdVarsL = new ArrayList<Variable>();
LhpnFile lhpn = new LhpnFile();
lhpn.load(learnFile);
HashMap<String, Properties> variablesMap = lhpn.getContinuous();
for (String s : variablesMap.keySet()) {
variablesList.add(s);
reqdVarsL.add(new Variable(s));
thresholds.put(s,new ArrayList<Double>());
}
// Loading the inputs and bins from the existing .lrn file.
Properties load = new Properties();
try {
FileInputStream in = new FileInputStream(new File(directory
+ separator + lrnFile));
load.load(in);
in.close();
int j = 0;
if (load.containsKey("learn.varsList")){
String varsListString = load.getProperty("learn.varsList");
String[] varsList = varsListString.split("\\s");
j = 0;
for (String st1 : varsList){
int varNum = findReqdVarslIndex(st1);
if (varNum == -1){
continue;
}
else{
String s = load.getProperty("learn.bins" + st1);
String[] savedBins = s.split("\\s");
//variablesList.add(savedBins[0]);
// ((JComboBox)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(2))).setSelectedItem(savedBins[1]);
for (int i = 2; i < savedBins.length ; i++){
// ((JTextField)(((JPanel)variablesPanel.getComponent(j+1)).getComponent(i+1))).setText(savedBins[i]);
if (varNum < variablesMap.size()) { // chk for varNum or j ????
thresholds.get(st1).add(Double.parseDouble(savedBins[i]));
}
}
}
}
}
if (load.containsKey("learn.inputs")){
String s = load.getProperty("learn.inputs");
String[] savedInputs = s.split("\\s");
for (String st1 : savedInputs){
int ind = findReqdVarslIndex(st1); //after adding allVars
if (ind != -1){
reqdVarsL.get(ind).setInput(true);
}
/*for (int i = 0; i < reqdVarsL.size(); i++){//commented after adding allVars
if ( reqdVarsL.get(i).getName().equalsIgnoreCase(st1)){
reqdVarsL.get(i).setInput(true);
break;
}
}*/
}
}
} catch (IOException e) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
/*
* try { FileWriter write = new FileWriter( new File(directory +
* separator + "background.gcm")); BufferedReader input = new
* BufferedReader(new FileReader(new File(learnFile))); String line =
* null; while ((line = input.readLine()) != null) { write.write(line +
* "\n"); } write.close(); input.close(); } catch (Exception e) {
* JOptionPane.showMessageDialog(biosim.frame(), "Unable to create
* background file!", "Error Writing Background",
* JOptionPane.ERROR_MESSAGE); }
*/
sortVariables();
if (user.isSelected()) {
// auto.doClick(); commented SB
// user.doClick(); commented SB
numBinsLabel.setEnabled(false);
numBins.setEnabled(false);
suggest.setEnabled(true);
variablesPanel.revalidate();
variablesPanel.repaint();
} else {
// user.doClick(); commented SB
// auto.doClick(); commented SB
numBinsLabel.setEnabled(true);
numBins.setEnabled(true);
suggest.setEnabled(false);
}
levels();
}
private void sortVariables() {
int i, j;
String index;
//TODO: AllVars has to be sorted?? Is sorting required at all??
for (i = 1; i < variablesList.size(); i++) {
index = variablesList.get(i);
j = i;
while ((j > 0)
&& variablesList.get(j - 1).compareToIgnoreCase(index) > 0) {
variablesList.set(j, variablesList.get(j - 1));
j = j - 1;
}
variablesList.set(j, index);
}
/* Collections.sort(divisionsL, new Comparator<ArrayList<Double>>(){
public int compare(ArrayList<Double> a, ArrayList<Double> b){
int ind1 = divisionsL.indexOf(a);
int ind2 = divisionsL.indexOf(b);
String var1 = reqdVarsL.get(ind1).getName();
String var2 = reqdVarsL.get(ind2).getName();
return (reqdVarsL.get(divisionsL.indexOf(a)).compareTo(reqdVarsL.get(divisionsL.indexOf(b))));
}
});*/
//TODO: SORTING OF thresholds NOT NECESSARY LIKE ABOVE ???
Collections.sort(reqdVarsL);
// sort divisionsL
}
public void setDirectory(String directory) {
this.directory = directory;
String[] getFilename = directory.split(separator);
lrnFile = getFilename[getFilename.length - 1] + ".lrn";
}
/**
* This method generates an LHPN model from the simulation traces provided
* in the learn view. The generated LHPN is stored in an object of type
* lhpn2sbml.parser.LHPNfile . It is then saved in *.lpn file using the
* save() method of the above class.
*
* Rev. 1 - Kevin Jones
* Rev. 2 - Scott Little (data2lhpn.py)
* Rev. 3 - Satish Batchu ( dataToLHPN() )
*/
public void dataToLHPN(JFrame running) {
try {
/* Initializations being done in resetAll method added on Aug 12,2009. These
* initializations ensure that place,transition numbers start from 0
* everytime we click play button on LEMA though compiled only once.
* Init values and rates being cleared for the same reason.
*/
resetAll();
lowerLimit = new Double[reqdVarsL.size()];
upperLimit = new Double[reqdVarsL.size()];
/* end Initializations */
//String[] getRootDir = directory.split(separator);
//String rootDir = directory;
//rootDir = rootDir.replace(getRootDir[getRootDir.length - 1], "") ;
// logFile = new File(rootDir + "atacs.log");
out.write("Running: dataToLHPN\n");
TSDParser tsd = new TSDParser(directory + separator + "run-1.tsd",
biosim, false);
varNames = tsd.getSpecies();
//String[] learnDir = lrnFile.split("\\.");
//File cvgFile = new File(directory + separator + learnDir[0] + ".cvg");
File cvgFile = new File(directory + separator + "run.cvg");
cvgFile.createNewFile();
BufferedWriter coverage = new BufferedWriter(new FileWriter(cvgFile));
//FileOutputStream coverage = new FileOutputStream(cvgFile);
// Check whether all the tsd files are following the same variables
// & order vars = varNames.toArray(new String[varNames.size()]);
int i = 1;
lowerLimit[0] = -800.0; // for integrator
upperLimit[0] = 800.0; // for integrator
String failProp = "";
String enFailAnd = "";
String enFail = "";
g = new LhpnFile(); // The generated lhpn is stored in this object
placeInfo = new HashMap<String, Properties>();
transitionInfo = new HashMap<String, Properties>();
cvgInfo = new HashMap<String, Properties>();
transientNetPlaces = new HashMap<String, Properties>();
transientNetTransitions = new HashMap<String, Properties>();
ratePlaces = new ArrayList<String>();
dmvcInputPlaces = new ArrayList<String>();
propPlaces = new ArrayList<String>();
if (!(propertyG.getText()).equals("")){
//BufferedReader prop = new BufferedReader(new FileReader(directory + separator + "learn" + ".prop"));
failProp = propertyG.getText().trim();
failProp = "~(" + failProp + ")";
failPropVHDL = failProp.replaceAll("~", "not ");
failPropVHDL = failPropVHDL.replaceAll("\\|", " or ");
failPropVHDL = failPropVHDL.replaceAll("\\&", " and ");
failPropVHDL = failPropVHDL.replaceAll(">=(-*[0-9]+\\.[0-9]*)", "'above($1)");
failPropVHDL = failPropVHDL.replaceAll(">=(-*[0-9]+)", "'above($1\\.0)");
failProp = failProp.replaceAll("\\.[0-9]*","");
Properties p0 = new Properties();
placeInfo.put("failProp", p0);
p0.setProperty("placeNum", numPlaces.toString());
p0.setProperty("type", "PROP");
p0.setProperty("initiallyMarked", "true");
g.addPlace("p" + numPlaces, true);
propPlaces.add("p" + numPlaces);
numPlaces++;
Properties p1 = new Properties();
transitionInfo.put("failProp", p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get("failProp").getProperty("placeNum"), "t" + transitionInfo.get("failProp").getProperty("transitionNum"));
g.getTransition("t" + numTransitions).setFail(true);
numTransitions++;
//enFailAnd = "&~fail";
//enFail = "~fail";
}
epsilon = Double.parseDouble(epsilonG.getText().trim());
rateSampling = Integer.parseInt(rateSamplingG.getText().trim());
pathLength = Integer.parseInt(pathLengthG.getText().trim());
percent = Double.parseDouble(percentG.getText().trim());
runLength = Integer.parseInt(runLengthG.getText().trim());
runTime = Double.parseDouble(runTimeG.getText().trim());
absoluteTime = absTimeG.isSelected();
while (new File(directory + separator + "run-" + i + ".tsd").exists()) {
Properties cProp = new Properties();
cvgInfo.put(String.valueOf(i), cProp);
cProp.setProperty("places", String.valueOf(0));
cProp.setProperty("transitions", String.valueOf(0));
cProp.setProperty("rates", String.valueOf(0));
cProp.setProperty("delays", String.valueOf(0));
tsd = new TSDParser(directory + separator + "run-" + i + ".tsd", biosim,false);
data = tsd.getData();
//ORDER REVERSED this first then detectDMV genBinsRates(divisionsL); // changes made here.. data being used was global before.
//genBinsRates("run-" + i + ".tsd", divisionsL);
findReqdVarIndices();
genBinsRates(thresholds); // moved this above detectDMV on May 11,2010 assuming this order reversal won't affect things.
detectDMV(data,false); // changes made here.. data being used was global before.
// genBinsRates(divisionsL); commented after replacing divisionsL with thresholds
updateGraph(bins, rates, cProp,running);
//cProp.store(coverage, "run-" + String.valueOf(i) + ".tsd");
coverage.write("run-" + String.valueOf(i) + ".tsd\t");
coverage.write("places : " + cProp.getProperty("places"));
coverage.write("\ttransitions : " + cProp.getProperty("transitions") + "\n");
i++;
}
coverage.close();
for (String st1 : g.getTransitionList()) {
out.write("\nTransition is " + st1);
if (isTransientTransition(st1)){
out.write(" Incoming place " + g.getPreset(st1)[0]);
if (g.getPostset(st1).length != 0){
out.write(" Outgoing place " + g.getPostset(st1)[0]);
}
continue;
}
String binEncoding = getPlaceInfoIndex(g.getPreset(st1)[0]);
out.write(" Incoming place " + g.getPreset(st1)[0]
+ " Bin encoding is " + binEncoding);
if (g.getPostset(st1).length != 0){
binEncoding = getPlaceInfoIndex(g.getPostset(st1)[0]);
out.write(" Outgoing place " + g.getPostset(st1)[0]
+ " Bin encoding is " + binEncoding);
}
}
out.write("\nTotal no of transitions : " + numTransitions);
out.write("\nTotal no of places : " + numPlaces);
Properties initCond = new Properties();
for (Variable v : reqdVarsL) {
if (v.isDmvc()) {
g.addInteger(v.getName(), v.getInitValue());
} else {
initCond.put("value", v.getInitValue());
initCond.put("rate", v.getInitRate());
g.addContinuous(v.getName(), initCond);
}
}
//g.addOutput("fail", "false");
HashMap<String, ArrayList<Double>> scaledThresholds; // scaledThresholds are scaleDiv
// temporary
/* Pattern pat = Pattern.compile("-*[0-9]+\\.*[0-9]*");
Matcher m = pat.matcher(failProp);
while(m.find()){
failProp = m.replaceFirst(String.valueOf(Double.parseDouble(m.group())*100.0));
}
System.out.println(failProp);
for (String t : g.getTransitionList()) {
if ((g.getPreset(t) != null) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("PROP"))){
g.addEnabling(t, failProp);
}
} */
// end temporary
scaledThresholds = normalize();
initCond = new Properties();
for (Variable v : reqdVarsL) { // Updating with scaled initial values & rates
if (v.isDmvc()) {
g.changeIntegerInitCond(v.getName(), v.getInitValue());
} else {
initCond.put("value", v.getInitValue());
initCond.put("rate", v.getInitRate());
g.changeContInitCond(v.getName(), initCond);
}
}
String[] transitionList = g.getTransitionList();
transEnablingsVHDL = new String[transitionList.length];
transDelayAssignVHDL = new String[transitionList.length];
transIntAssignVHDL = new String[transitionList.length][reqdVarsL.size()];
transEnablingsVAMS = new String[transitionList.length];
transConditionalsVAMS = new String[transitionList.length];
transIntAssignVAMS = new String[transitionList.length][reqdVarsL.size()];
transDelayAssignVAMS = new String[transitionList.length];
int transNum;
for (String t : transitionList) {
transNum = Integer.parseInt(t.split("t")[1]);
if ((g.getPreset(t) != null) && (g.getPostset(t) != null)){
if (!isTransientTransition(t)){
if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) {
// g.getPreset(t).length != 0 && g.getPostset(t).length != 0 ??
ArrayList<Integer> diffL = diff(getPlaceInfoIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0]));
String condStr = "";
transEnablingsVHDL[transNum] = "";
transEnablingsVAMS[transNum] = "";
String[] binIncoming = getPlaceInfoIndex(g.getPreset(t)[0]).split(",");
String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(",");
Boolean firstInputBinChg = true;
Boolean firstOutputBinChg = true;
Boolean opChange = false, ipChange = false;
for (int k : diffL) {
if (!((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput()))) {
// the above condition means that if the bin change is on a non-input dmv variable, there won't be any enabling condition
ipChange = true;
if (Integer.parseInt(binIncoming[k]) < Integer.parseInt(binOutgoing[k])) {
double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binIncoming[k])).doubleValue();
if (firstInputBinChg){
condStr += "(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")";
transEnablingsVHDL[transNum] += reqdVarsL.get(k).getName() + "'above(" + (int) Math.floor(val)+".0)";
transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/varScaleFactor +"),+1)"; // += temporary
transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") >= " + ((int)val)/varScaleFactor +"))";
}
else{
condStr += "&(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")";
transEnablingsVHDL[transNum] += " and " + reqdVarsL.get(k).getName() + "'above(" + (int) Math.floor(val)+".0)";
transEnablingsVAMS[transNum] += " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/varScaleFactor +"),+1)"; // += temporary
transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") >= " + ((int)val)/varScaleFactor +"))";
}
} else {
double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])).doubleValue();
if (firstInputBinChg){
condStr += "~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.ceil(val) + ")";
transEnablingsVHDL[transNum] += "not " + reqdVarsL.get(k).getName() + "'above(" + (int) Math.ceil(val)+".0)";
transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/varScaleFactor +"),-1)"; // +=; temporary
transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") < " + ((int)val)/varScaleFactor +"))";
}
else{
condStr += "&~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.ceil(val) + ")";
transEnablingsVHDL[transNum] += "and not " + reqdVarsL.get(k).getName() + "'above(" + (int) Math.ceil(val)+".0)";
transEnablingsVAMS[transNum] += " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/varScaleFactor +"),-1)"; // +=; temporary
transConditionalsVAMS[transNum] = "if ((place == " + g.getPreset(t)[0].split("p")[1] + ") && (V(" + reqdVarsL.get(k).getName() + ") < " + ((int)val)/varScaleFactor +"))";
}
}
//if (diffL.get(diffL.size() - 1) != k) {
// condStr += "&";
// transEnablingsVHDL[transNum] += " and ";
////COME BACK??? temporary transEnablingsVAMS[transNum] +=
firstInputBinChg = false;
}
// Enablings Till above.. Below one is dmvc delay,assignment. Whenever a transition's preset and postset places differ in dmvc vars, then this transition gets the assignment of the dmvc value in the postset place and delay assignment of the preset place's duration range. This has to be changed after taking the causal relation input
if ((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput())) { // require few more changes here.should check for those variables that are constant over these regions and make them as causal????? thesis
opChange = true;
String pPrev = g.getPreset(t)[0];
String nextPlace = g.getPostset(t)[0];
//if (!isTransientTransition(t)){
// int mind = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMin")));
// int maxd = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMax")));
int mind = (int) Math.floor(Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).getProperty("dMin")));
int maxd = (int) Math.ceil(Double.parseDouble(transitionInfo.get(getPlaceInfoIndex(pPrev) + getPlaceInfoIndex(nextPlace)).getProperty("dMax")));
if (mind != maxd)
g.changeDelay(t, "uniform(" + mind + "," + maxd + ")");
else
g.changeDelay(t, String.valueOf(mind));
int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")));
int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax")));
if (minv != maxv)
g.addIntAssign(t,reqdVarsL.get(k).getName(),"uniform(" + minv + ","+ maxv + ")");
else
g.addIntAssign(t,reqdVarsL.get(k).getName(), String.valueOf(minv));
int dmvTnum = Integer.parseInt(t.split("t")[1]);
transIntAssignVHDL[dmvTnum][k] = reqdVarsL.get(k).getName() +" => span(" + (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))) + ".0,"+ (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))) + ".0)";
transDelayAssignVHDL[dmvTnum] = "delay(" + mind + "," + maxd + ")";
if (!vamsRandom){
transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")) + Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))))/(2.0*varScaleFactor)+";\n";
//transDelayAssignVAMS[dmvTnum] = "#" + (int)(((Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMin"))) + Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMax"))))*Math.pow(10, 12))/(2.0*delayScaleFactor)); // converting seconds to ns using math.pow(10,9)
transDelayAssignVAMS[dmvTnum] = "#" + (int)((mind + maxd)/(2*delayScaleFactor)); // converting seconds to ns using math.pow(10,9)
}
else{
transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = $dist_uniform(seed,"+ String.valueOf((int)Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))/varScaleFactor)) + "," + String.valueOf((int)Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))/varScaleFactor))+");\n";
//transDelayAssignVAMS[dmvTnum] = "del = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," +(int)Math.ceil((Double.parseDouble(placeInfo.get(getPlaceInfoIndex(pPrev)).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t\t#del"; // converting seconds to ns using math.pow(10,9)
transDelayAssignVAMS[dmvTnum] = "del = $dist_uniform(seed," + (int) (mind/delayScaleFactor) + "," +(int) (maxd/delayScaleFactor) + ");\n\t\t\t#del"; // converting seconds to ns using math.pow(10,9)
}
/*}
else{
g.changeDelay(t, "[" + (int) Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin"))) + "," + (int) Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax"))) + "]");
g.addIntAssign(t,reqdVarsL.get(k).getName(),"[" + (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))) + ","+ (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))) + "]");
int dmvTnum = Integer.parseInt(t.split("t")[1]);
transIntAssignVHDL[dmvTnum][k] = reqdVarsL.get(k).getName() +" => span(" + (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))) + ".0,"+ (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))) + ".0)";
transDelayAssignVHDL[dmvTnum] = "delay(" + (int) Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin"))) + "," + (int) Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax"))) + ")";
transIntAssignVAMS[dmvTnum][k] = ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")) + Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))))/(2.0*varScaleFactor);
transDelayAssignVAMS[dmvTnum] = (int)(((Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin"))) + Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax"))))*Math.pow(10, 12))/(2.0*delayScaleFactor)); // converting seconds to ns using math.pow(10,9)
}*/
}
}
if (ipChange & opChange) // Both ip and op changes on same transition. Then delay should be 0. Not the previous bin duration.
g.changeDelay(t, "0");
if (diffL.size() > 1){
transEnablingsVHDL[transNum] = "(" + transEnablingsVHDL[transNum] + ")";
}
if ((transEnablingsVAMS[transNum] != "") && (transEnablingsVAMS[transNum] != null)){
transEnablingsVAMS[transNum] += ")";
}
if (!condStr.equalsIgnoreCase("")){
//condStr += enFailAnd;
g.addEnabling(t, condStr);
}
else{
//Nothing added to Enabling condition.
//condStr = enFail;
//g.addEnabling(t, condStr);
}
//transEnablingsVHDL[transNum] += enFailAnd;
}
/* Related to the separate net for DMV input driver
if ((placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("DMVC"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("DMVC"))) {
// Dealing with graphs obtained from DMVC INPUT variables
// NO ENABLINGS for these transitions
String nextPlace = g.getPostset(t)[0];
String prevPlace = g.getPreset(t)[0];
// A transition has delay from it's preset place &
// assignment from it's postset place
int mind = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(prevPlace)).getProperty("dMin")));
int maxd = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(prevPlace)).getProperty("dMax")));
if (mind != maxd)
g.changeDelay(t, "uniform(" + mind + "," + maxd + ")");
else
g.changeDelay(t, String.valueOf(mind));
int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("DMVCValue")));
int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("DMVCValue")));
if (minv != maxv)
g.addIntAssign(t, placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("DMVCVariable"), "uniform(" + minv + "," + maxv + ")");
else
g.addIntAssign(t, placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("DMVCVariable"), String.valueOf(minv));
g.addEnabling(t, enFail);
}
*/
}
else{
/* Related to the separate net for DMV input driver
if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("DMVC"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("DMVC"))){ // transient dmv transition
String prevPlace = g.getPreset(t)[0];
String nextPlace = g.getPostset(t)[0];
// delay from preset; assgnmt from postset
int mind = (int) Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(prevPlace)).getProperty("dMin")));
int maxd = (int) Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(prevPlace)).getProperty("dMax")));
if (mind != maxd)
g.changeDelay(t, "uniform(" + mind + "," + maxd + ")");
else
g.changeDelay(t, String.valueOf(mind));
int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("DMVCValue")));
int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("DMVCValue")));
if (minv != maxv)
g.addIntAssign(t, placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("DMVCVariable"), "uniform(" + minv + "," + maxv + ")");
else
g.addIntAssign(t, placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty("DMVCVariable"), String.valueOf(minv));
g.addEnabling(t, enFail);
}
*/
if ((transientNetPlaces.get(getTransientNetPlaceIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))){ // transient non-dmv transition
ArrayList<Integer> diffL = diff(getTransientNetPlaceIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0]));
String condStr = "";
transEnablingsVHDL[transNum] = "";
transEnablingsVAMS[transNum] = "";
String[] binIncoming = getTransientNetPlaceIndex(g.getPreset(t)[0]).split(",");
String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split(",");
Boolean firstInputBinChg = true;
Boolean opChange = false, ipChange = false;
for (int k : diffL) {
if (!((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput()))) {
ipChange = true;
if (Integer.parseInt(binIncoming[k]) < Integer.parseInt(binOutgoing[k])) {
// double val = divisionsL.get(k).get(Integer.parseInt(binIncoming[k])).doubleValue();
double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binIncoming[k])).doubleValue();
if (firstInputBinChg){
condStr += "(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")";
transEnablingsVHDL[transNum] += reqdVarsL.get(k).getName() + "'above(" + (int) Math.floor(val)+".0)";
transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/varScaleFactor +"),+1)"; // += temporary
}
else{
condStr += "&(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.floor(val) + ")";
transEnablingsVHDL[transNum] += " and " + reqdVarsL.get(k).getName() + "'above(" + (int) Math.floor(val)+".0)";
transEnablingsVAMS[transNum] += " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/varScaleFactor +"),+1)"; // += temporary
}
} else {
double val = scaledThresholds.get(reqdVarsL.get(k).getName()).get(Integer.parseInt(binOutgoing[k])).doubleValue();
if (firstInputBinChg){
condStr += "~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.ceil(val) + ")";
transEnablingsVHDL[transNum] += " and not " + reqdVarsL.get(k).getName() + "'above(" + (int) Math.ceil(val)+".0)";
transEnablingsVAMS[transNum] = "always@(cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/varScaleFactor +"),-1)"; // +=; temporary
}
else{
condStr += "&~(" + reqdVarsL.get(k).getName() + ">=" + (int) Math.ceil(val) + ")";
transEnablingsVHDL[transNum] += "not " + reqdVarsL.get(k).getName() + "'above(" + (int) Math.ceil(val)+".0)";
transEnablingsVAMS[transNum] = " and cross((V(" + reqdVarsL.get(k).getName() + ") - " + ((int)val)/varScaleFactor +"),-1)"; // +=; temporary
}
}
//if (diffL.get(diffL.size() - 1) != k) {
// condStr += "&";
// transEnablingsVHDL[transNum] += " and ";
// //COME BACK??? temporary transEnablingsVAMS[transNum] +=
firstInputBinChg = false;
}
if ((reqdVarsL.get(k).isDmvc()) && (!reqdVarsL.get(k).isInput())) { // require few more changes here.should check for those variables that are constant over these regions and make them as causal????? thesis
opChange = true;
String pPrev = g.getPreset(t)[0];
String nextPlace = g.getPostset(t)[0];
//int mind = (int) Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin")));
//int maxd = (int) Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax")));
int mind = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).getProperty("dMin")));
int maxd = (int) Math.floor(Double.parseDouble(transientNetTransitions.get(getTransientNetPlaceIndex(pPrev)+getPlaceInfoIndex(nextPlace)).getProperty("dMax")));
if (mind != maxd)
g.changeDelay(t, "uniform(" + mind + "," + maxd + ")");
else
g.changeDelay(t, String.valueOf(mind));
int minv = (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")));
int maxv = (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax")));
if (minv != maxv)
g.addIntAssign(t,reqdVarsL.get(k).getName(),"uniform(" + minv + ","+ maxv + ")");
else
g.addIntAssign(t,reqdVarsL.get(k).getName(),String.valueOf(minv));
int dmvTnum = Integer.parseInt(t.split("t")[1]);
transIntAssignVHDL[dmvTnum][k] = reqdVarsL.get(k).getName() +" => span(" + (int) Math.floor(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))) + ".0,"+ (int) Math.ceil(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))) + ".0)";
transDelayAssignVHDL[dmvTnum] = "delay(" + mind + "," + maxd + ")";
if (!vamsRandom){
transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin")) + Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))))/(2.0*varScaleFactor)+";\n";;
// transDelayAssignVAMS[dmvTnum] = "#" + (int)(((Math.floor(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin"))) + Math.ceil(Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax"))))*Math.pow(10, 12))/(2.0*delayScaleFactor)); // converting seconds to ns using math.pow(10,9)
transDelayAssignVAMS[dmvTnum] = "#" + (int)((mind + maxd)/(2*delayScaleFactor)); // converting seconds to ns using math.pow(10,9)
}
else{
transIntAssignVAMS[dmvTnum][k] = reqdVarsL.get(k).getName()+"Val = $dist_uniform(seed,"+ String.valueOf(Math.floor((Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMin"))/varScaleFactor))) + "," + String.valueOf(Math.ceil((Double.parseDouble(placeInfo.get(getPlaceInfoIndex(nextPlace)).getProperty(reqdVarsL.get(k).getName() + "_vMax"))/varScaleFactor)))+");\n";
//transDelayAssignVAMS[dmvTnum] = "del = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," + (int)Math.ceil((Double.parseDouble(transientNetPlaces.get(getTransientNetPlaceIndex(pPrev)).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t\t#del"; // converting seconds to ns using math.pow(10,9)
transDelayAssignVAMS[dmvTnum] = "del = $dist_uniform(seed," + (int) (mind/delayScaleFactor) + "," + (int) (maxd/delayScaleFactor) + ");\n\t\t\t#del"; // converting seconds to ns using math.pow(10,9)
}
}
}
if (ipChange & opChange) // Both ip and op changes on same transition. Then delay should be 0. Not the previous bin duration.
g.changeDelay(t, "0");
if (diffL.size() > 1){
transEnablingsVHDL[transNum] = "(" + transEnablingsVHDL[transNum] + ")";
}
if ((transEnablingsVAMS[transNum] != "") && (transEnablingsVAMS[transNum] != null)){
transEnablingsVAMS[transNum] += ")";
}
if (!condStr.equalsIgnoreCase("")){
//condStr += enFailAnd;
g.addEnabling(t, condStr);
}
else{
//condStr = enFail;
//g.addEnabling(t, condStr);
}
//transEnablingsVHDL[transNum] += enFailAnd;
}
}
}
if ((g.getPreset(t) != null) && (!isTransientTransition(t)) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("PROP"))){
g.addEnabling(t, failProp);
//g.addBoolAssign(t, "fail", "true"); // fail would be the variable name
//g.addProperty(failProp);
}
}
ArrayList<String> placesWithoutPostsetTrans = new ArrayList<String>();
for (String st1 : g.getPlaceList()) {
if (g.getPostset(st1).length == 0){ // a place without a postset transition
placesWithoutPostsetTrans.add(st1);
}
if (!isTransientPlace(st1)){
String p = getPlaceInfoIndex(st1);
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
if (g.getPreset(st1).length != 0){
for (String t : g.getPreset(st1)) {
for (int k = 0; k < reqdVarsL.size(); k++) {
if (!reqdVarsL.get(k).isDmvc()) {
int minr = getMinRate(p, reqdVarsL.get(k).getName());
int maxr = getMaxRate(p, reqdVarsL.get(k).getName());
if (minr != maxr)
g.addRateAssign(t, reqdVarsL.get(k).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign(t, reqdVarsL.get(k).getName(), String.valueOf(minr));
}
}
}
}
}
}
}
for (String st1 : transientNetTransitions.keySet()){
String s = g.getPostset("t" + transientNetTransitions.get(st1).getProperty("transitionNum"))[0];
// check TYPE of preset ????
String p = getPlaceInfoIndex(s);
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
for (int k = 0; k < reqdVarsL.size(); k++) {
if (!reqdVarsL.get(k).isDmvc()) {
// out.write("<" + t + "=[" + reqdVarsL.get(k).getName() + ":=[" + getMinRate(p, reqdVarsL.get(k).getName()) + "," + getMaxRate(p, reqdVarsL.get(k).getName()) + "]]>");
int minr = getMinRate(p, reqdVarsL.get(k).getName());
int maxr = getMaxRate(p, reqdVarsL.get(k).getName());
if (minr != maxr)
g.addRateAssign("t" + transientNetTransitions.get(st1).getProperty("transitionNum"), reqdVarsL.get(k).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + transientNetTransitions.get(st1).getProperty("transitionNum"), reqdVarsL.get(k).getName(), String.valueOf(minr));
}
}
}
}
for (String st1 : placesWithoutPostsetTrans){
placeInfo.remove(getPlaceInfoIndex(st1));
g.removePlace(st1);
}
out.close();
// addMetaBins();
// addMetaBinTransitions();
g.save(directory + separator + lhpnFile);
writeVHDLAMSFile(lhpnFile.replace(".lpn",".vhd"));
writeVerilogAMSFile(lhpnFile.replace(".lpn",".vams"));
new Lpn2verilog(directory + separator + lhpnFile); //writeSVFile(directory + separator + lhpnFile);
if (new File(learnFile).exists()){ //directory + separator + "complete.lpn").exists()){//
LhpnFile l1 = new LhpnFile();
l1.load(learnFile);
mergeLhpns(l1,g).save(directory + separator + lhpnFile);
//l1.load(directory + separator + "complete.lpn");
//mergeLhpns(l1,g).save(directory + separator + "complete.lpn");
} /*else {
g.save(directory + separator + "complete.lpn");
}*/
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"LPN file couldn't be created/written.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
catch (NullPointerException e4) {
e4.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"LPN file couldn't be created/written. Null exception",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
catch (ArrayIndexOutOfBoundsException e1) { // comes from initMark = -1 of updateGraph()
e1.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to calculate rates.\nWindow size or pathlength must be reduced.\nLearning unsuccessful.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
try {
out.write("ERROR! Unable to calculate rates.\nIf Window size = -1, pathlength must be reduced;\nElse, reduce windowsize\nLearning unsuccessful.");
out.close();
} catch (IOException e2) {
e2.printStackTrace();
}
running.setCursor(null);
running.dispose();
}
catch (java.lang.IllegalStateException e3){
e3.printStackTrace();
//System.out.println("LPN file couldn't be created/written ");
JOptionPane.showMessageDialog(biosim.frame(),
"LPN File not found for merging.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
private boolean isTransientPlace(String st1) {
for (String s : transientNetPlaces.keySet()){
if (st1.equalsIgnoreCase("p" + transientNetPlaces.get(s).getProperty("placeNum"))){
return true;
}
}
return false;
}
private boolean isTransientTransition(String st1) {
for (String s : transientNetTransitions.keySet()){
if (st1.equalsIgnoreCase("t" + transientNetTransitions.get(s).getProperty("transitionNum"))){
return true;
}
}
return false;
}
public void resetAll(){
dmvcCnt = 0;
numPlaces = 0;
numTransitions = 0;
delayScaleFactor = 1.0;
varScaleFactor = 1.0;
for (Variable v: reqdVarsL){
v.reset();
}
}
public void findReqdVarIndices(){
reqdVarIndices = new ArrayList<Integer>();
for (int i = 0; i < reqdVarsL.size(); i++) {
for (int j = 1; j < varNames.size(); j++) {
if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) {
reqdVarIndices.add(j);
}
}
}
}
/* Commented after replacing divisionsL with thresholds
public void genBinsRates(ArrayList<ArrayList<Double>> divisionsL) { // genBins
// public void genBinsRates(String datFile,ArrayList<ArrayList<Double>> divisionsL) { // genBins
// TSDParser tsd = new TSDParser(directory + separator + datFile, biosim,false);
// genBins
// data = tsd.getData();
reqdVarIndices = new ArrayList<Integer>();
bins = new int[reqdVarsL.size()][data.get(0).size()];
for (int i = 0; i < reqdVarsL.size(); i++) {
// System.out.println("Divisions " + divisionsL.get(i));
for (int j = 1; j < varNames.size(); j++) {
if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) {
// System.out.println(reqdVarsL.get(i) + " matched "+
// varNames.get(j) + " i = " + i + " j = " + j);
reqdVarIndices.add(j);
for (int k = 0; k < data.get(j).size(); k++) {
// System.out.print(data.get(j).get(k) + " ");
for (int l = 0; l < divisionsL.get(i).size(); l++) {
if (data.get(j).get(k) <= divisionsL.get(i).get(l)) {
bins[i][k] = l;
break;
} else {
bins[i][k] = l + 1; // indices of bins not same
// as that of the variable.
// i here. not j; if j
// wanted, then size of bins
// array should be varNames
// not reqdVars
}
}
}
// System.out.print(" ");
}
}
}
// System.out.println("array bins is :");
// for (int i = 0; i < reqdVarsL.size(); i++) {
// System.out.print(reqdVarsL.get(i).getName() + " ");
// for (int k = 0; k < data.get(0).size(); k++) {
// System.out.print(bins[i][k] + " ");
// }
// System.out.print("\n"); }
//
// genRates
rates = new Double[reqdVarsL.size()][data.get(0).size()];
duration = new Double[data.get(0).size()];
int mark, k; // indices of rates not same as that of the variable. if
// wanted, then size of rates array should be varNames
// not reqdVars
if (placeRates) {
if (rateSampling == -1) { // replacing inf with -1 since int
mark = 0;
for (int i = 0; i < data.get(0).size(); i++) {
if (i < mark) {
continue;
}
while ((mark < data.get(0).size()) && (compareBins(i, mark))) {
mark++;
}
if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLength) && (mark != data.get(0).size())) { // && (mark != (data.get(0).size() - 1 condition added on nov 23.. to avoid the last region bcoz it's not complete. rechk
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i)));
}
duration[i] = data.get(0).get(mark - 1) - data.get(0).get(i);
}
}
} else {
boolean calcRate;
boolean prevFail = true;
int binStartPoint = 0, binEndPoint = 0;
for (int i = 0; i < (data.get(0).size() - rateSampling); i++) {
calcRate = true;
for (int l = 0; l < rateSampling; l++) {
if (!compareBins(i, i + l)) {
if (!prevFail){
binEndPoint = i -2 + rateSampling;
duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint);
}
calcRate = false;
prevFail = true;
break;
}
}
if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) {
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(k).get(i + rateSampling) - data.get(k).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i)));
}
if (prevFail){
binStartPoint = i;
}
prevFail = false;
}
}
// commented on nov 23. don't need this. should avoid rate calculation too for this region. but not avoiding now.
// if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt
// duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint);
// }
}
}
//
// ADD LATER: duration[i] SHOULD BE ADDED TO THE NEXT 2 IF/ELSE
// BRANCHES(Transition based rate calc) ALSO
else { // Transition based rate calculation
if (rateSampling == -1) { // replacing inf with -1 since int
for (int j = 0; j < reqdVarsL.size(); j++) {
mark = 0;
k = reqdVarIndices.get(j);
for (int i = 0; i < data.get(0).size(); i++) {
if (i < mark) {
continue;
}
while ((mark < data.get(0).size())
&& (bins[k][i] == bins[k][mark])) {
mark++;
}
if ((data.get(0).get(mark - 1) != data.get(0).get(i))) {
rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i)));
}
}
}
} else {
boolean calcRate;
for (int i = 0; i < (data.get(0).size() - rateSampling); i++) {
for (int j = 0; j < reqdVarsL.size(); j++) {
calcRate = true;
k = reqdVarIndices.get(j);
for (int l = 0; l < rateSampling; l++) {
if (bins[k][i] != bins[k][i + l]) {
calcRate = false;
break;
}
}
if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) {
rates[j][i] = ((data.get(k).get(i + rateSampling) - data.get(k).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i)));
}
}
}
}
}
// try {
// for (int i = 0; i < (data.get(0).size()); i++) {
// for (int j = 0; j < reqdVarsL.size(); j++) {
// k = reqdVarIndices.get(j);
// out.write(data.get(k).get(i) + " ");// + bins[j][i] + " " +
// // rates[j][i] + " ");
// }
// for (int j = 0; j < reqdVarsL.size(); j++) {
// out.write(bins[j][i] + " ");
// }
// for (int j = 0; j < reqdVarsL.size(); j++) {
// out.write(rates[j][i] + " ");
// }
// out.write(duration[i] + " ");
// out.write("\n");
// }
// } catch (IOException e) {
// System.out
// .println("Log file couldn't be opened for writing rates and bins ");
// }
}
*/
public void genBinsRates(HashMap<String, ArrayList<Double>> localThresholds) { // genBins
// public void genBinsRates(String datFile,ArrayList<ArrayList<Double>> divisionsL) { // genBins
// TSDParser tsd = new TSDParser(directory + separator + datFile, biosim,false);
// genBins
// data = tsd.getData();
try{
reqdVarIndices = new ArrayList<Integer>();
bins = new int[reqdVarsL.size()][data.get(0).size()];
for (int i = 0; i < reqdVarsL.size(); i++) {
// System.out.println("Divisions " + divisionsL.get(i));
for (int j = 1; j < varNames.size(); j++) {
String currentVar = reqdVarsL.get(i).getName();
if (currentVar.equalsIgnoreCase(varNames.get(j))) {
// System.out.println(reqdVarsL.get(i) + " matched "+
// varNames.get(j) + " i = " + i + " j = " + j);
reqdVarIndices.add(j);
for (int k = 0; k < data.get(j).size(); k++) {
// System.out.print(data.get(j).get(k) + " ");
for (int l = 0; l < localThresholds.get(currentVar).size(); l++) {
if (data.get(j).get(k) <= localThresholds.get(currentVar).get(l)) {
bins[i][k] = l;
break;
} else {
bins[i][k] = l + 1; // indices of bins not same
// as that of the variable.
// i here. not j; if j wanted, then size of bins
// array should be varNames not reqdVars
}
}
}
// System.out.print(" ");
}
}
}
/*
* System.out.println("array bins is :"); for (int i = 0; i <
* reqdVarsL.size(); i++) { System.out.print(reqdVarsL.get(i).getName() + "
* "); for (int k = 0; k < data.get(0).size(); k++) {
* System.out.print(bins[i][k] + " "); } System.out.print("\n"); }
*/
// genRates
rates = new Double[reqdVarsL.size()][data.get(0).size()];
duration = new Double[data.get(0).size()];
int mark, k, previous = 0; // indices of rates not same as that of the variable. if
// wanted, then size of rates array should be varNames
// not reqdVars
if (rateSampling == -1) { // replacing inf with -1 since int
mark = 0;
for (int i = 0; i < data.get(0).size(); i++) {
if (i < mark) {
continue;
}
while ((mark < data.get(0).size()) && (compareBins(i, mark))) {
mark++;
}
if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLength) && (mark != data.get(0).size())) { // && (mark != (data.get(0).size() - 1 condition added on nov 23.. to avoid the last region bcoz it's not complete. rechk
if (!compareBins(previous,i)){
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(k).get(mark - 1) - data.get(k).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i)));
}
duration[i] = data.get(0).get(mark) - data.get(0).get(i); // changed (mark - 1) to mark on may 28,2010
previous = i;
} else{ // There was a glitch and you returned to the same region
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
rates[j][previous] = ((data.get(k).get(mark - 1) - data.get(k).get(previous)) / (data.get(0).get(mark - 1) - data.get(0).get(previous)));
}
duration[previous] = data.get(0).get(mark) - data.get(0).get(previous); // changed (mark - 1) to mark on may 28,2010
}
} else if ((mark - i) < pathLength) { // account for the glitch duration
duration[previous] += data.get(0).get(mark) - data.get(0).get(i);
}
}
} else { //TODO: This may have bugs in duration calculation etc.
boolean calcRate;
boolean prevFail = true;
int binStartPoint = 0, binEndPoint = 0;
for (int i = 0; i < (data.get(0).size() - rateSampling); i++) {
calcRate = true;
for (int l = 0; l < rateSampling; l++) {
if (!compareBins(i, i + l)) {
if (!prevFail){
binEndPoint = i -2 + rateSampling;
duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint);
}
calcRate = false;
prevFail = true;
break;
}
}
if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) {
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(k).get(i + rateSampling) - data.get(k).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i)));
}
if (prevFail){
binStartPoint = i;
}
prevFail = false;
}
}
// commented on nov 23. don't need this. should avoid rate calculation too for this region. but not avoiding now.
/* if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt
duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint);
}*/
}
} catch (NullPointerException e){
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Bins/Rates could not be generated. Please check thresholds.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
/*
try {
for (int i = 0; i < (data.get(0).size()); i++) {
for (int j = 0; j < reqdVarsL.size(); j++) {
k = reqdVarIndices.get(j);
out.write(data.get(k).get(i) + " ");// + bins[j][i] + " " +
// rates[j][i] + " ");
}
for (int j = 0; j < reqdVarsL.size(); j++) {
out.write(bins[j][i] + " ");
}
for (int j = 0; j < reqdVarsL.size(); j++) {
out.write(rates[j][i] + " ");
}
out.write(duration[i] + " ");
out.write("\n");
}
} catch (IOException e) {
System.out
.println("Log file couldn't be opened for writing rates and bins ");
}*/
}
public boolean compareBins(int j, int mark) {
for (int i = 0; i < reqdVarsL.size(); i++) {
if (bins[i][j] != bins[i][mark]) {
return false;
} else {
continue;
}
}
return true;
}
public void updateRateInfo(int[][] bins, Double[][] rates, Properties cvgProp) {
String prevPlaceKey = ""; // "" or " " ; rechk
String key = "";
Double prevPlaceDuration = null;
// boolean addNewPlace;
// ArrayList<String> ratePlaces = new ArrayList<String>(); // ratePlaces can include non-input dmv places.
// boolean newRate = false;
Properties p0, p1 = null;
for (int i = 0; i < (data.get(0).size() - 1); i++) {
if (rates[0][i] != null) { // check if indices are ok. 0???? or 1???
prevPlaceKey = key;
key = "" + bins[0][i];
for (int j = 1; j < reqdVarsL.size(); j++) {
// key += "" + bins[j][i];
key += "," + bins[j][i];
}
if (placeInfo.containsKey(key)) {
p0 = placeInfo.get(key);
}
else if ((transientNetPlaces.containsKey(key)) && (ratePlaces.size() == 1)){
p0 = transientNetPlaces.get(key);
}
else {
p0 = new Properties();
if (ratePlaces.size() == 0){
transientNetPlaces.put(key, p0);
g.addPlace("p" + numPlaces, true);
}
else{
placeInfo.put(key, p0);
g.addPlace("p" + numPlaces, false);
}
p0.setProperty("placeNum", numPlaces.toString());
p0.setProperty("type", "RATE");
p0.setProperty("initiallyMarked", "false");
p0.setProperty("metaType","false"); // REMOVE LATER?????
ratePlaces.add("p" + numPlaces);
numPlaces++;
cvgProp.setProperty("places", String.valueOf(Integer.parseInt(cvgProp.getProperty("places"))+1));
}
for (int j = 0; j < reqdVarsL.size(); j++) {
// rechk if (reqdVarsL.get(j).isDmvc() && reqdVarsL.get(j).isInput()) {
// continue;
if (reqdVarsL.get(j).isDmvc()) { // && !reqdVarsL.get(j).isInput()){
for (int k = 0; k < reqdVarsL.get(j).getRuns().getAvgVals().length; k++) {
if ((reqdVarsL.get(j).getRuns().getStartPoint(k) <= i) && (reqdVarsL.get(j).getRuns().getEndPoint(k) >= i)) {
addValue(p0,reqdVarsL.get(j).getName(),reqdVarsL.get(j).getRuns().getAvgVals()[k]);// data.get(reqdVarIndices.get(j)).get(i));
break;
}
if (reqdVarsL.get(j).getRuns().getStartPoint(k) >= i) {
addValue(p0,reqdVarsL.get(j).getName(),reqdVarsL.get(j).getRuns().getAvgVals()[k]);// data.get(reqdVarIndices.get(j)).get(i));
break;
}
// WRONG addValue(p0, reqdVarsL.get(j).getName(), data.get(reqdVarIndices.get(j)).get(i));
}
continue;
}
addRate(p0, reqdVarsL.get(j).getName(), rates[j][i]);
// newR, oldR, dmvc etc. left
}
boolean transientNet = false;
if (!prevPlaceKey.equalsIgnoreCase(key)) {
if (transitionInfo.containsKey(prevPlaceKey + key)) { // instead of tuple
p1 = transitionInfo.get(prevPlaceKey + key);
} else if (prevPlaceKey != "") {
// transition = new Transition(reqdVarsL.size(),place,prevPlace);
p1 = new Properties();
p1.setProperty("transitionNum", numTransitions.toString());
if (ratePlaces.size() == 2){
transientNetTransitions.put(prevPlaceKey + key, p1);
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + transientNetPlaces.get(prevPlaceKey).getProperty("placeNum"), "t" + transientNetTransitions.get(prevPlaceKey + key).getProperty("transitionNum"));
g.addMovement("t" + transientNetTransitions.get(prevPlaceKey + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
transientNet = true;
}
else{
transitionInfo.put(prevPlaceKey + key, p1);
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(prevPlaceKey).getProperty("placeNum"), "t" + transitionInfo.get(prevPlaceKey + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(prevPlaceKey + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
}
numTransitions++;
cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1));
// transition.setCore(true);
}
if (prevPlaceDuration != null){ //Delay on a transition is the duration spent at its preceding place
addDuration(p1, prevPlaceDuration);
}
}
prevPlaceDuration = duration[i];
/*if (duration[i] != null){ //STORING DELAYS AT TRANSITIONS NOW
addDuration(p0, duration[i]);
}*/
//else if (duration[i] != null && transientNet){
// addTransientDuration(p0, duration[i]);
if (p1 != null) {
for (int j = 0; j < reqdVarsL.size(); j++) {
if (reqdVarsL.get(j).isDmvc() && reqdVarsL.get(j).isInput()) {
continue;
}
if (reqdVarsL.get(j).isDmvc()) {
continue;
}
addRate(p1, reqdVarsL.get(j).getName(), rates[j][i]);
}
}
}
}
}
public void updateGraph(int[][] bins, Double[][] rates, Properties cvgProp,JFrame running) {
updateRateInfo(bins, rates, cvgProp);
//updateTimeInfo(bins,cvgProp);
int initMark = -1;
int k;
String key;
for (int i = 0; i < reqdVarsL.size(); i++) {
for (int j = 0; j < data.get(0).size(); j++) {
if (rates[i][j] != null) {
k = reqdVarIndices.get(i);
// addInitValues(data.get(k).get(j), i); // k or i think ??
// addInitRates(rates[i][j], i);// k or i think??
reqdVarsL.get(i).addInitValues(data.get(k).get(j)); // Do the same for initvals too??
//reqdVarsL.get(i).addInitRates(rates[i][j]); // this just adds the first rate; not the rates of entire 1st region.
initMark = j;
break;
}
}
key = "" + bins[0][initMark];
for (int l = 1; l < reqdVarsL.size(); l++) {
// key = key + "" + bins[l][initMark];
key = key + "," + bins[l][initMark];
}
if (!reqdVarsL.get(i).isDmvc()){
reqdVarsL.get(i).addInitRates((double)getMinRate(key, reqdVarsL.get(i).getName()));
reqdVarsL.get(i).addInitRates((double)getMaxRate(key, reqdVarsL.get(i).getName()));
}
/*
if (placeInfo.get(key).getProperty("initiallyMarked").equalsIgnoreCase("false")) {
placeInfo.get(key).setProperty("initiallyMarked", "true");
g.changeInitialMarking("p" + placeInfo.get(key).getProperty("placeNum"), true);
}
*/
}
}
public HashMap<String, ArrayList<Double>> detectDMV(ArrayList<ArrayList<Double>> data, Boolean callFromAutogen) {
int startPoint, endPoint, mark, numPoints;
HashMap<String, ArrayList<Double>> dmvDivisions = new HashMap<String, ArrayList<Double>>();
double absTime;
for (int i = 0; i < reqdVarsL.size(); i++) {
absTime = 0;
mark = 0;
DMVCrun runs = reqdVarsL.get(i).getRuns();
runs.clearAll(); // flush all the runs from previous dat file.
int lastRunPointsWithoutTransition = 0;
Double lastRunTimeWithoutTransition = 0.0;
if (!callFromAutogen) { // This flag is required because if the call is from autogenT, then data has just the reqdVarsL but otherwise, it has all other vars too. So reqdVarIndices not reqd when called from autogen
for (int j = 0; j <= data.get(0).size(); j++) {
if (j < mark) // not reqd??
continue;
if (((j+1) < data.get(reqdVarIndices.get(i)).size()) &&
Math.abs(data.get(reqdVarIndices.get(i)).get(j) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= epsilon) {
startPoint = j;
runs.addValue(data.get(reqdVarIndices.get(i)).get(j)); // chk carefully reqdVarIndices.get(i)
while (((j + 1) < data.get(0).size()) && (bins[i][startPoint] == bins[i][j+1]) && (Math.abs(data.get(reqdVarIndices.get(i)).get(startPoint) - data.get(reqdVarIndices.get(i)).get(j + 1)) <= epsilon)) { //checking of same bins[] condition added on May 11,2010.
runs.addValue(data.get(reqdVarIndices.get(i)).get(j + 1)); // chk carefully
// reqdVarIndices.get(i)
j++;
}
endPoint = j;
if (!absoluteTime) {
if ((endPoint < (data.get(0).size() - 1)) && ((endPoint - startPoint) + 1) >= runLength) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunPointsWithoutTransition = endPoint - startPoint + 1;
} else {
runs.removeValue();
}
} else {
if ((endPoint < (data.get(0).size() - 1)) && (calcDelay(startPoint, endPoint) >= runTime)) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
absTime += calcDelay(startPoint, endPoint);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunTimeWithoutTransition = calcDelay(startPoint, endPoint);
} else {
runs.removeValue();
}
}
mark = endPoint;
}
}
}
else{
epsilon = Double.parseDouble(epsilonG.getText().trim()); // because these are not extracted b4 data2lhpn()
percent = Double.parseDouble(percentG.getText().trim());
runLength = Integer.parseInt(runLengthG.getText().trim());
runTime = Double.parseDouble(runTimeG.getText().trim());
absoluteTime = absTimeG.isSelected();
for (int j = 0; j <= data.get(0).size(); j++) {
if (j < mark) // not reqd??
continue;
if (((j+1) < data.get(i+1).size()) &&
Math.abs(data.get(i+1).get(j) - data.get(i+1).get(j + 1)) <= epsilon) { //i+1 and not i bcoz 0th col is time
startPoint = j;
runs.addValue(data.get(i+1).get(j)); // chk carefully reqdVarIndices.get(i)
while (((j + 1) < data.get(0).size()) && (Math.abs(data.get(i+1).get(startPoint) - data.get(i+1).get(j + 1)) <= epsilon)) {
runs.addValue(data.get(i+1).get(j + 1)); // chk carefully
// reqdVarIndices.get(i)
j++;
}
endPoint = j;
if (!absoluteTime) {
if ((endPoint < (data.get(0).size() - 1)) && ((endPoint - startPoint) + 1) >= runLength) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunPointsWithoutTransition = endPoint - startPoint + 1;
} else {
runs.removeValue();
}
} else {
if ((endPoint < (data.get(0).size() - 1)) && (calcDelayWithData(startPoint, endPoint, data) >= runTime)) {
runs.addStartPoint(startPoint);
runs.addEndPoint(endPoint);
absTime += calcDelayWithData(startPoint, endPoint, data);
} else if (((endPoint - startPoint) + 1) >= runLength) {
lastRunTimeWithoutTransition = calcDelayWithData(startPoint, endPoint, data);
} else {
runs.removeValue();
}
}
mark = endPoint;
}
}
}
try {
if (!absoluteTime) {
numPoints = runs.getNumPoints();
if (((numPoints + lastRunPointsWithoutTransition)/ (double) data.get(0).size()) < percent) {
runs.clearAll();
reqdVarsL.get(i).setDmvc(false);
out.write(reqdVarsL.get(i).getName()
+ " is not a dmvc \n");
} else {
reqdVarsL.get(i).setDmvc(true);
Double[] dmvcValues = reqdVarsL.get(i).getRuns().getAvgVals();
Arrays.sort(dmvcValues);
//System.out.println("Sorted DMV values of " + reqdVarsL.get(i).getName() + " are ");
//for (Double l : dmvcValues){
// System.out.print(l + " ");
ArrayList<Double> dmvcValuesUnique = new ArrayList<Double>();
ArrayList<Double> dmvSplits = new ArrayList<Double>();
out.write("Final DMV values of " + reqdVarsL.get(i).getName() + " are ");
for (int j = 0; j < dmvcValues.length; j++){
dmvcValuesUnique.add(dmvcValues[j]);
out.write(dmvcValues[j] + " ");
if (dmvcValuesUnique.size() > 1){
dmvSplits.add((dmvcValuesUnique.get(dmvcValuesUnique.size() - 1) + dmvcValuesUnique.get(dmvcValuesUnique.size() - 2))/2);
}
for (int k = j+1; k < dmvcValues.length; k++){
if (Math.abs((dmvcValues[j] - dmvcValues[k])) > epsilon){
j = k-1;
break;
}
else if (k >= (dmvcValues.length -1)){
j = k;
}
}
}
dmvDivisions.put(reqdVarsL.get(i).getName(), dmvSplits);
out.write(reqdVarsL.get(i).getName() + " is a dmvc \n");
}
} else {
if (((absTime + lastRunTimeWithoutTransition)/ (data.get(0).get(data.get(0).size() - 1) - data
.get(0).get(0))) < percent) {
runs.clearAll();
reqdVarsL.get(i).setDmvc(false);
out.write(reqdVarsL.get(i).getName()
+ " is not a dmvc \n");
} else {
reqdVarsL.get(i).setDmvc(true);
Double[] dmvcValues = reqdVarsL.get(i).getRuns().getAvgVals();
Arrays.sort(dmvcValues);
ArrayList<Double> dmvcValuesUnique = new ArrayList<Double>();
ArrayList<Double> dmvSplits = new ArrayList<Double>();
for (int j = 0; j < dmvcValues.length; j++){
dmvcValuesUnique.add(dmvcValues[j]);
out.write(dmvcValues[j].toString());
if (dmvcValuesUnique.size() > 1){
double d1 = (dmvcValuesUnique.get(dmvcValuesUnique.size() - 1) + dmvcValuesUnique.get(dmvcValuesUnique.size() - 2))/2.0;
d1 = d1*10000;
int d2 = (int) d1;
//System.out.println(d2);
//System.out.println(((double)d2)/10000.0);
dmvSplits.add(((double)d2)/10000.0); // truncating to 4 decimal places
}
for (int k = j+1; k < dmvcValues.length; k++){
if (Math.abs((dmvcValues[j] - dmvcValues[k])) > epsilon){
j = k-1;
break;
}
else if (k >= (dmvcValues.length -1)){
j = k;
}
}
}
dmvDivisions.put(reqdVarsL.get(i).getName(), dmvSplits);
out.write(reqdVarsL.get(i).getName()
+ " is a dmvc \n");
}
}
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Log file couldn't be opened for writing rates and bins.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
return(dmvDivisions);
}
public double calcDelay(int i, int j) {
return (data.get(0).get(j) - data.get(0).get(i));
// should add some next run logic later..?
}
public double calcDelayWithData(int i, int j, ArrayList<ArrayList<Double>> data) {
return (data.get(0).get(j) - data.get(0).get(i));
}
public void addValue(Properties p, String name, Double v) { // latest
// change..
// above one
// working fine
// if this
// doesn't
Double vMin;
Double vMax;
if ((p.getProperty(name + "_vMin") == null)
&& (p.getProperty(name + "_vMax") == null)) {
p.setProperty(name + "_vMin", v.toString());
p.setProperty(name + "_vMax", v.toString());
return;
} else {
vMin = Double.parseDouble(p.getProperty(name + "_vMin"));
vMax = Double.parseDouble(p.getProperty(name + "_vMax"));
if (v < vMin) {
vMin = v;
} else if (v > vMax) {
vMax = v;
}
}
p.setProperty(name + "_vMin", vMin.toString());
p.setProperty(name + "_vMax", vMax.toString());
}
public void addRate(Properties p, String name, Double r) { // latest
// change.. above one working fine if this doesn't
Double rMin;
Double rMax;
if ((p.getProperty(name + "_rMin") == null)
&& (p.getProperty(name + "_rMax") == null)) {
p.setProperty(name + "_rMin", r.toString());
p.setProperty(name + "_rMax", r.toString());
return;
} else {
rMin = Double.parseDouble(p.getProperty(name + "_rMin"));
rMax = Double.parseDouble(p.getProperty(name + "_rMax"));
if (r < rMin) {
rMin = r;
} else if (r > rMax) {
rMax = r;
}
}
p.setProperty(name + "_rMin", rMin.toString());
p.setProperty(name + "_rMax", rMax.toString());
}
public void addDmvcTime(Properties p, String name, Double t) {
if (p.getProperty("dmvcTime_" + name) == null) {
p.setProperty("dmvcTime_" + name, t.toString());
} else {
// Double d = Double.parseDouble(p.getProperty("dmvcTime_" + name));
// d = d + t;
// p.setProperty("dmvcTime_" + name, d.toString());
p.setProperty("dmvcTime_" + name, p.getProperty("dmvcTime_" + name)
+ " " + t.toString());
}
}
public void deleteInvalidDmvcTime(Properties p, Double t) {
String[] times = null;
String name = p.getProperty("DMVCVariable");
String s = p.getProperty("dmvcTime_" + name);
String newS = null;
Double dMin = null, dMax = null;
if (s != null) {
times = s.split(" ");
for (int i = 0; i < times.length; i++) {
if (Double.parseDouble(times[i]) != t) {
if (newS == null){
newS = times[i];
dMin = Double.parseDouble(times[i]);
dMax = Double.parseDouble(times[i]);
}
else{
newS += " " + times[i];
dMin = (Double.parseDouble(times[i]) < dMin) ? Double.parseDouble(times[i]) : dMin;
dMax = (Double.parseDouble(times[i]) > dMax) ? Double.parseDouble(times[i]) : dMax;
}
}
}
p.setProperty("dmvcTime_" + name, newS);
}
if (dMin != null){
p.setProperty("dMin", dMin.toString());
p.setProperty("dMax", dMax.toString());
}
}
public HashMap<String,ArrayList<Double>> normalize() {
Double minDelay = getMinDelay();
Double maxDelay = getMaxDelay();
Double minDivision = null;
Double maxDivision = null;
Double scaleFactor = 1.0;
HashMap<String,ArrayList<Double>> scaledThresholds = new HashMap<String,ArrayList<Double>>();
// deep copy of divisions
//for (ArrayList<Double> o1 : divisionsL){
for (String s : thresholds.keySet()){
ArrayList<Double> o1 = thresholds.get(s);
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : o1){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
scaledThresholds.put(s,tempDiv);
}
try {
out.write("minimum delay is " + minDelay
+ " before scaling time.\n");
if ((minDelay != null) && (minDelay != 0)) {
for (int i = 0; i < 18; i++) {
if (scaleFactor > (minDelayVal / minDelay)) {
break;
}
scaleFactor *= 10.0;
}
if ((maxDelay != null) && ((int) (maxDelay * scaleFactor) > Integer.MAX_VALUE)) {
System.out.println("Delay Scaling has caused an overflow");
}
out.write("minimum delay value is " + scaleFactor * minDelay
+ "after scaling by " + scaleFactor + "\n");
delayScaleFactor = scaleFactor;
scaleDelay();
}
scaleFactor = 1.0;
Double minRate = getMinRate(); // minRate should return minimum by
// magnitude alone?? or even by sign..
Double maxRate = getMaxRate();
out.write("minimum rate is " + minRate + " before scaling the variable.\n");
if ((minRate != null) && (minRate != 0)) {
for (int i = 0; i < 14; i++) {
if (scaleFactor > Math.abs(minRateVal / minRate)) {
break;
}
scaleFactor *= 10.0;
}
for (int i = 0; i < 14; i++) {
if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) < Integer.MAX_VALUE)) {
break;
}
scaleFactor /= 10.0;
}
if ((maxRate != null) && (Math.abs((int) (maxRate * scaleFactor)) > Integer.MAX_VALUE)) {
System.out.println("Rate Scaling has caused an overflow");
}
out.write("minimum rate is " + minRate * scaleFactor + " after scaling by " + scaleFactor + "\n");
varScaleFactor = scaleFactor;
scaledThresholds = scaleVariable(scaleFactor,scaledThresholds);
// TEMPORARY
/* for (String p : g.getPlaceList()){
if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){
String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor);
System.out.println(s);
}
} */
// end TEMPORARY
}
minDivision = getMinDiv(scaledThresholds);
maxDivision = getMaxDiv(scaledThresholds);
out.write("minimum division is " + minDivision + " before scaling for division.\n");
scaleFactor = 1.0;
if ((minDivision != null) && (minDivision != 0)) {
for (int i = 0; i < 14; i++) {
if (Math.abs(scaleFactor * minDivision) > minDivisionVal) {
break;
}
scaleFactor *= 10;
}
if ((maxDivision != null)
&& (Math.abs((int) (maxDivision * scaleFactor)) > Integer.MAX_VALUE)) {
System.out.println("Division Scaling has caused an overflow");
}
out.write("minimum division is " + minDivision * scaleFactor
+ " after scaling by " + scaleFactor + "\n");
varScaleFactor *= scaleFactor;
scaledThresholds = scaleVariable(scaleFactor,scaledThresholds);
// TEMPORARY
/* for (String p : g.getPlaceList()){
if ((placeInfo.get(getPlaceInfoIndex(p)).getProperty("type")).equals("PROP")){
String s = g.scaleEnabling(g.getPostset(p)[0],scaleFactor);
System.out.println(s);
}
}*/
// END TEMPORARY
}
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"LPN file couldn't be created/written",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
return(scaledThresholds);
}
public HashMap<String,ArrayList<Double>> scaleVariable(Double scaleFactor, HashMap<String,ArrayList<Double>> localThresholds) {
String place;
Properties p;
try{
for (String st1 : g.getPlaceList()) {
if (!isTransientPlace(st1)){
place = getPlaceInfoIndex(st1);
p = placeInfo.get(place);
}
else{
place = getTransientNetPlaceIndex(st1);
p = transientNetPlaces.get(place);
}
if (place != "failProp"){
/* Related to the separate net for DMV input driver
if (p.getProperty("type").equals("DMVC")) {
p.setProperty("DMVCValue", Double.toString(Double.parseDouble(p.getProperty("DMVCValue"))* scaleFactor));
} else {
*/
for (Variable v : reqdVarsL) {
if (!v.isDmvc()) {
// p.setProperty(v.getName() +
// "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName()
// + "_rMin"))/delayScaleFactor)));
// p.setProperty(v.getName() +
// "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName()
// + "_rMax"))/delayScaleFactor)));
p.setProperty(v.getName() + "_rMin", Double
.toString(Double.parseDouble(p.getProperty(v.getName()
+ "_rMin"))* scaleFactor));
p.setProperty(v.getName() + "_rMax", Double
.toString(Double.parseDouble(p.getProperty(v.getName()
+ "_rMax"))* scaleFactor));
} else {
// p.setProperty(v.getName() +
// "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName()
// + "_rMin"))/delayScaleFactor)));
// p.setProperty(v.getName() +
// "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName()
// + "_rMax"))/delayScaleFactor)));
if (!v.isInput()) {
p.setProperty(v.getName() + "_vMin", Double
.toString(Double.parseDouble(p.getProperty(v.getName()
+ "_vMin"))* scaleFactor));
p.setProperty(v.getName() + "_vMax", Double
.toString(Double.parseDouble(p.getProperty(v.getName()
+ "_vMax")) * scaleFactor));
}
}
}
}
}
/*int i = 0;
for (Variable v : reqdVarsL) {
v.scaleInitByVar(scaleFactor);
for (int j = 0; j < divisions.get(i).size(); j++) {
divisions.get(i).set(j,divisions.get(i).get(j) * scaleFactor);
}
i++;
}*/
//commented above for replacing divisionsL with thresholds
for (Variable v : reqdVarsL) {
v.scaleInitByVar(scaleFactor);
for (int j = 0; j < localThresholds.get(v.getName()).size(); j++) {
localThresholds.get(v.getName()).set(j,localThresholds.get(v.getName()).get(j) * scaleFactor);
}
}
}
catch (NullPointerException e){
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Not all regions have values for all dmv variables",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
return localThresholds;
}
public void scaleDelay() {
try{
String place;
Properties p;
for (String st1 : g.getPlaceList()) {
if (!isTransientPlace(st1)){
place = getPlaceInfoIndex(st1);
p = placeInfo.get(place);
}
else{
place = getTransientNetPlaceIndex(st1);
p = transientNetPlaces.get(place);
}
if (place != "failProp"){
/* Related to the separate net for DMV input driver
if (p.getProperty("type").equals("DMVC")) {
String[] times = null;
String name = p.getProperty("DMVCVariable");
String s = p.getProperty("dmvcTime_" + name);
String newS = null;
if (s != null) {
times = s.split(" ");
for (int i = 0; i < times.length; i++) {
if (newS == null) {
// newS = Integer.toString((int)(Double.parseDouble(times[i])*delayScaleFactor));
newS = Double.toString(Double.parseDouble(times[i])
* delayScaleFactor);
} else {
// newS = newS + Integer.toString((int)(Double.parseDouble(times[i])*delayScaleFactor));
newS = newS + " " + Double.toString(Double
.parseDouble(times[i]) * delayScaleFactor);
}
}
p.setProperty("dmvcTime_" + name, newS);
}
p.setProperty("dMin", Double.toString(Double.parseDouble(p
.getProperty("dMin")) * delayScaleFactor));
p.setProperty("dMax", Double.toString(Double.parseDouble(p
.getProperty("dMax")) * delayScaleFactor));
} else{*/
// p.setProperty("dMin",Integer.toString((int)(Double.parseDouble(p.getProperty("dMin"))*delayScaleFactor)));
// p.setProperty("dMax",Integer.toString((int)(Double.parseDouble(p.getProperty("dMax"))*delayScaleFactor)));
p.setProperty("dMin", Double.toString(Double.parseDouble(p
.getProperty("dMin")) * delayScaleFactor));
p.setProperty("dMax", Double.toString(Double.parseDouble(p
.getProperty("dMax")) * delayScaleFactor));
for (Variable v : reqdVarsL) {
if (!v.isDmvc()) {
// p.setProperty(v.getName() +
// "_rMin",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName()
// + "_rMin"))/delayScaleFactor)));
// p.setProperty(v.getName() +
// "_rMax",Integer.toString((int)(Double.parseDouble(p.getProperty(v.getName()
// + "_rMax"))/delayScaleFactor)));
p.setProperty(v.getName() + "_rMin", Double
.toString(Double.parseDouble(p.getProperty(v
.getName() + "_rMin")) / delayScaleFactor));
p.setProperty(v.getName() + "_rMax", Double
.toString(Double.parseDouble(p.getProperty(v
.getName() + "_rMax")) / delayScaleFactor));
}
}
}
}
for (Variable v : reqdVarsL) {
// if (!v.isDmvc()){ this if maynot be required.. rates do exist for dmvc ones as well.. since calculated before detectDMV
v.scaleInitByDelay(delayScaleFactor);
}
// SEE IF RATES IN TRANSITIONS HAVE TO BE ADJUSTED HERE
}
catch(NullPointerException e){
System.out.println("Delay scaling error due to null. Check");
}
}
/*
public Double getMinDiv(ArrayList<ArrayList<Double>> divisions) {
Double minDiv = divisions.get(0).get(0);
for (int i = 0; i < divisions.size(); i++) {
for (int j = 0; j < divisions.get(i).size(); j++) {
if (divisions.get(i).get(j) < minDiv) {
minDiv = divisions.get(i).get(j);
}
}
}
return minDiv;
}
public Double getMaxDiv(ArrayList<ArrayList<Double>> divisions) {
Double maxDiv = divisions.get(0).get(0);
for (int i = 0; i < divisions.size(); i++) {
for (int j = 0; j < divisions.get(i).size(); j++) {
if (divisions.get(i).get(j) > maxDiv) {
maxDiv = divisions.get(i).get(j);
}
}
}
return maxDiv;
}
Commented above for replacing divisionsL with thresholds
*/
public Double getMinDiv(HashMap<String, ArrayList<Double>> divisions) {
Double minDiv = null;
for (String s : divisions.keySet()) {
if (minDiv == null){
minDiv = divisions.get(s).get(0);
}
for (int j = 0; j < divisions.get(s).size(); j++) {
if (divisions.get(s).get(j) < minDiv) {
minDiv = divisions.get(s).get(j);
}
}
}
return minDiv;
}
public Double getMaxDiv(HashMap<String, ArrayList<Double>> divisions) {
Double maxDiv = null;
for (String s : divisions.keySet()) {
if (maxDiv == null){
maxDiv = divisions.get(s).get(0);
}
for (int j = 0; j < divisions.get(s).size(); j++) {
if (divisions.get(s).get(j) > maxDiv) {
maxDiv = divisions.get(s).get(j);
}
}
}
return maxDiv;
}
public Double getMinRate() { // minimum of entire lpn
Double minRate = null;
for (String place : placeInfo.keySet()) {
Properties p = placeInfo.get(place);
if (p.getProperty("type").equals("RATE")) {
for (Variable v : reqdVarsL) {
if ((minRate == null)
&& (p.getProperty(v.getName() + "_rMin") != null)) {
minRate = Double.parseDouble(p.getProperty(v.getName()
+ "_rMin"));
} else if ((p.getProperty(v.getName() + "_rMin") != null)
&& (Double.parseDouble(p.getProperty(v.getName()
+ "_rMin")) < minRate)
&& (Double.parseDouble(p.getProperty(v.getName()
+ "_rMin")) != 0.0)) {
minRate = Double.parseDouble(p.getProperty(v.getName()
+ "_rMin"));
}
}
}
}
return minRate;
}
public Double getMaxRate() {
Double maxRate = null;
for (String place : placeInfo.keySet()) {
Properties p = placeInfo.get(place);
if (p.getProperty("type").equals("RATE")) {
for (Variable v : reqdVarsL) {
if ((maxRate == null)
&& (p.getProperty(v.getName() + "_rMax") != null)) {
maxRate = Double.parseDouble(p.getProperty(v.getName()
+ "_rMax"));
} else if ((p.getProperty(v.getName() + "_rMax") != null)
&& (Double.parseDouble(p.getProperty(v.getName()
+ "_rMax")) > maxRate)
&& (Double.parseDouble(p.getProperty(v.getName()
+ "_rMax")) != 0.0)) {
maxRate = Double.parseDouble(p.getProperty(v.getName()
+ "_rMax"));
}
}
}
}
return maxRate;
}
public Double getMinDelay() {
Double minDelay = null;
for (String place : placeInfo.keySet()) {
Properties p = placeInfo.get(place);
/* Related to the separate net for DMV input driver
if (p.getProperty("type").equals("DMVC")) {
if ((minDelay == null) && (getMinDmvcTime(p) != null)
&& (getMinDmvcTime(p) != 0)) {
minDelay = getMinDmvcTime(p);
} else if ((getMinDmvcTime(p) != null)
&& (getMinDmvcTime(p) != 0)
&& (getMinDmvcTime(p) < minDelay)) {
minDelay = getMinDmvcTime(p);
}
} else {*/
if ((minDelay == null) && (p.getProperty("dMin") != null)
&& (Double.parseDouble(p.getProperty("dMin")) != 0)) {
minDelay = Double.parseDouble(p.getProperty("dMin"));
} else if ((p.getProperty("dMin") != null)
&& (Double.parseDouble(p.getProperty("dMin")) != 0)
&& (Double.parseDouble(p.getProperty("dMin")) < minDelay)) {
minDelay = Double.parseDouble(p.getProperty("dMin"));
}
}
return minDelay;
}
public Double getMaxDelay() {
Double maxDelay = null;
for (String place : placeInfo.keySet()) {
Properties p = placeInfo.get(place);
/* Related to the separate net for DMV input driver
if (p.getProperty("type").equals("DMVC")) {
if ((maxDelay == null) && (getMaxDmvcTime(p) != null)
&& (getMaxDmvcTime(p) != 0)) {
maxDelay = getMaxDmvcTime(p);
} else if ((getMaxDmvcTime(p) != null)
&& (getMaxDmvcTime(p) != 0)
&& (getMaxDmvcTime(p) > maxDelay)) {
maxDelay = getMaxDmvcTime(p);
}
} else {*/
if ((maxDelay == null) && (p.getProperty("dMax") != null)
&& (Double.parseDouble(p.getProperty("dMax")) != 0)) {
maxDelay = Double.parseDouble(p.getProperty("dMax"));
} else if ((p.getProperty("dMax") != null)
&& (Double.parseDouble(p.getProperty("dMax")) != 0)
&& (Double.parseDouble(p.getProperty("dMax")) > maxDelay)) {
maxDelay = Double.parseDouble(p.getProperty("dMax"));
}
}
return maxDelay;
}
/* Related to the separate net for DMV input driver
public Double getMinDmvcTime(Properties p) {
String[] times = null;
String name = p.getProperty("DMVCVariable");
String s = p.getProperty("dmvcTime_" + name);
if (s != null) {
times = s.split(" ");
Double min = Double.parseDouble(times[0]);
for (int i = 0; i < times.length; i++) {
if (Double.parseDouble(times[i]) < min) {
min = Double.parseDouble(times[i]);
}
}
return min;
} else {
return null;
}
}
public Double getMaxDmvcTime(Properties p) {
String[] times = null;
String name = p.getProperty("DMVCVariable");
String s = p.getProperty("dmvcTime_" + name);
if (s != null) {
times = s.split(" ");
Double max = Double.parseDouble(times[0]);
for (int i = 0; i < times.length; i++) {
if (Double.parseDouble(times[i]) > max) {
max = Double.parseDouble(times[i]);
}
}
return max;
} else {
return null;
}
}
*/
public void addDuration(Properties p, Double d) {
Double dMin;
Double dMax;
// d = d*(10^6);
if ((p.getProperty("dMin") == null) && (p.getProperty("dMax") == null)) {
// p.setProperty("dMin", Integer.toString((int)(Math.floor(d))));
// p.setProperty("dMax", Integer.toString((int)(Math.floor(d))));
p.setProperty("dMin", d.toString());
p.setProperty("dMax", d.toString());
return;
} else {
dMin = Double.parseDouble(p.getProperty("dMin"));
dMax = Double.parseDouble(p.getProperty("dMax"));
if (d < dMin) {
dMin = d;
} else if (d > dMax) {
dMax = d;
}
}
p.setProperty("dMin", dMin.toString());
p.setProperty("dMax", dMax.toString());
// p.setProperty("dMin", Integer.toString((int)(Math.floor(dMin))));
// p.setProperty("dMax", Integer.toString((int)(Math.ceil(dMax))));
}
public String getPlaceInfoIndex(String s) {
String index = null;
for (String st2 : placeInfo.keySet()) {
if (("p" + placeInfo.get(st2).getProperty("placeNum"))
.equalsIgnoreCase(s)) {
index = st2;
break;
}
}
return index;
}
public String getTransientNetPlaceIndex(String s) {
String index = null;
for (String st2 : transientNetPlaces.keySet()) {
if (("p" + transientNetPlaces.get(st2).getProperty("placeNum"))
.equalsIgnoreCase(s)) {
index = st2;
break;
}
}
return index;
}
public ArrayList<Integer> diff(String pre_bin, String post_bin) {
ArrayList<Integer> diffL = new ArrayList<Integer>();
// String p_bin[] = p.getBinEncoding();
// String[] preset_encoding = pre_bin.split("");
// String[] postset_encoding = post_bin.split("");
String[] preset_encoding = pre_bin.split(",");
String[] postset_encoding = post_bin.split(",");
for (int j = 0; j < preset_encoding.length; j++) { // to account for ""
// being created in the array
if (Integer.parseInt(preset_encoding[j]) != Integer
.parseInt(postset_encoding[j])) {
diffL.add(j);// to account for "" being created in the
// array
}
}
return (diffL);
}
public int getMinRate(String place, String name) {
Properties p = placeInfo.get(place);
return ((int) Math.floor(Double.parseDouble(p.getProperty(name
+ "_rMin"))));
// return(rMin[i]);
}
public int getMaxRate(String place, String name) {
Properties p = placeInfo.get(place);
return ((int) Math.floor(Double.parseDouble(p.getProperty(name
+ "_rMax"))));
// return(rMin[i]);
}
/* public Double[][] getDataExtrema(ArrayList<ArrayList<Double>> data){
Double[][] extrema = new Double[reqdVarsL.size()][2];
for (int i=0; i<reqdVarsL.size(); i++){
//Object obj = Collections.min(data.get(reqdVarIndices.get(i)));
Object obj = Collections.min(data.get(i+1));
extrema[i][0] = Double.parseDouble(obj.toString());
//obj = Collections.max(data.get(reqdVarIndices.get(i)));
obj = Collections.max(data.get(i+1));
extrema[i][1] = Double.parseDouble(obj.toString());
}
return extrema;
}
*/
public HashMap <String, Double[]> getDataExtrema(ArrayList<ArrayList<Double>> data){
HashMap <String, Double[]> extrema = new HashMap <String, Double[]>();
for (int i=0; i<reqdVarsL.size(); i++){
//Object obj = Collections.min(data.get(reqdVarIndices.get(i)));
Object obj = Collections.min(data.get(i+1));
extrema.put(reqdVarsL.get(i).getName(),new Double[2]);
extrema.get(reqdVarsL.get(i).getName())[0] = Double.parseDouble(obj.toString());
//obj = Collections.max(data.get(reqdVarIndices.get(i)));
obj = Collections.max(data.get(i+1));
extrema.get(reqdVarsL.get(i).getName())[1] = Double.parseDouble(obj.toString());
}
return extrema;
}
/* //public ArrayList<ArrayList<Double>> initDivisions(Double[][] extrema, ArrayList<ArrayList<Double>> divisions ){
public ArrayList<ArrayList<Double>> initDivisions(Double[][] extrema){
//public HashMap<String, ArrayList<Double>> initDivisions(Double[][] extrema){
int numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1;
double interval;
ArrayList<ArrayList<Double>> divisions = new ArrayList<ArrayList<Double>>(); //changed for replacing divisionsL by threholds
//HashMap<String, ArrayList<Double>> localThresholds = new HashMap<String, ArrayList<Double>> ();
for (int i = 0; i < reqdVarsL.size(); i++){
divisions.add(new ArrayList<Double>());//changed for replacing divisionsL by threholds
//localThresholds.put(reqdVarsL.get(i).getName(),new ArrayList<Double>());
if (!suggestIsSource){ // could use user.isselected instead of this.
//numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1;
}
else{
numThresholds = Integer.parseInt((String)((JComboBox)((JPanel)variablesPanel.getComponent(i+1)).getComponent(3)).getSelectedItem())-1; // changed 2 to 3 after required
}
interval = (Math.abs(extrema[i][1] - extrema[i][0]))/(numThresholds + 1);
for (int j = 0; j< numThresholds; j++){
//if ((divisions.get(i).size() == 0) || (divisions.get(i).get(j) == null)){
// divisions.get(i).set(j,extrema[i][0] + interval*j);
//}
if (divisions.get(i).size() <= j){
divisions.get(i).add(extrema[i][0] + interval*(j+1)); // j+1
}
else{
divisions.get(i).set(j,extrema[i][0] + interval*(j+1)); // j+1
}//changed for replacing divisionsL by threholds
//if (localThresholds.get(reqdVarsL.get(i).getName()).size() <= j){
// localThresholds.get(reqdVarsL.get(i).getName()).add(extrema[i][0] + interval*(j+1)); // j+1
//}
//else{
// localThresholds.get(reqdVarsL.get(i).getName()).set(j,extrema[i][0] + interval*(j+1)); // j+1
//}
}
}
suggestIsSource = false;
return divisions;
//return localThresholds;
}*/
//public ArrayList<ArrayList<Double>> initDivisions(Double[][] extrema, ArrayList<ArrayList<Double>> divisions ){
//public ArrayList<ArrayList<Double>> initDivisions(Double[][] extrema){
public HashMap<String, ArrayList<Double>> initDivisions(HashMap<String,Double[]> extrema){
int numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1;
double interval;
//ArrayList<ArrayList<Double>> divisions = new ArrayList<ArrayList<Double>>(); //changed for replacing divisionsL by threholds
HashMap<String, ArrayList<Double>> localThresholds = new HashMap<String, ArrayList<Double>> ();
for (int i = 0; i < reqdVarsL.size(); i++){
//divisions.add(new ArrayList<Double>());//changed for replacing divisionsL by threholds
localThresholds.put(reqdVarsL.get(i).getName(),new ArrayList<Double>());
if (!suggestIsSource){ // could use user.isselected instead of this.
//numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1;
}
else{
for (int j = 1; j < variablesPanel.getComponentCount(); j++){
if ((((JTextField)((JPanel)variablesPanel.getComponent(j)).getComponent(0)).getText().trim()).equalsIgnoreCase(reqdVarsL.get(i).getName())){
numThresholds = Integer.parseInt((String)((JComboBox)((JPanel)variablesPanel.getComponent(j)).getComponent(3)).getSelectedItem())-1; // changed 2 to 3 after required
break;
}
}
}
if (numThresholds != -1){
interval = (Math.abs(extrema.get(reqdVarsL.get(i).getName())[1] - extrema.get(reqdVarsL.get(i).getName())[0]))/(numThresholds + 1);
for (int j = 0; j< numThresholds; j++){
//if ((divisions.get(i).size() == 0) || (divisions.get(i).get(j) == null)){
// divisions.get(i).set(j,extrema[i][0] + interval*j);
/*if (divisions.get(i).size() <= j){
divisions.get(i).add(extrema[i][0] + interval*(j+1)); // j+1
}
else{
divisions.get(i).set(j,extrema[i][0] + interval*(j+1)); // j+1
}*///changed for replacing divisionsL by threholds*/
if (localThresholds.get(reqdVarsL.get(i).getName()).size() <= j){
localThresholds.get(reqdVarsL.get(i).getName()).add(extrema.get(reqdVarsL.get(i).getName())[0] + interval*(j+1));
}
else{
localThresholds.get(reqdVarsL.get(i).getName()).set(j,extrema.get(reqdVarsL.get(i).getName())[0] + interval*(j+1));
}
}
}
}
suggestIsSource = false;
//return divisions;
return localThresholds;
}
/**
* This method generates thresholds for the variables in the learn view.
* If auto generate option is selected, then the number of thresholds for
* all the variables is same as the number selected in the number of bins.
* If user generation option is selected & suggest button is pressed, then
* the number of thresholds for each variable is equal to the number selected
* in the combobox against that variable in the variablesPanel.
*
* Rev. 1 - Scott Little (autogenT.py)
* Rev. 2 - Satish Batchu ( autogenT() ) -- Aug 12, 2009
*/
/*
//public ArrayList<ArrayList<Double>> autoGenT(ArrayList<ArrayList<Double>> divisions ){
public ArrayList<ArrayList<Double>> autoGenT(JFrame running){//changed for replacing divisionsL by threholds
//public HashMap<String,ArrayList<Double>> autoGenT(JFrame running){
//int iterations = Integer.parseInt(iteration.getText());
ArrayList<ArrayList<Double>> fullData = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> singleFileData = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> divisions = new ArrayList<ArrayList<Double>>(); //changed for replacing divisionsL by threholds
//HashMap<String, ArrayList<Double>> localThresholds = new HashMap<String, ArrayList<Double>>();
//ArrayList<String> allVars;
int i = 1;
try{
while (new File(directory + separator + "run-" + i + ".tsd").exists()) {
TSDParser tsd = new TSDParser(directory + separator + "run-" + i +".tsd",biosim, false);
singleFileData = tsd.getData();
varNames = tsd.getSpecies();
if (i == 1){
fullData.add(new ArrayList<Double>());
}
(fullData.get(0)).addAll(singleFileData.get(0));
for (int k = 0; k < reqdVarsL.size(); k++){
for (int j = 0; j< singleFileData.size(); j++){
if (reqdVarsL.get(k).getName().equalsIgnoreCase(varNames.get(j))) {
if (i == 1){
fullData.add(new ArrayList<Double>());
}
(fullData.get(k+1)).addAll(singleFileData.get(j));
break;
}
}
}
i++;
}
Double[][] extrema = getDataExtrema(fullData); //CHANGE THIS TO HASHMAP for replacing divisionsL by threholds
//divisions = initDivisions(extrema,divisions);
divisions = initDivisions(extrema); //changed for replacing divisionsL by threholds
divisions = greedyOpt(divisions,fullData,extrema); //changed for replacing divisionsL by threholds
//localThresholds = initDivisions(extrema);
//localThresholds = greedyOpt(localThresholds,fullData,extrema);
// Overwriting dmv divisions calculated above with those that come from detectDMV here.
findReqdVarIndices(); // not required in this case
HashMap<String, ArrayList<Double>> dmvDivs = detectDMV(fullData,true);
for (String k : dmvDivs.keySet()){
for (int l = 0; l < reqdVarsL.size(); l++){
if (k.equalsIgnoreCase(reqdVarsL.get(l).getName())){
divisions.get(l).clear();
divisions.get(l).addAll(dmvDivs.get(k));
//localThresholds.get(reqdVarsL.get(l).getName()).clear();
//localThresholds.get(reqdVarsL.get(l).getName()).addAll(dmvDivs.get(k));
// System.out.println("Divisions for " + k + " are ");
// for (Double d : dmvDivs.get(k)){
// System.out.println(d.toString() + " ");
// }
// System.out.print("\n");
}
}
}
}
catch(NullPointerException e){
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to calculate rates.\nThresholds could not be generated\nWindow size or pathlength must be reduced.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
try {
out.write("ERROR! Unable to calculate rates.\nThresholds could not be generated\nIf Window size = -1, pathlength must be reduced;\nElse, reduce windowsize\nLearning unsuccessful.");
out.close();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
running.setCursor(null);
running.dispose();
}
return divisions; //changed for replacing divisionsL by threholds
//return localThresholds;
}
*/
//public ArrayList<ArrayList<Double>> autoGenT(JFrame running){//changed for replacing divisionsL by threholds
public HashMap<String,ArrayList<Double>> autoGenT(JFrame running){
//int iterations = Integer.parseInt(iteration.getText());
ArrayList<ArrayList<Double>> fullData = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> singleFileData = new ArrayList<ArrayList<Double>>();
//ArrayList<ArrayList<Double>> divisions = new ArrayList<ArrayList<Double>>(); //changed for replacing divisionsL by threholds
HashMap<String, ArrayList<Double>> localThresholds = new HashMap<String, ArrayList<Double>>();
//ArrayList<String> allVars;
int i = 1;
try{
while (new File(directory + separator + "run-" + i + ".tsd").exists()) {
TSDParser tsd = new TSDParser(directory + separator + "run-" + i +".tsd",biosim, false);
singleFileData = tsd.getData();
varNames = tsd.getSpecies();
if (i == 1){
fullData.add(new ArrayList<Double>());
}
(fullData.get(0)).addAll(singleFileData.get(0));
for (int k = 0; k < reqdVarsL.size(); k++){
for (int j = 0; j< singleFileData.size(); j++){
if (reqdVarsL.get(k).getName().equalsIgnoreCase(varNames.get(j))) {
if (i == 1){
fullData.add(new ArrayList<Double>());
}
(fullData.get(k+1)).addAll(singleFileData.get(j));
break;
}
}
}
i++;
}
int numThresholds = -1;
findReqdVarIndices(); // not required in this case
HashMap<String, ArrayList<Double>> dmvDivs = detectDMV(fullData,true);
HashMap<String, Integer> varThresholds = new HashMap<String, Integer>();
if (!suggestIsSource){
numThresholds = Integer.parseInt(numBins.getSelectedItem().toString()) - 1; //after adding 0 to comboboxes
if (numThresholds == -1){
for (String k : dmvDivs.keySet()){
for (int l = 0; l < reqdVarsL.size(); l++){
if (!reqdVarsL.get(l).isDmvc()){
JOptionPane.showMessageDialog(biosim.frame(),
"Can't generate the number of thresholds for continuous variables.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
try {
out.write("ERROR! Can't generate the number of thresholds for continuous variables.");
out.close();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
running.setCursor(null);
running.dispose();
return(localThresholds);
}
if (k.equalsIgnoreCase(reqdVarsL.get(l).getName())){
localThresholds.put(k,dmvDivs.get(k));
}
}
}
}
}
else{
for (int k = 0; k < reqdVarsL.size(); k++){
for (int j = 1; j < variablesPanel.getComponentCount(); j++){
if ((((JTextField)((JPanel)variablesPanel.getComponent(j)).getComponent(0)).getText().trim()).equalsIgnoreCase(reqdVarsL.get(k).getName())){
numThresholds = Integer.parseInt((String)((JComboBox)((JPanel)variablesPanel.getComponent(j)).getComponent(3)).getSelectedItem()) -1; // changed 2 to 3 after required
varThresholds.put(reqdVarsL.get(k).getName(),Integer.valueOf(numThresholds));
if (numThresholds == -1){
if (!reqdVarsL.get(k).isDmvc()){
JOptionPane.showMessageDialog(biosim.frame(),
"Can't generate the number of thresholds for continuous variables.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
try {
out.write("ERROR! Can't generate the number of thresholds for continuous variables.");
out.close();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
running.setCursor(null);
running.dispose();
return(localThresholds);
}
localThresholds.put(reqdVarsL.get(k).getName(),dmvDivs.get(reqdVarsL.get(k).getName()));
}
break;
}
}
}
}
if ((suggestIsSource && (Collections.max(varThresholds.values()) == -1)) || (!suggestIsSource && (numThresholds == -1))){
}
else{
HashMap<String, Double[]> extrema = getDataExtrema(fullData); //CHANGE THIS TO HASHMAP for replacing divisionsL by threholds
//divisions = initDivisions(extrema,divisions);
//divisions = initDivisions(extrema); //changed for replacing divisionsL by threholds
//divisions = greedyOpt(divisions,fullData,extrema); //changed for replacing divisionsL by threholds
localThresholds = initDivisions(extrema);
localThresholds = greedyOpt(localThresholds,fullData,extrema);
// Overwriting dmv divisions calculated above with those that come from detectDMV here.
for (int l = 0; l < reqdVarsL.size(); l++){
for (String k : dmvDivs.keySet()){
if ((k.equalsIgnoreCase(reqdVarsL.get(l).getName())) && (varThresholds.get(k) == -1)){
//divisions.get(l).clear();
//divisions.get(l).addAll(dmvDivs.get(k));
localThresholds.get(reqdVarsL.get(l).getName()).clear();
localThresholds.get(reqdVarsL.get(l).getName()).addAll(dmvDivs.get(k));
// System.out.println("Divisions for " + k + " are ");
// for (Double d : dmvDivs.get(k)){
// System.out.println(d.toString() + " ");
// System.out.print("\n");
}
}
}
}
}
catch(NullPointerException e){
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to calculate rates.\nThresholds could not be generated\nWindow size or pathlength must be reduced.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
try {
out.write("ERROR! Unable to calculate rates.\nThresholds could not be generated\nIf Window size = -1, pathlength must be reduced;\nElse, reduce windowsize\nLearning unsuccessful.");
out.close();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
running.setCursor(null);
running.dispose();
}
//return divisions; //changed for replacing divisionsL by threholds
return localThresholds;
}
/* public ArrayList<ArrayList<Double>> greedyOpt(ArrayList<ArrayList<Double>> divisions,ArrayList<ArrayList<Double>> fullData, Double[][] extrema){
ArrayList<ArrayList<Double>> newDivs = new ArrayList<ArrayList<Double>>(); // = divisions; // initialization rechk??
ArrayList<Integer> res = new ArrayList<Integer>();
int updateVar = 0;
Double bestCost =0.0,newCost;
Double distance = 0.0;
boolean pointsSelected = false;
int numMoves = 0;
int iterations = Integer.parseInt(iteration.getText());
if (points.isSelected()){
pointsSelected = true;
bestCost = pointDistCost(fullData, divisions,res,updateVar);
}
else if (range.isSelected()){
pointsSelected = false;
bestCost = rateRangeCost(fullData, divisions);
}
while (numMoves < iterations){
for (int i = 0; i < divisions.size(); i++){
for (int j = 0; j < divisions.get(i).size(); j++){
if (j == 0){
if (divisions.get(i).get(j) != null){
distance = Math.abs(divisions.get(i).get(j) - extrema[i][0])/2;
}
else{// will else case ever occur???
distance = Math.abs(divisions.get(i).get(j) - divisions.get(i).get(j-1))/2;
}
}
else{
distance = Math.abs(divisions.get(i).get(j) - divisions.get(i).get(j-1))/2;
}
// deep copy
//newDivs = divisions;
newDivs = new ArrayList<ArrayList<Double>>();
for (ArrayList<Double> o1 : divisions){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : o1){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
newDivs.add(tempDiv);
}
newDivs.get(i).set(j,newDivs.get(i).get(j)-distance);
if (pointsSelected){
newCost = pointDistCost(fullData,newDivs,res,i+1);
}
else{
newCost = rateRangeCost(fullData, newDivs);
}
numMoves++;
if (numMoves % 500 == 0){
System.out.println("Iteration "+ numMoves + "/" + iterations);
}
if (newCost < bestCost){
bestCost = newCost;
divisions = new ArrayList<ArrayList<Double>>();
for (ArrayList<Double> o1 : newDivs){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : o1){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
divisions.add(tempDiv);
}
// divisions = newDivs; deep copy ?????
}
else{
if (j == (divisions.get(i).size() - 1)){
distance = Math.abs(extrema[i][1] - divisions.get(i).get(j))/2;
}
else{
distance = Math.abs(divisions.get(i).get(j+1) - divisions.get(i).get(j))/2;
}
// deep copy
//newDivs = divisions;
newDivs = new ArrayList<ArrayList<Double>>();
for (ArrayList<Double> o1 : divisions){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : o1){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
newDivs.add(tempDiv);
}
newDivs.get(i).set(j,newDivs.get(i).get(j)+distance);
if (pointsSelected){
newCost = pointDistCost(fullData,newDivs,res,i+1);
}
else{
newCost = rateRangeCost(fullData, newDivs);
}
numMoves++;
if (numMoves % 500 == 0){
System.out.println("Iteration "+ numMoves + "/" + iterations);
}
if (newCost < bestCost){
bestCost = newCost;
divisions = new ArrayList<ArrayList<Double>>();
for (ArrayList<Double> o1 : newDivs){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : o1){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
divisions.add(tempDiv);
}
// divisions = newDivs; deep copy ?????
}
if (numMoves > iterations){
return divisions;
}
}
}
}
}
return divisions;
}*/
public HashMap<String, ArrayList<Double>> greedyOpt(HashMap<String, ArrayList<Double>> localThresholds,ArrayList<ArrayList<Double>> fullData, HashMap<String,Double[]> extrema){
HashMap<String, ArrayList<Double>> newThresholds = new HashMap<String, ArrayList<Double>>(); // = divisions; // initialization rechk??
ArrayList<Integer> res = new ArrayList<Integer>();
int updateVar = 0;
Double bestCost =0.0,newCost;
Double distance = 0.0;
boolean pointsSelected = false;
int numMoves = 0;
int iterations = Integer.parseInt(iteration.getText());
if (points.isSelected()){
pointsSelected = true;
bestCost = pointDistCost(fullData, localThresholds,res,updateVar);
}
else if (range.isSelected()){
pointsSelected = false;
bestCost = rateRangeCost(fullData, localThresholds);
}
while (numMoves < iterations){ // Infinite loop here if thresholds not present in localThresholds
for (int i = 0; i < localThresholds.size(); i++){
for (int j = 0; j < localThresholds.get(reqdVarsL.get(i).getName()).size(); j++){
if (j == 0){
if (localThresholds.get(reqdVarsL.get(i).getName()).get(j) != null){
distance = Math.abs(localThresholds.get(reqdVarsL.get(i).getName()).get(j) - extrema.get(reqdVarsL.get(i).getName())[0])/2;
}
else{// will else case ever occur???
distance = Math.abs(localThresholds.get(reqdVarsL.get(i).getName()).get(j) - localThresholds.get(reqdVarsL.get(i).getName()).get(j-1))/2;
}
}
else{
distance = Math.abs(localThresholds.get(reqdVarsL.get(i).getName()).get(j) - localThresholds.get(reqdVarsL.get(i).getName()).get(j-1))/2;
}
// deep copy
//newDivs = divisions;
newThresholds = new HashMap<String, ArrayList<Double>>();
for (String s : localThresholds.keySet()){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : localThresholds.get(s)){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
newThresholds.put(s, tempDiv);
}
newThresholds.get(reqdVarsL.get(i).getName()).set(j,newThresholds.get(reqdVarsL.get(i).getName()).get(j)-distance);
if (pointsSelected){
newCost = pointDistCost(fullData,newThresholds,res,i+1);
}
else{
newCost = rateRangeCost(fullData, newThresholds);
}
numMoves++;
if (numMoves % 500 == 0){
System.out.println("Iteration "+ numMoves + "/" + iterations);
}
if (newCost < bestCost){
bestCost = newCost;
localThresholds = new HashMap<String, ArrayList<Double>>();
for (String s : newThresholds.keySet()){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : newThresholds.get(s)){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
localThresholds.put(s, tempDiv);
}
// divisions = newDivs; deep copy ?????
}
else{
if (j == (localThresholds.get(reqdVarsL.get(i).getName()).size() - 1)){
distance = Math.abs(extrema.get(reqdVarsL.get(i).getName())[1] - localThresholds.get(reqdVarsL.get(i).getName()).get(j))/2;
}
else{
distance = Math.abs(localThresholds.get(reqdVarsL.get(i).getName()).get(j+1) - localThresholds.get(reqdVarsL.get(i).getName()).get(j))/2;
}
// deep copy
//newDivs = divisions;
newThresholds = new HashMap<String, ArrayList<Double>>();
for (String s : localThresholds.keySet()){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : localThresholds.get(s)){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
newThresholds.put(s, tempDiv);
}
newThresholds.get(reqdVarsL.get(i).getName()).set(j,newThresholds.get(reqdVarsL.get(i).getName()).get(j)+distance);
if (pointsSelected){
newCost = pointDistCost(fullData,newThresholds,res,i+1);
}
else{
newCost = rateRangeCost(fullData, newThresholds);
}
numMoves++;
if (numMoves % 500 == 0){
System.out.println("Iteration "+ numMoves + "/" + iterations);
}
if (newCost < bestCost){
bestCost = newCost;
localThresholds = new HashMap<String, ArrayList<Double>>();
for (String s : newThresholds.keySet()){
ArrayList<Double> tempDiv = new ArrayList<Double>();
for (Double o2 : newThresholds.get(s)){
tempDiv.add( o2.doubleValue()); // clone() not working here
}
localThresholds.put(s, tempDiv);
}
// divisions = newDivs; deep copy ?????
}
if (numMoves > iterations){
return localThresholds;
}
}
}
}
}
return localThresholds;
}
// CHANGE EXTREMA TO HASHMAP for for replacing divisionsL by threholds in autogenT
/* public Double rateRangeCost(ArrayList<ArrayList<Double>> fullData, ArrayList<ArrayList<Double>> divisions){
Double total = 0.0;
Double[] minMaxR = {null,null};
//genBinsRates(datFile, divisions);
Double[][] rates = genBinsRatesForAutogen(fullData, divisions);
for (int i = 0; i < divisions.size(); i++){
minMaxR = getMinMaxRates(rates[i]);
total += Math.abs(minMaxR[1] - minMaxR[0]);
}
return total;
}*/
public Double rateRangeCost(ArrayList<ArrayList<Double>> fullData, HashMap<String, ArrayList<Double>> localThresholds){
Double total = 0.0;
Double[] minMaxR = {null,null};
//genBinsRates(datFile, divisions);
Double[][] rates = genBinsRatesForAutogen(fullData, localThresholds);
for (int i = 0; i < localThresholds.size(); i++){
minMaxR = getMinMaxRates(rates[i]);
total += Math.abs(minMaxR[1] - minMaxR[0]);
}
return total;
}
/* public Double pointDistCost(ArrayList<ArrayList<Double>> fullData,ArrayList<ArrayList<Double>> divisions, ArrayList<Integer> res, int updateVar ){
Double total = 0.0;
int pts = 0;
if (updateVar == 0){
for (int i = 0; i < divisions.size() + 1; i++){
res.add(0);
}
for (int i = 0; i < divisions.size(); i++){
pts = pointDistCostVar(fullData.get(i+1),divisions.get(i));
total += pts;
res.set(i,pts);
}
}
else if (updateVar > 0){ // res is kind of being passed by reference. it gets altered outside too.
res.set(updateVar-1, pointDistCostVar(fullData.get(updateVar),divisions.get(updateVar-1)));
for (Integer i : res){
total += i;
}
//for (int i = 0; i < res.size(); i++){
// if ((updateVar - 1) != i){
// total += res.get(i);
// }
// else{
// total += pointDistCostVar(fullData.get(updateVar),divisions.get(updateVar-1))
// }
//}
}
else{
for (int i = 0; i < divisions.size(); i++){
total += pointDistCostVar(fullData.get(i+1),divisions.get(i));
}
}
return total;
}*/
public Double pointDistCost(ArrayList<ArrayList<Double>> fullData,HashMap<String, ArrayList<Double>> localThresholds, ArrayList<Integer> res, int updateVar ){
Double total = 0.0;
int pts = 0;
if (updateVar == 0){
for (int i = 0; i < localThresholds.size() + 1; i++){
res.add(0);
}
for (int i = 0; i < localThresholds.size(); i++){
pts = pointDistCostVar(fullData.get(i+1),localThresholds.get(reqdVarsL.get(i).getName()));
total += pts;
res.set(i,pts);
}
}
else if (updateVar > 0){ // res is kind of being passed by reference. it gets altered outside too.
res.set(updateVar-1, pointDistCostVar(fullData.get(updateVar),localThresholds.get(reqdVarsL.get(updateVar-1).getName())));
for (Integer i : res){
total += i;
}
//for (int i = 0; i < res.size(); i++){
// if ((updateVar - 1) != i){
// total += res.get(i);
// else{
// total += pointDistCostVar(fullData.get(updateVar),divisions.get(updateVar-1))
}
else{
for (int i = 0; i < localThresholds.size(); i++){
total += pointDistCostVar(fullData.get(i+1),localThresholds.get(reqdVarsL.get(i).getName()));
}
}
return total;
}
public int pointDistCostVar(ArrayList<Double> dat,ArrayList<Double> div){
int optPointsPerBin = dat.size()/(div.size()+1);
boolean top = false;
ArrayList<Integer> pointsPerBin = new ArrayList<Integer>();
for (int i =0; i < (div.size() +1); i++){
pointsPerBin.add(0);
}
for (int i = 0; i <dat.size() ; i++){
top = true;
for (int j =0; j < div.size(); j++){
if (dat.get(i) <= div.get(j)){
pointsPerBin.set(j, pointsPerBin.get(j)+1);
top = false;
break;
}
}
if (top){
pointsPerBin.set(div.size(), pointsPerBin.get(div.size()) + 1);
}
}
int score = 0;
for (Integer pts : pointsPerBin){
score += Math.abs(pts - optPointsPerBin );
}
return score;
}
public Double[] getMinMaxRates(Double[] rateList){
ArrayList<Double> cmpL = new ArrayList<Double>();
Double[] minMax = {null,null};// new Double[2];
for (Double r : rateList){
if (r != null){
cmpL.add(r);
}
}
if (cmpL.size() > 0){
Object obj = Collections.min(cmpL);
minMax[0] = Double.parseDouble(obj.toString());
obj = Collections.max(cmpL);
minMax[1] = Double.parseDouble(obj.toString());
}
return minMax;
}
public Double[][] genBinsRatesForAutogen(ArrayList<ArrayList<Double>> data,ArrayList<ArrayList<Double>> divisionsL) { // genBins
// public void genBinsRates(String datFile,ArrayList<ArrayList<Double>> divisionsL) { // genBins
// TSDParser tsd = new TSDParser(directory + separator + datFile, biosim,false);
// genBins
// data = tsd.getData();
rateSampling = Integer.parseInt(rateSamplingG.getText().trim());
pathLength = Integer.parseInt(pathLengthG.getText().trim());
// ArrayList<Integer> reqdVarIndices = new ArrayList<Integer>();
int[][] bins = new int[reqdVarsL.size()][data.get(0).size()];
for (int i = 0; i < reqdVarsL.size(); i++) {
// for (int j = 1; j < varNames.size(); j++) {
// if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) {
// System.out.println(reqdVarsL.get(i) + " matched "+
// varNames.get(j) + " i = " + i + " j = " + j);
// reqdVarIndices.add(j);
for (int k = 0; k < data.get(i+1).size(); k++) {
for (int l = 0; l < divisionsL.get(i).size(); l++) {
if (data.get(i+1).get(k) <= divisionsL.get(i).get(l)) {
bins[i][k] = l;
break;
} else {
bins[i][k] = l + 1; // indices of bins not same as that of the variable. i here. not j; if j
// wanted, then size of bins array should be varNames not reqdVars
}
}
}
}
/*
* System.out.println("array bins is :"); for (int i = 0; i <
* reqdVarsL.size(); i++) { System.out.print(reqdVarsL.get(i).getName() + "
* "); for (int k = 0; k < data.get(0).size(); k++) {
* System.out.print(bins[i][k] + " "); } System.out.print("\n"); }
*/
// genRates
Double[][] rates = new Double[reqdVarsL.size()][data.get(0).size()];
Double[] duration = new Double[data.get(0).size()];
int mark ; //, k; // indices of rates not same as that of the variable. if
// wanted, then size of rates array should be varNames not reqdVars
if (placeRates) {
if (rateSampling == -1) { // replacing inf with -1 since int
mark = 0;
for (int i = 0; i < data.get(0).size(); i++) {
if (i < mark) {
continue;
}
while ((mark < data.get(0).size()) && (compareBins(i, mark,bins))) {
mark++;
}
if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLength)) {
for (int j = 0; j < reqdVarsL.size(); j++) {
//k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(j+1).get(mark - 1) - data.get(j+1).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i)));
}
duration[i] = data.get(0).get(mark - 1) - data.get(0).get(i);
}
}
} else {
boolean calcRate;
boolean prevFail = true;
int binStartPoint = 0, binEndPoint = 0;
for (int i = 0; i < (data.get(0).size() - rateSampling); i++) {
calcRate = true;
for (int l = 0; l < rateSampling; l++) {
if (!compareBins(i, i + l,bins)) {
if (!prevFail){
binEndPoint = i -2 + rateSampling;
duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint);
}
calcRate = false;
prevFail = true;
break;
}
}
if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) {
for (int j = 0; j < reqdVarsL.size(); j++) {
//k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(j+1).get(i + rateSampling) - data.get(j+1).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i)));
}
if (prevFail){
binStartPoint = i;
}
prevFail = false;
}
}
if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt
duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint);
}
}
}
/*
* ADD LATER: duration[i] SHOULD BE ADDED TO THE NEXT 2 IF/ELSE
* BRANCHES(Transition based rate calc) ALSO
*/
else { // Transition based rate calculation
if (rateSampling == -1) { // replacing inf with -1 since int
for (int j = 0; j < reqdVarsL.size(); j++) {
mark = 0;
//k = reqdVarIndices.get(j);
for (int i = 0; i < data.get(0).size(); i++) {
if (i < mark) {
continue;
}
while ((mark < data.get(0).size())
&& (bins[j][i] == bins[j][mark])) {
mark++;
}
if ((data.get(0).get(mark - 1) != data.get(0).get(i))) {
rates[j][i] = ((data.get(j+1).get(mark - 1) - data.get(j+1).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i)));
}
}
}
} else {
boolean calcRate;
for (int i = 0; i < (data.get(0).size() - rateSampling); i++) {
for (int j = 0; j < reqdVarsL.size(); j++) {
calcRate = true;
//k = reqdVarIndices.get(j);
for (int l = 0; l < rateSampling; l++) {
if (bins[j][i] != bins[j][i + l]) {
calcRate = false;
break;
}
}
if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) {
rates[j][i] = ((data.get(j+1).get(i + rateSampling) - data.get(j+1).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i)));
}
}
}
}
}
/*
try {
logFile = new File(directory + separator + "tmp.log");
logFile.createNewFile();
out = new BufferedWriter(new FileWriter(logFile));
for (int i = 0; i < (data.get(0).size()); i++) {
for (int j = 0; j < reqdVarsL.size(); j++) {
//k = reqdVarIndices.get(j);
out.write(data.get(j+1).get(i) + " ");// + bins[j][i] + " " +
// rates[j][i] + " ");
}
for (int j = 0; j < reqdVarsL.size(); j++) {
out.write(bins[j][i] + " ");
}
for (int j = 0; j < reqdVarsL.size(); j++) {
out.write(rates[j][i] + " ");
}
out.write(duration[i] + " ");
out.write("\n");
}
out.close();
} catch (IOException e) {
System.out.println("Log file couldn't be opened for writing rates and bins ");
}*/
return rates;
}
public Double[][] genBinsRatesForAutogen(ArrayList<ArrayList<Double>> data,HashMap<String, ArrayList<Double>> localThresholds) { // genBins
// public void genBinsRates(String datFile,ArrayList<ArrayList<Double>> divisionsL) { // genBins
// TSDParser tsd = new TSDParser(directory + separator + datFile, biosim,false);
// genBins
// data = tsd.getData();
rateSampling = Integer.parseInt(rateSamplingG.getText().trim());
pathLength = Integer.parseInt(pathLengthG.getText().trim());
// ArrayList<Integer> reqdVarIndices = new ArrayList<Integer>();
int[][] bins = new int[reqdVarsL.size()][data.get(0).size()];
for (int i = 0; i < reqdVarsL.size(); i++) {
// for (int j = 1; j < varNames.size(); j++) {
// if (reqdVarsL.get(i).getName().equalsIgnoreCase(varNames.get(j))) {
// System.out.println(reqdVarsL.get(i) + " matched "+
// varNames.get(j) + " i = " + i + " j = " + j);
// reqdVarIndices.add(j);
//changes made here for replacing divisionsL with thresholds
String currentVar = reqdVarsL.get(i).getName();
for (int k = 0; k < data.get(i+1).size(); k++) {
for (int l = 0; l < localThresholds.get(currentVar).size(); l++) {
if (data.get(i+1).get(k) <= localThresholds.get(currentVar).get(l)) {
bins[i][k] = l;
break;
} else {
bins[i][k] = l + 1; // indices of bins not same as that of the variable. i here. not j; if j
// wanted, then size of bins array should be varNames not reqdVars
}
}
}
}
/*
* System.out.println("array bins is :"); for (int i = 0; i <
* reqdVarsL.size(); i++) { System.out.print(reqdVarsL.get(i).getName() + "
* "); for (int k = 0; k < data.get(0).size(); k++) {
* System.out.print(bins[i][k] + " "); } System.out.print("\n"); }
*/
// genRates
Double[][] rates = new Double[reqdVarsL.size()][data.get(0).size()];
Double[] duration = new Double[data.get(0).size()];
int mark ; //, k; // indices of rates not same as that of the variable. if
// wanted, then size of rates array should be varNames not reqdVars
if (placeRates) {
if (rateSampling == -1) { // replacing inf with -1 since int
mark = 0;
for (int i = 0; i < data.get(0).size(); i++) {
if (i < mark) {
continue;
}
while ((mark < data.get(0).size()) && (compareBins(i, mark,bins))) {
mark++;
}
if ((data.get(0).get(mark - 1) != data.get(0).get(i)) && ((mark - i) >= pathLength)) {
for (int j = 0; j < reqdVarsL.size(); j++) {
//k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(j+1).get(mark - 1) - data.get(j+1).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i)));
}
duration[i] = data.get(0).get(mark - 1) - data.get(0).get(i);
}
}
} else {
boolean calcRate;
boolean prevFail = true;
int binStartPoint = 0, binEndPoint = 0;
for (int i = 0; i < (data.get(0).size() - rateSampling); i++) {
calcRate = true;
for (int l = 0; l < rateSampling; l++) {
if (!compareBins(i, i + l,bins)) {
if (!prevFail){
binEndPoint = i -2 + rateSampling;
duration[binStartPoint] = data.get(0).get(binEndPoint) - data.get(0).get(binStartPoint);
}
calcRate = false;
prevFail = true;
break;
}
}
if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) {
for (int j = 0; j < reqdVarsL.size(); j++) {
//k = reqdVarIndices.get(j);
rates[j][i] = ((data.get(j+1).get(i + rateSampling) - data.get(j+1).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i)));
}
if (prevFail){
binStartPoint = i;
}
prevFail = false;
}
}
if (!prevFail){ // for the last genuine rate-calculating region of the trace; this may not be required if the trace is incomplete.trace data may not necessarily end at a region endpt
duration[binStartPoint] = data.get(0).get(data.get(0).size()-1) - data.get(0).get(binStartPoint);
}
}
}
/*
* ADD LATER: duration[i] SHOULD BE ADDED TO THE NEXT 2 IF/ELSE
* BRANCHES(Transition based rate calc) ALSO
*/
else { // Transition based rate calculation
if (rateSampling == -1) { // replacing inf with -1 since int
for (int j = 0; j < reqdVarsL.size(); j++) {
mark = 0;
//k = reqdVarIndices.get(j);
for (int i = 0; i < data.get(0).size(); i++) {
if (i < mark) {
continue;
}
while ((mark < data.get(0).size())
&& (bins[j][i] == bins[j][mark])) {
mark++;
}
if ((data.get(0).get(mark - 1) != data.get(0).get(i))) {
rates[j][i] = ((data.get(j+1).get(mark - 1) - data.get(j+1).get(i)) / (data.get(0).get(mark - 1) - data.get(0).get(i)));
}
}
}
} else {
boolean calcRate;
for (int i = 0; i < (data.get(0).size() - rateSampling); i++) {
for (int j = 0; j < reqdVarsL.size(); j++) {
calcRate = true;
//k = reqdVarIndices.get(j);
for (int l = 0; l < rateSampling; l++) {
if (bins[j][i] != bins[j][i + l]) {
calcRate = false;
break;
}
}
if (calcRate && (data.get(0).get(i + rateSampling) != data.get(0).get(i))) {
rates[j][i] = ((data.get(j+1).get(i + rateSampling) - data.get(j+1).get(i)) / (data.get(0).get(i + rateSampling) - data.get(0).get(i)));
}
}
}
}
}
/*
try {
logFile = new File(directory + separator + "tmp.log");
logFile.createNewFile();
out = new BufferedWriter(new FileWriter(logFile));
for (int i = 0; i < (data.get(0).size()); i++) {
for (int j = 0; j < reqdVarsL.size(); j++) {
//k = reqdVarIndices.get(j);
out.write(data.get(j+1).get(i) + " ");// + bins[j][i] + " " +
// rates[j][i] + " ");
}
for (int j = 0; j < reqdVarsL.size(); j++) {
out.write(bins[j][i] + " ");
}
for (int j = 0; j < reqdVarsL.size(); j++) {
out.write(rates[j][i] + " ");
}
out.write(duration[i] + " ");
out.write("\n");
}
out.close();
} catch (IOException e) {
System.out.println("Log file couldn't be opened for writing rates and bins ");
}*/
return rates;
}
public boolean compareBins(int j, int mark,int[][] bins) {
for (int i = 0; i < reqdVarsL.size(); i++) {
if (bins[i][j] != bins[i][mark]) {
return false;
} else {
continue;
}
}
return true;
}
public void addMetaBins(){ // TODO: DIDN'T REPLACE divisionsL by thresholds IN THIS METHOD
boolean foundBin = false;
for (String st1 : g.getPlaceList()){
String p = getPlaceInfoIndex(st1);
String[] binEncoding ;
ArrayList<Integer> syncBinEncoding;
String o1;
// st1 w.r.t g
// p w.r.t placeInfo
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
// String [] bE = p.split("");
String [] bE = p.split(",");
binEncoding = new String[bE.length - 1];
for (int i = 0; i < bE.length; i++){
binEncoding[i] = bE[i]; // since p.split("") gives ,0,1 if p was 01
}
for (int i = 0; i < binEncoding.length ; i++){
if (!reqdVarsL.get(i).isDmvc()){
if ((lowerLimit[i] != null) && (getMinRate(p,reqdVarsL.get(i).getName()) < 0)){
syncBinEncoding = new ArrayList<Integer>();
// deep copy of bin encoding
for (int n = 0; n < binEncoding.length; n++){
o1 = binEncoding[n];
if (o1 == "A"){
syncBinEncoding.add(-1);
}
else if (o1 == "Z"){
syncBinEncoding.add(divisionsL.get(n).size());
}
else{
syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here
}
}
foundBin = false;
while (!foundBin){
syncBinEncoding.set(i,syncBinEncoding.get(i) - 1);
String key = "";
for (int m = 0; m < syncBinEncoding.size(); m++){
if (syncBinEncoding.get(m) != -1){
key += syncBinEncoding.get(m).toString();
}
else{
key += "A";
}
}
if ((syncBinEncoding.get(i) == -1) && (!placeInfo.containsKey(key))){
foundBin = true;
Properties p0 = new Properties();
placeInfo.put(key, p0);
p0.setProperty("placeNum", numPlaces.toString());
p0.setProperty("type", "RATE");
p0.setProperty("initiallyMarked", "false");
p0.setProperty("metaType","true");
p0.setProperty("metaVar", String.valueOf(i));
g.addPlace("p" + numPlaces, false);
//ratePlaces.add("p"+numPlaces);
numPlaces++;
if (getMaxRate(p,reqdVarsL.get(i).getName()) > 0){ // minrate is 0; maxrate remains the same if positive
addRate(p0, reqdVarsL.get(i).getName(), 0.0);
addRate(p0, reqdVarsL.get(i).getName(), (double)getMaxRate(p,reqdVarsL.get(i).getName()));
/*
* This transition should be added only in this case but
* since dotty cribs if there's no place on a transition's postset,
* moving this one down so that this transition is created even if the
* min,max rate is 0 in which case it wouldn't make sense to have this
* transition
* Properties p2 = new Properties();
transitionInfo.put(key + p, p2);
p2.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addControlFlow("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum"));
g.addControlFlow("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum"));
g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")" + "&~fail");
numTransitions++; */
}
else{
addRate(p0, reqdVarsL.get(i).getName(), 0.0); // if the maximum rate was negative, then make the min & max rates both as zero
}
Properties p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
numTransitions++;
Properties p2 = new Properties();
transitionInfo.put(key + p, p2);
p2.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum"));
g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")");
minr = getMinRate(p, reqdVarsL.get(i).getName());
maxr = getMaxRate(p, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
numTransitions++;
}
else if (placeInfo.containsKey(key)){
foundBin = true;
//Properties syncP = placeInfo.get(key);
Properties p1;
if (!transitionInfo.containsKey(p + key)) { // instead of tuple
p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
numTransitions++;
}
}
}
}
if ((upperLimit[i] != null) && getMaxRate(p,reqdVarsL.get(i).getName()) > 0){
syncBinEncoding = new ArrayList<Integer>();
// deep copy of bin encoding
for (int n = 0; n < binEncoding.length; n++){
o1 = binEncoding[n];
if (o1 == "A"){
syncBinEncoding.add(-1);
}
else if (o1 == "Z"){
syncBinEncoding.add(divisionsL.get(n).size()+1);
}
else{
syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here
}
}
foundBin = false;
while (!foundBin){
syncBinEncoding.set(i,syncBinEncoding.get(i) + 1);
String key = "";
for (int m = 0; m < syncBinEncoding.size(); m++){
if (syncBinEncoding.get(m) < divisionsL.get(i).size()+1){
key += syncBinEncoding.get(m).toString();
}
else{
key += "Z";
// encoding not required here.. but may be useful to distinguish the pseudobins from normal bins in future
}
}
if ((syncBinEncoding.get(i) == divisionsL.get(i).size() + 1) && (!placeInfo.containsKey(key))){
// divisionsL.get(i).size() + 1 or divisionsL.get(i).size()???
foundBin = true;
Properties p0 = new Properties();
placeInfo.put(key, p0);
p0.setProperty("placeNum", numPlaces.toString());
p0.setProperty("type", "RATE");
p0.setProperty("initiallyMarked", "false");
p0.setProperty("metaType","true");
p0.setProperty("metaVar", String.valueOf(i));
//ratePlaces.add("p"+numPlaces);
g.addPlace("p" + numPlaces, false);
numPlaces++;
if (getMinRate(p,reqdVarsL.get(i).getName()) < 0){ // maxrate is 0; minrate remains the same if negative
addRate(p0, reqdVarsL.get(i).getName(), 0.0);
addRate(p0, reqdVarsL.get(i).getName(), (double)getMinRate(p,reqdVarsL.get(i).getName()));
/*
* This transition should be added only in this case but
* since dotty cribs if there's no place on a transition's postset,
* moving this one down so that this transition is created even if the
* min,max rate is 0 in which case it wouldn't make sense to have this
* transition
*
Properties p2 = new Properties();
transitionInfo.put(key + p, p2);
p2.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addControlFlow("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum"));
g.addControlFlow("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum"));
g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")" + "&~fail");
numTransitions++;
*/
}
else{
addRate(p0, reqdVarsL.get(i).getName(), 0.0); // if the minimum rate was positive, then make the min & max rates both as zero
}
Properties p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")");
numTransitions++;
Properties p2 = new Properties();
transitionInfo.put(key + p, p2);
p2.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(key).getProperty("placeNum"), "t" + transitionInfo.get(key + p).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(key + p).getProperty("transitionNum"), "p" + placeInfo.get(p).getProperty("placeNum"));
g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")");
minr = getMinRate(p, reqdVarsL.get(i).getName());
maxr = getMaxRate(p, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
numTransitions++;
}
else if (placeInfo.containsKey(key)){
foundBin = true;
//Properties syncP = placeInfo.get(key);
Properties p1;
if (!transitionInfo.containsKey(p + key)) { // instead of tuple
p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")");
numTransitions++;
}
}
}
}
}
}
}
}
}
public void addMetaBinTransitions(){
// Adds transitions b/w existing metaBins.
// Doesn't add any new metabins. Doesn't add transitions b/w metabins & normal bins
boolean foundBin = false;
for (String st1 : g.getPlaceList()){
String p = getPlaceInfoIndex(st1);
Properties placeP = placeInfo.get(p);
String[] binEncoding ;
ArrayList<Integer> syncBinEncoding;
String o1;
// st1 w.r.t g
// p w.r.t placeInfo
if (placeP.getProperty("type").equalsIgnoreCase("RATE") && placeP.getProperty("metaType").equalsIgnoreCase("true")) {
// String [] bE = p.split("");
String [] bE = p.split(",");
binEncoding = new String[bE.length - 1];
for (int i = 0; i < bE.length; i++){
binEncoding[i] = bE[i]; // since p.split("") gives ,0,1 if p was 01
}
for (int i = 0; i < binEncoding.length ; i++){
if ((!reqdVarsL.get(i).isDmvc()) && (Integer.parseInt(placeP.getProperty("metaVar")) != i)){
if ((getMinRate(p,reqdVarsL.get(i).getName()) < 0)){
syncBinEncoding = new ArrayList<Integer>();
// deep copy of bin encoding
for (int n = 0; n < binEncoding.length; n++){
o1 = binEncoding[n];
if (o1 == "A"){
syncBinEncoding.add(-1);
}
else if (o1 == "Z"){
syncBinEncoding.add(divisionsL.get(n).size());
}
else{
syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here
}
}
foundBin = false;
while (!foundBin){
syncBinEncoding.set(i,syncBinEncoding.get(i) - 1);
String key = "";
for (int m = 0; m < syncBinEncoding.size(); m++){
if (syncBinEncoding.get(m) != -1){
key += syncBinEncoding.get(m).toString();
}
else{
key += "A";
}
}
if (placeInfo.containsKey(key)){
foundBin = true;
//Properties syncP = placeInfo.get(key);
Properties p1;
if (!transitionInfo.containsKey(p + key)) { // instead of tuple
p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
g.addEnabling("t" + numTransitions, "~(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.floor(lowerLimit[i]) + ")");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
numTransitions++;
}
}
}
}
if (getMaxRate(p,reqdVarsL.get(i).getName()) > 0){
syncBinEncoding = new ArrayList<Integer>();
// deep copy of bin encoding
for (int n = 0; n < binEncoding.length; n++){
o1 = binEncoding[n];
if (o1 == "A"){
syncBinEncoding.add(-1);
}
else if (o1 == "Z"){
syncBinEncoding.add(divisionsL.get(n).size()+1);
}
else{
syncBinEncoding.add( Integer.parseInt(o1)); // clone() not working here
}
}
foundBin = false;
while (!foundBin){
syncBinEncoding.set(i,syncBinEncoding.get(i) + 1);
String key = "";
for (int m = 0; m < syncBinEncoding.size(); m++){
if (syncBinEncoding.get(m) < divisionsL.get(i).size()+1){
key += syncBinEncoding.get(m).toString();
}
else{
key += "Z";
// encoding not required here.. but may be useful to distinguish the pseudobins from normal bins in future
}
}
if (placeInfo.containsKey(key)){
foundBin = true;
//Properties syncP = placeInfo.get(key);
Properties p1;
if (!transitionInfo.containsKey(p + key)) { // instead of tuple
p1 = new Properties();
transitionInfo.put(p + key, p1);
p1.setProperty("transitionNum", numTransitions.toString());
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + placeInfo.get(p).getProperty("placeNum"), "t" + transitionInfo.get(p + key).getProperty("transitionNum"));
g.addMovement("t" + transitionInfo.get(p + key).getProperty("transitionNum"), "p" + placeInfo.get(key).getProperty("placeNum"));
// g.addEnabling("t" + numTransitions, "~fail");
int minr = getMinRate(key, reqdVarsL.get(i).getName());
int maxr = getMaxRate(key, reqdVarsL.get(i).getName());
if (minr != maxr)
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), "uniform(" + minr + "," + maxr + ")");
else
g.addRateAssign("t" + numTransitions, reqdVarsL.get(i).getName(), String.valueOf(minr));
g.addEnabling("t" + numTransitions, "(" + reqdVarsL.get(i).getName() + ">=" + (int) Math.ceil(upperLimit[i]) + ")");
numTransitions++;
}
}
}
}
}
}
}
}
}
public void writeVHDLAMSFile(String vhdFile){
try{
ArrayList<String> ratePlaces = new ArrayList<String>();
ArrayList<String> dmvcPlaces = new ArrayList<String>();
File VHDLFile = new File(directory + separator + vhdFile);
VHDLFile.createNewFile();
BufferedWriter vhdlAms = new BufferedWriter(new FileWriter(VHDLFile));
StringBuffer buffer = new StringBuffer();
String pNum;
vhdlAms.write("library IEEE;\n");
vhdlAms.write("use IEEE.std_logic_1164.all;\n");
vhdlAms.write("use work.handshake.all;\n");
vhdlAms.write("use work.nondeterminism.all;\n\n");
vhdlAms.write("entity amsDesign is\n");
vhdlAms.write("end amsDesign;\n\n");
vhdlAms.write("architecture "+vhdFile.split("\\.")[0]+" of amsDesign is\n");
for (Variable v : reqdVarsL){
vhdlAms.write("\tquantity "+v.getName()+":real;\n");
}
for (int i = 0; i < numPlaces; i++){
if (!isTransientPlace("p"+i)){
String p = getPlaceInfoIndex("p"+i);
if (!placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
continue;
}
}
else {
String p = getTransientNetPlaceIndex("p"+i);
if (!transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
continue;
}
}
vhdlAms.write("\tshared variable place:integer:= "+i+";\n");
break;
}
if (failPropVHDL != null){
//TODO: Make this an assertion
//vhdlAms.write("\tshared variable fail:boolean:= false;\n");
}
for (String st1 : g.getPlaceList()){
if (!isTransientPlace(st1)){
String p = getPlaceInfoIndex(st1);
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
ratePlaces.add(st1); // w.r.t g here
}
/* Related to the separate net for DMV input driver
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("DMVC")) {
dmvcPlaces.add(p); // w.r.t placeInfo here
}*/
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("PROP")) {
}
}
else{
String p = getTransientNetPlaceIndex(st1);
if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")){
ratePlaces.add(st1); // w.r.t g here
}
/* Related to the separate net for DMV input driver
if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("DMVC")){
dmvcPlaces.add(p); // w.r.t g here
}*/
}
}
/*for (String st:dmvcPlaces){
System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable"));
}*/
/*
Collections.sort(dmvcPlaces,new Comparator<String>(){
public int compare(String a, String b){
String v1 = placeInfo.get(a).getProperty("DMVCVariable");
String v2 = placeInfo.get(b).getProperty("DMVCVariable");
if (reqdVarsL.indexOf(v1) < reqdVarsL.indexOf(v2)){
return -1;
}
else if (reqdVarsL.indexOf(v1) == reqdVarsL.indexOf(v2)){
return 0;
}
else{
return 1;
}
}
});*/
Collections.sort(dmvcPlaces,new Comparator<String>(){
public int compare(String a, String b){
if (Integer.parseInt(a.split("_")[1]) < Integer.parseInt(b.split("_")[1])){
return -1;
}
else if (Integer.parseInt(a.split("_")[1]) == Integer.parseInt(b.split("_")[1])){
return 0;
}
else{
return 1;
}
}
});
Collections.sort(ratePlaces,new Comparator<String>(){
String v1,v2;
public int compare(String a, String b){
if (!isTransientPlace(a) && !isTransientPlace(b)){
v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum");
v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum");
}
else if (!isTransientPlace(a) && isTransientPlace(b)){
v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum");
v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum");
}
else if (isTransientPlace(a) && !isTransientPlace(b)){
v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum");
v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum");
}
else {
v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum");
v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum");
}
if (Integer.parseInt(v1) < Integer.parseInt(v2)){
return -1;
}
else if (Integer.parseInt(v1) == Integer.parseInt(v2)){
return 0;
}
else{
return 1;
}
}
});
// sending the initial place to the end of the list. since if statements begin with preset of each place
//ratePlaces.add(ratePlaces.get(0));
//ratePlaces.remove(0);
/*System.out.println("after sorting:");
for (String st:dmvcPlaces){
System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable"));
}*/
vhdlAms.write("begin\n");
//buffer.append("\nbegin\n");
String[] vals;
for (Variable v : reqdVarsL){ // taking the lower value from the initial value range. Ok?
//vhdlAms.write("\tbreak "+v.getName()+" => "+((((v.getInitValue()).split("\\,"))[0]).split("\\["))[1]+".0;\n");
vals = v.getInitValue().split("\\,");
vhdlAms.write("\tbreak "+v.getName()+" => span("+((vals[0]).split("\\["))[1]+".0,"+ ((vals[1]).split("\\]"))[0] +".0);\n");
//buffer.append("\tbreak "+v.getName()+" => span("+((vals[0]).split("\\["))[1]+".0,"+ ((vals[1]).split("\\]"))[0] +".0);\n");
}
vhdlAms.write("\n");
//buffer.append("\n");
for (Variable v : reqdVarsL){
if (v.isDmvc()){
vhdlAms.write("\t"+v.getName()+"'dot == 0.0;\n");
//buffer.append("\t"+v.getName()+"'dot == 0.0;\n");
}
}
vhdlAms.write("\n");
//buffer.append("\n");
ArrayList<ArrayList<String>> dmvcVarPlaces = new ArrayList<ArrayList<String>>();
boolean contVarExists = false;
for (Variable v: reqdVarsL){
dmvcVarPlaces.add(new ArrayList<String>());
if (v.isDmvc()){
continue;
}
else{
contVarExists = true;
}
}
for (String st:dmvcPlaces){
dmvcVarPlaces.get(Integer.parseInt(st.split("_")[1])).add(st);
}
if (contVarExists){
if (ratePlaces.size() != 0){
//vhdlAms.write("\tcase place use\n");
buffer.append("\tcase place use\n");
}
//vhdlAms.write("\ntype rate_places is (");
for (String p : ratePlaces){
pNum = p.split("p")[1];
//vhdlAms.write("\t\twhen "+p.split("p")[1] +" =>\n");
buffer.append("\t\twhen "+ pNum +" =>\n");
if (!isTransientPlace(p)){
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
//if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){
//vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n");
buffer.append("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n");
}
}
}
else{
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
//if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){
//vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0);\n");
buffer.append("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getTransientNetPlaceIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getTransientNetPlaceIndex(p), reqdVarsL.get(j).getName())+".0);\n");
}
}
}
}
vhdlAms.write(buffer.toString());
vhdlAms.write("\t\twhen others =>\n");
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
//if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){
vhdlAms.write("\t\t\t" + reqdVarsL.get(j).getName() + "'dot == 0.0;\n");
}
}
vhdlAms.write("\tend case;\n");
}
vhdlAms.write("\tprocess\n");
vhdlAms.write("\tbegin\n");
vhdlAms.write("\tcase place is\n");
buffer.delete(0, buffer.length());
String[] transL;
int transNum;
for (String p : ratePlaces){
pNum = p.split("p")[1];
vhdlAms.write("\t\twhen "+pNum +" =>\n");
vhdlAms.write("\t\t\twait until ");
transL = g.getPostset(p);
if (transL.length == 1){
transNum = Integer.parseInt(transL[0].split("t")[1]);
vhdlAms.write(transEnablingsVHDL[transNum] + ";\n");
if (transDelayAssignVHDL[transNum] != null){
vhdlAms.write("\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n");
//vhdlAms.write("\t\t\tbreak "+ transIntAssignVHDL[transNum]+";\n");
for (String s : transIntAssignVHDL[transNum]){
if (s != null){
vhdlAms.write("\t\t\tbreak "+ s +";\n");
}
}
}
if (g.getPostset(transL[0]).length != 0)
vhdlAms.write("\t\t\tplace := " + g.getPostset(transL[0])[0].split("p")[1] + ";\n");
}
else{
boolean firstTrans = true;
buffer.delete(0, buffer.length());
for (String t : transL){
transNum = Integer.parseInt(t.split("t")[1]);
if (firstTrans){
firstTrans = false;
vhdlAms.write("(" + transEnablingsVHDL[transNum]);
buffer.append("\t\t\tif " + transEnablingsVHDL[transNum] + " then\n");
if (transDelayAssignVHDL[transNum] != null){
buffer.append("\t\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n");
for (String s : transIntAssignVHDL[transNum]){
if (s != null){
buffer.append("\t\t\t\tbreak "+ s +";\n");
}
}
}
buffer.append("\t\t\t\tplace := " + g.getPostset(t)[0].split("p")[1] + ";\n");
}
else{
vhdlAms.write(" or " +transEnablingsVHDL[transNum] );
buffer.append("\t\t\telsif " + transEnablingsVHDL[transNum] + " then\n");
if (transDelayAssignVHDL[transNum] != null){
buffer.append("\t\t\t\twait for "+ transDelayAssignVHDL[transNum]+";\n");
//buffer.append("\t\t\t\tbreak "+ transIntAssignVHDL[transNum]+";\n");
for (String s : transIntAssignVHDL[transNum]){
if (s != null){
buffer.append("\t\t\t\tbreak "+ s +";\n");
}
}
}
buffer.append("\t\t\t\tplace := " + g.getPostset(t)[0].split("p")[1] + ";\n");
}
}
vhdlAms.write(");\n");
buffer.append("\t\t\tend if;\n");
vhdlAms.write(buffer.toString());
}
}
vhdlAms.write("\t\twhen others =>\n\t\t\twait for 0.0;\n\t\t\tplace := "+ ratePlaces.get(0).split("p")[1] + ";\n\tend case;\n\tend process;\n");
for (int i = 0; i < dmvcVarPlaces.size(); i++){
if (dmvcVarPlaces.get(i).size() != 0){
vhdlAms.write("\tprocess\n");
vhdlAms.write("\tbegin\n");
for (String p : dmvcVarPlaces.get(i)){
if (!transientNetPlaces.containsKey(p)){
vhdlAms.write("\t\twait for delay("+ (int) Math.floor(Double.parseDouble(placeInfo.get(p).getProperty("dMin")))+","+(int)Math.ceil(Double.parseDouble(placeInfo.get(p).getProperty("dMax"))) +");\n");
// recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/
vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ (int) Math.floor(Double.parseDouble(placeInfo.get(p).getProperty("DMVCValue"))) + ".0;\n");
}
else{
vhdlAms.write("\t\twait for delay("+ (int) Math.floor(Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))+","+(int)Math.ceil(Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))) +");\n");
// recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/
vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ (int) Math.floor(Double.parseDouble(transientNetPlaces.get(p).getProperty("DMVCValue"))) + ".0;\n");
}
}
vhdlAms.write("\tend process;\n\n");
}
}
if (failPropVHDL != null){
vhdlAms.write("\tprocess\n");
vhdlAms.write("\tbegin\n");
vhdlAms.write("\t\twait until " + failPropVHDL + ";\n");
//TODO: Change this to assertion
//vhdlAms.write("\t\tfail := true;\n");
vhdlAms.write("\tend process;\n\n");
}
// vhdlAms.write("\tend process;\n\n");
vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n");
vhdlAms.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(biosim.frame(),
"VHDL-AMS model couldn't be created/written.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
catch(Exception e){
JOptionPane.showMessageDialog(biosim.frame(),
"Error in VHDL-AMS model generation.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
public void writeVerilogAMSFile(String vamsFileName){
try{
ArrayList<String> ratePlaces = new ArrayList<String>();
ArrayList<String> dmvcPlaces = new ArrayList<String>();
File vamsFile = new File(directory + separator + vamsFileName);
vamsFile.createNewFile();
Double rateFactor = varScaleFactor/delayScaleFactor;
BufferedWriter vams = new BufferedWriter(new FileWriter(vamsFile));
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
StringBuffer buffer3 = new StringBuffer();
StringBuffer buffer4 = new StringBuffer();
StringBuffer initBuffer = new StringBuffer();
vams.write("`include \"constants.vams\"\n");
vams.write("`include \"disciplines.vams\"\n");
vams.write("`timescale 1ps/1ps\n\n");
vams.write("module "+vamsFileName.split("\\.")[0]+" (");
buffer.append("\tparameter delay = 0, rtime = 1p, ftime = 1p;\n");
Variable v;
String[] vals;
for (int i = 0; i < reqdVarsL.size(); i++){
v = reqdVarsL.get(i);
if ( i!= 0){
vams.write(",");
}
vams.write(" "+v.getName());
if (v.isInput()){
buffer.append("\tinput "+v.getName()+";\n\telectrical "+v.getName()+";\n");
} else{
buffer.append("\tinout "+v.getName()+";\n\telectrical "+v.getName()+";\n");
if (!v.isDmvc()){
buffer2.append("\treal change_"+v.getName()+";\n");
buffer2.append("\treal rate_"+v.getName()+";\n");
vals = v.getInitValue().split("\\,");
double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*varScaleFactor);
initBuffer.append("\t\tchange_"+v.getName()+" = "+ spanAvg+";\n");
vals = v.getInitRate().split("\\,");
spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*rateFactor);
initBuffer.append("\t\trate_"+v.getName()+" = "+ (int)spanAvg+";\n");
}
else{
buffer2.append("\treal "+v.getName()+"Val;\n"); // changed from real to int.. check??
vals = reqdVarsL.get(i).getInitValue().split("\\,");
double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*varScaleFactor);
initBuffer.append("\t\t"+reqdVarsL.get(i).getName()+"Val = "+ spanAvg+";\n");
}
}
}
// if (failPropVHDL != null){
// buffer.append("\toutput reg fail;\n\tlogic fail;\n");
// vams.write(", fail");
vams.write(");\n" + buffer+"\n");
if (buffer2.length() != 0){
vams.write(buffer2.toString());
}
vams.write("\treal entryTime;\n");
if (vamsRandom){
vams.write("\tinteger seed;\n\tinteger del;\n");
}
vams.write("\tinteger place;\n\n\tinitial\n\tbegin\n");
vams.write(initBuffer.toString());
vams.write("\t\tentryTime = 0;\n");
if (vamsRandom){
vams.write("\t\tseed = 0;\n");
}
buffer.delete(0, buffer.length());
buffer2.delete(0, buffer2.length());
for (int i = 0; i < numPlaces; i++){
String p;
if (!isTransientPlace("p"+i)){
p = getPlaceInfoIndex("p"+i);
if (!placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
continue;
}
}
else{
p = getTransientNetPlaceIndex("p"+i);
if (!transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
continue;
}
}
vams.write("\t\tplace = "+i+";\n");
break;
}
//if (failPropVHDL != null){
// vams.write("\t\t\tfail = 1'b0;\n");
vams.write("\tend\n\n");
for (String st1 : g.getPlaceList()){
if (!isTransientPlace(st1)){
String p = getPlaceInfoIndex(st1);
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("RATE")) {
ratePlaces.add(st1); // w.r.t g here
}
/* Related to the separate net for DMV input driver
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("DMVC")) {
dmvcPlaces.add(p); // w.r.t placeInfo here
}*/
if (placeInfo.get(p).getProperty("type").equalsIgnoreCase("PROP")) {
}
}
else{
String p = getTransientNetPlaceIndex(st1);
if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("RATE")){
ratePlaces.add(st1); // w.r.t g here
}
/* Related to the separate net for DMV input driver
if (transientNetPlaces.get(p).getProperty("type").equalsIgnoreCase("DMVC")){
dmvcPlaces.add(p); // w.r.t placeInfo here
}*/
}
}
/*for (String st:dmvcPlaces){
System.out.println("p" + placeInfo.get(st).getProperty("placeNum") + "," +placeInfo.get(st).getProperty("DMVCVariable"));
}*/
Collections.sort(dmvcPlaces,new Comparator<String>(){
public int compare(String a, String b){
if (Integer.parseInt(a.split("_")[1]) < Integer.parseInt(b.split("_")[1])){
return -1;
}
else if (Integer.parseInt(a.split("_")[1]) == Integer.parseInt(b.split("_")[1])){
if (Integer.parseInt(a.split("_")[2]) < Integer.parseInt(b.split("_")[2])){
return -1;
}
else if (Integer.parseInt(a.split("_")[2]) == Integer.parseInt(b.split("_")[2])){
return 0;
}
else{
return 1;
}
}
else{
return 1;
}
}
});
Collections.sort(ratePlaces,new Comparator<String>(){
String v1,v2;
public int compare(String a, String b){
if (!isTransientPlace(a) && !isTransientPlace(b)){
v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum");
v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum");
}
else if (!isTransientPlace(a) && isTransientPlace(b)){
v1 = placeInfo.get(getPlaceInfoIndex(a)).getProperty("placeNum");
v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum");
}
else if (isTransientPlace(a) && !isTransientPlace(b)){
v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum");
v2 = placeInfo.get(getPlaceInfoIndex(b)).getProperty("placeNum");
}
else {
v1 = transientNetPlaces.get(getTransientNetPlaceIndex(a)).getProperty("placeNum");
v2 = transientNetPlaces.get(getTransientNetPlaceIndex(b)).getProperty("placeNum");
}
if (Integer.parseInt(v1) < Integer.parseInt(v2)){
return -1;
}
else if (Integer.parseInt(v1) == Integer.parseInt(v2)){
return 0;
}
else{
return 1;
}
}
});
ArrayList<String> transitions = new ArrayList<String>();
for (String t : g.getTransitionList()){
transitions.add(t);
}
Collections.sort(transitions,new Comparator<String>(){
public int compare(String a, String b){
String v1 = a.split("t")[1];
String v2 = b.split("t")[1];
if (Integer.parseInt(v1) < Integer.parseInt(v2)){
return -1;
}
else if (Integer.parseInt(v1) == Integer.parseInt(v2)){
return 0;
}
else{
return 1;
}
}
});
// sending the initial place to the end of the list. since if statements begin with preset of each place
//ratePlaces.add(ratePlaces.get(0));
//ratePlaces.remove(0);
ArrayList<ArrayList<String>> dmvcVarPlaces = new ArrayList<ArrayList<String>>();
boolean contVarExists = false;
for (Variable var: reqdVarsL){
dmvcVarPlaces.add(new ArrayList<String>());
if (var.isDmvc()){
continue;
}
else{
contVarExists = true;
}
}
for (String st:dmvcPlaces){
dmvcVarPlaces.get(Integer.parseInt(st.split("_")[1])).add(st);
}
int transNum;
buffer.delete(0, buffer.length());
initBuffer.delete(0, initBuffer.length());
String presetPlace = null,postsetPlace = null;
StringBuffer[] transBuffer = new StringBuffer[transitions.size()];
int cnt = 0;
StringBuffer transAlwaysPlaceBuffer = new StringBuffer();
int placeAlwaysBlockNum = -1;
for (String t : transitions){
presetPlace = g.getPreset(t)[0];
//if (g.getPostset(t) != null){
// postsetPlace = g.getPostset(t)[0];
transNum = Integer.parseInt(t.split("t")[1]);
cnt = transNum;
if (!isTransientTransition(t)){
if (placeInfo.get(getPlaceInfoIndex(presetPlace)).getProperty("type").equals("RATE")){
if (g.getPostset(t).length != 0)
postsetPlace = g.getPostset(t)[0];
for (int j = 0; j < transNum; j++){
if ((transEnablingsVAMS[j] != null) && (transEnablingsVAMS[j].equalsIgnoreCase(transEnablingsVAMS[transNum]))){
cnt = j;
break;
}
}
if ( cnt == transNum){
transBuffer[cnt] = new StringBuffer();
if (transEnablingsVAMS[transNum].equalsIgnoreCase("")){
//transBuffer[cnt].append("\talways@(place)" + "\n\tbegin\n"); May 14, 2010
placeAlwaysBlockNum = cnt;
}
else{
transBuffer[cnt].append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n");
transAlwaysPlaceBuffer.append("\t\t" + transConditionalsVAMS[transNum] + "\n\t\tbegin\n\t\t\tentryTime = $abstime;\n");
if (g.getPostset(t).length != 0)
transAlwaysPlaceBuffer.append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n");
}
}
else{
String s = transBuffer[cnt].toString();
s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n");
transBuffer[cnt].delete(0, transBuffer[cnt].length());
transBuffer[cnt].append(s);
if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){
transAlwaysPlaceBuffer.append("\t\t" + transConditionalsVAMS[transNum] + "\n\t\tbegin\n\t\t\tentryTime = $abstime;\n" + "\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n");
}
}
transBuffer[cnt].append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n");
if (transDelayAssignVAMS[transNum] != null){
transBuffer[cnt].append("\t\t\t"+transDelayAssignVAMS[transNum]+";\n");
for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){
if (transIntAssignVAMS[transNum][i] != null){
transBuffer[cnt].append("\t\t\t"+ transIntAssignVAMS[transNum][i]);
}
}
}
transBuffer[cnt].append("\t\t\tentryTime = $abstime;\n");
transBuffer[cnt].append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n");
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
transBuffer[cnt].append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n");
transBuffer[cnt].append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n");
if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){
transAlwaysPlaceBuffer.append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n");
transAlwaysPlaceBuffer.append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n");
}
}
}
transBuffer[cnt].append("\t\tend\n");
//if ( cnt == transNum){
transBuffer[cnt].append("\tend\n");
if (!transEnablingsVAMS[transNum].equalsIgnoreCase("")){
transAlwaysPlaceBuffer.append("\t\tend\n");
}
}
}
else{
if (transientNetPlaces.get(getTransientNetPlaceIndex(presetPlace)).getProperty("type").equals("RATE")){
if (g.getPostset(t).length != 0)
postsetPlace = g.getPostset(t)[0];
for (int j = 0; j < transNum; j++){
if ((transEnablingsVAMS[j] != null) && (transEnablingsVAMS[j].equalsIgnoreCase(transEnablingsVAMS[transNum]))){
cnt = j;
break;
}
}
if ( cnt == transNum){
transBuffer[cnt] = new StringBuffer();
transBuffer[cnt].append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n");
}
else{
String s = transBuffer[cnt].toString();
s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n");
transBuffer[cnt].delete(0, transBuffer[cnt].length());
transBuffer[cnt].append(s);
}
transBuffer[cnt].append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n");
if (transDelayAssignVAMS[transNum] != null){
transBuffer[cnt].append("\t\t\t"+transDelayAssignVAMS[transNum]+";\n");
for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){
if (transIntAssignVAMS[transNum][i] != null){
transBuffer[cnt].append("\t\t\t"+ transIntAssignVAMS[transNum][i]);
}
}
}
transBuffer[cnt].append("\t\t\tentryTime = $abstime;\n");
if (g.getPostset(t).length != 0)
transBuffer[cnt].append("\t\t\tplace = " + postsetPlace.split("p")[1] + ";\n");
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
transBuffer[cnt].append("\t\t\trate_"+reqdVarsL.get(j).getName()+ " = "+(int)((getMinRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName())+getMaxRate(getPlaceInfoIndex(postsetPlace), reqdVarsL.get(j).getName()))/(2.0*rateFactor)) + ";\n");
transBuffer[cnt].append("\t\t\tchange_" + reqdVarsL.get(j).getName()+ " = V("+ reqdVarsL.get(j).getName()+ ");\n");
}
}
transBuffer[cnt].append("\t\tend\n");
//if ( cnt == transNum){
transBuffer[cnt].append("\tend\n");
}
}
//if (transDelayAssignVAMS[transNum] != null){
// buffer.append("\t"+transEnablingsVAMS[transNum] + "\n\tbegin\n");
// buffer.append("\t\tif (place == "+ presetPlace.split("p")[1] +")\n\t\tbegin\n");
// buffer.append("\t\t\t#"+transDelayAssignVAMS[transNum]+";\n");
// for (int i = 0; i < transIntAssignVAMS[transNum].length; i++){
// if (transIntAssignVAMS[transNum][i] != null){
// buffer.append("\t\t\t"+reqdVarsL.get(i).getName()+"Val = "+ transIntAssignVAMS[transNum][i]+";\n");
// buffer.append("\t\tend\n\tend\n");
}
if (placeAlwaysBlockNum == -1){
vams.write("\talways@(place)" + "\n\tbegin\n");
vams.write(transAlwaysPlaceBuffer.toString());
vams.write("\tend\n");
}
else{
String s = transBuffer[placeAlwaysBlockNum].toString();
s = s.replaceAll("\t\tend\n\tend\n", "\t\tend\n");
transBuffer[placeAlwaysBlockNum].delete(0, transBuffer[placeAlwaysBlockNum].length());
transBuffer[placeAlwaysBlockNum].append("\talways@(place)" + "\n\tbegin\n");
transBuffer[placeAlwaysBlockNum].append(transAlwaysPlaceBuffer);
transBuffer[placeAlwaysBlockNum].append(s);
transBuffer[placeAlwaysBlockNum].append("\tend\n");
}
for (int j = 0; j < transitions.size(); j++){
if (transBuffer[j] != null){
vams.write(transBuffer[j].toString());
}
}
vams.write("\tanalog\n\tbegin\n");
for (int j = 0; j<reqdVarsL.size(); j++){
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
vams.write("\t\tV("+reqdVarsL.get(j).getName()+") <+ transition(change_" + reqdVarsL.get(j).getName() + " + rate_" + reqdVarsL.get(j).getName()+"*($abstime-entryTime));\n");
}
if ((!reqdVarsL.get(j).isInput()) && (reqdVarsL.get(j).isDmvc())){
vams.write("\t\tV("+reqdVarsL.get(j).getName()+") <+ transition(" + reqdVarsL.get(j).getName() + "Val,delay,rtime,ftime);\n");
//vals = reqdVarsL.get(j).getInitValue().split("\\,");
//double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*varScaleFactor);
//initBuffer.append("\t\t"+reqdVarsL.get(j).getName()+"Val = "+ spanAvg+";\n");
}
}
vams.write("\tend\n");
// if (initBuffer.length() != 0){
// vams.write("\n\tinitial\n\tbegin\n"+initBuffer+"\tend\n");
//if (buffer.length() != 0){
// vams.write(buffer.toString());
vams.write("endmodule\n\n");
buffer.delete(0, buffer.length());
buffer2.delete(0, buffer2.length());
initBuffer.delete(0, initBuffer.length());
int count = 0;
for (int i = 0; i < dmvcVarPlaces.size(); i++){
if (dmvcVarPlaces.get(i).size() != 0){
if (count == 0){
vams.write("module driver ( " + reqdVarsL.get(i).getName() + "drive ");
count++;
}
else{
vams.write(", " + reqdVarsL.get(i).getName() + "drive ");
count++;
}
buffer.append("\n\toutput "+ reqdVarsL.get(i).getName() + "drive;\n");
buffer.append("\telectrical "+ reqdVarsL.get(i).getName() + "drive;\n");
buffer2.append("\treal " + reqdVarsL.get(i).getName() + "Val" + ";\n");
vals = reqdVarsL.get(i).getInitValue().split("\\,");
double spanAvg = (Double.parseDouble(((vals[0]).split("\\["))[1])+Double.parseDouble(((vals[1]).split("\\]"))[0]))/(2.0*varScaleFactor);
initBuffer.append("\n\tinitial\n\tbegin\n"+"\t\t"+ reqdVarsL.get(i).getName() + "Val = "+ spanAvg+";\n");
if ((count == 1) && (vamsRandom) ){
initBuffer.append("\t\tseed = 0;\n");
}
//buffer3.append("\talways\n\tbegin\n");
boolean transientDoneFirst = false;
for (String p : dmvcVarPlaces.get(i)){
if (!transientNetPlaces.containsKey(p)){ // since p is w.r.t placeInfo & not w.r.t g
// buffer3.append("\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
// recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/
// buffer3.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + placeInfo.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/varScaleFactor + ";\n");
if (transientDoneFirst){
initBuffer.append("\t\tforever\n\t\tbegin\n");
transientDoneFirst = false;
}
if (g.getPostset("p" + placeInfo.get(p).getProperty("placeNum")).length != 0){
if (!vamsRandom){
//initBuffer.append("\t\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
initBuffer.append("\t\t\t#"+ (int)(((Double.parseDouble(placeInfo.get(p).getProperty("dMin"))+ Double.parseDouble(placeInfo.get(p).getProperty("dMax"))))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
}
else{
//initBuffer.append("\t\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(placeInfo.get(p).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," +(int)Math.ceil((Double.parseDouble(placeInfo.get(p).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t\t#del "); // converting seconds to ns using math.pow(10,9)
initBuffer.append("\t\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(placeInfo.get(p).getProperty("dMin")))/delayScaleFactor)) + "," +(int)Math.ceil((Double.parseDouble(placeInfo.get(p).getProperty("dMax"))/delayScaleFactor)) + ");\n\t\t\t#del "); // converting seconds to ns using math.pow(10,9)
}
initBuffer.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + placeInfo.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/varScaleFactor + ";\n");
}
else{
}
}
else{
/*buffer3.append("\tinitial\n\tbegin\n");
buffer3.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
// recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/
buffer3.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + transientNetPlaces.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/varScaleFactor + ";\n");
buffer3.append("\tend\n");*/
transientDoneFirst = true;
if (!vamsRandom){
//initBuffer.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax")))*Math.pow(10, 12))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
initBuffer.append("\t\t#"+ (int)(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin"))+ Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))))/(2.0*delayScaleFactor)) +" "); // converting seconds to nanosec. hence pow(10,9)
}
else{
//initBuffer.append("\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))/delayScaleFactor)*Math.pow(10, 12)) + "," +(int)Math.ceil((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))/delayScaleFactor)*Math.pow(10, 12)) + ");\n\t\t#del "); // converting seconds to ns using math.pow(10,9)
initBuffer.append("\t\tdel = $dist_uniform(seed," + (int)Math.floor(((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMin")))/delayScaleFactor)) + "," +(int)Math.ceil((Double.parseDouble(transientNetPlaces.get(p).getProperty("dMax"))/delayScaleFactor)) + ");\n\t\t#del "); // converting seconds to ns using math.pow(10,9)
}
initBuffer.append(reqdVarsL.get(i).getName()+ "Val = "+ ((int)(Double.parseDouble(placeInfo.get(getPlaceInfoIndex(g.getPostset(g.getPostset("p" + transientNetPlaces.get(p).getProperty("placeNum"))[0])[0])).getProperty("DMVCValue"))))/varScaleFactor + ";\n" );
// initBuffer.append("\tend\n");
}
}
// buffer3.append("\tend\n");
initBuffer.append("\t\tend\n\tend\n");
buffer4.append("\t\tV("+reqdVarsL.get(i).getName() + "drive) <+ transition("+reqdVarsL.get(i).getName() + "Val,delay,rtime,ftime);\n");
}
}
BufferedWriter topV = new BufferedWriter(new FileWriter(new File(directory + separator + "top.vams")));
topV.write("`timescale 1ps/1ps\n\nmodule top();\n\n");
if (count != 0){
vams.write(");\n");
vams.write("\tparameter delay = 0, rtime = 1p, ftime = 1p;\n");
if (vamsRandom){
vams.write("\tinteger del;\n\tinteger seed;\n");
}
vams.write(buffer+"\n"+buffer2+initBuffer+buffer3);
vams.write("\tanalog\n\tbegin\n"+buffer4+"\tend\nendmodule");
count = 0;
for (int i = 0; i < dmvcVarPlaces.size(); i++){
if (dmvcVarPlaces.get(i).size() != 0){
if (count == 0){
topV.write("\tdriver tb(\n\t\t." + reqdVarsL.get(i).getName() + "drive(" + reqdVarsL.get(i).getName() + ")");
count++;
}
else{
topV.write(",\n\t\t." + reqdVarsL.get(i).getName() + "drive(" + reqdVarsL.get(i).getName() + ")");
count++;
}
}
}
topV.write("\n\t);\n\n");
}
for (int i = 0; i < reqdVarsL.size(); i++){
v = reqdVarsL.get(i);
if ( i== 0){
topV.write("\t"+vamsFileName.split("\\.")[0]+" dut(\n\t\t."+ v.getName() + "(" + v.getName() + ")");
}
else{
topV.write(",\n\t\t." + v.getName() + "(" + reqdVarsL.get(i).getName() + ")");
count++;
}
}
topV.write("\n\t);\n\nendmodule");
topV.close();
vams.close();
/*if (failPropVHDL != null){
vhdlAms.write("\tprocess\n");
vhdlAms.write("\tbegin\n");
vhdlAms.write("\t\twait until " + failPropVHDL + ";\n");
vhdlAms.write("\t\tfail := true;\n");
vhdlAms.write("\tend process;\n\n");
}
// vhdlAms.write("\tend process;\n\n");
vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n");*/
}
catch(IOException e){
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Verilog-AMS model couldn't be created/written.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
catch(Exception e){
JOptionPane.showMessageDialog(biosim.frame(),
"Error in Verilog-AMS model generation.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
//T[] aux = (T[])a.clone();
public LhpnFile mergeLhpns(LhpnFile l1,LhpnFile l2){//(LhpnFile l1, LhpnFile l2){
String place1 = "p([-\\d]+)", place2 = "P([-\\d]+)";
String transition1 = "t([-\\d]+)", transition2 = "T([-\\d]+)";
int placeNum, transitionNum;
int minPlace=0, maxPlace=0, minTransition = 0, maxTransition = 0;
Boolean first = true;
try{
for (String st1: l1.getPlaceList()){
if ((st1.matches(place1)) || (st1.matches(place2))){
st1 = st1.replaceAll("p", "");
st1 = st1.replaceAll("P", "");
placeNum = Integer.valueOf(st1);
if (placeNum > maxPlace){
maxPlace = placeNum;
if (first){
first = false;
minPlace = placeNum;
}
}
if (placeNum < minPlace){
minPlace = placeNum;
if (first){
first = false;
maxPlace = placeNum;
}
}
}
}
for (String st1: l2.getPlaceList()){
if ((st1.matches(place1)) || (st1.matches(place2))){
st1 = st1.replaceAll("p", "");
st1 = st1.replaceAll("P", "");
placeNum = Integer.valueOf(st1);
if (placeNum > maxPlace)
maxPlace = placeNum;
if (placeNum < minPlace)
minPlace = placeNum;
}
}
//System.out.println("min place and max place in both lpns are : " + minPlace + "," + maxPlace);
for (String st2: l2.getPlaceList()){
for (String st1: l1.getPlaceList()){
if (st1.equalsIgnoreCase(st2)){
maxPlace++;
l2.renamePlace(st2, "p" + maxPlace);//, l2.getPlace(st2).isMarked());
break;
}
}
}
first = true;
for (String st1: l1.getTransitionList()){
if ((st1.matches(transition1)) || (st1.matches(transition2))){
st1 = st1.replaceAll("t", "");
st1 = st1.replaceAll("T", "");
transitionNum = Integer.valueOf(st1);
if (transitionNum > maxTransition){
maxTransition = transitionNum;
if (first){
first = false;
minTransition = transitionNum;
}
}
if (transitionNum < minTransition){
minTransition = transitionNum;
if (first){
first = false;
maxTransition = transitionNum;
}
}
}
}
for (String st1: l2.getTransitionList()){
if ((st1.matches(transition1)) || (st1.matches(transition2))){
st1 = st1.replaceAll("t", "");
st1 = st1.replaceAll("T", "");
transitionNum = Integer.valueOf(st1);
if (transitionNum > maxTransition)
maxTransition = transitionNum;
if (transitionNum < minTransition)
minTransition = transitionNum;
}
}
//System.out.println("min transition and max transition in both lpns are : " + minTransition + "," + maxTransition);
for (String st2: l2.getTransitionList()){
for (String st1: l1.getTransitionList()){
if (st1.equalsIgnoreCase(st2)){
maxTransition++;
l2.renameTransition(st2, "t" + maxTransition);
break;
}
}
}
l2.save(directory + separator + "tmp.lpn");
l1.load(directory + separator + "tmp.lpn");
File tmp = new File(directory + separator + "tmp.lpn");
tmp.delete();
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Problem while merging lpns",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
return l1;
}
}
/* This method is used for creating separate nets for each DMV input variable driver.
public void updateTimeInfo(int[][] bins, Properties cvgProp) {
String prevPlace = null;
String currPlace = null;
Properties p3 = null;
//ArrayList<String> dmvcPlaceL = new ArrayList<String>(); // only dmvc inputs
boolean exists;
// int dmvcCnt = 0; making this global .. rechk
String[] places;
try {
for (int i = 0; i < reqdVarsL.size(); i++) {
if (reqdVarsL.get(i).isDmvc() && reqdVarsL.get(i).isInput()) {
out.write(reqdVarsL.get(i).getName() + " is a dmvc input variable \n");
// dmvcCnt = 0; in case of multiple tsd files, this may be a problem. may create a new distinct place with an existing key.??
prevPlace = null;
currPlace = null;
p3 = null;
Properties p2 = null;
String k;
DMVCrun runs = reqdVarsL.get(i).getRuns();
Double[] avgVals = runs.getAvgVals();
out.write("variable " + reqdVarsL.get(i).getName() + " Number of runs = " + avgVals.length + "Avg Values are : " + avgVals.toString() + "\n");
for (int j = 0; j < avgVals.length; j++) { // this gives number of runs/startpoints/endpoints
exists = false;
places = g.getPlaceList();
if (places.length > 1) {
for (String st : places) {
k = getPlaceInfoIndex(st);
if (!isTransientPlace(st) && (placeInfo.get(k).getProperty("type").equalsIgnoreCase("DMVC"))) {
if ((Math.abs(Double.parseDouble(placeInfo.get(k).getProperty("DMVCValue")) - avgVals[j]) < epsilon)
&& (placeInfo.get(k).getProperty("DMVCVariable").equalsIgnoreCase(reqdVarsL.get(i).getName()))) {
// out.write("Place with key " + k + "already exists. so adding dmvcTime to it\n");
addDmvcTime(placeInfo.get(k), reqdVarsL.get(i).getName(), calcDelay(runs.getStartPoint(j), runs.getEndPoint(j)));
addDuration(placeInfo.get(k),calcDelay(runs.getStartPoint(j), runs.getEndPoint(j)));
exists = true;
prevPlace = currPlace;
currPlace = getPlaceInfoIndex(st);// k;
p2 = placeInfo.get(currPlace);
//next few lines commented to remove multiple dmv input places of same variable from being marked initially.
// if (j == 0) { // adding the place corresponding to the first dmv run to initial marking.
// placeInfo.get(k).setProperty("initiallyMarked", "true");
// g.changeInitialMarking("p" + placeInfo.get(k).getProperty("placeNum"),true);
//}
// break ; here?
}
}
}
}
if (!exists) {
prevPlace = currPlace;
currPlace = "d_" + i + "_" + dmvcCnt;
p2 = new Properties();
p2.setProperty("placeNum", numPlaces.toString());
p2.setProperty("type", "DMVC");
p2.setProperty("DMVCVariable", reqdVarsL.get(i).getName());
p2.setProperty("DMVCValue", avgVals[j].toString());
p2.setProperty("initiallyMarked", "false");
addDmvcTime(p2, reqdVarsL.get(i).getName(),calcDelay(runs.getStartPoint(j), runs.getEndPoint(j)));
//placeInfo.put("d_" + i + "_" + dmvcCnt, p2);
if (j == 0) {
transientNetPlaces.put("d_" + i + "_" + dmvcCnt, p2);
g.addPlace("p" + numPlaces, true);
p2.setProperty("initiallyMarked", "true");
}
else{
placeInfo.put("d_" + i + "_" + dmvcCnt, p2);
g.addPlace("p" + numPlaces, false);
}
dmvcInputPlaces.add("p" + numPlaces);
if (j == 0) { // adding the place corresponding to the first dmv run to initial marking
p2.setProperty("initiallyMarked", "true");
g.changeInitialMarking("p" + p2.getProperty("placeNum"), true);
}
numPlaces++;
out.write("Created new place with key " + "d_" + i + "_" + dmvcCnt + "\n");
dmvcCnt++;
//dmvcPlaceL.add(currPlace);
cvgProp.setProperty("places", String.valueOf(Integer.parseInt(cvgProp.getProperty("places"))+1));
}
Double d = calcDelay(runs.getStartPoint(j), runs.getEndPoint(j));// data.get(0).get(runs.getEndPoint(j)) - data.get(0).get(runs.getStartPoint(j));
// data.get(0).get(reqdVarsL.get(prevPlace.getDmvcVar()).getRuns().getEndPoint(j-1));
// TEMPORARY FIX
//Double minTime = getMinDmvcTime(p2);
//if ((d > minTime*Math.pow(10.0, 4.0))){ // && (getMinDmvcTime(p2) == getMaxDmvcTime(p2))){
// deleteInvalidDmvcTime(p2, getMinDmvcTime(p2)); // updates dmin,dmax too
//}
//END TEMPORARY FIX
// For dmv input nets, transition's delay assignment is
// it's preset's duration; value assgnmt is value in postset.
addDuration(p2,d);
//boolean transientNet = false;
// out.write("Delay in place p"+ p2.getProperty("placeNum")+ " after updating " + d + " is ["+ p2.getProperty("dMin") + ","+ p2.getProperty("dMax") + "]\n");
if (prevPlace != null) {
if (transitionInfo.containsKey(prevPlace + currPlace)) {
p3 = transitionInfo.get(prevPlace + currPlace);
} else {
p3 = new Properties();
p3.setProperty("transitionNum", numTransitions.toString());
if (transientNetPlaces.containsKey(prevPlace)){
transientNetTransitions.put(prevPlace + currPlace, p3);
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p" + transientNetPlaces.get(prevPlace).getProperty("placeNum"), "t" + transientNetTransitions.get(prevPlace + currPlace).getProperty("transitionNum"));
g.addMovement("t" + transientNetTransitions.get(prevPlace + currPlace).getProperty("transitionNum"), "p" + placeInfo.get(currPlace).getProperty("placeNum"));
// transientNet = true;
}
else{
transitionInfo.put(prevPlace + currPlace, p3);
g.addTransition("t" + numTransitions); // prevTranKey+key);
g.addMovement("p"+ placeInfo.get(prevPlace).getProperty("placeNum"), "t"+ transitionInfo.get(prevPlace + currPlace).getProperty("transitionNum"));
g.addMovement("t"+ transitionInfo.get(prevPlace+ currPlace).getProperty("transitionNum"),"p"+ placeInfo.get(currPlace).getProperty("placeNum"));
}
numTransitions++;
cvgProp.setProperty("transitions", String.valueOf(Integer.parseInt(cvgProp.getProperty("transitions"))+1));
}
}
//if (!transientNet){ // assuming postset duration
// addDuration(p2, d);
//}
//else {
// addTransientDuration(p2, d);
//}
}
} else if (reqdVarsL.get(i).isDmvc()) { // non-input dmvc
}
}
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(biosim.frame(),
"Log file couldn't be opened for writing rates and bins.",
"ERROR!", JOptionPane.ERROR_MESSAGE);
}
}
*/
/*
ArrayList<ArrayList<String>> ifL = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> ifRateL = new ArrayList<ArrayList<String>>();
for (Variable v: reqdVarsL){
ifL.add(new ArrayList<String>());
ifRateL.add(new ArrayList<String>());
}
String[] tL;
for (String p : ratePlaces){
tL = g.getPreset(p);
for (String t : tL){
if ((g.getPreset(t).length != 0) && (g.getPostset(t).length != 0) && (placeInfo.get(getPlaceInfoIndex(g.getPreset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))
&& (placeInfo.get(getPlaceInfoIndex(g.getPostset(t)[0])).getProperty("type").equalsIgnoreCase("RATE"))) {
ArrayList<Integer> diffL = diff(getPlaceInfoIndex(g.getPreset(t)[0]), getPlaceInfoIndex(g.getPostset(t)[0]));
String ifStr = "";
String[] binIncoming = getPlaceInfoIndex(g.getPreset(t)[0]).split("");
String[] binOutgoing = getPlaceInfoIndex(g.getPostset(t)[0]).split("");
boolean above;
double val;
for (int k : diffL) {
if (Integer.parseInt(binIncoming[k + 1]) < Integer.parseInt(binOutgoing[k + 1])) {
val = divisionsL.get(k).get(Integer.parseInt(binIncoming[k + 1])).doubleValue();
above = true;
} else {
val = divisionsL.get(k).get(Integer.parseInt(binOutgoing[k + 1])).doubleValue();
above = false;
}
if (above) {
ifStr = reqdVarsL.get(k).getName()+"'above("+val+")";
}
else{
ifStr = "not "+ reqdVarsL.get(k).getName()+"'above("+val+")";
}
for (int j = 0; j<reqdVarsL.size(); j++){
String rateStr = "";
if ((!reqdVarsL.get(j).isInput()) && (!reqdVarsL.get(j).isDmvc())){
//if (!(reqdVarsL.get(j).isInput() && reqdVarsL.get(j).isDmvc())){
rateStr = reqdVarsL.get(j).getName() + "'dot == span(" + getMinRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0,"+getMaxRate(getPlaceInfoIndex(p), reqdVarsL.get(j).getName())+".0)";
ifL.get(j).add(ifStr);
ifRateL.get(j).add(rateStr);
}
}
}
}
}
}
for (int i = 0; i<reqdVarsL.size(); i++){
for (int j = 0; j<ifL.get(i).size(); j++){
if (j==0){
vhdlAms.write("\tif "+ifL.get(i).get(j)+" use\n");
}
else{
vhdlAms.write("\telsif "+ifL.get(i).get(j)+" use\n");
}
vhdlAms.write("\t\t"+ ifRateL.get(i).get(j)+";\n");
}
if (ifL.get(i).size() != 0){
vhdlAms.write("\tend use;\n\n");
}
}
// vhdlAms.write("\tprocess\n");
// vhdlAms.write("\tbegin\n");
for (int i = 0; i < dmvcVarPlaces.size(); i++){
if (dmvcVarPlaces.get(i).size() != 0){
vhdlAms.write("\tprocess\n");
vhdlAms.write("\tbegin\n");
for (String p : dmvcVarPlaces.get(i)){
vhdlAms.write("\t\twait for delay("+placeInfo.get(p).getProperty("dMax")+","+placeInfo.get(p).getProperty("dMin") +");\n");
// recheck above line.. truncating double to int.. becomes 0 in most unscaled cases?/
vhdlAms.write("\t\tbreak "+reqdVarsL.get(i).getName()+ " => "+ placeInfo.get(p).getProperty("DMVCValue") + ";\n");
}
vhdlAms.write("\tend process;\n\n");
}
}
// vhdlAms.write("\tend process;\n\n");
vhdlAms.write("end "+vhdFile.split("\\.")[0]+";\n");
vhdlAms.close();
}
catch(IOException e){
}
}
//T[] aux = (T[])a.clone();
}
*/
/* OBSOLETE METHODS
public ArrayList<ArrayList<Double>> parseBinFile() {
reqdVarsL = new ArrayList<Variable>();
ArrayList<String> linesBinFileL = null;
int h = 0;
//ArrayList<ArrayList<Double>> divisionsL = new ArrayList<ArrayList<Double>>();
try {
Scanner f1 = new Scanner(new File(directory + separator + binFile));
// log.addText(directory + separator + binFile);
linesBinFileL = new ArrayList<String>();
linesBinFileL.add(f1.nextLine());
while (f1.hasNextLine()) {
linesBinFileL.add(f1.nextLine());
}
out.write("Required variables and their levels are :");
for (String st : linesBinFileL) {
divisionsL.add(new ArrayList<Double>());
String[] wordsBinFileL = st.split("\\s");
for (int i = 0; i < wordsBinFileL.length; i++) {
if (i == 0) {
reqdVarsL.add(new Variable(wordsBinFileL[i]));
out.write("\n" + reqdVarsL.get(reqdVarsL.size() - 1).getName());
} else {
divisionsL.get(h).add(Double.parseDouble(wordsBinFileL[i]));
}
}
out.write(" " + divisionsL.get(h));
h++;
// max = Math.max(max, wordsBinFileL.length + 1);
}
f1.close();
} catch (Exception e1) {
}
return divisionsL;
}
public String cleanRow (String row){
String rowNS,rowTS = null;
try{
rowNS =lParenR.matcher(row).replaceAll("");
rowTS = rParenR.matcher(rowNS).replaceAll("");
return rowTS;
}
catch(PatternSyntaxException pse){
System.out.format("There is a problem withthe regular expression!%n");
System.out.format("The pattern in question is:%s%n",pse.getPattern());
System.out.format("The description is:%s%n",pse.getDescription());
System.out.format("The message is:%s%n",pse.getMessage());
System.out.format("The index is:%s%n",pse.getIndex());
System.exit(0);
return rowTS;
}
}
*/
|
package reb2sac;
import java.io.*;
import java.util.*;
import java.util.prefs.Preferences;
import java.util.regex.Pattern;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import lhpn2sbml.gui.LHPNEditor;
import lhpn2sbml.parser.Abstraction;
import lhpn2sbml.parser.LhpnFile;
import lhpn2sbml.parser.Translator;
import org.sbml.libsbml.*;
import sbmleditor.*;
import verification.AbstPane;
import gcm2sbml.gui.GCM2SBMLEditor;
import graph.*;
import biomodelsim.*;
import buttons.*;
/**
* This class creates a GUI for the reb2sac program. It implements the
* ActionListener class, the KeyListener class, the MouseListener class, and the
* Runnable class. This allows the GUI to perform actions when buttons are
* pressed, text is entered into a field, or the mouse is clicked. It also
* allows this class to execute many reb2sac programs at the same time on
* different threads.
*
* @author Curtis Madsen
*/
public class Reb2Sac extends JPanel implements ActionListener, Runnable, MouseListener {
private static final long serialVersionUID = 3181014495993143825L;
private JTextField amountTerm; // Amount for termination condition
/*
* Buttons for adding and removing conditions and species
*/
private JButton addIntSpecies, removeIntSpecies, editIntSpecies, addTermCond, removeTermCond,
clearIntSpecies, clearTermCond;
/*
* Radio Buttons that represent the different abstractions
*/
private JRadioButton none, abstraction, nary, ODE, monteCarlo, markov;
private JRadioButton sbml, dot, xhtml, lhpn; // Radio Buttons output option
/*
* Radio Buttons for termination conditions
*/
private JRadioButton ge, gt, eq, le, lt;
private JButton run, save; // The save and run button
/*
* Added interesting species and termination conditions
*/
private JList terminations;
private JList termCond; // List of species in sbml file
private JLabel spLabel, speciesLabel; // Labels for interesting species
private JPanel speciesPanel;
private ArrayList<ArrayList<Component>> speciesInt;
/*
* Text fields for changes in the abstraction
*/
private JTextField limit, interval, minStep, step, absErr, seed, runs, fileStem;
private JComboBox intervalLabel;
/*
* Labels for the changes in the abstraction
*/
private JLabel limitLabel, minStepLabel, stepLabel, errorLabel, seedLabel, runsLabel,
fileStemLabel;
/*
* Description of selected simulator
*/
private JLabel description, explanation;
/*
* List of interesting species
*/
private Object[] allSpecies = new Object[0];
private Object[] preAbstractions = new Object[0];
private Object[] loopAbstractions = new Object[0];
private Object[] postAbstractions = new Object[0];
/*
* List of species with termination conditions
*/
private Object[] termConditions = new Object[0];
private JComboBox simulators; // Combo Box for possible simulators
private JLabel simulatorsLabel; // Label for possible simulators
private JTextField rapid1, rapid2, qssa, maxCon; // advanced options
/*
* advanced labels
*/
private JLabel rapidLabel1, rapidLabel2, qssaLabel, maxConLabel;
private JCheckBox usingSSA, usingSAD; // check box for using ssa
private JComboBox availSpecies; // species for SSA
private JList ssa, sad; // list of ssa
private JTextField time; // time for ssa
private JTextField TCid; // id for sad
private JTextField desc; // description for sad
private JTextField cond; // condition for sad
private JTextField ssaModNum; // number that the ssa is changed by
private JComboBox ssaMod; // amount to mod the ssa species by
private JButton addSSA, editSSA, removeSSA; // Buttons for editing SSA
private JButton addSAD, editSAD, removeSAD; // Buttons for editing SAD
private JButton newSSA; // Buttons for SSA file
private JButton newSAD; // Buttons for SAD file
private JLabel timeLabel; // Label for SSA
private JLabel idLabel; // ID label for SAD
private JLabel descLabel; // Description label for SAD
private JLabel condLabel; // Condition label for SAD
private Object[] ssaList, sadList; // array for ssa/sad JList
private JList properties; // JList for properties
private JTextField prop, value; // text areas for properties
private JButton addProp, editProp, removeProp, newProp; // buttons for
// properties
private Object[] props; // array for properties JList
private String sbmlFile, root; // sbml file and root directory
private BioSim biomodelsim; // reference to the tstubd class
private String simName; // simulation id
private Log log; // the log
private JTabbedPane simTab; // the simulation tab
private SBML_Editor sbmlEditor; // sbml editor
private GCM2SBMLEditor gcmEditor; // gcm editor
private JRadioButton overwrite, append;
private JRadioButton amounts, concentrations;
private JLabel choose3;
private JLabel report;
private boolean runFiles;
private String separator;
private String sbmlProp;
private boolean change;
private ArrayList<JFrame> frames;
private Pattern stemPat = Pattern.compile("([a-zA-Z]|[0-9]|_)*");
private JPanel propertiesPanel, advanced;
private JList preAbs;
private JList loopAbs;
private JList postAbs;
private JLabel preAbsLabel;
private JLabel loopAbsLabel;
private JLabel postAbsLabel;
private JButton addPreAbs;
private JButton rmPreAbs;
private JButton editPreAbs;
private JButton addLoopAbs;
private JButton rmLoopAbs;
private JButton editLoopAbs;
private JButton addPostAbs;
private JButton rmPostAbs;
private JButton editPostAbs;
private String modelFile;
private AbstPane lhpnAbstraction;
private JComboBox lpnProperties;
/**
* This is the constructor for the GUI. It initializes all the input fields,
* puts them on panels, adds the panels to the frame, and then displays the
* GUI.
*
* @param modelFile
*/
public Reb2Sac(String sbmlFile, String sbmlProp, String root, BioSim biomodelsim,
String simName, Log log, JTabbedPane simTab, String open, String modelFile,
AbstPane lhpnAbstraction) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
this.biomodelsim = biomodelsim;
this.sbmlFile = sbmlFile;
this.sbmlProp = sbmlProp;
this.root = root;
this.simName = simName;
this.log = log;
this.simTab = simTab;
this.lhpnAbstraction = lhpnAbstraction;
change = false;
frames = new ArrayList<JFrame>();
String[] tempArray = modelFile.split(separator);
this.modelFile = tempArray[tempArray.length - 1];
SBMLDocument document = BioSim.readSBML(sbmlFile);
Model model = document.getModel();
ArrayList<String> listOfSpecs = new ArrayList<String>();
if (model != null) {
ListOf listOfSpecies = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) listOfSpecies.get(i);
listOfSpecs.add(species.getId());
}
}
allSpecies = listOfSpecs.toArray();
for (int i = 1; i < allSpecies.length; i++) {
String index = (String) allSpecies[i];
int j = i;
while ((j > 0) && ((String) allSpecies[j - 1]).compareToIgnoreCase(index) > 0) {
allSpecies[j] = allSpecies[j - 1];
j = j - 1;
}
allSpecies[j] = index;
}
// Creates the input fields for the changes in abstraction
Preferences biosimrc = Preferences.userRoot();
String[] odeSimulators = new String[6];
odeSimulators[0] = "euler";
odeSimulators[1] = "gear1";
odeSimulators[2] = "gear2";
odeSimulators[3] = "rk4imp";
odeSimulators[4] = "rk8pd";
odeSimulators[5] = "rkf45";
explanation = new JLabel("Description Of Selected Simulator: ");
description = new JLabel("Embedded Runge-Kutta-Fehlberg (4, 5) method");
simulators = new JComboBox(odeSimulators);
simulators.setSelectedItem("rkf45");
simulators.addActionListener(this);
limit = new JTextField(biosimrc.get("biosim.sim.limit", ""), 39);
interval = new JTextField(biosimrc.get("biosim.sim.interval", ""), 15);
minStep = new JTextField(biosimrc.get("biosim.sim.min.step", ""), 15);
step = new JTextField(biosimrc.get("biosim.sim.step", ""), 15);
absErr = new JTextField(biosimrc.get("biosim.sim.error", ""), 15);
int next = 1;
String filename = "sim" + next;
while (new File(root + separator + filename).exists()) {
next++;
filename = "sim" + next;
}
// dir = new JTextField(filename, 15);
seed = new JTextField(biosimrc.get("biosim.sim.seed", ""), 15);
runs = new JTextField(biosimrc.get("biosim.sim.runs", ""), 15);
simulatorsLabel = new JLabel("Possible Simulators/Analyzers:");
limitLabel = new JLabel("Time Limit:");
String[] intervalChoices = { "Print Interval", "Minimum Print Interval", "Number Of Steps" };
intervalLabel = new JComboBox(intervalChoices);
intervalLabel.setSelectedItem(biosimrc.get("biosim.sim.useInterval", ""));
minStepLabel = new JLabel("Minimum Time Step:");
stepLabel = new JLabel("Maximum Time Step:");
errorLabel = new JLabel("Absolute Error:");
seedLabel = new JLabel("Random Seed:");
runsLabel = new JLabel("Runs:");
fileStem = new JTextField("", 15);
fileStemLabel = new JLabel("Simulation ID:");
JPanel inputHolder = new JPanel(new BorderLayout());
JPanel inputHolderLeft;
JPanel inputHolderRight;
if (modelFile.contains(".lpn")) {
JLabel prop = new JLabel("Properties:");
LhpnFile lpn = new LhpnFile();
lpn.load(root + separator + modelFile);
lpnProperties = new JComboBox(lpn.getProperties().toArray(new String[0]));
inputHolderLeft = new JPanel(new GridLayout(11, 1));
inputHolderRight = new JPanel(new GridLayout(11, 1));
inputHolderLeft.add(prop);
inputHolderRight.add(lpnProperties);
}
else {
inputHolderLeft = new JPanel(new GridLayout(10, 1));
inputHolderRight = new JPanel(new GridLayout(10, 1));
}
inputHolderLeft.add(simulatorsLabel);
inputHolderRight.add(simulators);
inputHolderLeft.add(explanation);
inputHolderRight.add(description);
inputHolderLeft.add(limitLabel);
inputHolderRight.add(limit);
inputHolderLeft.add(intervalLabel);
inputHolderRight.add(interval);
inputHolderLeft.add(minStepLabel);
inputHolderRight.add(minStep);
inputHolderLeft.add(stepLabel);
inputHolderRight.add(step);
inputHolderLeft.add(errorLabel);
inputHolderRight.add(absErr);
inputHolderLeft.add(seedLabel);
inputHolderRight.add(seed);
inputHolderLeft.add(runsLabel);
inputHolderRight.add(runs);
inputHolderLeft.add(fileStemLabel);
inputHolderRight.add(fileStem);
inputHolder.add(inputHolderLeft, "West");
inputHolder.add(inputHolderRight, "Center");
JPanel topInputHolder = new JPanel();
topInputHolder.add(inputHolder);
// Creates the interesting species JList
preAbs = new JList();
loopAbs = new JList();
postAbs = new JList();
preAbsLabel = new JLabel("Preprocess abstraction methods:");
loopAbsLabel = new JLabel("Main loop abstraction methods:");
postAbsLabel = new JLabel("Postprocess abstraction methods:");
JPanel absHolder = new JPanel(new BorderLayout());
JPanel listOfAbsLabelHolder = new JPanel(new GridLayout(1, 3));
JPanel listOfAbsHolder = new JPanel(new GridLayout(1, 3));
JPanel listOfAbsButtonHolder = new JPanel(new GridLayout(1, 3));
JScrollPane preAbsScroll = new JScrollPane();
JScrollPane loopAbsScroll = new JScrollPane();
JScrollPane postAbsScroll = new JScrollPane();
preAbsScroll.setMinimumSize(new Dimension(260, 200));
preAbsScroll.setPreferredSize(new Dimension(276, 132));
preAbsScroll.setViewportView(preAbs);
loopAbsScroll.setMinimumSize(new Dimension(260, 200));
loopAbsScroll.setPreferredSize(new Dimension(276, 132));
loopAbsScroll.setViewportView(loopAbs);
postAbsScroll.setMinimumSize(new Dimension(260, 200));
postAbsScroll.setPreferredSize(new Dimension(276, 132));
postAbsScroll.setViewportView(postAbs);
addPreAbs = new JButton("Add");
rmPreAbs = new JButton("Remove");
editPreAbs = new JButton("Edit");
JPanel preAbsButtonHolder = new JPanel();
preAbsButtonHolder.add(addPreAbs);
preAbsButtonHolder.add(rmPreAbs);
// preAbsButtonHolder.add(editPreAbs);
addLoopAbs = new JButton("Add");
rmLoopAbs = new JButton("Remove");
editLoopAbs = new JButton("Edit");
JPanel loopAbsButtonHolder = new JPanel();
loopAbsButtonHolder.add(addLoopAbs);
loopAbsButtonHolder.add(rmLoopAbs);
// loopAbsButtonHolder.add(editLoopAbs);
addPostAbs = new JButton("Add");
rmPostAbs = new JButton("Remove");
editPostAbs = new JButton("Edit");
JPanel postAbsButtonHolder = new JPanel();
postAbsButtonHolder.add(addPostAbs);
postAbsButtonHolder.add(rmPostAbs);
// postAbsButtonHolder.add(editPostAbs);
listOfAbsLabelHolder.add(preAbsLabel);
listOfAbsHolder.add(preAbsScroll);
listOfAbsLabelHolder.add(loopAbsLabel);
listOfAbsHolder.add(loopAbsScroll);
listOfAbsLabelHolder.add(postAbsLabel);
listOfAbsHolder.add(postAbsScroll);
listOfAbsButtonHolder.add(preAbsButtonHolder);
listOfAbsButtonHolder.add(loopAbsButtonHolder);
listOfAbsButtonHolder.add(postAbsButtonHolder);
absHolder.add(listOfAbsLabelHolder, "North");
absHolder.add(listOfAbsHolder, "Center");
absHolder.add(listOfAbsButtonHolder, "South");
preAbs.setEnabled(false);
loopAbs.setEnabled(false);
postAbs.setEnabled(false);
preAbs.addMouseListener(this);
loopAbs.addMouseListener(this);
postAbs.addMouseListener(this);
preAbsLabel.setEnabled(false);
loopAbsLabel.setEnabled(false);
postAbsLabel.setEnabled(false);
addPreAbs.setEnabled(false);
rmPreAbs.setEnabled(false);
editPreAbs.setEnabled(false);
addPreAbs.addActionListener(this);
rmPreAbs.addActionListener(this);
editPreAbs.addActionListener(this);
addLoopAbs.setEnabled(false);
rmLoopAbs.setEnabled(false);
editLoopAbs.setEnabled(false);
addLoopAbs.addActionListener(this);
rmLoopAbs.addActionListener(this);
editLoopAbs.addActionListener(this);
addPostAbs.setEnabled(false);
rmPostAbs.setEnabled(false);
editPostAbs.setEnabled(false);
addPostAbs.addActionListener(this);
rmPostAbs.addActionListener(this);
editPostAbs.addActionListener(this);
// Creates the interesting species JList intSpecies = new JList();
// species = new JList();
spLabel = new JLabel("Available Species:");
speciesLabel = new JLabel("Interesting Species:");
JPanel speciesHolder = new JPanel(new BorderLayout());
JPanel listOfSpeciesLabelHolder = new JPanel(new GridLayout(1, 2));
JPanel listOfSpeciesHolder = new JPanel(new GridLayout(1, 2));
JScrollPane scroll = new JScrollPane();
JScrollPane scroll1 = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 200));
scroll.setPreferredSize(new Dimension(276, 132));
// scroll.setViewportView(species);
scroll1.setMinimumSize(new Dimension(260, 200));
scroll1.setPreferredSize(new Dimension(276, 132));
// scroll1.setViewportView(intSpecies);
addIntSpecies = new JButton("Add Species");
editIntSpecies = new JButton("Edit Species");
removeIntSpecies = new JButton("Remove Species");
clearIntSpecies = new JButton("Clear Species");
listOfSpeciesLabelHolder.add(spLabel);
listOfSpeciesHolder.add(scroll1);
listOfSpeciesLabelHolder.add(speciesLabel);
listOfSpeciesHolder.add(scroll);
speciesHolder.add(listOfSpeciesLabelHolder, "North");
speciesHolder.add(listOfSpeciesHolder, "Center");
JPanel buttonHolder = new JPanel();
buttonHolder.add(addIntSpecies);
buttonHolder.add(editIntSpecies);
buttonHolder.add(removeIntSpecies);
buttonHolder.add(clearIntSpecies);
speciesHolder.add(buttonHolder, "South");
// intSpecies.setEnabled(false);
// species.setEnabled(false);
// intSpecies.addMouseListener(this);
// species.addMouseListener(this);
spLabel.setEnabled(false);
speciesLabel.setEnabled(false);
addIntSpecies.setEnabled(false);
editIntSpecies.setEnabled(false);
removeIntSpecies.setEnabled(false);
addIntSpecies.addActionListener(this);
editIntSpecies.addActionListener(this);
removeIntSpecies.addActionListener(this);
clearIntSpecies.setEnabled(false);
clearIntSpecies.addActionListener(this);
speciesPanel = new JPanel();
JPanel sP = new JPanel();
((FlowLayout) sP.getLayout()).setAlignment(FlowLayout.LEFT);
sP.add(speciesPanel);
JLabel interestingLabel = new JLabel("Interesting Species:");
JScrollPane sPScroll = new JScrollPane();
sPScroll.setMinimumSize(new Dimension(260, 200));
sPScroll.setPreferredSize(new Dimension(276, 132));
sPScroll.setViewportView(sP);
JPanel interestingPanel = new JPanel(new BorderLayout());
interestingPanel.add(interestingLabel, "North");
interestingPanel.add(sPScroll, "Center");
speciesInt = new ArrayList<ArrayList<Component>>();
createInterestingSpeciesPanel();
// Creates some abstraction options
JPanel advancedGrid = new JPanel(new GridLayout(2, 4));
advanced = new JPanel(new BorderLayout());
// JPanel rapidSpace1 = new JPanel();
// JPanel rapidSpace2 = new JPanel();
// JPanel rapidSpace3 = new JPanel();
// JPanel rapidSpace4 = new JPanel();
// JPanel qssaSpace1 = new JPanel();
// JPanel qssaSpace2 = new JPanel();
// JPanel maxConSpace1 = new JPanel();
// JPanel maxConSpace2 = new JPanel();
rapidLabel1 = new JLabel("Rapid Equilibrium Condition 1:");
rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", ""), 15);
rapidLabel2 = new JLabel("Rapid Equilibrium Condition 2:");
rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", ""), 15);
qssaLabel = new JLabel("QSSA Condition:");
qssa = new JTextField(biosimrc.get("biosim.sim.qssa", ""), 15);
maxConLabel = new JLabel("Max Concentration Threshold:");
maxCon = new JTextField(biosimrc.get("biosim.sim.concentration", ""), 15);
maxConLabel.setEnabled(false);
maxCon.setEnabled(false);
qssaLabel.setEnabled(false);
qssa.setEnabled(false);
rapidLabel1.setEnabled(false);
rapid1.setEnabled(false);
rapidLabel2.setEnabled(false);
rapid2.setEnabled(false);
advancedGrid.add(rapidLabel1);
advancedGrid.add(rapid1);
// advancedGrid.add(rapidSpace1);
// advancedGrid.add(rapidSpace2);
advancedGrid.add(rapidLabel2);
advancedGrid.add(rapid2);
// advancedGrid.add(rapidSpace3);
// advancedGrid.add(rapidSpace4);
advancedGrid.add(qssaLabel);
advancedGrid.add(qssa);
// advancedGrid.add(qssaSpace1);
// advancedGrid.add(qssaSpace2);
advancedGrid.add(maxConLabel);
advancedGrid.add(maxCon);
// advancedGrid.add(maxConSpace1);
// advancedGrid.add(maxConSpace2);
JPanel advAbs = new JPanel(new BorderLayout());
advAbs.add(absHolder, "Center");
advAbs.add(advancedGrid, "South");
advanced.add(advAbs, "North");
// JPanel space = new JPanel();
// advanced.add(space);
advanced.add(interestingPanel, "Center");
// Sets up the radio buttons for Abstraction and Nary
JLabel choose = new JLabel("Abstraction:");
none = new JRadioButton("None");
abstraction = new JRadioButton("Abstraction");
nary = new JRadioButton("Logical Abstraction");
ButtonGroup abs = new ButtonGroup();
abs.add(none);
abs.add(abstraction);
abs.add(nary);
none.setSelected(true);
if (modelFile.contains(".lpn")) {
nary.setEnabled(false);
}
JPanel topPanel = new JPanel(new BorderLayout());
JPanel backgroundPanel = new JPanel();
JLabel backgroundLabel = new JLabel("Model File:");
JTextField backgroundField = new JTextField(this.modelFile);
backgroundField.setEditable(false);
backgroundPanel.add(backgroundLabel);
backgroundPanel.add(backgroundField);
JPanel absAndNaryPanel = new JPanel();
absAndNaryPanel.add(choose);
absAndNaryPanel.add(none);
absAndNaryPanel.add(abstraction);
absAndNaryPanel.add(nary);
topPanel.add(backgroundPanel, BorderLayout.NORTH);
topPanel.add(absAndNaryPanel, BorderLayout.SOUTH);
none.addActionListener(this);
abstraction.addActionListener(this);
nary.addActionListener(this);
// Sets up the radio buttons for ODE, Monte Carlo, and Markov
JLabel choose2 = new JLabel("Simulation Type:");
ODE = new JRadioButton("ODE");
monteCarlo = new JRadioButton("Monte Carlo");
markov = new JRadioButton("Markov");
ODE.setSelected(true);
seed.setEnabled(true);
seedLabel.setEnabled(true);
runs.setEnabled(true);
runsLabel.setEnabled(true);
fileStem.setEnabled(true);
fileStemLabel.setEnabled(true);
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
absErr.setEnabled(true);
errorLabel.setEnabled(true);
JPanel odeMonteAndMarkovPanel = new JPanel();
odeMonteAndMarkovPanel.add(choose2);
odeMonteAndMarkovPanel.add(ODE);
odeMonteAndMarkovPanel.add(monteCarlo);
odeMonteAndMarkovPanel.add(markov);
ODE.addActionListener(this);
monteCarlo.addActionListener(this);
markov.addActionListener(this);
// Sets up the radio buttons for output option
sbml = new JRadioButton("SBML");
dot = new JRadioButton("Network");
xhtml = new JRadioButton("Browser");
lhpn = new JRadioButton("LPN");
sbml.setSelected(true);
odeMonteAndMarkovPanel.add(sbml);
odeMonteAndMarkovPanel.add(dot);
odeMonteAndMarkovPanel.add(xhtml);
odeMonteAndMarkovPanel.add(lhpn);
sbml.addActionListener(this);
dot.addActionListener(this);
xhtml.addActionListener(this);
lhpn.addActionListener(this);
ButtonGroup sim = new ButtonGroup();
sim.add(ODE);
sim.add(monteCarlo);
sim.add(markov);
sim.add(sbml);
sim.add(dot);
sim.add(xhtml);
sim.add(lhpn);
report = new JLabel("Report:");
amounts = new JRadioButton("Amounts");
concentrations = new JRadioButton("Concentrations");
amounts.setSelected(true);
amounts.setEnabled(true);
concentrations.setEnabled(true);
JPanel reportPanel = new JPanel();
reportPanel.add(report);
reportPanel.add(amounts);
reportPanel.add(concentrations);
amounts.addActionListener(this);
concentrations.addActionListener(this);
ButtonGroup rept = new ButtonGroup();
rept.add(amounts);
rept.add(concentrations);
choose3 = new JLabel("Choose One:");
overwrite = new JRadioButton("Overwrite");
append = new JRadioButton("Append");
overwrite.setSelected(true);
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
JPanel overwritePanel = new JPanel();
overwritePanel.add(choose3);
overwritePanel.add(overwrite);
overwritePanel.add(append);
overwrite.addActionListener(this);
append.addActionListener(this);
ButtonGroup over = new ButtonGroup();
over.add(overwrite);
over.add(append);
// Puts all the radio buttons in a panel
JPanel radioButtonPanel = new JPanel(new BorderLayout());
radioButtonPanel.add(topPanel, "North");
radioButtonPanel.add(odeMonteAndMarkovPanel, "Center");
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(overwritePanel, "North");
bottomPanel.add(reportPanel, "South");
radioButtonPanel.add(bottomPanel, "South");
// Creates the main tabbed panel
JPanel mainTabbedPanel = new JPanel(new BorderLayout());
mainTabbedPanel.add(topInputHolder, "Center");
mainTabbedPanel.add(radioButtonPanel, "North");
// Creates the run button
run = new JButton("Save and Run");
save = new JButton("Save Parameters");
JPanel runHolder = new JPanel();
runHolder.add(run);
run.addActionListener(this);
run.setMnemonic(KeyEvent.VK_R);
runHolder.add(save);
save.addActionListener(this);
save.setMnemonic(KeyEvent.VK_S);
// Creates the termination conditions tab
termCond = new JList();
terminations = new JList();
addTermCond = new JButton("Add Condition");
removeTermCond = new JButton("Remove Condition");
clearTermCond = new JButton("Clear Conditions");
addTermCond.addActionListener(this);
removeTermCond.addActionListener(this);
clearTermCond.addActionListener(this);
amountTerm = new JTextField("0.0", 15);
JLabel spLabel2 = new JLabel("Available Species:");
JLabel specLabel = new JLabel("Termination Conditions:");
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(260, 200));
scroll2.setPreferredSize(new Dimension(276, 132));
scroll2.setViewportView(termCond);
JScrollPane scroll3 = new JScrollPane();
scroll3.setMinimumSize(new Dimension(260, 200));
scroll3.setPreferredSize(new Dimension(276, 132));
scroll3.setViewportView(terminations);
JPanel mainTermCond = new JPanel(new BorderLayout());
JPanel termCondPanel = new JPanel(new GridLayout(1, 2));
JPanel speciesPanel = new JPanel(new GridLayout(1, 2));
ge = new JRadioButton(">=");
gt = new JRadioButton(">");
eq = new JRadioButton("=");
le = new JRadioButton("<=");
lt = new JRadioButton("<");
ButtonGroup condition = new ButtonGroup();
condition.add(gt);
condition.add(ge);
condition.add(eq);
condition.add(le);
condition.add(lt);
gt.setSelected(true);
JPanel termOptionsPanel = new JPanel(new BorderLayout());
JPanel termSelectionPanel = new JPanel();
JPanel termButtonPanel = new JPanel();
termSelectionPanel.add(gt);
termSelectionPanel.add(ge);
termSelectionPanel.add(eq);
termSelectionPanel.add(le);
termSelectionPanel.add(lt);
termSelectionPanel.add(amountTerm);
termButtonPanel.add(addTermCond);
termButtonPanel.add(removeTermCond);
termButtonPanel.add(clearTermCond);
termOptionsPanel.add(termSelectionPanel, "North");
termOptionsPanel.add(termButtonPanel, "South");
speciesPanel.add(spLabel2);
speciesPanel.add(specLabel);
termCondPanel.add(scroll2);
termCondPanel.add(scroll3);
termCond.addMouseListener(this);
terminations.addMouseListener(this);
mainTermCond.add(speciesPanel, "North");
mainTermCond.add(termCondPanel, "Center");
mainTermCond.add(termOptionsPanel, "South");
JPanel sadTermCondPanel = new JPanel(new BorderLayout());
// sadFile = new JTextArea();
// JScrollPane scroll9 = new JScrollPane();
// scroll9.setViewportView(sadFile);
// sadTermCondPanel.add(scroll9, "Center");
newSAD = new JButton("Clear Conditions");
newSAD.setEnabled(false);
newSAD.addActionListener(this);
usingSAD = new JCheckBox("Use Termination Conditions");
usingSAD.setSelected(false);
usingSAD.addActionListener(this);
sad = new JList();
sad.setEnabled(false);
sad.addMouseListener(this);
sadList = new Object[0];
JScrollPane scroll9 = new JScrollPane();
scroll9.setMinimumSize(new Dimension(260, 200));
scroll9.setPreferredSize(new Dimension(276, 132));
scroll9.setViewportView(sad);
JPanel sadAddPanel = new JPanel(new BorderLayout());
JPanel sadAddPanel1 = new JPanel();
JPanel sadAddPanel3 = new JPanel();
idLabel = new JLabel("ID: ");
idLabel.setEnabled(false);
TCid = new JTextField(10);
TCid.setEnabled(false);
descLabel = new JLabel("Description: ");
descLabel.setEnabled(false);
desc = new JTextField(20);
desc.setEnabled(false);
condLabel = new JLabel("Condition: ");
condLabel.setEnabled(false);
cond = new JTextField(35);
cond.setEnabled(false);
sadAddPanel1.add(idLabel);
sadAddPanel1.add(TCid);
sadAddPanel1.add(descLabel);
sadAddPanel1.add(desc);
sadAddPanel1.add(condLabel);
sadAddPanel1.add(cond);
addSAD = new JButton("Add Condition");
addSAD.setEnabled(false);
addSAD.addActionListener(this);
editSAD = new JButton("Edit Condition");
editSAD.setEnabled(false);
editSAD.addActionListener(this);
removeSAD = new JButton("Remove Condition");
removeSAD.setEnabled(false);
removeSAD.addActionListener(this);
sadAddPanel3.add(addSAD);
sadAddPanel3.add(editSAD);
sadAddPanel3.add(removeSAD);
sadAddPanel3.add(newSAD);
sadAddPanel.add(sadAddPanel1, "North");
// sadAddPanel.add(sadAddPanel2, "Center");
sadAddPanel.add(sadAddPanel3, "South");
sadTermCondPanel.add(usingSAD, "North");
sadTermCondPanel.add(scroll9, "Center");
sadTermCondPanel.add(sadAddPanel, "South");
if (new File(root + separator + simName + separator + "termCond.sad").exists()) {
try {
BufferedReader input = new BufferedReader(new FileReader(root + separator + simName
+ separator + "termCond.sad"));
// + load.getProperty("computation.analysis.sad.path")));
String read = input.readLine();
while (read != null) {
String[] TCid = read.split(" ");
String desc = input.readLine();
String cond = input.readLine();
String add = TCid[1] + "; " + desc.substring(8, desc.length() - 2) + "; "
+ cond.substring(7, cond.indexOf(';'));
JList addSAD = new JList();
Object[] adding = { add };
addSAD.setListData(adding);
addSAD.setSelectedIndex(0);
sadList = Buttons.add(sadList, sad, addSAD, false, null, null, null, null,
null, null, this);
// sadFile.append("" + (char) read);
read = input.readLine();
read = input.readLine();
}
sad.setListData(sadList);
input.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Unable to load termination condition file!", "Error Loading File",
JOptionPane.ERROR_MESSAGE);
}
}
// Creates the ssa with user defined species level update feature tab
JPanel ssaPanel = new JPanel(new BorderLayout());
newSSA = new JButton("Clear Data Points");
newSSA.setEnabled(false);
newSSA.addActionListener(this);
usingSSA = new JCheckBox("Use User Defined Data");
usingSSA.setSelected(false);
usingSSA.addActionListener(this);
ssa = new JList();
ssa.setEnabled(false);
ssa.addMouseListener(this);
ssaList = new Object[0];
JScrollPane scroll5 = new JScrollPane();
scroll5.setMinimumSize(new Dimension(260, 200));
scroll5.setPreferredSize(new Dimension(276, 132));
scroll5.setViewportView(ssa);
JPanel ssaAddPanel = new JPanel(new BorderLayout());
JPanel ssaAddPanel1 = new JPanel();
JPanel ssaAddPanel2 = new JPanel();
JPanel ssaAddPanel3 = new JPanel();
timeLabel = new JLabel("At time step: ");
timeLabel.setEnabled(false);
time = new JTextField(15);
time.setEnabled(false);
availSpecies = new JComboBox();
availSpecies.setEnabled(false);
String[] mod = new String[5];
mod[0] = "goes to";
mod[1] = "is added by";
mod[2] = "is subtracted by";
mod[3] = "is multiplied by";
mod[4] = "is divided by";
ssaMod = new JComboBox(mod);
ssaMod.setEnabled(false);
ssaModNum = new JTextField(15);
ssaModNum.setEnabled(false);
ssaAddPanel1.add(timeLabel);
ssaAddPanel1.add(time);
ssaAddPanel1.add(availSpecies);
ssaAddPanel2.add(ssaMod);
ssaAddPanel2.add(ssaModNum);
addSSA = new JButton("Add Data Point");
addSSA.setEnabled(false);
addSSA.addActionListener(this);
editSSA = new JButton("Edit Data Point");
editSSA.setEnabled(false);
editSSA.addActionListener(this);
removeSSA = new JButton("Remove Data Point");
removeSSA.setEnabled(false);
removeSSA.addActionListener(this);
ssaAddPanel3.add(addSSA);
ssaAddPanel3.add(editSSA);
ssaAddPanel3.add(removeSSA);
ssaAddPanel3.add(newSSA);
ssaAddPanel.add(ssaAddPanel1, "North");
ssaAddPanel.add(ssaAddPanel2, "Center");
ssaAddPanel.add(ssaAddPanel3, "South");
ssaPanel.add(usingSSA, "North");
ssaPanel.add(scroll5, "Center");
ssaPanel.add(ssaAddPanel, "South");
if (new File(root + separator + simName + separator + "user-defined.dat").exists()) {
String getData = "";
try {
Scanner scan = new Scanner(new File(root + separator + simName + separator
+ "user-defined.dat"));
while (scan.hasNextLine()) {
String get = scan.nextLine();
if (get.split(" ").length == 3) {
if (scan.hasNextLine()) {
getData += get + "\n";
}
else {
getData += get;
}
}
else {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Unable to load user defined file!", "Error Loading File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Unable to load user defined file!", "Error Loading File",
JOptionPane.ERROR_MESSAGE);
}
if (!getData.equals("")) {
ssaList = getData.split("\n");
ArrayList<String> sortName = new ArrayList<String>();
for (int i = 0; i < ssaList.length; i++) {
sortName.add(((String) ssaList[i]).split(" ")[1]);
}
int in, out;
for (out = 1; out < sortName.size(); out++) {
String temp = sortName.get(out);
String temp2 = (String) ssaList[out];
in = out;
while (in > 0 && sortName.get(in - 1).compareToIgnoreCase(temp) > 0) {
sortName.set(in, sortName.get(in - 1));
ssaList[in] = ssaList[in - 1];
--in;
}
sortName.set(in, temp);
ssaList[in] = temp2;
}
ArrayList<Double> sort = new ArrayList<Double>();
for (int i = 0; i < ssaList.length; i++) {
sort.add(Double.parseDouble(((String) ssaList[i]).split(" ")[0]));
}
for (out = 1; out < sort.size(); out++) {
double temp = sort.get(out);
String temp2 = (String) ssaList[out];
in = out;
while (in > 0 && sort.get(in - 1) > temp) {
sort.set(in, sort.get(in - 1));
ssaList[in] = ssaList[in - 1];
--in;
}
sort.set(in, temp);
ssaList[in] = temp2;
}
}
else {
ssaList = new Object[0];
}
ssa.setListData(ssaList);
ssa.setEnabled(true);
timeLabel.setEnabled(true);
time.setEnabled(true);
availSpecies.setEnabled(true);
ssaMod.setEnabled(true);
ssaModNum.setEnabled(true);
addSSA.setEnabled(true);
editSSA.setEnabled(true);
removeSSA.setEnabled(true);
}
// Creates tab for adding properties
propertiesPanel = new JPanel(new BorderLayout());
JPanel propertiesPanel1 = new JPanel(new BorderLayout());
JPanel propertiesPanel2 = new JPanel(new BorderLayout());
JPanel propertiesInput = new JPanel();
JPanel propertiesButtons = new JPanel();
// JLabel propertiesLabel = new JLabel("Properties To Add:");
JLabel propLabel = new JLabel("Option:");
JLabel valueLabel = new JLabel("Value:");
properties = new JList();
properties.addMouseListener(this);
JScrollPane scroll6 = new JScrollPane();
scroll6.setMinimumSize(new Dimension(260, 200));
scroll6.setPreferredSize(new Dimension(276, 132));
scroll6.setViewportView(properties);
props = new Object[0];
prop = new JTextField(20);
value = new JTextField(20);
addProp = new JButton("Add Option");
addProp.addActionListener(this);
editProp = new JButton("Edit Option");
editProp.addActionListener(this);
removeProp = new JButton("Remove Option");
removeProp.addActionListener(this);
newProp = new JButton("Clear Options");
newProp.addActionListener(this);
propertiesInput.add(propLabel);
propertiesInput.add(prop);
propertiesInput.add(valueLabel);
propertiesInput.add(value);
propertiesButtons.add(addProp);
propertiesButtons.add(editProp);
propertiesButtons.add(removeProp);
propertiesButtons.add(newProp);
propertiesPanel2.add(propertiesInput, "Center");
propertiesPanel2.add(propertiesButtons, "South");
// propertiesPanel1.add(propertiesLabel, "North");
propertiesPanel1.add(scroll6, "Center");
propertiesPanel.add(propertiesPanel1, "Center");
propertiesPanel.add(propertiesPanel2, "South");
// Creates the tabs and adds them to the main panel
// JTabbedPane tab = new JTabbedPane();
// tab.addTab("Simulation Options", mainTabbedPanel);
// tab.addTab("Interesting Species", speciesHolder);
// tab.addTab("User Defined Data", ssaPanel);
// tab.addTab("Abstraction Options", advanced);
// tab.addTab("Termination Conditions", mainTermCond);
// tab.addTab("Termination Conditions", sadTermCondPanel);
// tab.addTab("Advanced Options", propertiesPanel);
this.setLayout(new BorderLayout());
this.add(mainTabbedPanel, "Center");
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// runHolder, null);
// splitPane.setDividerSize(0);
// this.add(splitPane, "South");
// intSpecies.setListData(allSpecies);
termCond.setListData(allSpecies);
int rem = availSpecies.getItemCount();
for (int i = 0; i < rem; i++) {
availSpecies.removeItemAt(0);
}
for (int i = 0; i < allSpecies.length; i++) {
availSpecies.addItem(((String) allSpecies[i]).replace(" ", "_"));
}
runFiles = false;
String[] searchForRunFiles = new File(root + separator + simName).list();
for (String s : searchForRunFiles) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
runFiles = true;
}
}
if (biosimrc.get("biosim.sim.abs", "").equals("None")) {
none.doClick();
}
else if (biosimrc.get("biosim.sim.abs", "").equals("Abstraction")) {
abstraction.doClick();
}
else {
nary.doClick();
}
if (biosimrc.get("biosim.sim.type", "").equals("ODE")) {
ODE.doClick();
simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
}
else if (biosimrc.get("biosim.sim.type", "").equals("Monte Carlo")) {
monteCarlo.doClick();
simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
}
else if (biosimrc.get("biosim.sim.type", "").equals("Markov")) {
markov.doClick();
simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
}
else if (biosimrc.get("biosim.sim.type", "").equals("SBML")) {
sbml.doClick();
simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
sbml.doClick();
}
else if (biosimrc.get("biosim.sim.type", "").equals("LPN")) {
if (lhpn.isEnabled()) {
lhpn.doClick();
simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
lhpn.doClick();
}
}
else if (biosimrc.get("biosim.sim.type", "").equals("Network")) {
dot.doClick();
simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
dot.doClick();
}
else {
xhtml.doClick();
simulators.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
xhtml.doClick();
}
if (open != null) {
open(open);
}
}
/**
* This method performs different functions depending on what buttons are
* pushed and what input fields contain data.
*/
public void actionPerformed(ActionEvent e) {
// if the none Radio Button is selected
change = true;
if (e.getSource() == none) {
Button_Enabling.enableNoneOrAbs(ODE, monteCarlo, markov, seed, seedLabel, runs,
runsLabel, minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel,
explanation, description, none, spLabel, speciesLabel, addIntSpecies,
editIntSpecies, removeIntSpecies, rapid1, rapid2, qssa, maxCon, rapidLabel1,
rapidLabel2, qssaLabel, maxConLabel, usingSSA, clearIntSpecies, fileStem,
fileStemLabel, preAbs, loopAbs, postAbs, preAbsLabel, loopAbsLabel,
postAbsLabel, addPreAbs, rmPreAbs, editPreAbs, addLoopAbs, rmLoopAbs,
editLoopAbs, addPostAbs, rmPostAbs, editPostAbs, lhpn, speciesInt);
if (modelFile.contains(".lpn")) {
markov.setEnabled(true);
lhpn.setEnabled(true);
}
if (!sbml.isSelected() && !xhtml.isSelected() && !dot.isSelected() && runFiles) {
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
amounts.setEnabled(true);
concentrations.setEnabled(true);
report.setEnabled(true);
if (overwrite.isSelected()) {
limit.setEnabled(true);
interval.setEnabled(true);
limitLabel.setEnabled(true);
intervalLabel.setEnabled(true);
}
else {
limit.setEnabled(false);
interval.setEnabled(false);
limitLabel.setEnabled(false);
intervalLabel.setEnabled(false);
}
}
}
// if the abstraction Radio Button is selected
else if (e.getSource() == abstraction) {
Button_Enabling.enableNoneOrAbs(ODE, monteCarlo, markov, seed, seedLabel, runs,
runsLabel, minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators, simulatorsLabel,
explanation, description, none, spLabel, speciesLabel, addIntSpecies,
editIntSpecies, removeIntSpecies, rapid1, rapid2, qssa, maxCon, rapidLabel1,
rapidLabel2, qssaLabel, maxConLabel, usingSSA, clearIntSpecies, fileStem,
fileStemLabel, preAbs, loopAbs, postAbs, preAbsLabel, loopAbsLabel,
postAbsLabel, addPreAbs, rmPreAbs, editPreAbs, addLoopAbs, rmLoopAbs,
editLoopAbs, addPostAbs, rmPostAbs, editPostAbs, lhpn, speciesInt);
if (modelFile.contains(".lpn")) {
markov.setEnabled(true);
lhpn.setEnabled(true);
}
if (!sbml.isSelected() && !xhtml.isSelected() && !dot.isSelected() && runFiles) {
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
amounts.setEnabled(true);
concentrations.setEnabled(true);
report.setEnabled(true);
if (overwrite.isSelected()) {
limit.setEnabled(true);
interval.setEnabled(true);
limitLabel.setEnabled(true);
intervalLabel.setEnabled(true);
}
else {
limit.setEnabled(false);
interval.setEnabled(false);
limitLabel.setEnabled(false);
intervalLabel.setEnabled(false);
}
}
}
// if the nary Radio Button is selected
else if (e.getSource() == nary) {
Button_Enabling.enableNary(ODE, monteCarlo, markov, seed, seedLabel, runs, runsLabel,
minStepLabel, minStep, stepLabel, step, errorLabel, absErr, limitLabel, limit,
intervalLabel, interval, simulators, simulatorsLabel, explanation, description,
spLabel, speciesLabel, addIntSpecies, editIntSpecies, removeIntSpecies, rapid1,
rapid2, qssa, maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel,
usingSSA, clearIntSpecies, fileStem, fileStemLabel, preAbs, loopAbs, postAbs,
preAbsLabel, loopAbsLabel, postAbsLabel, addPreAbs, rmPreAbs, editPreAbs,
addLoopAbs, rmLoopAbs, editLoopAbs, addPostAbs, rmPostAbs, editPostAbs, lhpn,
gcmEditor, speciesInt);
if (!sbml.isSelected() && !xhtml.isSelected() && !dot.isSelected() && runFiles) {
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
amounts.setEnabled(true);
concentrations.setEnabled(true);
report.setEnabled(true);
if (overwrite.isSelected()) {
limit.setEnabled(true);
interval.setEnabled(true);
limitLabel.setEnabled(true);
intervalLabel.setEnabled(true);
}
else {
limit.setEnabled(false);
interval.setEnabled(false);
limitLabel.setEnabled(false);
intervalLabel.setEnabled(false);
}
}
}
// if the ODE Radio Button is selected
else if (e.getSource() == ODE) {
Button_Enabling.enableODE(seed, seedLabel, runs, runsLabel, minStepLabel, minStep,
stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel,
interval, simulators, simulatorsLabel, explanation, description, usingSSA,
fileStem, fileStemLabel, postAbs);
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
amounts.setEnabled(true);
concentrations.setEnabled(true);
report.setEnabled(true);
}
// if the monteCarlo Radio Button is selected
else if (e.getSource() == monteCarlo) {
Button_Enabling.enableMonteCarlo(seed, seedLabel, runs, runsLabel, minStepLabel,
minStep, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel,
interval, simulators, simulatorsLabel, explanation, description, usingSSA,
fileStem, fileStemLabel, postAbs);
if (runFiles) {
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
amounts.setEnabled(true);
concentrations.setEnabled(true);
report.setEnabled(true);
if (overwrite.isSelected()) {
limit.setEnabled(true);
interval.setEnabled(true);
limitLabel.setEnabled(true);
intervalLabel.setEnabled(true);
}
else {
limit.setEnabled(false);
interval.setEnabled(false);
limitLabel.setEnabled(false);
intervalLabel.setEnabled(false);
}
}
}
// if the markov Radio Button is selected
else if (e.getSource() == markov) {
Button_Enabling.enableMarkov(seed, seedLabel, runs, runsLabel, minStepLabel, minStep,
stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel,
interval, simulators, simulatorsLabel, explanation, description, usingSSA,
fileStem, fileStemLabel, gcmEditor, postAbs, modelFile);
overwrite.setEnabled(false);
append.setEnabled(false);
choose3.setEnabled(false);
amounts.setEnabled(false);
concentrations.setEnabled(false);
report.setEnabled(false);
}
// if the sbml Radio Button is selected
else if (e.getSource() == sbml) {
Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, minStepLabel,
minStep, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel,
interval, simulators, simulatorsLabel, explanation, description, fileStem,
fileStemLabel, postAbs);
overwrite.setEnabled(false);
append.setEnabled(false);
choose3.setEnabled(false);
amounts.setEnabled(false);
concentrations.setEnabled(false);
report.setEnabled(false);
absErr.setEnabled(false);
}
// if the dot Radio Button is selected
else if (e.getSource() == dot) {
Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, minStepLabel,
minStep, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel,
interval, simulators, simulatorsLabel, explanation, description, fileStem,
fileStemLabel, postAbs);
overwrite.setEnabled(false);
append.setEnabled(false);
choose3.setEnabled(false);
amounts.setEnabled(false);
concentrations.setEnabled(false);
report.setEnabled(false);
absErr.setEnabled(false);
}
// if the xhtml Radio Button is selected
else if (e.getSource() == xhtml) {
Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, minStepLabel,
minStep, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel,
interval, simulators, simulatorsLabel, explanation, description, fileStem,
fileStemLabel, postAbs);
overwrite.setEnabled(false);
append.setEnabled(false);
choose3.setEnabled(false);
amounts.setEnabled(false);
concentrations.setEnabled(false);
report.setEnabled(false);
absErr.setEnabled(false);
}
// if the lhpn Radio Button is selected
else if (e.getSource() == lhpn) {
Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel, minStepLabel,
minStep, stepLabel, step, errorLabel, absErr, limitLabel, limit, intervalLabel,
interval, simulators, simulatorsLabel, explanation, description, fileStem,
fileStemLabel, postAbs);
overwrite.setEnabled(false);
append.setEnabled(false);
choose3.setEnabled(false);
amounts.setEnabled(false);
concentrations.setEnabled(false);
report.setEnabled(false);
absErr.setEnabled(false);
}
// if the add interesting species button is clicked
// else if (e.getSource() == addIntSpecies) {
// addInterstingSpecies();
// if the add interesting species button is clicked
// else if (e.getSource() == editIntSpecies) {
// editInterstingSpecies();
// if the remove interesting species button is clicked
// else if (e.getSource() == removeIntSpecies) {
// removeIntSpecies();
// if the clear interesting species button is clicked
// else if (e.getSource() == clearIntSpecies) {
// int[] select = new int[interestingSpecies.length];
// for (int i = 0; i < interestingSpecies.length; i++) {
// select[i] = i;
// //species.setSelectedIndices(select);
// removeIntSpecies();
// if the add termination conditions button is clicked
else if (e.getSource() == addTermCond) {
termConditions = Buttons.add(termConditions, terminations, termCond, true, amountTerm,
ge, gt, eq, lt, le, this);
}
// if the remove termination conditions button is clicked
else if (e.getSource() == removeTermCond) {
termConditions = Buttons.remove(terminations, termConditions);
}
// if the clear termination conditions button is clicked
else if (e.getSource() == clearTermCond) {
termConditions = new Object[0];
terminations.setListData(termConditions);
}
// if the simulators combo box is selected
else if (e.getSource() == simulators) {
if (simulators.getItemCount() == 0) {
description.setText("");
}
else if (simulators.getSelectedItem().equals("euler")) {
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
absErr.setEnabled(false);
errorLabel.setEnabled(false);
description.setText("Euler method");
}
else if (simulators.getSelectedItem().equals("gear1")) {
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
absErr.setEnabled(true);
errorLabel.setEnabled(true);
description.setText("Gear method, M=1");
}
else if (simulators.getSelectedItem().equals("gear2")) {
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
absErr.setEnabled(true);
errorLabel.setEnabled(true);
description.setText("Gear method, M=2");
}
else if (simulators.getSelectedItem().equals("rk4imp")) {
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
absErr.setEnabled(true);
errorLabel.setEnabled(true);
description.setText("Implicit 4th order Runge-Kutta at Gaussian points");
}
else if (simulators.getSelectedItem().equals("rk8pd")) {
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
absErr.setEnabled(true);
errorLabel.setEnabled(true);
description.setText("Embedded Runge-Kutta Prince-Dormand (8,9) method");
}
else if (simulators.getSelectedItem().equals("rkf45")) {
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
absErr.setEnabled(true);
errorLabel.setEnabled(true);
description.setText("Embedded Runge-Kutta-Fehlberg (4, 5) method");
}
else if (simulators.getSelectedItem().equals("gillespie")) {
description.setText("Gillespie's direct method");
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("mpde")) {
description.setText("iSSA (Marginal Probability Density Evolution)");
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("mp")) {
description.setText("iSSA (Mean Path)");
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("mp-adaptive")) {
description.setText("iSSA (Mean Path Adaptive)");
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("mp-event")) {
description.setText("iSSA (Mean Path Event)");
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("emc-sim")) {
description.setText("Monte Carlo sim with jump count as" + " independent variable");
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("bunker")) {
description.setText("Bunker's method");
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("nmc")) {
description.setText("Monte Carlo simulation with normally"
+ " distributed waiting time");
minStep.setEnabled(true);
minStepLabel.setEnabled(true);
step.setEnabled(true);
stepLabel.setEnabled(true);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("ctmc-transient")) {
description.setText("Transient Distribution Analysis");
minStep.setEnabled(false);
minStepLabel.setEnabled(false);
step.setEnabled(false);
stepLabel.setEnabled(false);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("atacs")) {
description.setText("ATACS Analysis Tool");
minStep.setEnabled(false);
minStepLabel.setEnabled(false);
step.setEnabled(false);
stepLabel.setEnabled(false);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
else if (simulators.getSelectedItem().equals("markov-chain-analysis")) {
description.setText("Markov Chain Analysis");
minStep.setEnabled(false);
minStepLabel.setEnabled(false);
step.setEnabled(false);
stepLabel.setEnabled(false);
errorLabel.setEnabled(false);
absErr.setEnabled(false);
}
}
// if the Run button is clicked
else if (e.getSource() == run) {
String stem = "";
if (!fileStem.getText().trim().equals("")) {
if (!(stemPat.matcher(fileStem.getText().trim()).matches())) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"A file stem can only contain letters, numbers, and underscores.",
"Invalid File Stem", JOptionPane.ERROR_MESSAGE);
return;
}
stem += fileStem.getText().trim();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (sbmlEditor != null) {
if (biomodelsim.getTab().getTitleAt(i).equals(sbmlEditor.getRefFile())) {
if (biomodelsim.getTab().getComponentAt(i) instanceof SBML_Editor) {
SBML_Editor sbml = ((SBML_Editor) (biomodelsim.getTab()
.getComponentAt(i)));
if (sbml.isDirty()) {
Object[] options = { "Yes", "No" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(),
"Do you want to save changes to " + sbmlEditor.getRefFile()
+ " before running the simulation?",
"Save Changes", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
sbml.save(true, stem, true);
}
}
}
else if (biomodelsim.getTab().getComponentAt(i) instanceof GCM2SBMLEditor) {
GCM2SBMLEditor gcm = ((GCM2SBMLEditor) (biomodelsim.getTab()
.getComponentAt(i)));
if (gcm.isDirty()) {
Object[] options = { "Yes", "No" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(),
"Do you want to save changes to " + sbmlEditor.getRefFile()
+ " before running the simulation?",
"Save Changes", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
gcm.save("gcm");
}
}
}
}
}
else if (gcmEditor != null) {
if (biomodelsim.getTab().getTitleAt(i).equals(gcmEditor.getRefFile())) {
if (biomodelsim.getTab().getComponentAt(i) instanceof GCM2SBMLEditor) {
GCM2SBMLEditor gcm = ((GCM2SBMLEditor) (biomodelsim.getTab()
.getComponentAt(i)));
if (gcm.isDirty()) {
Object[] options = { "Yes", "No" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(),
"Do you want to save changes to " + gcmEditor.getRefFile()
+ " before running the simulation?",
"Save Changes", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
gcm.save("gcm");
}
}
}
}
}
else {
if (biomodelsim.getTab().getTitleAt(i).equals(modelFile)) {
if (biomodelsim.getTab().getComponentAt(i) instanceof LHPNEditor) {
LHPNEditor lpn = ((LHPNEditor) (biomodelsim.getTab().getComponentAt(i)));
if (lpn.isDirty()) {
Object[] options = { "Yes", "No" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(),
"Do you want to save changes to " + modelFile
+ " before running the simulation?",
"Save Changes", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
lpn.save();
}
}
}
}
}
}
if (sbmlEditor != null) {
sbmlEditor.save(true, stem, true);
}
else if (gcmEditor != null) {
gcmEditor.saveParams(true, stem);
}
else {
if (!stem.equals("")) {
}
Translator t1 = new Translator();
if (abstraction.isSelected()) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(root + separator + modelFile);
Abstraction abst = new Abstraction(lhpnFile, lhpnAbstraction);
abst.abstractSTG(false);
abst.save(root + separator + simName + separator + modelFile);
t1.BuildTemplate(root + separator + simName + separator + modelFile,
((String) lpnProperties.getSelectedItem()));
}
else {
t1.BuildTemplate(root + separator + modelFile, ((String) lpnProperties
.getSelectedItem()));
}
t1.setFilename(root + separator + simName + separator + stem + separator
+ modelFile.replace(".lpn", ".sbml"));
t1.outputSBML();
if (!stem.equals("")) {
new File(root + separator + simName + separator + stem).mkdir();
new Reb2SacThread(this).start(stem);
}
else {
new Reb2SacThread(this).start(".");
}
emptyFrames();
}
}
else if (e.getSource() == save) {
if (sbmlEditor != null) {
sbmlEditor.save(false, "", true);
}
else if (gcmEditor != null) {
gcmEditor.saveParams(false, "");
}
save();
}
// if the using ssa check box is clicked
else if (e.getSource() == usingSSA) {
if (usingSSA.isSelected()) {
newSSA.setEnabled(true);
usingSSA.setSelected(true);
description.setEnabled(false);
explanation.setEnabled(false);
simulators.setEnabled(false);
simulatorsLabel.setEnabled(false);
ODE.setEnabled(false);
if (ODE.isSelected()) {
ODE.setSelected(false);
monteCarlo.setSelected(true);
Button_Enabling.enableMonteCarlo(seed, seedLabel, runs, runsLabel,
minStepLabel, minStep, stepLabel, step, errorLabel, absErr, limitLabel,
limit, intervalLabel, interval, simulators, simulatorsLabel,
explanation, description, usingSSA, fileStem, fileStemLabel, postAbs);
if (runFiles) {
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
amounts.setEnabled(true);
concentrations.setEnabled(true);
report.setEnabled(true);
if (overwrite.isSelected()) {
limit.setEnabled(true);
interval.setEnabled(true);
limitLabel.setEnabled(true);
intervalLabel.setEnabled(true);
}
else {
limit.setEnabled(false);
interval.setEnabled(false);
limitLabel.setEnabled(false);
intervalLabel.setEnabled(false);
}
}
}
markov.setEnabled(false);
if (markov.isSelected()) {
markov.setSelected(false);
monteCarlo.setSelected(true);
Button_Enabling.enableMonteCarlo(seed, seedLabel, runs, runsLabel,
minStepLabel, minStep, stepLabel, step, errorLabel, absErr, limitLabel,
limit, intervalLabel, interval, simulators, simulatorsLabel,
explanation, description, usingSSA, fileStem, fileStemLabel, postAbs);
if (runFiles) {
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
amounts.setEnabled(true);
concentrations.setEnabled(true);
report.setEnabled(true);
if (overwrite.isSelected()) {
limit.setEnabled(true);
interval.setEnabled(true);
limitLabel.setEnabled(true);
intervalLabel.setEnabled(true);
}
else {
limit.setEnabled(false);
interval.setEnabled(false);
limitLabel.setEnabled(false);
intervalLabel.setEnabled(false);
}
}
}
ssa.setEnabled(true);
timeLabel.setEnabled(true);
time.setEnabled(true);
availSpecies.setEnabled(true);
ssaMod.setEnabled(true);
ssaModNum.setEnabled(true);
addSSA.setEnabled(true);
editSSA.setEnabled(true);
removeSSA.setEnabled(true);
// for (int i = 0; i < ssaList.length; i++)
// addToIntSpecies(((String) ssaList[i]).split(" ")[1]);
}
else {
description.setEnabled(true);
explanation.setEnabled(true);
simulators.setEnabled(true);
simulatorsLabel.setEnabled(true);
newSSA.setEnabled(false);
usingSSA.setSelected(false);
ssa.setEnabled(false);
timeLabel.setEnabled(false);
time.setEnabled(false);
availSpecies.setEnabled(false);
ssaMod.setEnabled(false);
ssaModNum.setEnabled(false);
addSSA.setEnabled(false);
editSSA.setEnabled(false);
removeSSA.setEnabled(false);
if (!nary.isSelected()) {
ODE.setEnabled(true);
}
else {
markov.setEnabled(true);
}
}
}
// if the using sad check box is clicked
else if (e.getSource() == usingSAD) {
if (usingSAD.isSelected()) {
sad.setEnabled(true);
newSAD.setEnabled(true);
usingSAD.setSelected(true);
idLabel.setEnabled(true);
TCid.setEnabled(true);
descLabel.setEnabled(true);
desc.setEnabled(true);
condLabel.setEnabled(true);
cond.setEnabled(true);
addSAD.setEnabled(true);
editSAD.setEnabled(true);
removeSAD.setEnabled(true);
for (int i = 0; i < sadList.length; i++) {
String[] get = ((String) sadList[i]).split(";");
String cond = get[2];
cond = cond.replace('>', ' ');
cond = cond.replace('<', ' ');
cond = cond.replace('=', ' ');
cond = cond.replace('&', ' ');
cond = cond.replace('|', ' ');
cond = cond.replace('+', ' ');
cond = cond.replace('-', ' ');
cond = cond.replace('*', ' ');
cond = cond.replace('/', ' ');
cond = cond.replace('
cond = cond.replace('%', ' ');
cond = cond.replace('@', ' ');
cond = cond.replace('(', ' ');
cond = cond.replace(')', ' ');
cond = cond.replace('!', ' ');
get = cond.split(" ");
// for (int j = 0; j < get.length; j++)
// if (get[j].length() > 0)
// if ((get[j].charAt(0) != '0') && (get[j].charAt(0) !=
// && (get[j].charAt(0) != '2') && (get[j].charAt(0) != '3')
// && (get[j].charAt(0) != '4') && (get[j].charAt(0) != '5')
// && (get[j].charAt(0) != '6') && (get[j].charAt(0) != '7')
// && (get[j].charAt(0) != '8') && (get[j].charAt(0) !=
// addToIntSpecies(get[j]);
}
}
else {
sad.setEnabled(false);
newSAD.setEnabled(false);
usingSAD.setSelected(false);
idLabel.setEnabled(false);
TCid.setEnabled(false);
descLabel.setEnabled(false);
desc.setEnabled(false);
condLabel.setEnabled(false);
cond.setEnabled(false);
addSAD.setEnabled(false);
editSAD.setEnabled(false);
removeSAD.setEnabled(false);
}
}
// if the add ssa button is clicked
else if (e.getSource() == addSSA) {
double time = 0;
int mod = 0;
try {
time = Double.parseDouble(this.time.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "You must enter a real "
+ "number into the time text field!", "Time Must Be A Real Number",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
mod = Integer.parseInt(ssaModNum.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "You must enter an integer "
+ "into the amount change text field!", "Amount Change Must Be An Integer",
JOptionPane.ERROR_MESSAGE);
return;
}
String modify;
if (ssaMod.getSelectedItem().equals("goes to")) {
modify = "=";
}
else if (ssaMod.getSelectedItem().equals("is added by")) {
modify = "+";
}
else if (ssaMod.getSelectedItem().equals("is subtracted by")) {
modify = "-";
}
else if (ssaMod.getSelectedItem().equals("is multiplied by")) {
modify = "*";
}
else {
modify = "/";
}
if (availSpecies.getSelectedItem() == null) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"You must select a model for simulation "
+ "in order to add a user defined condition.",
"Select A Model For Simulation", JOptionPane.ERROR_MESSAGE);
return;
}
// addToIntSpecies((String) availSpecies.getSelectedItem());
String add = time + " " + availSpecies.getSelectedItem() + " " + modify + mod;
boolean done = false;
for (int i = 0; i < ssaList.length; i++) {
String[] get = ((String) ssaList[i]).split(" ");
if (get[0].equals(time + "") && get[1].equals(availSpecies.getSelectedItem() + "")) {
ssaList[i] = add;
done = true;
}
}
if (!done) {
JList addSSA = new JList();
Object[] adding = { add };
addSSA.setListData(adding);
addSSA.setSelectedIndex(0);
ssaList = Buttons.add(ssaList, ssa, addSSA, false, null, null, null, null, null,
null, this);
int[] index = ssa.getSelectedIndices();
ssaList = Buttons.getList(ssaList, ssa);
ssa.setSelectedIndices(index);
ArrayList<String> sortName = new ArrayList<String>();
for (int i = 0; i < ssaList.length; i++) {
sortName.add(((String) ssaList[i]).split(" ")[1]);
}
int in, out;
for (out = 1; out < sortName.size(); out++) {
String temp = sortName.get(out);
String temp2 = (String) ssaList[out];
in = out;
while (in > 0 && sortName.get(in - 1).compareToIgnoreCase(temp) > 0) {
sortName.set(in, sortName.get(in - 1));
ssaList[in] = ssaList[in - 1];
--in;
}
sortName.set(in, temp);
ssaList[in] = temp2;
}
ArrayList<Double> sort = new ArrayList<Double>();
for (int i = 0; i < ssaList.length; i++) {
sort.add(Double.parseDouble(((String) ssaList[i]).split(" ")[0]));
}
for (out = 1; out < sort.size(); out++) {
double temp = sort.get(out);
String temp2 = (String) ssaList[out];
in = out;
while (in > 0 && sort.get(in - 1) > temp) {
sort.set(in, sort.get(in - 1));
ssaList[in] = ssaList[in - 1];
--in;
}
sort.set(in, temp);
ssaList[in] = temp2;
}
}
ssa.setListData(ssaList);
}
// if the add sad button is clicked
else if (e.getSource() == addSAD) {
SBMLDocument document = BioSim.readSBML(sbmlFile);
Model model = document.getModel();
ArrayList<String> listOfSpecs = new ArrayList<String>();
ArrayList<String> listOfReacs = new ArrayList<String>();
if (model != null) {
ListOf listOfSpecies = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) listOfSpecies.get(i);
listOfSpecs.add(species.getId());
}
ListOf listOfReactions = model.getListOfReactions();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) listOfReactions.get(i);
listOfReacs.add(reaction.getId());
}
}
TermCond TCparser = new TermCond(false);
int result = TCparser.ParseTermCond(biomodelsim, (this), listOfSpecs, listOfReacs, cond
.getText().trim());
if (result == 0) {
String add = TCid.getText().trim() + "; " + desc.getText().trim() + "; "
+ cond.getText().trim();
JList addSAD = new JList();
Object[] adding = { add };
addSAD.setListData(adding);
addSAD.setSelectedIndex(0);
TCid.setText("");
desc.setText("");
cond.setText("");
sadList = Buttons.add(sadList, sad, addSAD, false, null, null, null, null, null,
null, this);
sad.setListData(sadList);
}
else if (result == 1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Syntax error in the termination condition!", "Syntax Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the edit ssa button is clicked
else if (e.getSource() == editSSA) {
if (ssa.getSelectedIndex() != -1) {
String[] get = ((String) ssaList[ssa.getSelectedIndex()]).split(" ");
JPanel ssaAddPanel = new JPanel(new BorderLayout());
JPanel ssaAddPanel1 = new JPanel();
JPanel ssaAddPanel2 = new JPanel();
JLabel timeLabel = new JLabel("At time step: ");
JTextField time = new JTextField(15);
time.setText(get[0]);
String filename = sbmlFile;
SBMLDocument document = BioSim.readSBML(filename);
Model model = document.getModel();
ArrayList<String> listOfSpecs = new ArrayList<String>();
if (model != null) {
ListOf listOfSpecies = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) listOfSpecies.get(i);
listOfSpecs.add(species.getId());
}
}
Object[] list = listOfSpecs.toArray();
for (int i = 1; i < list.length; i++) {
String index = (String) list[i];
int j = i;
while ((j > 0) && ((String) list[j - 1]).compareToIgnoreCase(index) > 0) {
list[j] = list[j - 1];
j = j - 1;
}
list[j] = index;
}
JComboBox availSpecies = new JComboBox();
for (int i = 0; i < list.length; i++) {
availSpecies.addItem(((String) list[i]).replace(" ", "_"));
}
availSpecies.setSelectedItem(get[1]);
String[] mod = new String[5];
mod[0] = "goes to";
mod[1] = "is added by";
mod[2] = "is subtracted by";
mod[3] = "is multiplied by";
mod[4] = "is divided by";
JComboBox ssaMod = new JComboBox(mod);
if (get[2].substring(0, 1).equals("=")) {
ssaMod.setSelectedItem("goes to");
}
else if (get[2].substring(0, 1).equals("+")) {
ssaMod.setSelectedItem("is added by");
}
else if (get[2].substring(0, 1).equals("-")) {
ssaMod.setSelectedItem("is subtracted by");
}
else if (get[2].substring(0, 1).equals("*")) {
ssaMod.setSelectedItem("is multiplied by");
}
else if (get[2].substring(0, 1).equals("/")) {
ssaMod.setSelectedItem("is divided by");
}
JTextField ssaModNum = new JTextField(15);
ssaModNum.setText(get[2].substring(1));
ssaAddPanel1.add(timeLabel);
ssaAddPanel1.add(time);
ssaAddPanel1.add(availSpecies);
ssaAddPanel2.add(ssaMod);
ssaAddPanel2.add(ssaModNum);
ssaAddPanel.add(ssaAddPanel1, "North");
ssaAddPanel.add(ssaAddPanel2, "Center");
String[] options = { "Save", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), ssaAddPanel,
"Edit User Defined Data", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double time1 = 0;
int mod1 = 0;
try {
time1 = Double.parseDouble(time.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"You must enter a real number " + "into the time text field!",
"Time Must Be A Real Number", JOptionPane.ERROR_MESSAGE);
return;
}
try {
mod1 = Integer.parseInt(ssaModNum.getText().trim());
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(biomodelsim.frame(),
"You must enter an integer "
+ "into the amount change text field!",
"Amount Change Must Be An Integer",
JOptionPane.ERROR_MESSAGE);
return;
}
String modify;
if (ssaMod.getSelectedItem().equals("goes to")) {
modify = "=";
}
else if (ssaMod.getSelectedItem().equals("is added by")) {
modify = "+";
}
else if (ssaMod.getSelectedItem().equals("is subtracted by")) {
modify = "-";
}
else if (ssaMod.getSelectedItem().equals("is multiplied by")) {
modify = "*";
}
else {
modify = "/";
}
if (availSpecies.getSelectedItem() == null) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"You must select a model for simulation "
+ "in order to add a user defined condition.",
"Select A Model For Simulation", JOptionPane.ERROR_MESSAGE);
return;
}
// addToIntSpecies((String) availSpecies.getSelectedItem());
ssaList[ssa.getSelectedIndex()] = time1 + " " + availSpecies.getSelectedItem()
+ " " + modify + mod1;
int[] index = ssa.getSelectedIndices();
ssa.setListData(ssaList);
ssaList = Buttons.getList(ssaList, ssa);
ssa.setSelectedIndices(index);
ArrayList<String> sortName = new ArrayList<String>();
for (int i = 0; i < ssaList.length; i++) {
sortName.add(((String) ssaList[i]).split(" ")[1]);
}
int in, out;
for (out = 1; out < sortName.size(); out++) {
String temp = sortName.get(out);
String temp2 = (String) ssaList[out];
in = out;
while (in > 0 && sortName.get(in - 1).compareToIgnoreCase(temp) > 0) {
sortName.set(in, sortName.get(in - 1));
ssaList[in] = ssaList[in - 1];
--in;
}
sortName.set(in, temp);
ssaList[in] = temp2;
}
ArrayList<Double> sort = new ArrayList<Double>();
for (int i = 0; i < ssaList.length; i++) {
sort.add(Double.parseDouble(((String) ssaList[i]).split(" ")[0]));
}
for (out = 1; out < sort.size(); out++) {
double temp = sort.get(out);
String temp2 = (String) ssaList[out];
in = out;
while (in > 0 && sort.get(in - 1) > temp) {
sort.set(in, sort.get(in - 1));
ssaList[in] = ssaList[in - 1];
--in;
}
sort.set(in, temp);
ssaList[in] = temp2;
}
ssa.setListData(ssaList);
ArrayList<Integer> count = new ArrayList<Integer>();
for (int i = 0; i < ssaList.length; i++) {
String[] remove = ((String) ssaList[i]).split(" ");
if (remove[0].equals(time1 + "")
&& remove[1].equals(availSpecies.getSelectedItem() + "")) {
count.add(i);
}
}
if (count.size() > 1) {
boolean done = false;
for (int i : count) {
String[] remove = ((String) ssaList[i]).split(" ");
if (!remove[2].equals(modify + mod1) && !done) {
ssa.setSelectedIndex(i);
ssaList = Buttons.remove(ssa, ssaList);
index = ssa.getSelectedIndices();
// ssaList = Buttons.getList(ssaList, ssa);
ssa.setSelectedIndices(index);
done = true;
}
}
if (!done) {
ssa.setSelectedIndex(count.get(0));
ssaList = Buttons.remove(ssa, ssaList);
index = ssa.getSelectedIndices();
// ssaList = Buttons.getList(ssaList, ssa);
ssa.setSelectedIndices(index);
}
}
}
}
}
// if the edit sad button is clicked
else if (e.getSource() == editSAD) {
if (sad.getSelectedIndex() != -1) {
String[] get = ((String) sadList[sad.getSelectedIndex()]).split(";");
JPanel sadAddPanel = new JPanel(new BorderLayout());
JPanel sadAddPanel0 = new JPanel();
JPanel sadAddPanel1 = new JPanel();
JPanel sadAddPanel2 = new JPanel();
JLabel idLabel = new JLabel("ID: ");
JTextField TCid = new JTextField(10);
TCid.setText(get[0].trim());
JLabel descLabel = new JLabel("Description: ");
JTextField desc = new JTextField(20);
desc.setText(get[1].trim());
JLabel condLabel = new JLabel("Condition: ");
JTextField cond = new JTextField(35);
cond.setText(get[2].trim());
sadAddPanel0.add(idLabel);
sadAddPanel0.add(TCid);
sadAddPanel1.add(descLabel);
sadAddPanel1.add(desc);
sadAddPanel2.add(condLabel);
sadAddPanel2.add(cond);
sadAddPanel.add(sadAddPanel0, "North");
sadAddPanel.add(sadAddPanel1, "Center");
sadAddPanel.add(sadAddPanel2, "South");
String[] options = { "Save", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), sadAddPanel,
"Edit Termination Condition", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
SBMLDocument document = BioSim.readSBML(sbmlFile);
Model model = document.getModel();
ArrayList<String> listOfSpecs = new ArrayList<String>();
ArrayList<String> listOfReacs = new ArrayList<String>();
if (model != null) {
ListOf listOfSpecies = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) listOfSpecies.get(i);
listOfSpecs.add(species.getId());
}
ListOf listOfReactions = model.getListOfReactions();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) listOfReactions.get(i);
listOfReacs.add(reaction.getId());
}
}
TermCond TCparser = new TermCond(false);
int result = TCparser.ParseTermCond(biomodelsim, (this), listOfSpecs,
listOfReacs, cond.getText().trim());
if (result == 0) {
sadList[sad.getSelectedIndex()] = TCid.getText().trim() + "; "
+ desc.getText().trim() + "; " + cond.getText().trim();
int[] index = sad.getSelectedIndices();
sad.setListData(sadList);
sadList = Buttons.getList(sadList, sad);
sad.setSelectedIndices(index);
sad.setListData(sadList);
}
else if (result == 1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Syntax error in the termination condition!", "Syntax Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
// if the edit option button is clicked
else if (e.getSource() == editProp) {
if (properties.getSelectedIndex() != -1) {
String[] get = ((String) props[properties.getSelectedIndex()]).split("=");
JPanel OptAddPanel = new JPanel(new BorderLayout());
JPanel OptAddPanel0 = new JPanel();
JPanel OptAddPanel1 = new JPanel();
JLabel OptionLabel = new JLabel("Option: ");
JTextField Option = new JTextField(20);
Option.setText(get[0].trim());
JLabel ValueLabel = new JLabel("Value: ");
JTextField Value = new JTextField(20);
Value.setText(get[1].trim());
OptAddPanel0.add(OptionLabel);
OptAddPanel0.add(Option);
OptAddPanel1.add(ValueLabel);
OptAddPanel1.add(Value);
OptAddPanel.add(OptAddPanel0, "North");
OptAddPanel.add(OptAddPanel1, "Center");
String[] options = { "Save", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), OptAddPanel,
"Edit Option", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
props[properties.getSelectedIndex()] = Option.getText().trim() + "="
+ Value.getText().trim();
int[] index = properties.getSelectedIndices();
properties.setListData(props);
props = Buttons.getList(props, properties);
properties.setSelectedIndices(index);
properties.setListData(props);
}
}
}
else if ((e.getSource() == addPreAbs) || (e.getSource() == addLoopAbs)
|| (e.getSource() == addPostAbs)) {
JPanel addAbsPanel = new JPanel(new BorderLayout());
JComboBox absList = new JComboBox();
absList.addItem("absolute-activation/inhibition-generator");
absList.addItem("absolute-inhibition-generator");
absList.addItem("birth-death-generator");
absList.addItem("birth-death-generator2");
absList.addItem("birth-death-generator3");
absList.addItem("birth-death-generator4");
absList.addItem("birth-death-generator5");
absList.addItem("birth-death-generator6");
absList.addItem("birth-death-generator7");
absList.addItem("degradation-stoichiometry-amplifier");
absList.addItem("degradation-stoichiometry-amplifier2");
absList.addItem("degradation-stoichiometry-amplifier3");
absList.addItem("degradation-stoichiometry-amplifier4");
absList.addItem("degradation-stoichiometry-amplifier5");
absList.addItem("degradation-stoichiometry-amplifier6");
absList.addItem("degradation-stoichiometry-amplifier7");
absList.addItem("degradation-stoichiometry-amplifier8");
absList.addItem("dimer-to-monomer-substitutor");
absList.addItem("dimerization-reduction");
absList.addItem("dimerization-reduction-level-assignment");
absList.addItem("distribute-transformer");
absList.addItem("enzyme-kinetic-qssa-1");
absList.addItem("enzyme-kinetic-rapid-equilibrium-1");
absList.addItem("enzyme-kinetic-rapid-equilibrium-2");
absList.addItem("final-state-generator");
absList.addItem("inducer-structure-transformer");
absList.addItem("irrelevant-species-remover");
absList.addItem("kinetic-law-constants-simplifier");
absList.addItem("max-concentration-reaction-adder");
absList.addItem("modifier-constant-propagation");
absList.addItem("modifier-structure-transformer");
absList.addItem("multiple-products-reaction-eliminator");
absList.addItem("multiple-reactants-reaction-eliminator");
absList.addItem("nary-order-unary-transformer");
absList.addItem("nary-order-unary-transformer2");
absList.addItem("nary-order-unary-transformer3");
absList.addItem("operator-site-forward-binding-remover");
absList.addItem("operator-site-forward-binding-remover2");
absList.addItem("pow-kinetic-law-transformer");
absList.addItem("ppta");
absList.addItem("reversible-reaction-structure-transformer");
absList.addItem("reversible-to-irreversible-transformer");
absList.addItem("similar-reaction-combiner");
absList.addItem("single-reactant-product-reaction-eliminator");
absList.addItem("stoichiometry-amplifier");
absList.addItem("stoichiometry-amplifier2");
absList.addItem("stoichiometry-amplifier3");
absList.addItem("stop-flag-generator");
addAbsPanel.add(absList, "Center");
String[] options = { "Add", "Cancel" };
int value = JOptionPane.showOptionDialog(biomodelsim.frame(), addAbsPanel,
"Add abstraction method", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (e.getSource() == addPreAbs) {
Buttons.add(preAbs, absList.getSelectedItem());
}
else if (e.getSource() == addLoopAbs) {
Buttons.add(loopAbs, absList.getSelectedItem());
}
else {
Buttons.add(postAbs, absList.getSelectedItem());
}
}
}
else if (e.getSource() == rmPreAbs) {
Buttons.remove(preAbs);
}
else if (e.getSource() == rmLoopAbs) {
Buttons.remove(loopAbs);
}
else if (e.getSource() == rmPostAbs) {
Buttons.remove(postAbs);
}
// if the remove ssa button is clicked
else if (e.getSource() == removeSSA) {
ssaList = Buttons.remove(ssa, ssaList);
}
// if the remove sad button is clicked
else if (e.getSource() == removeSAD) {
sadList = Buttons.remove(sad, sadList);
}
// if the new ssa button is clicked
else if (e.getSource() == newSSA) {
ssaList = new Object[0];
ssa.setListData(ssaList);
ssa.setEnabled(true);
timeLabel.setEnabled(true);
time.setEnabled(true);
availSpecies.setEnabled(true);
ssaMod.setEnabled(true);
ssaModNum.setEnabled(true);
addSSA.setEnabled(true);
editSSA.setEnabled(true);
removeSSA.setEnabled(true);
}
// if the new sad button is clicked
else if (e.getSource() == newSAD) {
sadList = new Object[0];
sad.setListData(sadList);
TCid.setText("");
desc.setText("");
cond.setText("");
}
// if the new sad button is clicked
else if (e.getSource() == newProp) {
props = new Object[0];
properties.setListData(props);
prop.setText("");
value.setText("");
}
// if the remove properties button is clicked
else if (e.getSource() == removeProp) {
props = Buttons.remove(properties, props);
}
// if the add properties button is clicked
else if (e.getSource() == addProp) {
if (prop.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Enter a option into the option field!", "Must Enter an Option",
JOptionPane.ERROR_MESSAGE);
return;
}
if (value.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Enter a value into the value field!", "Must Enter a Value",
JOptionPane.ERROR_MESSAGE);
return;
}
String add = prop.getText().trim() + "=" + value.getText().trim();
JList addPropery = new JList();
Object[] adding = { add };
addPropery.setListData(adding);
addPropery.setSelectedIndex(0);
props = Buttons.add(props, properties, addPropery, false, null, null, null, null, null,
null, this);
}
else if (e.getSource() == overwrite) {
limit.setEnabled(true);
interval.setEnabled(true);
limitLabel.setEnabled(true);
intervalLabel.setEnabled(true);
}
else if (e.getSource() == append) {
limit.setEnabled(false);
interval.setEnabled(false);
limitLabel.setEnabled(false);
intervalLabel.setEnabled(false);
Random rnd = new Random();
seed.setText("" + rnd.nextInt());
int cut = 0;
String[] getFilename = sbmlProp.split(separator);
for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) {
if (getFilename[getFilename.length - 1].charAt(i) == '.') {
cut = i;
}
}
String propName = sbmlProp.substring(0, sbmlProp.length()
- getFilename[getFilename.length - 1].length())
+ getFilename[getFilename.length - 1].substring(0, cut) + ".properties";
try {
if (new File(propName).exists()) {
Properties getProps = new Properties();
FileInputStream load = new FileInputStream(new File(propName));
getProps.load(load);
load.close();
if (getProps.containsKey("monte.carlo.simulation.time.limit")) {
minStep.setText(getProps
.getProperty("monte.carlo.simulation.min.time.step"));
step.setText(getProps.getProperty("monte.carlo.simulation.time.step"));
limit.setText(getProps.getProperty("monte.carlo.simulation.time.limit"));
interval.setText(getProps
.getProperty("monte.carlo.simulation.print.interval"));
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Unable to restore time limit and print interval.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().contains("box")) {
int num = Integer.parseInt(e.getActionCommand().substring(3)) - 1;
if (!((JCheckBox) speciesInt.get(num).get(0)).isSelected()) {
for (int i = 2; i < speciesInt.get(num).size(); i++) {
speciesInt.get(num).get(i).setEnabled(false);
}
}
else {
for (int i = 2; i < speciesInt.get(num).size(); i++) {
speciesInt.get(num).get(i).setEnabled(true);
}
}
}
else if (e.getActionCommand().contains("text")) {
int num = Integer.parseInt(e.getActionCommand().substring(4)) - 1;
editNumThresholds(num);
speciesPanel.revalidate();
speciesPanel.repaint();
}
}
/**
* If the run button is pressed, this method starts a new thread for the
* simulation.
*/
public void run(String direct) {
double timeLimit = 100.0;
double printInterval = 1.0;
double minTimeStep = 0.0;
double timeStep = 1.0;
double absError = 1.0e-9;
String outDir = "";
long rndSeed = 314159;
int run = 1;
try {
timeLimit = Double.parseDouble(limit.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Time Limit Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
if (((String) intervalLabel.getSelectedItem()).contains("Print Interval")) {
printInterval = Double.parseDouble(interval.getText().trim());
if (printInterval < 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Positive Number Into The Print Interval Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (printInterval == 0
&& !((String) intervalLabel.getSelectedItem()).contains("Minimum")) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Positive Number Into The Print Interval Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}
else {
printInterval = Integer.parseInt(interval.getText().trim());
if (printInterval <= 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Positive Number Into The Number of Steps Field.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
catch (Exception e1) {
if (((String) intervalLabel.getSelectedItem()).contains("Print Interval")) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Print Interval Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter An Integer Into The Number Of Steps Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}
String sim = (String) simulators.getSelectedItem();
if (step.getText().trim().equals("inf") && !sim.equals("euler")) {
timeStep = Double.MAX_VALUE;
}
else if (step.getText().trim().equals("inf") && sim.equals("euler")) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Cannot Select An Infinite Time Step With Euler Simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else {
try {
// if (step.isEnabled()) {
timeStep = Double.parseDouble(step.getText().trim());
}
catch (Exception e1) {
// if (step.isEnabled()) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Time Step Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}
try {
minTimeStep = Double.parseDouble(minStep.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Minimum Time Step Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
// if (absErr.isEnabled()) {
absError = Double.parseDouble(absErr.getText().trim());
}
catch (Exception e1) {
// if (absErr.isEnabled()) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Absolute Error Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (direct.equals(".")) {
outDir = simName;
}
else {
outDir = simName + separator + direct;
}
try {
// if (seed.isEnabled()) {
rndSeed = Long.parseLong(seed.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter An Integer Into The Random Seed Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
Preferences biosimrc = Preferences.userRoot();
try {
// if (runs.isEnabled()) {
run = Integer.parseInt(runs.getText().trim());
if (run < 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Positive Integer Into The Runs Field."
+ "\nProceding With Default: "
+ biosimrc.get("biosim.sim.runs", ""), "Error",
JOptionPane.ERROR_MESSAGE);
run = Integer.parseInt(biosimrc.get("biosim.sim.runs", ""));
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Positive Integer Into The Runs Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (!runs.isEnabled()) {
for (String runs : new File(root + separator + outDir).list()) {
if (runs.length() >= 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = runs.charAt(runs.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (runs.contains("run-")) {
run = Math.max(run, Integer.parseInt(runs.substring(4, runs.length()
- end.length())));
}
}
}
}
}
String printer_id = "tsd.printer";
String printer_track_quantity = "amount";
if (concentrations.isSelected()) {
printer_track_quantity = "concentration";
}
int[] index = terminations.getSelectedIndices();
String[] termCond = Buttons.getList(termConditions, terminations);
terminations.setSelectedIndices(index);
// index = species.getSelectedIndices();
String[] intSpecies = getInterestingSpecies();
// if (none.isSelected()) {
// intSpecies = new String[allSpecies.length];
// for (int j = 0; j < allSpecies.length; j++) {
// intSpecies[j] = (String) allSpecies[j];
// else {
// intSpecies = Buttons.getList(interestingSpecies, species);
// species.setSelectedIndices(index);
String selectedButtons = "";
double rap1 = 0.1;
double rap2 = 0.1;
double qss = 0.1;
int con = 15;
try {
// if (rapid1.isEnabled()) {
rap1 = Double.parseDouble(rapid1.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The"
+ " Rapid Equilibrium Condition 1 Field.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try {
// if (rapid2.isEnabled()) {
rap2 = Double.parseDouble(rapid2.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The"
+ " Rapid Equilibrium Condition 2 Field.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try {
// if (qssa.isEnabled()) {
qss = Double.parseDouble(qssa.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The QSSA Condition Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
// if (maxCon.isEnabled()) {
con = Integer.parseInt(maxCon.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter An Integer Into The Max"
+ " Concentration Threshold Field.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (none.isSelected() && ODE.isSelected()) {
selectedButtons = "none_ODE";
}
else if (none.isSelected() && monteCarlo.isSelected()) {
selectedButtons = "none_monteCarlo";
}
else if (abstraction.isSelected() && ODE.isSelected()) {
selectedButtons = "abs_ODE";
}
else if (abstraction.isSelected() && monteCarlo.isSelected()) {
selectedButtons = "abs_monteCarlo";
}
else if (nary.isSelected() && monteCarlo.isSelected()) {
selectedButtons = "nary_monteCarlo";
}
else if (nary.isSelected() && markov.isSelected()) {
selectedButtons = "nary_markov";
}
else if (none.isSelected() && markov.isSelected()) {
selectedButtons = "none_markov";
}
else if (abstraction.isSelected() && markov.isSelected()) {
selectedButtons = "abs_markov";
}
else if (none.isSelected() && sbml.isSelected()) {
selectedButtons = "none_sbml";
}
else if (abstraction.isSelected() && sbml.isSelected()) {
selectedButtons = "abs_sbml";
}
else if (nary.isSelected() && sbml.isSelected()) {
selectedButtons = "nary_sbml";
}
else if (none.isSelected() && dot.isSelected()) {
selectedButtons = "none_dot";
}
else if (none.isSelected() && lhpn.isSelected()) {
selectedButtons = "none_lhpn";
}
else if (abstraction.isSelected() && dot.isSelected()) {
selectedButtons = "abs_dot";
}
else if (nary.isSelected() && dot.isSelected()) {
selectedButtons = "nary_dot";
}
else if (none.isSelected() && xhtml.isSelected()) {
selectedButtons = "none_xhtml";
}
else if (abstraction.isSelected() && xhtml.isSelected()) {
selectedButtons = "abs_xhtml";
}
else if (nary.isSelected() && xhtml.isSelected()) {
selectedButtons = "nary_xhtml";
}
else if (nary.isSelected() && lhpn.isSelected()) {
selectedButtons = "nary_lhpn";
}
else if (abstraction.isSelected() && lhpn.isSelected()) {
selectedButtons = "abs_lhpn";
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator + outDir
+ separator + "user-defined.dat"));
int[] indecies = ssa.getSelectedIndices();
ssaList = Buttons.getList(ssaList, ssa);
ssa.setSelectedIndices(indecies);
String save = "";
for (int i = 0; i < ssaList.length; i++) {
if (i == ssaList.length - 1) {
save += ssaList[i];
}
else {
save += ssaList[i] + "\n";
}
}
byte[] output = save.getBytes();
out.write(output);
out.close();
if (!usingSSA.isSelected() && save.trim().equals("")) {
new File(root + separator + outDir + separator + "user-defined.dat").delete();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to save user defined file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
return;
}
int cut = 0;
String simProp = sbmlProp;
boolean saveTopLevel = false;
if (!direct.equals(".")) {
simProp = simProp.substring(0, simProp.length()
- simProp.split(separator)[simProp.split(separator).length - 1].length())
+ direct
+ separator
+ simProp.substring(simProp.length()
- simProp.split(separator)[simProp.split(separator).length - 1]
.length());
saveTopLevel = true;
}
String[] getFilename = simProp.split(separator);
for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) {
if (getFilename[getFilename.length - 1].charAt(i) == '.') {
cut = i;
}
}
String propName = simProp.substring(0, simProp.length()
- getFilename[getFilename.length - 1].length())
+ getFilename[getFilename.length - 1].substring(0, cut) + ".properties";
String topLevelProps = null;
if (saveTopLevel) {
topLevelProps = sbmlProp.substring(0, sbmlProp.length()
- getFilename[getFilename.length - 1].length())
+ getFilename[getFilename.length - 1].substring(0, cut) + ".properties";
}
/*
* String monteLimit = ""; String monteInterval = ""; try { if (new
* File(propName).exists()) { Properties getProps = new Properties();
* FileInputStream load = new FileInputStream(new File(propName));
* getProps.load(load); load.close(); if
* (getProps.containsKey("monte.carlo.simulation.time.limit")) {
* monteLimit =
* getProps.getProperty("monte.carlo.simulation.time.limit");
* monteInterval =
* getProps.getProperty("monte.carlo.simulation.print.interval"); } } }
* catch (Exception e) {
* JOptionPane.showMessageDialog(biomodelsim.frame(),
* "Unable to add properties to property file.", "Error",
* JOptionPane.ERROR_MESSAGE); }
*/
log.addText("Creating properties file:\n" + propName + "\n");
final JButton cancel = new JButton("Cancel");
final JFrame running = new JFrame("Progress");
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
cancel.doClick();
running.dispose();
}
public void windowOpened(WindowEvent arg0) {
}
public void windowClosed(WindowEvent arg0) {
}
public void windowIconified(WindowEvent arg0) {
}
public void windowDeiconified(WindowEvent arg0) {
}
public void windowActivated(WindowEvent arg0) {
}
public void windowDeactivated(WindowEvent arg0) {
}
};
running.addWindowListener(w);
JPanel text = new JPanel();
JPanel progBar = new JPanel();
JPanel button = new JPanel();
JPanel all = new JPanel(new BorderLayout());
JLabel label;
if (!direct.equals(".")) {
label = new JLabel("Running " + simName + " " + direct);
}
else {
label = new JLabel("Running " + simName);
}
// int steps;
double runTime;
if (((String) intervalLabel.getSelectedItem()).contains("Print Interval")) {
if (simulators.getSelectedItem().equals("mpde")
|| simulators.getSelectedItem().equals("mp")
|| simulators.getSelectedItem().equals("mp-adaptive")
|| simulators.getSelectedItem().equals("mp-event")) {
// double test = printInterval / timeStep;
// double error = test - ((int) test);
// if (error > 0.0001) {
// JOptionPane.showMessageDialog(biomodelsim.frame(),
// "Print Interval Must Be A Multiple Of Time Step.", "Error",
// JOptionPane.ERROR_MESSAGE);
// return;
// test = timeLimit / printInterval;
// error = test - ((int) test);
// if (error > 0.0001) {
// JOptionPane.showMessageDialog(biomodelsim.frame(),
// "Time Limit Must Be A Multiple Of Print Interval.", "Error",
// JOptionPane.ERROR_MESSAGE);
// return;
// if (printInterval != 0.0) {
// steps = (int) (timeLimit / printInterval);
// else {
// steps = ((int) timeLimit);
runTime = timeLimit;
// progress = new JProgressBar(0, (int) timeLimit);
}
else {
// if (printInterval != 0.0) {
// steps = (int) ((timeLimit / printInterval) * run);
// else {
// steps = ((int) timeLimit * run);
runTime = timeLimit * run;
// progress = new JProgressBar(0, (int) (timeLimit * run));//
// steps);
}
}
else {
if (simulators.getSelectedItem().equals("mpde")
|| simulators.getSelectedItem().equals("mp")
|| simulators.getSelectedItem().equals("mp-adaptive")
|| simulators.getSelectedItem().equals("mp-event")) {
// steps = (int) (printInterval);
runTime = timeLimit;
// progress = new JProgressBar(0, (int) timeLimit);
// double interval = timeLimit / steps;
// double test = interval / timeStep;
// double error = test - ((int) test);
// if (error > 0.0001) {
// JOptionPane.showMessageDialog(biomodelsim.frame(),
// "Print Interval Must Be A Multiple Of Time Step.", "Error",
// JOptionPane.ERROR_MESSAGE);
// return;
}
else {
// steps = (int) (printInterval * run);
runTime = timeLimit * run;
// progress = new JProgressBar(0, (int) timeLimit * run);//
// steps);
}
}
JProgressBar progress = new JProgressBar(0, 100);
progress.setStringPainted(true);
// progress.setString("");
// progress.setIndeterminate(true);
progress.setValue(0);
text.add(label);
progBar.add(progress);
button.add(cancel);
all.add(text, "North");
all.add(progBar, "Center");
all.add(button, "South");
running.setContentPane(all);
running.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = running.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
running.setLocation(x, y);
running.setVisible(true);
running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Run runProgram = new Run(this);
cancel.addActionListener(runProgram);
biomodelsim.getExitButton().addActionListener(runProgram);
saveSAD(outDir);
runProgram.createProperties(timeLimit, ((String) (intervalLabel.getSelectedItem())),
printInterval, minTimeStep, timeStep, absError, ".",
// root + separator + outDir,
rndSeed, run, termCond, intSpecies, printer_id, printer_track_quantity, simProp
.split(separator), selectedButtons, this, simProp, rap1, rap2, qss, con,
usingSSA,
// root + separator + simName + separator +
"user-defined.dat", usingSAD, new File(root + separator + outDir + separator
+ "termCond.sad"), preAbs, loopAbs, postAbs, lhpnAbstraction);
int[] indecies = properties.getSelectedIndices();
props = Buttons.getList(props, properties);
properties.setSelectedIndices(indecies);
try {
Properties getProps = new Properties();
FileInputStream load = new FileInputStream(new File(propName));
getProps.load(load);
load.close();
// for (int i = 0; i < props.length; i++) {
// String[] split = ((String) props[i]).split("=");
// getProps.setProperty(split[0], split[1]);
getProps.setProperty("selected.simulator", sim);
if (!fileStem.getText().trim().equals("")) {
getProps.setProperty("file.stem", fileStem.getText().trim());
}
if (monteCarlo.isSelected() || ODE.isSelected()) {
if (append.isSelected()) {
String[] searchForRunFiles = new File(root + separator + outDir).list();
int start = 1;
for (String s : searchForRunFiles) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")
&& new File(root + separator + outDir + separator + s).isFile()) {
String getNumber = s.substring(4, s.length());
String number = "";
for (int i = 0; i < getNumber.length(); i++) {
if (Character.isDigit(getNumber.charAt(i))) {
number += getNumber.charAt(i);
}
else {
break;
}
}
start = Math.max(Integer.parseInt(number), start);
}
}
getProps.setProperty("monte.carlo.simulation.start.index", (start + 1) + "");
}
else {
String[] searchForRunFiles = new File(root + separator + outDir).list();
for (String s : searchForRunFiles) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")
&& new File(root + separator + outDir + separator + s).isFile()) {
new File(root + separator + outDir + separator + s).delete();
}
}
getProps.setProperty("monte.carlo.simulation.start.index", "1");
}
}
// if (getProps.containsKey("ode.simulation.time.limit")) {
// if (!monteLimit.equals("")) {
// getProps.setProperty("monte.carlo.simulation.time.limit",
// monteLimit);
// getProps.setProperty("monte.carlo.simulation.print.interval",
// monteInterval);
FileOutputStream store = new FileOutputStream(new File(propName));
getProps.store(store, getFilename[getFilename.length - 1].substring(0, cut)
+ " Properties");
store.close();
if (saveTopLevel) {
store = new FileOutputStream(new File(topLevelProps));
getProps.store(store, getFilename[getFilename.length - 1].substring(0, cut)
+ " Properties");
store.close();
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Unable to add properties to property file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
if (monteCarlo.isSelected() || ODE.isSelected()) {
File[] files = new File(root + separator + outDir).listFiles();
for (File f : files) {
if (f.getName().contains("mean.") || f.getName().contains("standard_deviation.")
|| f.getName().contains("variance.")) {
f.delete();
}
}
}
int exit;
if (!direct.equals(".")) {
if (gcmEditor != null) {
try {
FileInputStream source = new FileInputStream(new File(root + separator
+ modelFile));
FileOutputStream destination = new FileOutputStream(new File(root + separator
+ simName + separator + direct + separator + modelFile));
int read = source.read();
while (read != -1) {
destination.write(read);
read = source.read();
}
source.close();
destination.close();
}
catch (Exception e) {
}
}
String lpnProperty = "";
if (lpnProperties != null) {
lpnProperty = ((String) lpnProperties.getSelectedItem());
}
exit = runProgram.execute(simProp, sbml, dot, xhtml, lhpn, biomodelsim.frame(), ODE,
monteCarlo, sim, printer_id, printer_track_quantity,
root + separator + simName, nary, 1, intSpecies, log, usingSSA, root
+ separator + outDir + separator + "user-defined.dat", biomodelsim,
simTab, root, progress, simName + " " + direct, gcmEditor, direct, timeLimit,
runTime, modelFile, lhpnAbstraction, abstraction, lpnProperty);
}
else {
if (gcmEditor != null) {
try {
FileInputStream source = new FileInputStream(new File(root + separator
+ modelFile));
FileOutputStream destination = new FileOutputStream(new File(root + separator
+ simName + separator + modelFile));
int read = source.read();
while (read != -1) {
destination.write(read);
read = source.read();
}
source.close();
destination.close();
}
catch (Exception e) {
}
}
String lpnProperty = "";
if (lpnProperties != null) {
lpnProperty = ((String) lpnProperties.getSelectedItem());
}
exit = runProgram.execute(simProp, sbml, dot, xhtml, lhpn, biomodelsim.frame(), ODE,
monteCarlo, sim, printer_id, printer_track_quantity,
root + separator + simName, nary, 1, intSpecies, log, usingSSA, root
+ separator + outDir + separator + "user-defined.dat", biomodelsim,
simTab, root, progress, simName, gcmEditor, null, timeLimit, runTime,
modelFile, lhpnAbstraction, abstraction, lpnProperty);
}
if (nary.isSelected() && gcmEditor == null && !sim.equals("markov-chain-analysis")
&& !lhpn.isSelected() && exit == 0) {
String d = null;
if (!direct.equals(".")) {
d = direct;
}
new Nary_Run(this, amountTerm, ge, gt, eq, lt, le, simulators,
simProp.split(separator), simProp, sbml, dot, xhtml, lhpn, nary, ODE,
monteCarlo, timeLimit, ((String) (intervalLabel.getSelectedItem())),
printInterval, minTimeStep, timeStep, root + separator + simName, rndSeed, run,
printer_id, printer_track_quantity, termCond, intSpecies, rap1, rap2, qss, con,
log, usingSSA, root + separator + outDir + separator + "user-defined.dat",
biomodelsim, simTab, root, d, modelFile, abstraction, lhpnAbstraction);
}
running.setCursor(null);
running.dispose();
biomodelsim.getExitButton().removeActionListener(runProgram);
String[] searchForRunFiles = new File(root + separator + outDir).list();
for (String s : searchForRunFiles) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
runFiles = true;
}
}
if (monteCarlo.isSelected()) {
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
amounts.setEnabled(true);
concentrations.setEnabled(true);
report.setEnabled(true);
if (overwrite.isSelected()) {
limit.setEnabled(true);
interval.setEnabled(true);
limitLabel.setEnabled(true);
intervalLabel.setEnabled(true);
}
else {
limit.setEnabled(false);
interval.setEnabled(false);
limitLabel.setEnabled(false);
intervalLabel.setEnabled(false);
}
}
if (append.isSelected()) {
Random rnd = new Random();
seed.setText("" + rnd.nextInt());
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getComponentAt(i) instanceof Graph) {
((Graph) biomodelsim.getTab().getComponentAt(i)).refresh();
}
}
}
public void emptyFrames() {
for (JFrame f : frames) {
f.dispose();
}
}
/**
* Invoked when the mouse is double clicked in the interesting species
* JLists or termination conditions JLists. Adds or removes the selected
* interesting species or termination conditions.
*/
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
// if (e.getSource() == intSpecies) {
// addInterstingSpecies();
// else if (e.getSource() == species) {
// editInterstingSpecies();
if (e.getSource() == termCond) {
termConditions = Buttons.add(termConditions, terminations, termCond, true,
amountTerm, ge, gt, eq, lt, le, this);
}
else if (e.getSource() == terminations) {
termConditions = Buttons.remove(terminations, termConditions);
}
else if (e.getSource() == ssa) {
editSSA.doClick();
}
else if (e.getSource() == properties) {
props = Buttons.remove(properties, props);
}
}
}
/**
* This method currently does nothing.
*/
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseReleased(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
/**
* Saves the simulate options.
*/
public void save() {
double timeLimit = 100.0;
double printInterval = 1.0;
double minTimeStep = 0.0;
double timeStep = 1.0;
double absError = 1.0e-9;
String outDir = ".";
long rndSeed = 314159;
int run = 1;
try {
timeLimit = Double.parseDouble(limit.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Time Limit Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
if (((String) intervalLabel.getSelectedItem()).contains("Print Interval")) {
printInterval = Double.parseDouble(interval.getText().trim());
}
else {
printInterval = Integer.parseInt(interval.getText().trim());
}
}
catch (Exception e1) {
if (((String) intervalLabel.getSelectedItem()).contains("Print Interval")) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Print Interval Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter An Integer Into The Number Of Steps Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}
if (step.getText().trim().equals("inf")) {
timeStep = Double.MAX_VALUE;
}
else {
try {
timeStep = Double.parseDouble(step.getText().trim());
}
catch (Exception e1) {
if (step.isEnabled()) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Time Step Field.", "Error",
JOptionPane.ERROR_MESSAGE);
}
return;
}
}
try {
minTimeStep = Double.parseDouble(minStep.getText().trim());
}
catch (Exception e1) {
if (minStep.isEnabled()) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Time Step Field.", "Error",
JOptionPane.ERROR_MESSAGE);
}
return;
}
try {
// if (absErr.isEnabled()) {
absError = Double.parseDouble(absErr.getText().trim());
}
catch (Exception e1) {
// if (absErr.isEnabled()) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The Absolute Error Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
outDir = simName;
// outDir = root + separator + simName;
try {
// if (seed.isEnabled()) {
rndSeed = Long.parseLong(seed.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter An Integer Into The Random Seed Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
// if (runs.isEnabled()) {
run = Integer.parseInt(runs.getText().trim());
if (run < 0) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Positive Integer Into The Runs Field."
+ "\nProceding With Default: 1", "Error",
JOptionPane.ERROR_MESSAGE);
run = 1;
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Positive Integer Into The Runs Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
String printer_id = "tsd.printer";
String printer_track_quantity = "amount";
if (concentrations.isSelected()) {
printer_track_quantity = "concentration";
}
int[] index = terminations.getSelectedIndices();
String[] termCond = Buttons.getList(termConditions, terminations);
terminations.setSelectedIndices(index);
// index = species.getSelectedIndices();
String[] intSpecies = getInterestingSpecies();
// if (none.isSelected()) {
// intSpecies = new String[allSpecies.length];
// for (int j = 0; j < allSpecies.length; j++) {
// intSpecies[j] = (String) allSpecies[j];
// else {
// intSpecies = Buttons.getList(interestingSpecies, species);
// species.setSelectedIndices(index);
String selectedButtons = "";
double rap1 = 0.1;
double rap2 = 0.1;
double qss = 0.1;
int con = 15;
try {
// if (rapid1.isEnabled()) {
rap1 = Double.parseDouble(rapid1.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The"
+ " Rapid Equilibrium Condition 1 Field.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try {
// if (rapid2.isEnabled()) {
rap2 = Double.parseDouble(rapid2.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter A Real Number Into The"
+ " Rapid Equilibrium Condition 2 Field.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try {
// if (qssa.isEnabled()) {
qss = Double.parseDouble(qssa.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Must Enter A Real Number Into The QSSA Condition Field.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
// if (maxCon.isEnabled()) {
con = Integer.parseInt(maxCon.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Must Enter An Integer Into The Max"
+ " Concentration Threshold Field.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (none.isSelected() && ODE.isSelected()) {
selectedButtons = "none_ODE";
}
else if (none.isSelected() && monteCarlo.isSelected()) {
selectedButtons = "none_monteCarlo";
}
else if (abstraction.isSelected() && ODE.isSelected()) {
selectedButtons = "abs_ODE";
}
else if (abstraction.isSelected() && monteCarlo.isSelected()) {
selectedButtons = "abs_monteCarlo";
}
else if (nary.isSelected() && monteCarlo.isSelected()) {
selectedButtons = "nary_monteCarlo";
}
else if (nary.isSelected() && markov.isSelected()) {
selectedButtons = "nary_markov";
}
else if (none.isSelected() && markov.isSelected()) {
selectedButtons = "none_markov";
}
else if (abstraction.isSelected() && markov.isSelected()) {
selectedButtons = "abs_markov";
}
else if (none.isSelected() && sbml.isSelected()) {
selectedButtons = "none_sbml";
}
else if (abstraction.isSelected() && sbml.isSelected()) {
selectedButtons = "abs_sbml";
}
else if (nary.isSelected() && sbml.isSelected()) {
selectedButtons = "nary_sbml";
}
else if (none.isSelected() && dot.isSelected()) {
selectedButtons = "none_dot";
}
else if (none.isSelected() && lhpn.isSelected()) {
selectedButtons = "none_lhpn";
}
else if (abstraction.isSelected() && dot.isSelected()) {
selectedButtons = "abs_dot";
}
else if (nary.isSelected() && dot.isSelected()) {
selectedButtons = "nary_dot";
}
else if (none.isSelected() && xhtml.isSelected()) {
selectedButtons = "none_xhtml";
}
else if (abstraction.isSelected() && xhtml.isSelected()) {
selectedButtons = "abs_xhtml";
}
else if (nary.isSelected() && xhtml.isSelected()) {
selectedButtons = "nary_xhtml";
}
else if (nary.isSelected() && lhpn.isSelected()) {
selectedButtons = "nary_lhpn";
}
else if (abstraction.isSelected() && lhpn.isSelected()) {
selectedButtons = "abs_lhpn";
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator + simName
+ separator + "user-defined.dat"));
int[] indecies = ssa.getSelectedIndices();
ssaList = Buttons.getList(ssaList, ssa);
ssa.setSelectedIndices(indecies);
String save = "";
for (int i = 0; i < ssaList.length; i++) {
if (i == ssaList.length - 1) {
save += ssaList[i];
}
else {
save += ssaList[i] + "\n";
}
}
byte[] output = save.getBytes();
out.write(output);
out.close();
if (!usingSSA.isSelected() && save.trim().equals("")) {
new File(root + separator + simName + separator + "user-defined.dat").delete();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to save user defined file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
return;
}
Run runProgram = new Run(this);
int cut = 0;
String[] getFilename = sbmlProp.split(separator);
for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) {
if (getFilename[getFilename.length - 1].charAt(i) == '.') {
cut = i;
}
}
String propName = sbmlProp.substring(0, sbmlProp.length()
- getFilename[getFilename.length - 1].length())
+ getFilename[getFilename.length - 1].substring(0, cut) + ".properties";
// String monteLimit = "";
// String monteInterval = "";
// try {
// if (new File(propName).exists()) {
// Properties getProps = new Properties();
// FileInputStream load = new FileInputStream(new File(propName));
// getProps.load(load);
// load.close();
// if (getProps.containsKey("monte.carlo.simulation.time.limit")) {
// monteLimit =
// getProps.getProperty("monte.carlo.simulation.time.limit");
// monteInterval =
// getProps.getProperty("monte.carlo.simulation.print.interval");
// catch (Exception e) {
// JOptionPane.showMessageDialog(biomodelsim.frame(),
// "Unable to add properties to property file.", "Error",
// JOptionPane.ERROR_MESSAGE);
log.addText("Creating properties file:\n" + propName + "\n");
saveSAD(simName);
runProgram.createProperties(timeLimit, ((String) (intervalLabel.getSelectedItem())),
printInterval, minTimeStep, timeStep, absError, ".",
// outDir,
rndSeed, run, termCond, intSpecies, printer_id, printer_track_quantity, sbmlProp
.split(separator), selectedButtons, this, sbmlProp, rap1, rap2, qss, con,
usingSSA,
// root + separator + simName + separator +
"user-defined.dat", usingSAD, new File(root + separator + outDir + separator
+ "termCond.sad"), preAbs, loopAbs, postAbs, lhpnAbstraction);
int[] indecies = properties.getSelectedIndices();
props = Buttons.getList(props, properties);
properties.setSelectedIndices(indecies);
try {
Properties getProps = new Properties();
FileInputStream load = new FileInputStream(new File(propName));
getProps.load(load);
load.close();
// for (int i = 0; i < props.length; i++) {
// String[] split = ((String) props[i]).split("=");
// getProps.setProperty(split[0], split[1]);
getProps.setProperty("selected.simulator", (String) simulators.getSelectedItem());
if (!fileStem.getText().trim().equals("")) {
getProps.setProperty("file.stem", fileStem.getText().trim());
}
FileOutputStream store = new FileOutputStream(new File(propName));
getProps.store(store, getFilename[getFilename.length - 1].substring(0, cut)
+ " Properties");
store.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Unable to add properties to property file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
biomodelsim.refreshTree();
change = false;
}
public void saveSAD(String outDir) {
try {
int[] indecies = sad.getSelectedIndices();
sadList = Buttons.getList(sadList, sad);
if (sadList.length == 0)
return;
FileOutputStream out = new FileOutputStream(new File(root + separator + outDir
+ separator + "termCond.sad"));
sad.setSelectedIndices(indecies);
String save = "";
for (int i = 0; i < sadList.length; i++) {
String[] get = ((String) sadList[i]).split(";");
save += "term " + get[0].trim() + " {\n";
save += " desc \"" + get[1].trim() + "\";\n";
save += " cond " + get[2].trim() + ";\n";
save += "}\n";
}
byte[] output = save.getBytes();
out.write(output);
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biomodelsim.frame(),
"Unable to save termination conditions!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
/**
* Loads the simulate options.
*/
public void open(String openFile) {
Properties load = new Properties();
try {
if (!openFile.equals("")) {
FileInputStream in = new FileInputStream(new File(openFile));
load.load(in);
in.close();
ArrayList<String> loadProperties = new ArrayList<String>();
for (Object key : load.keySet()) {
if (key.equals("reb2sac.abstraction.method.0.1")) {
if (!load.getProperty("reb2sac.abstraction.method.0.1").equals(
"enzyme-kinetic-qssa-1")) {
loadProperties.add("reb2sac.abstraction.method.0.1="
+ load.getProperty("reb2sac.abstraction.method.0.1"));
}
}
else if (key.equals("reb2sac.abstraction.method.0.2")) {
if (!load.getProperty("reb2sac.abstraction.method.0.2").equals(
"reversible-to-irreversible-transformer")) {
loadProperties.add("reb2sac.abstraction.method.0.2="
+ load.getProperty("reb2sac.abstraction.method.0.2"));
}
}
else if (key.equals("reb2sac.abstraction.method.0.3")) {
if (!load.getProperty("reb2sac.abstraction.method.0.3").equals(
"multiple-products-reaction-eliminator")) {
loadProperties.add("reb2sac.abstraction.method.0.3="
+ load.getProperty("reb2sac.abstraction.method.0.3"));
}
}
else if (key.equals("reb2sac.abstraction.method.0.4")) {
if (!load.getProperty("reb2sac.abstraction.method.0.4").equals(
"multiple-reactants-reaction-eliminator")) {
loadProperties.add("reb2sac.abstraction.method.0.4="
+ load.getProperty("reb2sac.abstraction.method.0.4"));
}
}
else if (key.equals("reb2sac.abstraction.method.0.5")) {
if (!load.getProperty("reb2sac.abstraction.method.0.5").equals(
"single-reactant-product-reaction-eliminator")) {
loadProperties.add("reb2sac.abstraction.method.0.5="
+ load.getProperty("reb2sac.abstraction.method.0.5"));
}
}
else if (key.equals("reb2sac.abstraction.method.0.6")) {
if (!load.getProperty("reb2sac.abstraction.method.0.6").equals(
"dimer-to-monomer-substitutor")) {
loadProperties.add("reb2sac.abstraction.method.0.6="
+ load.getProperty("reb2sac.abstraction.method.0.6"));
}
}
else if (key.equals("reb2sac.abstraction.method.0.7")) {
if (!load.getProperty("reb2sac.abstraction.method.0.7").equals(
"inducer-structure-transformer")) {
loadProperties.add("reb2sac.abstraction.method.0.7="
+ load.getProperty("reb2sac.abstraction.method.0.7"));
}
}
else if (key.equals("reb2sac.abstraction.method.1.1")) {
if (!load.getProperty("reb2sac.abstraction.method.1.1").equals(
"modifier-structure-transformer")) {
loadProperties.add("reb2sac.abstraction.method.1.1="
+ load.getProperty("reb2sac.abstraction.method.1.1"));
}
}
else if (key.equals("reb2sac.abstraction.method.1.2")) {
if (!load.getProperty("reb2sac.abstraction.method.1.2").equals(
"modifier-constant-propagation")) {
loadProperties.add("reb2sac.abstraction.method.1.2="
+ load.getProperty("reb2sac.abstraction.method.1.2"));
}
}
else if (key.equals("reb2sac.abstraction.method.2.1")) {
if (!load.getProperty("reb2sac.abstraction.method.2.1").equals(
"operator-site-forward-binding-remover")) {
loadProperties.add("reb2sac.abstraction.method.2.1="
+ load.getProperty("reb2sac.abstraction.method.2.1"));
}
}
else if (key.equals("reb2sac.abstraction.method.2.3")) {
if (!load.getProperty("reb2sac.abstraction.method.2.3").equals(
"enzyme-kinetic-rapid-equilibrium-1")) {
loadProperties.add("reb2sac.abstraction.method.2.3="
+ load.getProperty("reb2sac.abstraction.method.2.3"));
}
}
else if (key.equals("reb2sac.abstraction.method.2.4")) {
if (!load.getProperty("reb2sac.abstraction.method.2.4").equals(
"irrelevant-species-remover")) {
loadProperties.add("reb2sac.abstraction.method.2.4="
+ load.getProperty("reb2sac.abstraction.method.2.4"));
}
}
else if (key.equals("reb2sac.abstraction.method.2.5")) {
if (!load.getProperty("reb2sac.abstraction.method.2.5").equals(
"inducer-structure-transformer")) {
loadProperties.add("reb2sac.abstraction.method.2.5="
+ load.getProperty("reb2sac.abstraction.method.2.5"));
}
}
else if (key.equals("reb2sac.abstraction.method.2.6")) {
if (!load.getProperty("reb2sac.abstraction.method.2.6").equals(
"modifier-constant-propagation")) {
loadProperties.add("reb2sac.abstraction.method.2.6="
+ load.getProperty("reb2sac.abstraction.method.2.6"));
}
}
else if (key.equals("reb2sac.abstraction.method.2.7")) {
if (!load.getProperty("reb2sac.abstraction.method.2.7").equals(
"similar-reaction-combiner")) {
loadProperties.add("reb2sac.abstraction.method.2.7="
+ load.getProperty("reb2sac.abstraction.method.2.7"));
}
}
else if (key.equals("reb2sac.abstraction.method.2.8")) {
if (!load.getProperty("reb2sac.abstraction.method.2.8").equals(
"modifier-constant-propagation")) {
loadProperties.add("reb2sac.abstraction.method.2.8="
+ load.getProperty("reb2sac.abstraction.method.2.8"));
}
}
else if (key.equals("reb2sac.abstraction.method.2.2")) {
if (!load.getProperty("reb2sac.abstraction.method.2.2").equals(
"dimerization-reduction")
&& !load.getProperty("reb2sac.abstraction.method.2.2").equals(
"dimerization-reduction-level-assignment")) {
loadProperties.add("reb2sac.abstraction.method.2.2="
+ load.getProperty("reb2sac.abstraction.method.2.2"));
}
}
else if (key.equals("reb2sac.abstraction.method.3.1")) {
if (!load.getProperty("reb2sac.abstraction.method.3.1").equals(
"kinetic-law-constants-simplifier")
&& !load.getProperty("reb2sac.abstraction.method.3.1").equals(
"reversible-to-irreversible-transformer")
&& !load.getProperty("reb2sac.abstraction.method.3.1").equals(
"nary-order-unary-transformer")) {
loadProperties.add("reb2sac.abstraction.method.3.1="
+ load.getProperty("reb2sac.abstraction.method.3.1"));
}
}
else if (key.equals("reb2sac.abstraction.method.3.2")) {
if (!load.getProperty("reb2sac.abstraction.method.3.2").equals(
"kinetic-law-constants-simplifier")
&& !load.getProperty("reb2sac.abstraction.method.3.2").equals(
"modifier-constant-propagation")) {
loadProperties.add("reb2sac.abstraction.method.3.2="
+ load.getProperty("reb2sac.abstraction.method.3.2"));
}
}
else if (key.equals("reb2sac.abstraction.method.3.3")) {
if (!load.getProperty("reb2sac.abstraction.method.3.3").equals(
"absolute-inhibition-generator")) {
loadProperties.add("reb2sac.abstraction.method.3.3="
+ load.getProperty("reb2sac.abstraction.method.3.3"));
}
}
else if (key.equals("reb2sac.abstraction.method.3.4")) {
if (!load.getProperty("reb2sac.abstraction.method.3.4").equals(
"final-state-generator")) {
loadProperties.add("reb2sac.abstraction.method.3.4="
+ load.getProperty("reb2sac.abstraction.method.3.4"));
}
}
else if (key.equals("reb2sac.abstraction.method.3.5")) {
if (!load.getProperty("reb2sac.abstraction.method.3.5").equals(
"stop-flag-generator")) {
loadProperties.add("reb2sac.abstraction.method.3.5="
+ load.getProperty("reb2sac.abstraction.method.3.5"));
}
}
else if (key.equals("reb2sac.nary.order.decider")) {
if (!load.getProperty("reb2sac.nary.order.decider").equals("distinct")) {
loadProperties.add("reb2sac.nary.order.decider="
+ load.getProperty("reb2sac.nary.order.decider"));
}
}
else if (key.equals("simulation.printer")) {
if (!load.getProperty("simulation.printer").equals("tsd.printer")) {
loadProperties.add("simulation.printer="
+ load.getProperty("simulation.printer"));
}
}
else if (key.equals("simulation.printer.tracking.quantity")) {
if (!load.getProperty("simulation.printer.tracking.quantity").equals(
"amount")) {
loadProperties.add("simulation.printer.tracking.quantity="
+ load.getProperty("simulation.printer.tracking.quantity"));
}
}
else if (((String) key).length() > 27
&& ((String) key).substring(0, 28).equals(
"reb2sac.interesting.species.")) {
}
else if (key.equals("reb2sac.rapid.equilibrium.condition.1")) {
}
else if (key.equals("reb2sac.rapid.equilibrium.condition.2")) {
}
else if (key.equals("reb2sac.qssa.condition.1")) {
}
else if (key.equals("reb2sac.operator.max.concentration.threshold")) {
}
else if (key.equals("ode.simulation.time.limit")) {
}
else if (key.equals("ode.simulation.print.interval")) {
}
else if (key.equals("ode.simulation.number.steps")) {
}
else if (key.equals("ode.simulation.min.time.step")) {
}
else if (key.equals("ode.simulation.time.step")) {
}
else if (key.equals("ode.simulation.absolute.error")) {
}
else if (key.equals("ode.simulation.out.dir")) {
}
else if (key.equals("monte.carlo.simulation.time.limit")) {
}
else if (key.equals("monte.carlo.simulation.print.interval")) {
}
else if (key.equals("monte.carlo.simulation.number.steps")) {
}
else if (key.equals("monte.carlo.simulation.min.time.step")) {
}
else if (key.equals("monte.carlo.simulation.time.step")) {
}
else if (key.equals("monte.carlo.simulation.random.seed")) {
}
else if (key.equals("monte.carlo.simulation.runs")) {
}
else if (key.equals("monte.carlo.simulation.out.dir")) {
}
else if (key.equals("simulation.run.termination.decider")) {
if (load.getProperty("simulation.run.termination.decider").equals("sad")) {
sad.setEnabled(true);
newSAD.setEnabled(true);
usingSAD.setSelected(true);
idLabel.setEnabled(true);
TCid.setEnabled(true);
descLabel.setEnabled(true);
desc.setEnabled(true);
condLabel.setEnabled(true);
cond.setEnabled(true);
addSAD.setEnabled(true);
editSAD.setEnabled(true);
removeSAD.setEnabled(true);
// loadProperties.add(
// "simulation.run.termination.decider="
// + load.getProperty(
// "simulation.run.termination.decider"));
}
}
else if (key.equals("computation.analysis.sad.path")) {
}
else if (key.equals("simulation.time.series.species.level.file")) {
}
else if (key.equals("reb2sac.simulation.method")) {
}
else if (key.equals("reb2sac.abstraction.method")) {
}
else if (key.equals("selected.simulator")) {
}
else if (key.equals("file.stem")) {
}
else if (((String) key).length() > 36
&& ((String) key).substring(0, 37).equals(
"simulation.run.termination.condition.")) {
}
else if (((String) key).length() > 37
&& ((String) key).substring(0, 38).equals(
"reb2sac.absolute.inhibition.threshold.")) {
}
else if (((String) key).length() > 27
&& ((String) key).substring(0, 28).equals(
"reb2sac.concentration.level.")) {
}
else if (((String) key).length() > 19
&& ((String) key).substring(0, 20).equals("reb2sac.final.state.")) {
}
else if (key.equals("reb2sac.analysis.stop.enabled")) {
}
else if (key.equals("reb2sac.analysis.stop.rate")) {
}
else if (key.equals("monte.carlo.simulation.start.index")) {
}
else if (key.equals("abstraction.interesting")) {
String intVars = load.getProperty("abstraction.interesting");
String[] array = intVars.split(" ");
for (String s : array) {
if (!s.equals("")) {
lhpnAbstraction.addIntVar(s);
}
}
}
else if (key.equals("abstraction.transforms")) {
lhpnAbstraction.removeAllXform();
String xforms = load.getProperty("abstraction.transforms");
String[] array = xforms.split(", ");
for (String s : array) {
if (!s.equals("")) {
lhpnAbstraction.addXform(s.replace(",", ""));
}
}
}
else if (key.equals("abstraction.factor")) {
lhpnAbstraction.factorField.setText(load.getProperty("abstraction.factor"));
}
else if (key.equals("abstraction.iterations")) {
lhpnAbstraction.iterField.setText(load
.getProperty("abstraction.iterations"));
}
else {
loadProperties.add(key + "=" + load.getProperty((String) key));
}
}
props = loadProperties.toArray(props);
properties.setListData(props);
String[] getFilename = openFile.split(separator);
int cut = 0;
for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) {
if (getFilename[getFilename.length - 1].charAt(i) == '.') {
cut = i;
}
}
String filename = "";
if (new File((openFile.substring(0, openFile.length()
- getFilename[getFilename.length - 1].length()))
+ getFilename[getFilename.length - 1].substring(0, cut) + ".sbml").exists()) {
filename = (openFile.substring(0, openFile.length()
- getFilename[getFilename.length - 1].length()))
+ getFilename[getFilename.length - 1].substring(0, cut) + ".sbml";
}
else if (new File((openFile.substring(0, openFile.length()
- getFilename[getFilename.length - 1].length()))
+ getFilename[getFilename.length - 1].substring(0, cut) + ".xml").exists()) {
filename = (openFile.substring(0, openFile.length()
- getFilename[getFilename.length - 1].length()))
+ getFilename[getFilename.length - 1].substring(0, cut) + ".xml";
}
try {
filename = sbmlFile;
ArrayList<String> listOfSpecs = new ArrayList<String>();
SBMLDocument document = BioSim.readSBML(filename);
Model model = document.getModel();
if (model != null) {
ListOf listOfSpecies = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) listOfSpecies.get(i);
listOfSpecs.add(species.getId());
}
}
allSpecies = listOfSpecs.toArray();
for (int i = 1; i < allSpecies.length; i++) {
String index = (String) allSpecies[i];
int j = i;
while ((j > 0)
&& ((String) allSpecies[j - 1]).compareToIgnoreCase(index) > 0) {
allSpecies[j] = allSpecies[j - 1];
j = j - 1;
}
allSpecies[j] = index;
}
// intSpecies.setListData(list);
termCond.setListData(allSpecies);
int rem = availSpecies.getItemCount();
for (int i = 0; i < rem; i++) {
availSpecies.removeItemAt(0);
}
for (int i = 0; i < allSpecies.length; i++) {
availSpecies.addItem(((String) allSpecies[i]).replace(" ", "_"));
}
String[] allSpecies = getAllSpecies();
String[] intSpecies = getInterestingSpecies();
createInterestingSpeciesPanel();
for (int i = 0; i < speciesInt.size(); i++) {
for (String s : intSpecies) {
if (s.contains(((JTextField) speciesInt.get(i).get(1)).getText() + " ")) {
((JCheckBox) speciesInt.get(i).get(0)).doClick();
}
}
}
for (int i = 0; i < allSpecies.length; i++) {
String[] split1 = allSpecies[i].split(" ");
if (split1.length > 1) {
editLine(i, split1[1]);
}
}
speciesPanel.revalidate();
speciesPanel.repaint();
}
catch (Exception e1) {
}
// species.setListData(new Object[0]);
terminations.setListData(new Object[0]);
if (load.getProperty("reb2sac.abstraction.method").equals("none")) {
none.setSelected(true);
Button_Enabling.enableNoneOrAbs(ODE, monteCarlo, markov, seed, seedLabel, runs,
runsLabel, minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators,
simulatorsLabel, explanation, description, none, spLabel, speciesLabel,
addIntSpecies, editIntSpecies, removeIntSpecies, rapid1, rapid2, qssa,
maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel, usingSSA,
clearIntSpecies, fileStem, fileStemLabel, preAbs, loopAbs, postAbs,
preAbsLabel, loopAbsLabel, postAbsLabel, addPreAbs, rmPreAbs,
editPreAbs, addLoopAbs, rmLoopAbs, editLoopAbs, addPostAbs, rmPostAbs,
editPostAbs, lhpn, speciesInt);
if (modelFile.contains(".lpn")) {
markov.setEnabled(true);
lhpn.setEnabled(true);
}
}
else if (load.getProperty("reb2sac.abstraction.method").equals("abs")) {
abstraction.setSelected(true);
Button_Enabling.enableNoneOrAbs(ODE, monteCarlo, markov, seed, seedLabel, runs,
runsLabel, minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators,
simulatorsLabel, explanation, description, none, spLabel, speciesLabel,
addIntSpecies, editIntSpecies, removeIntSpecies, rapid1, rapid2, qssa,
maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel, usingSSA,
clearIntSpecies, fileStem, fileStemLabel, preAbs, loopAbs, postAbs,
preAbsLabel, loopAbsLabel, postAbsLabel, addPreAbs, rmPreAbs,
editPreAbs, addLoopAbs, rmLoopAbs, editLoopAbs, addPostAbs, rmPostAbs,
editPostAbs, lhpn, speciesInt);
if (modelFile.contains(".lpn")) {
markov.setEnabled(true);
lhpn.setEnabled(true);
}
}
else {
nary.setSelected(true);
Button_Enabling.enableNary(ODE, monteCarlo, markov, seed, seedLabel, runs,
runsLabel, minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators,
simulatorsLabel, explanation, description, spLabel, speciesLabel,
addIntSpecies, editIntSpecies, removeIntSpecies, rapid1, rapid2, qssa,
maxCon, rapidLabel1, rapidLabel2, qssaLabel, maxConLabel, usingSSA,
clearIntSpecies, fileStem, fileStemLabel, preAbs, loopAbs, postAbs,
preAbsLabel, loopAbsLabel, postAbsLabel, addPreAbs, rmPreAbs,
editPreAbs, addLoopAbs, rmLoopAbs, editLoopAbs, addPostAbs, rmPostAbs,
editPostAbs, lhpn, gcmEditor, speciesInt);
}
if (load.containsKey("ode.simulation.absolute.error")) {
absErr.setText(load.getProperty("ode.simulation.absolute.error"));
}
else {
absErr.setText("1.0E-9");
}
if (load.containsKey("monte.carlo.simulation.time.step")) {
step.setText(load.getProperty("monte.carlo.simulation.time.step"));
}
else {
step.setText("inf");
}
if (load.containsKey("monte.carlo.simulation.min.time.step")) {
minStep.setText(load.getProperty("monte.carlo.simulation.min.time.step"));
}
else {
minStep.setText("0");
}
if (load.containsKey("monte.carlo.simulation.time.limit")) {
limit.setText(load.getProperty("monte.carlo.simulation.time.limit"));
}
else {
limit.setText("100.0");
}
if (load.containsKey("monte.carlo.simulation.print.interval")) {
intervalLabel.setSelectedItem("Print Interval");
interval.setText(load.getProperty("monte.carlo.simulation.print.interval"));
}
else if (load.containsKey("monte.carlo.simulation.minimum.print.interval")) {
intervalLabel.setSelectedItem("Minimum Print Interval");
interval.setText(load
.getProperty("monte.carlo.simulation.minimum.print.interval"));
}
else if (load.containsKey("monte.carlo.simulation.number.steps")) {
intervalLabel.setSelectedItem("Number Of Steps");
interval.setText(load.getProperty("monte.carlo.simulation.number.steps"));
}
else {
interval.setText("1.0");
}
if (load.containsKey("monte.carlo.simulation.random.seed")) {
seed.setText(load.getProperty("monte.carlo.simulation.random.seed"));
}
if (load.containsKey("monte.carlo.simulation.runs")) {
runs.setText(load.getProperty("monte.carlo.simulation.runs"));
}
if (load.containsKey("simulation.run.termination.decider")
&& load.getProperty("simulation.run.termination.decider").equals("sad")) {
sad.setEnabled(true);
newSAD.setEnabled(true);
usingSAD.setSelected(true);
idLabel.setEnabled(true);
TCid.setEnabled(true);
descLabel.setEnabled(true);
desc.setEnabled(true);
condLabel.setEnabled(true);
cond.setEnabled(true);
addSAD.setEnabled(true);
editSAD.setEnabled(true);
removeSAD.setEnabled(true);
}
if (load.containsKey("simulation.time.series.species.level.file")) {
usingSSA.doClick();
}
else {
description.setEnabled(true);
explanation.setEnabled(true);
simulators.setEnabled(true);
simulatorsLabel.setEnabled(true);
newSSA.setEnabled(false);
usingSSA.setSelected(false);
ssa.setEnabled(false);
timeLabel.setEnabled(false);
time.setEnabled(false);
availSpecies.setEnabled(false);
ssaMod.setEnabled(false);
ssaModNum.setEnabled(false);
addSSA.setEnabled(false);
editSSA.setEnabled(false);
removeSSA.setEnabled(false);
if (!nary.isSelected()) {
ODE.setEnabled(true);
}
else {
markov.setEnabled(true);
}
}
if (load.containsKey("reb2sac.simulation.method")) {
if (load.getProperty("reb2sac.simulation.method").equals("ODE")) {
ODE.setSelected(true);
if (load.containsKey("ode.simulation.time.limit")) {
limit.setText(load.getProperty("ode.simulation.time.limit"));
}
if (load.containsKey("ode.simulation.print.interval")) {
intervalLabel.setSelectedItem("Print Interval");
interval.setText(load.getProperty("ode.simulation.print.interval"));
}
if (load.containsKey("ode.simulation.minimum.print.interval")) {
intervalLabel.setSelectedItem("Minimum Print Interval");
interval.setText(load
.getProperty("ode.simulation.minimum.print.interval"));
}
else if (load.containsKey("ode.simulation.number.steps")) {
intervalLabel.setSelectedItem("Number Of Steps");
interval.setText(load.getProperty("ode.simulation.number.steps"));
}
if (load.containsKey("ode.simulation.time.step")) {
step.setText(load.getProperty("ode.simulation.time.step"));
}
if (load.containsKey("ode.simulation.min.time.step")) {
minStep.setText(load.getProperty("ode.simulation.min.time.step"));
}
Button_Enabling.enableODE(seed, seedLabel, runs, runsLabel, minStepLabel,
minStep, stepLabel, step, errorLabel, absErr, limitLabel, limit,
intervalLabel, interval, simulators, simulatorsLabel, explanation,
description, usingSSA, fileStem, fileStemLabel, postAbs);
if (load.containsKey("selected.simulator")) {
simulators.setSelectedItem(load.getProperty("selected.simulator"));
}
if (load.containsKey("file.stem")) {
fileStem.setText(load.getProperty("file.stem"));
}
if (load.containsKey("simulation.printer.tracking.quantity")) {
if (load.getProperty("simulation.printer.tracking.quantity").equals(
"amount")) {
amounts.doClick();
}
else if (load.getProperty("simulation.printer.tracking.quantity")
.equals("concentration")) {
concentrations.doClick();
}
}
}
else if (load.getProperty("reb2sac.simulation.method").equals("monteCarlo")) {
monteCarlo.setSelected(true);
if (runFiles) {
overwrite.setEnabled(true);
append.setEnabled(true);
choose3.setEnabled(true);
}
Button_Enabling.enableMonteCarlo(seed, seedLabel, runs, runsLabel,
minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators,
simulatorsLabel, explanation, description, usingSSA, fileStem,
fileStemLabel, postAbs);
if (load.containsKey("selected.simulator")) {
simulators.setSelectedItem(load.getProperty("selected.simulator"));
}
if (load.containsKey("file.stem")) {
fileStem.setText(load.getProperty("file.stem"));
}
absErr.setEnabled(false);
}
else if (load.getProperty("reb2sac.simulation.method").equals("markov")) {
markov.setSelected(true);
Button_Enabling.enableMarkov(seed, seedLabel, runs, runsLabel,
minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators,
simulatorsLabel, explanation, description, usingSSA, fileStem,
fileStemLabel, gcmEditor, postAbs, modelFile);
absErr.setEnabled(false);
}
else if (load.getProperty("reb2sac.simulation.method").equals("SBML")) {
sbml.setSelected(true);
Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel,
minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators,
simulatorsLabel, explanation, description, fileStem, fileStemLabel,
postAbs);
absErr.setEnabled(false);
}
else if (load.getProperty("reb2sac.simulation.method").equals("Network")) {
dot.setSelected(true);
Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel,
minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators,
simulatorsLabel, explanation, description, fileStem, fileStemLabel,
postAbs);
absErr.setEnabled(false);
}
else if (load.getProperty("reb2sac.simulation.method").equals("Browser")) {
xhtml.setSelected(true);
Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel,
minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators,
simulatorsLabel, explanation, description, fileStem, fileStemLabel,
postAbs);
absErr.setEnabled(false);
}
else if (load.getProperty("reb2sac.simulation.method").equals("LPN")) {
lhpn.setSelected(true);
Button_Enabling.enableSbmlDotAndXhtml(seed, seedLabel, runs, runsLabel,
minStepLabel, minStep, stepLabel, step, errorLabel, absErr,
limitLabel, limit, intervalLabel, interval, simulators,
simulatorsLabel, explanation, description, fileStem, fileStemLabel,
postAbs);
absErr.setEnabled(false);
}
}
if (load.containsKey("reb2sac.abstraction.method")) {
if (load.getProperty("reb2sac.abstraction.method").equals("none")) {
none.setSelected(true);
abstraction.setSelected(false);
nary.setSelected(false);
}
else if (load.getProperty("reb2sac.abstraction.method").equals("abs")) {
none.setSelected(false);
abstraction.setSelected(true);
nary.setSelected(false);
}
else if (load.getProperty("reb2sac.abstraction.method").equals("nary")) {
none.setSelected(false);
abstraction.setSelected(false);
nary.setSelected(true);
}
}
ArrayList<String> getLists = new ArrayList<String>();
int i = 1;
while (load.containsKey("simulation.run.termination.condition." + i)) {
getLists.add(load.getProperty("simulation.run.termination.condition." + i));
i++;
}
termConditions = getLists.toArray();
terminations.setListData(termConditions);
getLists = new ArrayList<String>();
i = 1;
while (load.containsKey("reb2sac.interesting.species." + i)) {
String species = load.getProperty("reb2sac.interesting.species." + i);
int j = 2;
String interesting = " ";
if (load.containsKey("reb2sac.concentration.level." + species + ".1")) {
interesting += load.getProperty("reb2sac.concentration.level." + species
+ ".1");
}
while (load.containsKey("reb2sac.concentration.level." + species + "." + j)) {
interesting += ","
+ load.getProperty("reb2sac.concentration.level." + species + "."
+ j);
j++;
}
if (!interesting.equals(" ")) {
species += interesting;
}
getLists.add(species);
i++;
}
for (String s : getLists) {
String[] split1 = s.split(" ");
for (int j = 0; j < speciesInt.size(); j++) {
if (((JTextField) speciesInt.get(j).get(1)).getText().equals(split1[0])) {
((JCheckBox) speciesInt.get(j).get(0)).doClick();
if (split1.length > 1) {
editLine(j, split1[1]);
}
}
}
}
// species.setListData(interestingSpecies);
getLists = new ArrayList<String>();
i = 1;
while (load.containsKey("reb2sac.abstraction.method.1." + i)) {
getLists.add(load.getProperty("reb2sac.abstraction.method.1." + i));
i++;
}
preAbstractions = getLists.toArray();
preAbs.setListData(preAbstractions);
getLists = new ArrayList<String>();
i = 1;
while (load.containsKey("reb2sac.abstraction.method.2." + i)) {
getLists.add(load.getProperty("reb2sac.abstraction.method.2." + i));
i++;
}
loopAbstractions = getLists.toArray();
loopAbs.setListData(loopAbstractions);
getLists = new ArrayList<String>();
i = 1;
while (load.containsKey("reb2sac.abstraction.method.3." + i)) {
getLists.add(load.getProperty("reb2sac.abstraction.method.3." + i));
i++;
}
postAbstractions = getLists.toArray();
postAbs.setListData(postAbstractions);
if (load.containsKey("reb2sac.rapid.equilibrium.condition.1")) {
rapid1.setText(load.getProperty("reb2sac.rapid.equilibrium.condition.1"));
}
if (load.containsKey("reb2sac.rapid.equilibrium.condition.2")) {
rapid2.setText(load.getProperty("reb2sac.rapid.equilibrium.condition.2"));
}
if (load.containsKey("reb2sac.qssa.condition.1")) {
qssa.setText(load.getProperty("reb2sac.qssa.condition.1"));
}
if (load.containsKey("reb2sac.operator.max.concentration.threshold")) {
maxCon
.setText(load
.getProperty("reb2sac.operator.max.concentration.threshold"));
}
}
else {
if (load.containsKey("selected.simulator")) {
simulators.setSelectedItem(load.getProperty("selected.simulator"));
}
if (load.containsKey("file.stem")) {
fileStem.setText(load.getProperty("file.stem"));
}
if (load.containsKey("simulation.printer.tracking.quantity")) {
if (load.getProperty("simulation.printer.tracking.quantity").equals("amount")) {
amounts.doClick();
}
else if (load.getProperty("simulation.printer.tracking.quantity").equals(
"concentration")) {
concentrations.doClick();
}
}
}
change = false;
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
}
public Graph createGraph(String open) {
String outDir = root + separator + simName;
String printer_id = "tsd.printer";
String printer_track_quantity = "amount";
if (concentrations.isSelected()) {
printer_track_quantity = "concentration";
}
// int[] index = species.getSelectedIndices();
// species.setSelectedIndices(index);
return new Graph(this, printer_track_quantity, simName + " simulation results", printer_id,
outDir, "time", biomodelsim, open, log, null, true, false);
}
public JButton getRunButton() {
return run;
}
public JButton getSaveButton() {
return save;
}
public void setSbml(SBML_Editor sbml) {
sbmlEditor = sbml;
}
public void setGcm(GCM2SBMLEditor gcm) {
gcmEditor = gcm;
if (nary.isSelected()) {
lhpn.setEnabled(true);
}
if (markov.isSelected()) {
simulators.removeAllItems();
simulators.addItem("markov-chain-analysis");
simulators.addItem("atacs");
simulators.addItem("ctmc-transient");
}
change = false;
}
public void updateSpeciesList() {
SBMLDocument document = BioSim.readSBML(sbmlFile);
Model model = document.getModel();
ArrayList<String> listOfSpecs = new ArrayList<String>();
if (model != null) {
ListOf listOfSpecies = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) listOfSpecies.get(i);
listOfSpecs.add(species.getId());
}
}
allSpecies = listOfSpecs.toArray();
for (int i = 1; i < allSpecies.length; i++) {
String index = (String) allSpecies[i];
int j = i;
while ((j > 0) && ((String) allSpecies[j - 1]).compareToIgnoreCase(index) > 0) {
allSpecies[j] = allSpecies[j - 1];
j = j - 1;
}
allSpecies[j] = index;
}
// intSpecies.setListData(list);
termCond.setListData(allSpecies);
int rem = availSpecies.getItemCount();
for (int i = 0; i < rem; i++) {
availSpecies.removeItemAt(0);
}
for (int i = 0; i < allSpecies.length; i++) {
availSpecies.addItem(((String) allSpecies[i]).replace(" ", "_"));
}
String[] allSpecies = getAllSpecies();
String[] intSpecies = getInterestingSpecies();
createInterestingSpeciesPanel();
for (int i = 0; i < speciesInt.size(); i++) {
for (String s : intSpecies) {
if (s.contains(((JTextField) speciesInt.get(i).get(1)).getText() + " ")) {
((JCheckBox) speciesInt.get(i).get(0)).doClick();
}
}
}
for (int i = 0; i < allSpecies.length; i++) {
String[] split1 = allSpecies[i].split(" ");
if (split1.length > 1) {
editLine(i, split1[1]);
}
}
speciesPanel.revalidate();
speciesPanel.repaint();
}
public void setSim(String newSimName) {
sbmlProp = root + separator + newSimName + separator
+ sbmlFile.split(separator)[sbmlFile.split(separator).length - 1];
simName = newSimName;
}
public boolean hasChanged() {
return change;
}
public void addLhpnAbstraction(AbstPane pane) {
lhpnAbstraction = pane;
}
/*
* private void addInterstingSpecies() { ArrayList<String> intSpecs = new
* ArrayList<String>(); for (Object spec : interestingSpecies) {
* intSpecs.add(((String) spec).split(" ")[0]); } for (Object spec :
* intSpecies.getSelectedValues()) { if (intSpecs.contains((String) spec)) {
* JOptionPane .showMessageDialog(biomodelsim.frame(), spec +
* " is already an interesting species.", "Error",
* JOptionPane.ERROR_MESSAGE); return; } } JTabbedPane naryTabs = new
* JTabbedPane(); ArrayList<JPanel> specProps = new ArrayList<JPanel>();
* final ArrayList<JTextField> texts = new ArrayList<JTextField>(); final
* ArrayList<JList> consLevel = new ArrayList<JList>(); final
* ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); final
* ArrayList<String> specs = new ArrayList<String>(); for (Object spec :
* intSpecies.getSelectedValues()) { specs.add((String) spec); JPanel
* newPanel1 = new JPanel(new GridLayout(1, 2)); JPanel newPanel2 = new
* JPanel(new GridLayout(1, 2)); JPanel otherLabel = new JPanel();
* otherLabel.add(new JLabel(spec + " Amount:")); newPanel2.add(otherLabel);
* consLevel.add(new JList()); conLevel.add(new Object[0]);
* consLevel.get(consLevel.size() - 1).setListData(new Object[0]);
* conLevel.set(conLevel.size() - 1, new Object[0]); JScrollPane scroll =
* new JScrollPane(); scroll.setPreferredSize(new Dimension(260, 100));
* scroll.setViewportView(consLevel.get(consLevel.size() - 1)); JPanel area
* = new JPanel(); area.add(scroll); newPanel2.add(area); JPanel
* addAndRemove = new JPanel(); JTextField adding = new JTextField(15);
* texts.add(adding); JButton Add = new JButton("Add"); JButton Remove = new
* JButton("Remove"); Add.addActionListener(new ActionListener() { public
* void actionPerformed(ActionEvent e) { int number =
* Integer.parseInt(e.getActionCommand().substring(3,
* e.getActionCommand().length())); try { int get =
* Integer.parseInt(texts.get(number).getText().trim()); if (get <= 0) {
* JOptionPane.showMessageDialog(biomodelsim.frame(),
* "Amounts Must Be Positive Integers.", "Error",
* JOptionPane.ERROR_MESSAGE); } else { JList add = new JList(); Object[]
* adding = { "" + get }; add.setListData(adding); add.setSelectedIndex(0);
* Object[] sort = Buttons.add(conLevel.get(number), consLevel.get(number),
* add, false, null, null, null, null, null, null, biomodelsim.frame()); int
* in; for (int out = 1; out < sort.length; out++) { int temp =
* Integer.parseInt((String) sort[out]); in = out; while (in > 0 &&
* Integer.parseInt((String) sort[in - 1]) >= temp) { sort[in] = sort[in -
* 1]; --in; } sort[in] = temp + ""; } conLevel.set(number, sort); } } catch
* (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(),
* "Amounts Must Be Positive Integers.", "Error",
* JOptionPane.ERROR_MESSAGE); } } }); Add.setActionCommand("Add" +
* (consLevel.size() - 1)); Remove.addActionListener(new ActionListener() {
* public void actionPerformed(ActionEvent e) { int number =
* Integer.parseInt(e.getActionCommand().substring(6,
* e.getActionCommand().length())); conLevel.set(number, Buttons
* .remove(consLevel.get(number), conLevel.get(number))); } });
* Remove.setActionCommand("Remove" + (consLevel.size() - 1));
* addAndRemove.add(adding); addAndRemove.add(Add);
* addAndRemove.add(Remove); JPanel newnewPanel = new JPanel(new
* BorderLayout()); newnewPanel.add(newPanel1, "North");
* newnewPanel.add(newPanel2, "Center"); newnewPanel.add(addAndRemove,
* "South"); specProps.add(newnewPanel); naryTabs.addTab(spec +
* " Properties", specProps.get(specProps.size() - 1)); } Object[] options =
* { "Add", "Cancel" }; int value =
* JOptionPane.showOptionDialog(biomodelsim.frame(), naryTabs, "Thresholds",
* JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
* options[0]); if (value == JOptionPane.YES_OPTION) { String[] add = new
* String[specs.size()]; for (int i = 0; i < specs.size(); i++) { add[i] =
* specs.get(i); if (conLevel.get(i).length > 0) { add[i] += " " +
* conLevel.get(i)[0]; } for (int j = 1; j < conLevel.get(i).length; j++) {
* add[i] += "," + conLevel.get(i)[j]; } } JList list = new JList(add);
* int[] select = new int[add.length]; for (int i = 0; i < add.length; i++)
* { select[i] = i; } list.setSelectedIndices(select); interestingSpecies =
* Buttons.add(interestingSpecies, species, list, false, amountTerm, ge, gt,
* eq, lt, le, biomodelsim.frame()); } }
*
* private void editInterstingSpecies() { JTabbedPane naryTabs = new
* JTabbedPane(); ArrayList<JPanel> specProps = new ArrayList<JPanel>();
* final ArrayList<JTextField> texts = new ArrayList<JTextField>(); final
* ArrayList<JList> consLevel = new ArrayList<JList>(); final
* ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); final
* ArrayList<String> specs = new ArrayList<String>(); for (Object spec :
* species.getSelectedValues()) { String[] split = ((String)
* spec).split(" "); specs.add(split[0]); JPanel newPanel1 = new JPanel(new
* GridLayout(1, 2)); JPanel newPanel2 = new JPanel(new GridLayout(1, 2));
* JPanel otherLabel = new JPanel(); otherLabel.add(new JLabel(split[0] +
* " Amount:")); newPanel2.add(otherLabel); consLevel.add(new JList());
* Object[] cons; if (split.length > 1) { cons = split[1].split(","); } else
* { cons = new Object[0]; } conLevel.add(cons);
* consLevel.get(consLevel.size() - 1).setListData(cons);
* conLevel.set(conLevel.size() - 1, cons); JScrollPane scroll = new
* JScrollPane(); scroll.setPreferredSize(new Dimension(260, 100));
* scroll.setViewportView(consLevel.get(consLevel.size() - 1)); JPanel area
* = new JPanel(); area.add(scroll); newPanel2.add(area); JPanel
* addAndRemove = new JPanel(); JTextField adding = new JTextField(15);
* texts.add(adding); JButton Add = new JButton("Add"); JButton Remove = new
* JButton("Remove"); Add.addActionListener(new ActionListener() { public
* void actionPerformed(ActionEvent e) { int number =
* Integer.parseInt(e.getActionCommand().substring(3,
* e.getActionCommand().length())); try { int get =
* Integer.parseInt(texts.get(number).getText().trim()); if (get <= 0) {
* JOptionPane.showMessageDialog(biomodelsim.frame(),
* "Amounts Must Be Positive Integers.", "Error",
* JOptionPane.ERROR_MESSAGE); } else { JList add = new JList(); Object[]
* adding = { "" + get }; add.setListData(adding); add.setSelectedIndex(0);
* Object[] sort = Buttons.add(conLevel.get(number), consLevel.get(number),
* add, false, null, null, null, null, null, null, biomodelsim.frame()); int
* in; for (int out = 1; out < sort.length; out++) { int temp =
* Integer.parseInt((String) sort[out]); in = out; while (in > 0 &&
* Integer.parseInt((String) sort[in - 1]) >= temp) { sort[in] = sort[in -
* 1]; --in; } sort[in] = temp + ""; } conLevel.set(number, sort); } } catch
* (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(),
* "Amounts Must Be Positive Integers.", "Error",
* JOptionPane.ERROR_MESSAGE); } } }); Add.setActionCommand("Add" +
* (consLevel.size() - 1)); Remove.addActionListener(new ActionListener() {
* public void actionPerformed(ActionEvent e) { int number =
* Integer.parseInt(e.getActionCommand().substring(6,
* e.getActionCommand().length())); conLevel.set(number, Buttons
* .remove(consLevel.get(number), conLevel.get(number))); } });
* Remove.setActionCommand("Remove" + (consLevel.size() - 1));
* addAndRemove.add(adding); addAndRemove.add(Add);
* addAndRemove.add(Remove); JPanel newnewPanel = new JPanel(new
* BorderLayout()); newnewPanel.add(newPanel1, "North");
* newnewPanel.add(newPanel2, "Center"); newnewPanel.add(addAndRemove,
* "South"); specProps.add(newnewPanel); naryTabs.addTab(split[0] +
* " Properties", specProps.get(specProps.size() - 1)); } Object[] options =
* { "Add", "Cancel" }; int value =
* JOptionPane.showOptionDialog(biomodelsim.frame(), naryTabs, "Thresholds",
* JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
* options[0]); if (value == JOptionPane.YES_OPTION) {
* Buttons.remove(species); String[] add = new String[specs.size()]; for
* (int i = 0; i < specs.size(); i++) { add[i] = specs.get(i); if
* (conLevel.get(i).length > 0) { add[i] += " " + conLevel.get(i)[0]; } for
* (int j = 1; j < conLevel.get(i).length; j++) { add[i] += "," +
* conLevel.get(i)[j]; } } JList list = new JList(add); int[] select = new
* int[add.length]; for (int i = 0; i < add.length; i++) { select[i] = i; }
* list.setSelectedIndices(select); interestingSpecies =
* Buttons.add(interestingSpecies, species, list, false, amountTerm, ge, gt,
* eq, lt, le, biomodelsim.frame()); } }
*/
private void createInterestingSpeciesPanel() {
speciesPanel.removeAll();
speciesInt = new ArrayList<ArrayList<Component>>();
speciesPanel.setLayout(new GridLayout(allSpecies.length + 1, 1));
JPanel label = new JPanel(new GridLayout());
label.add(new JLabel("Use"));
label.add(new JLabel("Species"));
label.add(new JLabel("Number Of Thresholds"));
speciesPanel.add(label);
int j = 0;
for (Object s : allSpecies) {
j++;
JPanel sp = new JPanel(new GridLayout());
ArrayList<Component> specs = new ArrayList<Component>();
JCheckBox check = new JCheckBox();
check.setSelected(false);
specs.add(check);
specs.add(new JTextField((String) s));
String[] options = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
JComboBox combo = new JComboBox(options);
combo.setEnabled(false);
specs.add(combo);
((JTextField) specs.get(1)).setEditable(false);
sp.add(specs.get(0));
((JCheckBox) specs.get(0)).addActionListener(this);
((JCheckBox) specs.get(0)).setActionCommand("box" + j);
sp.add(specs.get(1));
sp.add(specs.get(2));
((JComboBox) specs.get(2)).addActionListener(this);
((JComboBox) specs.get(2)).setActionCommand("text" + j);
speciesInt.add(specs);
speciesPanel.add(sp);
}
}
private void editLine(int num, String thresholds) {
String[] thresh = thresholds.split(",");
ArrayList<Component> specs = speciesInt.get(num);
((JComboBox) specs.get(2)).setSelectedItem("" + thresh.length);
for (int i = 0; i < thresh.length; i++) {
((JTextField) specs.get(i + 3)).setText(thresh[i]);
}
}
private String getLine(int num) {
String line = "";
ArrayList<Component> specs = speciesInt.get(num);
int boxes = Integer.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem());
for (int i = 0; i < boxes; i++) {
line += ((JTextField) specs.get(i + 3)).getText() + ",";
}
if (line.equals("")) {
return "";
}
else {
return line.substring(0, line.length() - 1);
}
}
private String[] getInterestingSpecies() {
ArrayList<String> species = new ArrayList<String>();
for (int i = 0; i < speciesInt.size(); i++) {
if (((JCheckBox) speciesInt.get(i).get(0)).isSelected()) {
String add = ((JTextField) speciesInt.get(i).get(1)).getText();
String line = getLine(i);
if (line.equals("")) {
species.add(add);
}
else {
species.add(add + " " + line);
}
}
}
return species.toArray(new String[0]);
}
private String[] getAllSpecies() {
ArrayList<String> species = new ArrayList<String>();
for (Object s : allSpecies) {
species.add((String) s);
}
for (int i = 0; i < speciesInt.size(); i++) {
String spec = ((JTextField) speciesInt.get(i).get(1)).getText();
if (species.contains(spec)) {
species.set(species.indexOf(spec), spec + " " + getLine(i));
}
}
String[] speciesArray = species.toArray(new String[0]);
for (int i = 1; i < speciesArray.length; i++) {
String index = (String) speciesArray[i];
int j = i;
while ((j > 0) && ((String) speciesArray[j - 1]).compareToIgnoreCase(index) > 0) {
speciesArray[j] = speciesArray[j - 1];
j = j - 1;
}
speciesArray[j] = index;
}
return speciesArray;
}
private void editNumThresholds(int num) {
try {
ArrayList<Component> specs = speciesInt.get(num);
Component[] panels = speciesPanel.getComponents();
int boxes = Integer.parseInt((String) ((JComboBox) specs.get(2)).getSelectedItem());
if ((specs.size() - 3) < boxes) {
for (int i = 0; i < boxes; i++) {
try {
specs.get(i + 3);
}
catch (Exception e1) {
JTextField temp = new JTextField("");
((JPanel) panels[num + 1]).add(temp);
specs.add(temp);
}
}
}
else {
try {
if (boxes > 0) {
while (true) {
specs.remove(boxes + 3);
((JPanel) panels[num + 1]).remove(boxes + 3);
}
}
else if (boxes == 0) {
while (true) {
specs.remove(3);
((JPanel) panels[num + 1]).remove(3);
}
}
}
catch (Exception e1) {
}
}
int max = 0;
for (int i = 0; i < speciesInt.size(); i++) {
max = Math.max(max, speciesInt.get(i).size());
}
if (((JPanel) panels[0]).getComponentCount() < max) {
for (int i = 0; i < max - 3; i++) {
try {
((JPanel) panels[0]).getComponent(i + 3);
}
catch (Exception e) {
((JPanel) panels[0]).add(new JLabel("Threshold " + (i + 1)));
}
}
}
else {
try {
while (true) {
((JPanel) panels[0]).remove(max);
}
}
catch (Exception e) {
}
}
for (int i = 1; i < panels.length; i++) {
JPanel sp = (JPanel) panels[i];
for (int j = sp.getComponentCount() - 1; j >= 3; j
if (sp.getComponent(j) instanceof JLabel) {
sp.remove(j);
}
}
if (max > sp.getComponentCount()) {
for (int j = sp.getComponentCount(); j < max; j++) {
sp.add(new JLabel());
}
}
else {
for (int j = sp.getComponentCount() - 3; j >= max; j
sp.remove(j);
}
}
}
}
catch (Exception e) {
}
}
/*
* public void addToIntSpecies(String newSpecies) { JList addIntSpecies =
* new JList(); Object[] addObj = { newSpecies };
* addIntSpecies.setListData(addObj); addIntSpecies.setSelectedIndex(0);
* interestingSpecies = Buttons.add(interestingSpecies, species,
* addIntSpecies, false, amountTerm, ge, gt, eq, lt, le, this); }
*
* public void removeIntSpecies() { String message =
* "These species cannot be removed.\n"; boolean displayMessage1 = false; if
* (usingSSA.isSelected()) { ArrayList<String> keepers = new
* ArrayList<String>(); for (int i = 0; i < ssaList.length; i++) { String[]
* get = ((String) ssaList[i]).split(" "); keepers.add(get[1]); } int[]
* selected = species.getSelectedIndices(); for (int i = 0; i <
* selected.length; i++) { for (int j = 0; j < keepers.size(); j++) { if
* ((keepers.get(j)).equals(interestingSpecies[selected[i]])) {
* species.removeSelectionInterval(selected[i], selected[i]); if
* (!displayMessage1) { message +=
* "These species are used in user-defined data.\n"; displayMessage1 = true;
* } message += interestingSpecies[selected[i]] + "\n"; break; } } } }
* boolean displayMessage2 = false; if (usingSAD.isSelected()) {
* ArrayList<String> keepers = new ArrayList<String>(); for (int i = 0; i <
* sadList.length; i++) { String[] get = ((String) sadList[i]).split(";");
* String cond = get[2]; cond = cond.replace('>', ' '); cond =
* cond.replace('<', ' '); cond = cond.replace('=', ' '); cond =
* cond.replace('&', ' '); cond = cond.replace('|', ' '); cond =
* cond.replace('+', ' '); cond = cond.replace('-', ' '); cond =
* cond.replace('*', ' '); cond = cond.replace('/', ' '); cond =
* cond.replace('#', ' '); cond = cond.replace('%', ' '); cond =
* cond.replace('@', ' '); cond = cond.replace('(', ' '); cond =
* cond.replace(')', ' '); cond = cond.replace('!', ' '); get =
* cond.split(" "); for (int j = 0; j < get.length; j++) if (get[j].length()
* > 0) if ((get[j].charAt(0) != '0') && (get[j].charAt(0) != '1') &&
* (get[j].charAt(0) != '2') && (get[j].charAt(0) != '3') &&
* (get[j].charAt(0) != '4') && (get[j].charAt(0) != '5') &&
* (get[j].charAt(0) != '6') && (get[j].charAt(0) != '7') &&
* (get[j].charAt(0) != '8') && (get[j].charAt(0) != '9')) {
* keepers.add(get[j]); } } int[] selected = species.getSelectedIndices();
* for (int i = 0; i < selected.length; i++) { for (int j = 0; j <
* keepers.size(); j++) { if
* ((keepers.get(j)).equals(interestingSpecies[selected[i]])) {
* species.removeSelectionInterval(selected[i], selected[i]); if
* (!displayMessage2) { message +=
* "These species are used in termination conditions.\n"; displayMessage2 =
* true; } message += interestingSpecies[selected[i]] + "\n"; break; } } } }
* if (displayMessage1 || displayMessage2) { JTextArea messageArea = new
* JTextArea(message); messageArea.setEditable(false); JScrollPane scroll =
* new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300));
* scroll.setPreferredSize(new Dimension(300, 300));
* scroll.setViewportView(messageArea);
* JOptionPane.showMessageDialog(biomodelsim.frame(), scroll,
* "Unable To Remove Species", JOptionPane.ERROR_MESSAGE); }
* interestingSpecies = Buttons.remove(species, interestingSpecies); }
*/
public Graph createProbGraph(String open) {
String outDir = root + separator + simName;
String printer_id = "tsd.printer";
String printer_track_quantity = "amount";
if (concentrations.isSelected()) {
printer_track_quantity = "concentration";
}
return new Graph(this, printer_track_quantity, simName + " simulation results", printer_id,
outDir, "time", biomodelsim, open, log, null, false, false);
}
public void run() {
}
public JPanel getAdvanced() {
JPanel constructPanel = new JPanel(new BorderLayout());
constructPanel.add(advanced, "Center");
JButton runButton = new JButton("Save and Run");
JButton saveButton = new JButton("Save Parameters");
JPanel runHolder = new JPanel();
runHolder.add(runButton);
runButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
run.doClick();
}
});
runButton.setMnemonic(KeyEvent.VK_R);
runHolder.add(saveButton);
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
save.doClick();
}
});
saveButton.setMnemonic(KeyEvent.VK_S);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// runHolder, null);
// splitPane.setDividerSize(0);
// constructPanel.add(splitPane, "South");
return constructPanel;
}
public JPanel getProperties() {
JPanel constructPanel = new JPanel(new BorderLayout());
constructPanel.add(propertiesPanel, "Center");
JButton runButton = new JButton("Save and Run");
JButton saveButton = new JButton("Save Parameters");
JPanel runHolder = new JPanel();
runHolder.add(runButton);
runButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
run.doClick();
}
});
runButton.setMnemonic(KeyEvent.VK_R);
runHolder.add(saveButton);
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
save.doClick();
}
});
saveButton.setMnemonic(KeyEvent.VK_S);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, runHolder, null);
splitPane.setDividerSize(0);
constructPanel.add(splitPane, "South");
return constructPanel;
}
public String getSimName() {
return simName;
}
public String getSimID() {
return fileStem.getText().trim();
}
public String getSimPath() {
if (!fileStem.getText().trim().equals("")) {
return root + separator + simName + separator + fileStem.getText().trim();
}
else {
return root + separator + simName;
}
}
}
|
package org.jfree.chart.plot.junit;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.CategoryTextAnnotation;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.AxisSpace;
import org.jfree.chart.axis.CategoryAnchor;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.event.MarkerChangeListener;
import org.jfree.chart.plot.CategoryMarker;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.IntervalMarker;
import org.jfree.chart.plot.Marker;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.renderer.category.AreaRenderer;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.Range;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.Layer;
import org.jfree.ui.RectangleInsets;
import org.jfree.util.SortOrder;
/**
* Tests for the {@link CategoryPlot} class.
*/
public class CategoryPlotTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(CategoryPlotTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public CategoryPlotTests(String name) {
super(name);
}
/**
* Some checks for the constructor.
*/
public void testConstructor() {
CategoryPlot plot = new CategoryPlot();
assertEquals(RectangleInsets.ZERO_INSETS, plot.getAxisOffset());
}
/**
* A test for a bug reported in the forum.
*/
public void testAxisRange() {
DefaultCategoryDataset datasetA = new DefaultCategoryDataset();
DefaultCategoryDataset datasetB = new DefaultCategoryDataset();
datasetB.addValue(50.0, "R1", "C1");
datasetB.addValue(80.0, "R1", "C1");
CategoryPlot plot = new CategoryPlot(datasetA, new CategoryAxis(null),
new NumberAxis(null), new LineAndShapeRenderer());
plot.setDataset(1, datasetB);
plot.setRenderer(1, new LineAndShapeRenderer());
Range r = plot.getRangeAxis().getRange();
assertEquals(84.0, r.getUpperBound(), 0.00001);
}
/**
* Test that the equals() method differentiates all the required fields.
*/
public void testEquals() {
CategoryPlot plot1 = new CategoryPlot();
CategoryPlot plot2 = new CategoryPlot();
assertTrue(plot1.equals(plot2));
assertTrue(plot2.equals(plot1));
// orientation...
plot1.setOrientation(PlotOrientation.HORIZONTAL);
assertFalse(plot1.equals(plot2));
plot2.setOrientation(PlotOrientation.HORIZONTAL);
assertTrue(plot1.equals(plot2));
// axisOffset...
plot1.setAxisOffset(new RectangleInsets(0.05, 0.05, 0.05, 0.05));
assertFalse(plot1.equals(plot2));
plot2.setAxisOffset(new RectangleInsets(0.05, 0.05, 0.05, 0.05));
assertTrue(plot1.equals(plot2));
// domainAxis - no longer a separate field but test anyway...
plot1.setDomainAxis(new CategoryAxis("Category Axis"));
assertFalse(plot1.equals(plot2));
plot2.setDomainAxis(new CategoryAxis("Category Axis"));
assertTrue(plot1.equals(plot2));
// domainAxes...
plot1.setDomainAxis(11, new CategoryAxis("Secondary Axis"));
assertFalse(plot1.equals(plot2));
plot2.setDomainAxis(11, new CategoryAxis("Secondary Axis"));
assertTrue(plot1.equals(plot2));
// domainAxisLocation - no longer a separate field but test anyway...
plot1.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
assertFalse(plot1.equals(plot2));
plot2.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
assertTrue(plot1.equals(plot2));
// domainAxisLocations...
plot1.setDomainAxisLocation(11, AxisLocation.TOP_OR_RIGHT);
assertFalse(plot1.equals(plot2));
plot2.setDomainAxisLocation(11, AxisLocation.TOP_OR_RIGHT);
assertTrue(plot1.equals(plot2));
// draw shared domain axis...
plot1.setDrawSharedDomainAxis(!plot1.getDrawSharedDomainAxis());
assertFalse(plot1.equals(plot2));
plot2.setDrawSharedDomainAxis(!plot2.getDrawSharedDomainAxis());
assertTrue(plot1.equals(plot2));
// rangeAxis - no longer a separate field but test anyway...
plot1.setRangeAxis(new NumberAxis("Range Axis"));
assertFalse(plot1.equals(plot2));
plot2.setRangeAxis(new NumberAxis("Range Axis"));
assertTrue(plot1.equals(plot2));
// rangeAxes...
plot1.setRangeAxis(11, new NumberAxis("Secondary Range Axis"));
assertFalse(plot1.equals(plot2));
plot2.setRangeAxis(11, new NumberAxis("Secondary Range Axis"));
assertTrue(plot1.equals(plot2));
// rangeAxisLocation - no longer a separate field but test anyway...
plot1.setRangeAxisLocation(AxisLocation.TOP_OR_RIGHT);
assertFalse(plot1.equals(plot2));
plot2.setRangeAxisLocation(AxisLocation.TOP_OR_RIGHT);
assertTrue(plot1.equals(plot2));
// rangeAxisLocations...
plot1.setRangeAxisLocation(11, AxisLocation.TOP_OR_RIGHT);
assertFalse(plot1.equals(plot2));
plot2.setRangeAxisLocation(11, AxisLocation.TOP_OR_RIGHT);
assertTrue(plot1.equals(plot2));
// datasetToDomainAxisMap...
plot1.mapDatasetToDomainAxis(11, 11);
assertFalse(plot1.equals(plot2));
plot2.mapDatasetToDomainAxis(11, 11);
assertTrue(plot1.equals(plot2));
// datasetToRangeAxisMap...
plot1.mapDatasetToRangeAxis(11, 11);
assertFalse(plot1.equals(plot2));
plot2.mapDatasetToRangeAxis(11, 11);
assertTrue(plot1.equals(plot2));
// renderer - no longer a separate field but test anyway...
plot1.setRenderer(new AreaRenderer());
assertFalse(plot1.equals(plot2));
plot2.setRenderer(new AreaRenderer());
assertTrue(plot1.equals(plot2));
// renderers...
plot1.setRenderer(11, new AreaRenderer());
assertFalse(plot1.equals(plot2));
plot2.setRenderer(11, new AreaRenderer());
assertTrue(plot1.equals(plot2));
// rendering order...
plot1.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
assertFalse(plot1.equals(plot2));
plot2.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
assertTrue(plot1.equals(plot2));
// columnRenderingOrder...
plot1.setColumnRenderingOrder(SortOrder.DESCENDING);
assertFalse(plot1.equals(plot2));
plot2.setColumnRenderingOrder(SortOrder.DESCENDING);
assertTrue(plot1.equals(plot2));
// rowRenderingOrder...
plot1.setRowRenderingOrder(SortOrder.DESCENDING);
assertFalse(plot1.equals(plot2));
plot2.setRowRenderingOrder(SortOrder.DESCENDING);
assertTrue(plot1.equals(plot2));
// domainGridlinesVisible
plot1.setDomainGridlinesVisible(true);
assertFalse(plot1.equals(plot2));
plot2.setDomainGridlinesVisible(true);
assertTrue(plot1.equals(plot2));
// domainGridlinePosition
plot1.setDomainGridlinePosition(CategoryAnchor.END);
assertFalse(plot1.equals(plot2));
plot2.setDomainGridlinePosition(CategoryAnchor.END);
assertTrue(plot1.equals(plot2));
// domainGridlineStroke
Stroke stroke = new BasicStroke(2.0f);
plot1.setDomainGridlineStroke(stroke);
assertFalse(plot1.equals(plot2));
plot2.setDomainGridlineStroke(stroke);
assertTrue(plot1.equals(plot2));
// domainGridlinePaint
plot1.setDomainGridlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.yellow));
assertFalse(plot1.equals(plot2));
plot2.setDomainGridlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.yellow));
assertTrue(plot1.equals(plot2));
// rangeGridlinesVisible
plot1.setRangeGridlinesVisible(false);
assertFalse(plot1.equals(plot2));
plot2.setRangeGridlinesVisible(false);
assertTrue(plot1.equals(plot2));
// rangeGridlineStroke
plot1.setRangeGridlineStroke(stroke);
assertFalse(plot1.equals(plot2));
plot2.setRangeGridlineStroke(stroke);
assertTrue(plot1.equals(plot2));
// rangeGridlinePaint
plot1.setRangeGridlinePaint(new GradientPaint(1.0f, 2.0f, Color.green,
3.0f, 4.0f, Color.yellow));
assertFalse(plot1.equals(plot2));
plot2.setRangeGridlinePaint(new GradientPaint(1.0f, 2.0f, Color.green,
3.0f, 4.0f, Color.yellow));
assertTrue(plot1.equals(plot2));
// anchorValue
plot1.setAnchorValue(100.0);
assertFalse(plot1.equals(plot2));
plot2.setAnchorValue(100.0);
assertTrue(plot1.equals(plot2));
// rangeCrosshairVisible
plot1.setRangeCrosshairVisible(true);
assertFalse(plot1.equals(plot2));
plot2.setRangeCrosshairVisible(true);
assertTrue(plot1.equals(plot2));
// rangeCrosshairValue
plot1.setRangeCrosshairValue(100.0);
assertFalse(plot1.equals(plot2));
plot2.setRangeCrosshairValue(100.0);
assertTrue(plot1.equals(plot2));
// rangeCrosshairStroke
plot1.setRangeCrosshairStroke(stroke);
assertFalse(plot1.equals(plot2));
plot2.setRangeCrosshairStroke(stroke);
assertTrue(plot1.equals(plot2));
// rangeCrosshairPaint
plot1.setRangeCrosshairPaint(new GradientPaint(1.0f, 2.0f, Color.white,
3.0f, 4.0f, Color.yellow));
assertFalse(plot1.equals(plot2));
plot2.setRangeCrosshairPaint(new GradientPaint(1.0f, 2.0f, Color.white,
3.0f, 4.0f, Color.yellow));
assertTrue(plot1.equals(plot2));
// rangeCrosshairLockedOnData
plot1.setRangeCrosshairLockedOnData(false);
assertFalse(plot1.equals(plot2));
plot2.setRangeCrosshairLockedOnData(false);
assertTrue(plot1.equals(plot2));
// range markers - no longer separate fields but test anyway...
plot1.addRangeMarker(new ValueMarker(4.0), Layer.FOREGROUND);
assertFalse(plot1.equals(plot2));
plot2.addRangeMarker(new ValueMarker(4.0), Layer.FOREGROUND);
assertTrue(plot1.equals(plot2));
plot1.addRangeMarker(new ValueMarker(5.0), Layer.BACKGROUND);
assertFalse(plot1.equals(plot2));
plot2.addRangeMarker(new ValueMarker(5.0), Layer.BACKGROUND);
assertTrue(plot1.equals(plot2));
// foreground range markers...
plot1.addRangeMarker(1, new ValueMarker(4.0), Layer.FOREGROUND);
assertFalse(plot1.equals(plot2));
plot2.addRangeMarker(1, new ValueMarker(4.0), Layer.FOREGROUND);
assertTrue(plot1.equals(plot2));
// background range markers...
plot1.addRangeMarker(1, new ValueMarker(5.0), Layer.BACKGROUND);
assertFalse(plot1.equals(plot2));
plot2.addRangeMarker(1, new ValueMarker(5.0), Layer.BACKGROUND);
assertTrue(plot1.equals(plot2));
// annotations
plot1.addAnnotation(
new CategoryTextAnnotation("Text", "Category", 43.0)
);
assertFalse(plot1.equals(plot2));
plot2.addAnnotation(new CategoryTextAnnotation("Text", "Category",
43.0));
assertTrue(plot1.equals(plot2));
// weight
plot1.setWeight(3);
assertFalse(plot1.equals(plot2));
plot2.setWeight(3);
assertTrue(plot1.equals(plot2));
// fixed domain axis space...
plot1.setFixedDomainAxisSpace(new AxisSpace());
assertFalse(plot1.equals(plot2));
plot2.setFixedDomainAxisSpace(new AxisSpace());
assertTrue(plot1.equals(plot2));
// fixed range axis space...
plot1.setFixedRangeAxisSpace(new AxisSpace());
assertFalse(plot1.equals(plot2));
plot2.setFixedRangeAxisSpace(new AxisSpace());
assertTrue(plot1.equals(plot2));
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
CategoryPlot p1 = new CategoryPlot();
p1.setRangeCrosshairPaint(new GradientPaint(1.0f, 2.0f, Color.white,
3.0f, 4.0f, Color.yellow));
CategoryPlot p2 = null;
try {
p2 = (CategoryPlot) p1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
System.err.println("Failed to clone.");
}
assertTrue(p1 != p2);
assertTrue(p1.getClass() == p2.getClass());
assertTrue(p1.equals(p2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
CategoryAxis domainAxis = new CategoryAxis("Domain");
NumberAxis rangeAxis = new NumberAxis("Range");
BarRenderer renderer = new BarRenderer();
CategoryPlot p1 = new CategoryPlot(dataset, domainAxis, rangeAxis,
renderer);
p1.setOrientation(PlotOrientation.HORIZONTAL);
CategoryPlot p2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(p1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
p2 = (CategoryPlot) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertTrue(p1.equals(p2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization2() {
DefaultCategoryDataset data = new DefaultCategoryDataset();
CategoryAxis domainAxis = new CategoryAxis("Domain");
NumberAxis rangeAxis = new NumberAxis("Range");
BarRenderer renderer = new BarRenderer();
CategoryPlot p1 = new CategoryPlot(data, domainAxis, rangeAxis,
renderer);
p1.setOrientation(PlotOrientation.VERTICAL);
CategoryPlot p2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(p1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
p2 = (CategoryPlot) in.readObject();
in.close();
}
catch (Exception e) {
fail(e.toString());
}
assertEquals(p1, p2);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization3() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
JFreeChart chart = ChartFactory.createBarChart(
"Test Chart",
"Category Axis",
"Value Axis",
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
JFreeChart chart2 = null;
// serialize and deserialize the chart....
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(chart);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
chart2 = (JFreeChart) in.readObject();
in.close();
}
catch (Exception e) {
fail(e.toString());
}
// now check that the chart is usable...
boolean passed = true;
try {
chart2.createBufferedImage(300, 200);
}
catch (Exception e) {
passed = false;
e.printStackTrace();
}
assertTrue(passed);
}
/**
* This test ensures that a plot with markers is serialized correctly.
*/
public void testSerialization4() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
JFreeChart chart = ChartFactory.createBarChart(
"Test Chart",
"Category Axis",
"Value Axis",
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.addRangeMarker(new ValueMarker(1.1), Layer.FOREGROUND);
plot.addRangeMarker(new IntervalMarker(2.2, 3.3), Layer.BACKGROUND);
JFreeChart chart2 = null;
// serialize and deserialize the chart....
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(chart);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
chart2 = (JFreeChart) in.readObject();
in.close();
}
catch (Exception e) {
fail(e.toString());
}
assertEquals(chart, chart2);
// now check that the chart is usable...
boolean passed = true;
try {
chart2.createBufferedImage(300, 200);
}
catch (Exception e) {
passed = false;
e.printStackTrace();
}
assertTrue(passed);
}
/**
* Tests a bug where the plot is no longer registered as a listener
* with the dataset(s) and axes after deserialization. See patch 1209475
* at SourceForge.
*/
public void testSerialization5() {
DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();
CategoryAxis domainAxis1 = new CategoryAxis("Domain 1");
NumberAxis rangeAxis1 = new NumberAxis("Range 1");
BarRenderer renderer1 = new BarRenderer();
CategoryPlot p1 = new CategoryPlot(dataset1, domainAxis1, rangeAxis1,
renderer1);
CategoryAxis domainAxis2 = new CategoryAxis("Domain 2");
NumberAxis rangeAxis2 = new NumberAxis("Range 2");
BarRenderer renderer2 = new BarRenderer();
DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();
p1.setDataset(1, dataset2);
p1.setDomainAxis(1, domainAxis2);
p1.setRangeAxis(1, rangeAxis2);
p1.setRenderer(1, renderer2);
CategoryPlot p2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(p1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
p2 = (CategoryPlot) in.readObject();
in.close();
}
catch (Exception e) {
fail(e.toString());
}
assertEquals(p1, p2);
// now check that all datasets, renderers and axes are being listened
// too...
CategoryAxis domainAxisA = p2.getDomainAxis(0);
NumberAxis rangeAxisA = (NumberAxis) p2.getRangeAxis(0);
DefaultCategoryDataset datasetA
= (DefaultCategoryDataset) p2.getDataset(0);
BarRenderer rendererA = (BarRenderer) p2.getRenderer(0);
CategoryAxis domainAxisB = p2.getDomainAxis(1);
NumberAxis rangeAxisB = (NumberAxis) p2.getRangeAxis(1);
DefaultCategoryDataset datasetB
= (DefaultCategoryDataset) p2.getDataset(1);
BarRenderer rendererB = (BarRenderer) p2.getRenderer(1);
assertTrue(datasetA.hasListener(p2));
assertTrue(domainAxisA.hasListener(p2));
assertTrue(rangeAxisA.hasListener(p2));
assertTrue(rendererA.hasListener(p2));
assertTrue(datasetB.hasListener(p2));
assertTrue(domainAxisB.hasListener(p2));
assertTrue(rangeAxisB.hasListener(p2));
assertTrue(rendererB.hasListener(p2));
}
/**
* A test for a bug where setting the renderer doesn't register the plot
* as a RendererChangeListener.
*/
public void testSetRenderer() {
CategoryPlot plot = new CategoryPlot();
CategoryItemRenderer renderer = new LineAndShapeRenderer();
plot.setRenderer(renderer);
// now make a change to the renderer and see if it triggers a plot
// change event...
MyPlotChangeListener listener = new MyPlotChangeListener();
plot.addChangeListener(listener);
renderer.setSeriesPaint(0, Color.black);
assertTrue(listener.getEvent() != null);
}
/**
* A test for bug report 1169972.
*/
public void test1169972() {
CategoryPlot plot = new CategoryPlot(null, null, null, null);
plot.setDomainAxis(new CategoryAxis("C"));
plot.setRangeAxis(new NumberAxis("Y"));
plot.setRenderer(new BarRenderer());
plot.setDataset(new DefaultCategoryDataset());
assertTrue(plot != null);
}
/**
* Some tests for the addDomainMarker() method(s).
*/
public void testAddDomainMarker() {
CategoryPlot plot = new CategoryPlot();
CategoryMarker m = new CategoryMarker("C1");
plot.addDomainMarker(m);
List listeners = Arrays.asList(m.getListeners(
MarkerChangeListener.class));
assertTrue(listeners.contains(plot));
plot.clearDomainMarkers();
listeners = Arrays.asList(m.getListeners(MarkerChangeListener.class));
assertFalse(listeners.contains(plot));
}
/**
* Some tests for the addRangeMarker() method(s).
*/
public void testAddRangeMarker() {
CategoryPlot plot = new CategoryPlot();
Marker m = new ValueMarker(1.0);
plot.addRangeMarker(m);
List listeners = Arrays.asList(m.getListeners(
MarkerChangeListener.class));
assertTrue(listeners.contains(plot));
plot.clearRangeMarkers();
listeners = Arrays.asList(m.getListeners(MarkerChangeListener.class));
assertFalse(listeners.contains(plot));
}
/**
* A test for bug 1654215 (where a renderer is added to the plot without
* a corresponding dataset and it throws an exception at drawing time).
*/
public void test1654215() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
JFreeChart chart = ChartFactory.createLineChart("Title", "X", "Y",
dataset, PlotOrientation.VERTICAL, true, false, false);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setRenderer(1, new LineAndShapeRenderer());
boolean success = false;
try {
BufferedImage image = new BufferedImage(200 , 100,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null);
g2.dispose();
success = true;
}
catch (Exception e) {
e.printStackTrace();
success = false;
}
assertTrue(success);
}
/**
* Some checks for the getDomainAxisIndex() method.
*/
public void testGetDomainAxisIndex() {
CategoryAxis domainAxis1 = new CategoryAxis("X1");
CategoryAxis domainAxis2 = new CategoryAxis("X2");
NumberAxis rangeAxis1 = new NumberAxis("Y1");
CategoryPlot plot = new CategoryPlot(null, domainAxis1, rangeAxis1,
null);
assertEquals(0, plot.getDomainAxisIndex(domainAxis1));
assertEquals(-1, plot.getDomainAxisIndex(domainAxis2));
plot.setDomainAxis(1, domainAxis2);
assertEquals(1, plot.getDomainAxisIndex(domainAxis2));
assertEquals(-1, plot.getDomainAxisIndex(new CategoryAxis("X2")));
boolean pass = false;
try {
plot.getDomainAxisIndex(null);
}
catch (IllegalArgumentException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Some checks for the getRangeAxisIndex() method.
*/
public void testGetRangeAxisIndex() {
CategoryAxis domainAxis1 = new CategoryAxis("X1");
NumberAxis rangeAxis1 = new NumberAxis("Y1");
NumberAxis rangeAxis2 = new NumberAxis("Y2");
CategoryPlot plot = new CategoryPlot(null, domainAxis1, rangeAxis1,
null);
assertEquals(0, plot.getRangeAxisIndex(rangeAxis1));
assertEquals(-1, plot.getRangeAxisIndex(rangeAxis2));
plot.setRangeAxis(1, rangeAxis2);
assertEquals(1, plot.getRangeAxisIndex(rangeAxis2));
assertEquals(-1, plot.getRangeAxisIndex(new NumberAxis("Y2")));
boolean pass = false;
try {
plot.getRangeAxisIndex(null);
}
catch (IllegalArgumentException e) {
pass = true;
}
assertTrue(pass);
}
}
|
package controllers;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import play.Logger;
import play.api.libs.Codecs;
import play.mvc.Http.Request;
public class DigestRequest {
private Map<String, String> params = new HashMap<String, String>();
private Request request;
public DigestRequest(Request request) {
this.request = request;
}
public boolean isAuthorized() {
return this.isValid() && this.compareResponse();
}
public String getUsername() {
if (params.containsKey("username")) {
return params.get("username");
} else {
return null;
}
}
private boolean isValid() {
if (!request.headers().containsKey("Authorization")) {
return false;
}
String authString = request.headers().get("Authorization")[0];
if (StringUtils.isEmpty(authString) || !authString.startsWith("Digest ")) {
return false;
}
for (String keyValuePair : authString.replaceFirst("Digest ", "").split(",")) {
String data[] = keyValuePair.trim().split("=", 2);
String key = data[0];
String value = data[1].replaceAll("\"", "");
if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
params.put(key, value);
}
}
return params.containsKey("username") && params.containsKey("realm")
&& params.containsKey("uri") && params.containsKey("nonce")
&& params.containsKey("response");
}
private boolean compareResponse() {
String htdigestLocation = LoadConfig.loadStringFromConfig("de.cismet.users.htdigest-file");
String ha1 = HtdigestFileParser.getHA1(htdigestLocation, params.get("username"), params.get("realm"));
if (ha1 == null) {
return false;
//throw new UnauthorizedDigest(params.get("realm"));
}
String digest = createDigest(ha1);
return digest.equals(params.get("response"));
}
private String createDigest(String ha1) {
String digest1 = ha1; //md5(username + ":" + realm + ":" + pass)
String digest2 = Codecs.md5((request.method() + ":" + params.get("uri")).getBytes());
String digest3 = Codecs.md5((digest1 + ":" + params.get("nonce") + ":" + digest2).getBytes());
Logger.debug("digest1: " + digest1);
Logger.debug("digest2: " + digest2);
Logger.debug("digest3: " + digest3);
return digest3;
}
}
|
package SW9;
import SW9.abstractions.Component;
import SW9.abstractions.Project;
import SW9.abstractions.Query;
import SW9.controllers.CanvasController;
import SW9.presentations.HUPPAALPresentation;
import SW9.presentations.UndoRedoHistoryPresentation;
import SW9.utility.keyboard.Keybind;
import SW9.utility.keyboard.KeyboardTracker;
import com.google.common.io.Files;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.text.Font;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import jiconfont.icons.GoogleMaterialDesignIcons;
import jiconfont.javafx.IconFontFX;
import java.io.File;
import java.nio.charset.Charset;
public class HUPPAAL extends Application {
private static Project project;
private Stage debugStage;
public static void main(final String[] args) {
launch(HUPPAAL.class, args);
}
public static Project getProject() {
return project;
}
@Override
public void start(final Stage stage) throws Exception {
// Load or create new project
project = new Project();
// Set the title and icon for the application
stage.setTitle("H-UPPAAL");
stage.getIcons().add(new Image("SW9/uppaal.ico"));
// Load the fonts required for the project
IconFontFX.register(GoogleMaterialDesignIcons.getIconFont());
loadFonts();
// Remove the classic decoration
stage.initStyle(StageStyle.UNIFIED);
// Make the view used for the application
final HUPPAALPresentation huppaal = new HUPPAALPresentation();
// Make the scene that we will use, and set its size to 80% of the primary screen
final Screen screen = Screen.getPrimary();
final Scene scene = new Scene(huppaal, screen.getVisualBounds().getWidth() * 0.8, screen.getVisualBounds().getHeight() * 0.8);
stage.setScene(scene);
// Load all .css files used todo: these should be loaded in the view classes (?)
scene.getStylesheets().add("SW9/main.css");
scene.getStylesheets().add("SW9/colors.css");
scene.getStylesheets().add("SW9/model_canvas.css");
// Handle a mouse click as a deselection of all elements
scene.setOnMousePressed(event -> {
if (scene.getFocusOwner() == null || scene.getFocusOwner().getParent() == null) return;
scene.getFocusOwner().getParent().requestFocus();
});
// Let our keyboard tracker handle all key presses
scene.setOnKeyPressed(KeyboardTracker.handleKeyPress);
// Set the icon for the application
stage.getIcons().addAll(
new Image(getClass().getResource("ic_launcher/mipmap-hdpi/ic_launcher.png").toExternalForm()),
new Image(getClass().getResource("ic_launcher/mipmap-mdpi/ic_launcher.png").toExternalForm()),
new Image(getClass().getResource("ic_launcher/mipmap-xhdpi/ic_launcher.png").toExternalForm()),
new Image(getClass().getResource("ic_launcher/mipmap-xxhdpi/ic_launcher.png").toExternalForm()),
new Image(getClass().getResource("ic_launcher/mipmap-xxxhdpi/ic_launcher.png").toExternalForm())
);
// Make sure that the project directory exists
final File projectFolder = new File("project");
projectFolder.mkdir();
// Load the project from disk
for (final File file : projectFolder.listFiles()) {
if (!file.getName().equals("Queries.json")) {
final Component componentFromFile = new Component(file.getName().replace(".json", ""));
getProject().getComponents().add(componentFromFile);
}
}
// Load the project from disk
for (final File file : projectFolder.listFiles()) {
final String fileContent = Files.toString(file, Charset.defaultCharset());
final JsonParser parser = new JsonParser();
final JsonElement element = parser.parse(fileContent);
if (file.getName().equals("Queries.json")) {
element.getAsJsonArray().forEach(jsonElement -> {
final Query newQuery = new Query((JsonObject) jsonElement);
getProject().getQueries().add(newQuery);
});
} else {
final Component componentFromFile = HUPPAAL.getProject().getComponents().filtered(component -> component.getName().equals(file.getName().replace(".json", ""))).get(0);
componentFromFile.deserialize(element.getAsJsonObject());
}
}
// Generate all component presentations by making them the active component in the view one by one
Component initialShownComponent = null;
for (Component component : HUPPAAL.getProject().getComponents()) {
// The first component should be shown if there is no main
if(initialShownComponent == null) {
initialShownComponent = component;
}
// If the component is the main show that one
if(component.isIsMain()) {
initialShownComponent = component;
}
CanvasController.setActiveComponent(component);
}
// If we found a component (preferably main) set that as active
if(initialShownComponent != null) {
CanvasController.setActiveComponent(initialShownComponent);
}
// We're now ready! Let the curtains fall!
stage.show();
// Register a key-bind for showing debug-information
KeyboardTracker.registerKeybind("DEBUG", new Keybind(new KeyCodeCombination(KeyCode.D), () -> {
// Toggle the debug mode for the debug class (will update misc. debug variables which presentations bind to)
Debug.debugModeEnabled.set(!Debug.debugModeEnabled.get());
if (debugStage != null) {
debugStage.close();
debugStage = null;
return;
}
try {
final UndoRedoHistoryPresentation undoRedoHistoryPresentation = new UndoRedoHistoryPresentation();
debugStage = new Stage();
debugStage.setScene(new Scene(undoRedoHistoryPresentation));
debugStage.getScene().getStylesheets().add("SW9/main.css");
debugStage.getScene().getStylesheets().add("SW9/colors.css");
debugStage.setWidth(screen.getVisualBounds().getWidth() * 0.2);
debugStage.setHeight(screen.getVisualBounds().getWidth() * 0.3);
debugStage.show();
//stage.requestFocus();
} catch (final Exception e) {
e.printStackTrace();
}
}));
}
private void loadFonts() {
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Black.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-BlackItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Bold.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-BoldItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-Bold.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-BoldItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-Italic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-Light.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-LightItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-Regular.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Italic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Light.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-LightItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Medium.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-MediumItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Regular.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Thin.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-ThinItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Bold.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-BoldItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Italic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Light.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-LightItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Medium.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-MediumItalic.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Regular.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Thin.ttf"), 14);
Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-ThinItalic.ttf"), 14);
}
}
|
package debugging.jsonclientcaller;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonClientCallerGutsTest {
// private static final String METHOD = "ProteinInfo.fids_to_domains";
// private static final Object ARGS =
// Arrays.asList(Arrays.asList("kb|g.3899.CDS.10"));
// private static final String METHOD = "AbstractHandle.list_handles";
// private static final String METHOD = "AbstractHandle.list_handles";
// private static final String METHOD = "PyLog.ver";
private static final String URL = "http://localhost/services/pl";
private static final String METHOD = "PyLog.ver";
// private static final String METHOD = "Workspace.ver";
private static final Object ARGS = new ArrayList<Object>();
private static final int SLEEP = 1000; //ms between requests
private static final int COUNT = 10;
public static void main(String [] args) throws Exception{
System.out.println(URL);
int excepts = 0;
for (int i = 0; i < COUNT; i++) {
System.out.print(i + "\n");
try {
HttpURLConnection conn =
(HttpURLConnection) new URL(URL).openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
final long[] sizeWrapper = new long[] {0};
OutputStream os = new OutputStream() {
@Override
public void write(int b) {sizeWrapper[0]++;}
@Override
public void write(byte[] b) {sizeWrapper[0] += b.length;}
@Override
public void write(byte[] b, int o, int l) {sizeWrapper[0] += l;}
};
String id = "12345";
writeRequestData(METHOD, ARGS, os, id);
// Set content-length
conn.setFixedLengthStreamingMode(sizeWrapper[0]);
// conn.setChunkedStreamingMode(0);
writeRequestData(METHOD, ARGS, conn.getOutputStream(), id);
System.out.print(conn.getResponseCode() + " ");
System.out.println(conn.getResponseMessage());
InputStream istream = conn.getInputStream();
// Parse response into json
System.out.println(streamToString(istream));
// conn.disconnect();
} catch (Exception e) {
excepts++;
System.out.println(e.getClass().getName() + ": " +
e.getLocalizedMessage());
}
Thread.sleep(SLEEP);
}
System.out.println(String.format("Sleep: %s, failures %s/%s",
SLEEP, excepts, COUNT));
}
public static void writeRequestData(String method, Object arg,
OutputStream os, String id)
throws IOException {
JsonGenerator g = new ObjectMapper().getFactory()
.createGenerator(os, JsonEncoding.UTF8);
g.writeStartObject();
g.writeObjectField("params", arg);
g.writeStringField("method", method);
g.writeStringField("version", "1.1");
g.writeStringField("id", id);
g.writeEndObject();
g.close();
os.flush();
}
public static String streamToString(InputStream os) {
Scanner s = new Scanner(os);
s.useDelimiter("\\A");
String ret = s.next();
s.close();
return ret;
}
}
|
package tlc2.module;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import tlc2.overrides.TLAPlusOperator;
import tlc2.value.IValue;
import tlc2.value.impl.BoolValue;
import tlc2.value.impl.FcnLambdaValue;
import tlc2.value.impl.FcnRcdValue;
import tlc2.value.impl.IntValue;
import tlc2.value.impl.IntervalValue;
import tlc2.value.impl.ModelValue;
import tlc2.value.impl.RecordValue;
import tlc2.value.impl.SetEnumValue;
import tlc2.value.impl.SetOfFcnsValue;
import tlc2.value.impl.SetOfRcdsValue;
import tlc2.value.impl.SetOfTuplesValue;
import tlc2.value.impl.StringValue;
import tlc2.value.impl.SubsetValue;
import tlc2.value.impl.TupleValue;
import tlc2.value.impl.Value;
import util.UniqueString;
/**
* Module overrides for operators to read and write JSON.
*/
public class Json {
public static final long serialVersionUID = 20210223L;
/**
* Encodes the given value as a JSON string.
*
* @param value the value to encode
* @return the JSON string value
*/
@TLAPlusOperator(identifier = "ToJson", module = "Json", warn = false)
public static StringValue toJson(final IValue value) throws IOException {
return new StringValue(getNode(value).toString());
}
/**
* Encodes the given value as a JSON array string.
*
* @param value the value to encode
* @return the JSON array string value
*/
@TLAPlusOperator(identifier = "ToJsonArray", module = "Json", warn = false)
public static StringValue toJsonArray(final IValue value) throws IOException {
return new StringValue(getArrayNode(value).toString());
}
/**
* Encodes the given value as a JSON object string.
*
* @param value the value to encode
* @return the JSON object string value
*/
@TLAPlusOperator(identifier = "ToJsonObject", module = "Json", warn = false)
public static StringValue toJsonObject(final IValue value) throws IOException {
return new StringValue(getObjectNode(value).toString());
}
/**
* Deserializes a tuple of newline delimited JSON values from the given path.
*
* @param path the JSON file path
* @return a tuple of JSON values
*/
@TLAPlusOperator(identifier = "ndJsonDeserialize", module = "Json", warn = false)
public static IValue ndDeserialize(final StringValue path) throws IOException {
List<Value> values = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(path.val.toString())))) {
String line = reader.readLine();
while (line != null) {
JsonElement node = JsonParser.parseString(line);
values.add(getValue(node));
line = reader.readLine();
}
}
return new TupleValue(values.toArray(new Value[0]));
}
/**
* Deserializes a tuple of *plain* JSON values from the given path.
*
* @param path the JSON file path
* @return a tuple of JSON values
*/
@TLAPlusOperator(identifier = "JsonDeserialize", module = "Json", warn = false)
public static IValue deserialize(final StringValue path) throws IOException {
JsonElement node = JsonParser.parseReader(new FileReader(new File(path.val.toString())));
return getValue(node);
}
/**
* Serializes a tuple of values to newline delimited JSON.
*
* @param path the file to which to write the values
* @param value the values to write
* @return a boolean value indicating whether the serialization was successful
*/
@TLAPlusOperator(identifier = "ndJsonSerialize", module = "Json", warn = false)
public synchronized static BoolValue ndSerialize(final StringValue path, final TupleValue value) throws IOException {
File file = new File(path.val.toString());
if (file.getParentFile() != null) {file.getParentFile().mkdirs();} // Cannot create parent dir for relative path.
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path.val.toString())))) {
for (int i = 0; i < value.elems.length; i++) {
writer.write(getNode(value.elems[i]).toString() + "\n");
}
}
return BoolValue.ValTrue;
}
/**
* Serializes a tuple of values to newline delimited JSON.
*
* @param path the file to which to write the values
* @param value the values to write
* @return a boolean value indicating whether the serialization was successful
*/
@TLAPlusOperator(identifier = "JsonSerialize", module = "Json", warn = false)
public synchronized static BoolValue serialize(final StringValue path, final TupleValue value) throws IOException {
File file = new File(path.val.toString());
if (file.getParentFile() != null) {file.getParentFile().mkdirs();} // Cannot create parent dir for relative path.
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path.val.toString())))) {
writer.write("[\n");
for (int i = 0; i < value.elems.length; i++) {
writer.write(getNode(value.elems[i]).toString());
if (i < value.elems.length - 1) {
// No dangling "," after last element.
writer.write(",\n");
}
}
writer.write("\n]\n");
}
return BoolValue.ValTrue;
}
/**
* Recursively converts the given value to a {@code JsonElement}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getNode(IValue value) throws IOException {
if (value instanceof RecordValue) {
return getObjectNode((RecordValue) value);
} else if (value instanceof TupleValue) {
return getArrayNode((TupleValue) value);
} else if (value instanceof StringValue) {
return new JsonPrimitive(((StringValue) value).val.toString());
} else if (value instanceof ModelValue) {
return new JsonPrimitive(((ModelValue) value).val.toString());
} else if (value instanceof IntValue) {
return new JsonPrimitive(((IntValue) value).val);
} else if (value instanceof BoolValue) {
return new JsonPrimitive(((BoolValue) value).val);
} else if (value instanceof FcnRcdValue) {
return getObjectNode((FcnRcdValue) value);
} else if (value instanceof FcnLambdaValue) {
return getObjectNode((FcnRcdValue) ((FcnLambdaValue) value).toFcnRcd());
} else if (value instanceof SetEnumValue) {
return getArrayNode((SetEnumValue) value);
} else if (value instanceof SetOfRcdsValue) {
return getArrayNode((SetEnumValue) ((SetOfRcdsValue) value).toSetEnum());
} else if (value instanceof SetOfTuplesValue) {
return getArrayNode((SetEnumValue) ((SetOfTuplesValue) value).toSetEnum());
} else if (value instanceof SetOfFcnsValue) {
return getArrayNode((SetEnumValue) ((SetOfFcnsValue) value).toSetEnum());
} else if (value instanceof SubsetValue) {
return getArrayNode((SetEnumValue) ((SubsetValue) value).toSetEnum());
} else if (value instanceof IntervalValue) {
return getArrayNode((SetEnumValue) ((IntervalValue) value).toSetEnum());
} else {
throw new IOException("Cannot convert value: unsupported value type " + value.getClass().getName());
}
}
/**
* Returns a boolean indicating whether the given value is a valid sequence.
*
* @param value the value to check
* @return indicates whether the value is a valid sequence
*/
private static boolean isValidSequence(FcnRcdValue value) {
final Value[] domain = value.getDomainAsValues();
for (Value d : domain) {
if (!(d instanceof IntValue)) {
return false;
}
}
value.normalize();
for (int i = 0; i < domain.length; i++) {
if (((IntValue) domain[i]).val != (i + 1)) {
return false;
}
}
return true;
}
/**
* Recursively converts the given value to an {@code JsonObject}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getObjectNode(IValue value) throws IOException {
if (value instanceof RecordValue) {
return getObjectNode((RecordValue) value);
} else if (value instanceof TupleValue) {
return getObjectNode((TupleValue) value);
} else if (value instanceof FcnRcdValue) {
return getObjectNode((FcnRcdValue) value);
} else if (value instanceof FcnLambdaValue) {
return getObjectNode((FcnRcdValue) ((FcnLambdaValue) value).toFcnRcd());
} else {
throw new IOException("Cannot convert value: unsupported value type " + value.getClass().getName());
}
}
/**
* Converts the given record value to a {@code JsonObject}, recursively converting values.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getObjectNode(FcnRcdValue value) throws IOException {
if (isValidSequence(value)) {
return getArrayNode(value);
}
final Value[] domain = value.getDomainAsValues();
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < domain.length; i++) {
Value domainValue = domain[i];
if (domainValue instanceof StringValue) {
jsonObject.add(((StringValue) domainValue).val.toString(), getNode(value.values[i]));
} else {
jsonObject.add(domainValue.toString(), getNode(value.values[i]));
}
}
return jsonObject;
}
/**
* Converts the given record value to an {@code JsonObject}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getObjectNode(RecordValue value) throws IOException {
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < value.names.length; i++) {
jsonObject.add(value.names[i].toString(), getNode(value.values[i]));
}
return jsonObject;
}
/**
* Converts the given tuple value to an {@code JsonObject}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getObjectNode(TupleValue value) throws IOException {
JsonObject jsonObject = new JsonObject();
for (int i = 0; i < value.elems.length; i++) {
jsonObject.add(String.valueOf(i), getNode(value.elems[i]));
}
return jsonObject;
}
/**
* Recursively converts the given value to an {@code JsonArray}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getArrayNode(IValue value) throws IOException {
if (value instanceof TupleValue) {
return getArrayNode((TupleValue) value);
} else if (value instanceof FcnRcdValue) {
return getArrayNode((FcnRcdValue) value);
} else if (value instanceof FcnLambdaValue) {
return getArrayNode((FcnRcdValue) ((FcnLambdaValue) value).toFcnRcd());
} else if (value instanceof SetEnumValue) {
return getArrayNode((SetEnumValue) value);
} else if (value instanceof SetOfRcdsValue) {
return getArrayNode((SetEnumValue) ((SetOfRcdsValue) value).toSetEnum());
} else if (value instanceof SetOfTuplesValue) {
return getArrayNode((SetEnumValue) ((SetOfTuplesValue) value).toSetEnum());
} else if (value instanceof SetOfFcnsValue) {
return getArrayNode((SetEnumValue) ((SetOfFcnsValue) value).toSetEnum());
} else if (value instanceof SubsetValue) {
return getArrayNode((SetEnumValue) ((SubsetValue) value).toSetEnum());
} else if (value instanceof IntervalValue) {
return getArrayNode((SetEnumValue) ((IntervalValue) value).toSetEnum());
} else {
throw new IOException("Cannot convert value: unsupported value type " + value.getClass().getName());
}
}
/**
* Converts the given tuple value to an {@code JsonArray}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getArrayNode(TupleValue value) throws IOException {
JsonArray jsonArray = new JsonArray(value.elems.length);
for (int i = 0; i < value.elems.length; i++) {
jsonArray.add(getNode(value.elems[i]));
}
return jsonArray;
}
/**
* Converts the given record value to an {@code JsonArray}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getArrayNode(FcnRcdValue value) throws IOException {
if (!isValidSequence(value)) {
return getObjectNode(value);
}
value.normalize();
JsonArray jsonArray = new JsonArray(value.values.length);
for (int i = 0; i < value.values.length; i++) {
jsonArray.add(getNode(value.values[i]));
}
return jsonArray;
}
/**
* Converts the given tuple value to an {@code JsonArray}.
*
* @param value the value to convert
* @return the converted {@code JsonElement}
*/
private static JsonElement getArrayNode(SetEnumValue value) throws IOException {
value.normalize();
Value[] values = value.elems.toArray();
JsonArray jsonArray = new JsonArray(values.length);
for (int i = 0; i < values.length; i++) {
jsonArray.add(getNode(values[i]));
}
return jsonArray;
}
/**
* Recursively converts the given {@code JsonElement} to a TLC value.
*
* @param node the {@code JsonElement} to convert
* @return the converted value
*/
private static Value getValue(JsonElement node) throws IOException {
if (node.isJsonArray()) {
return getTupleValue(node);
}
else if (node.isJsonObject()) {
return getRecordValue(node);
}
else if (node.isJsonPrimitive()) {
JsonPrimitive primitive = node.getAsJsonPrimitive();
if (primitive.isNumber()) {
return IntValue.gen(primitive.getAsInt());
}
else if (primitive.isBoolean()) {
return new BoolValue(primitive.getAsBoolean());
}
else if (primitive.isString()) {
return new StringValue(primitive.getAsString());
}
}
else if (node.isJsonNull()) {
return null;
}
throw new IOException("Cannot convert value: unsupported JSON value " + node.toString());
}
/**
* Converts the given {@code JsonElement} to a tuple.
*
* @param node the {@code JsonElement} to convert
* @return the tuple value
*/
private static TupleValue getTupleValue(JsonElement node) throws IOException {
List<Value> values = new ArrayList<>();
JsonArray jsonArray = node.getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
values.add(getValue(jsonArray.get(i)));
}
return new TupleValue(values.toArray(new Value[0]));
}
/**
* Converts the given {@code JsonElement} to a record.
*
* @param node the {@code JsonElement} to convert
* @return the record value
*/
private static RecordValue getRecordValue(JsonElement node) throws IOException {
List<UniqueString> keys = new ArrayList<>();
List<Value> values = new ArrayList<>();
Iterator<Map.Entry<String, JsonElement>> iterator = node.getAsJsonObject().entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
keys.add(UniqueString.uniqueStringOf(entry.getKey()));
values.add(getValue(entry.getValue()));
}
return new RecordValue(keys.toArray(new UniqueString[0]), values.toArray(new Value[0]), false);
}
}
|
package global;
/**
*
* @author nick
*/
public class Data {
// software info
public static final String APP_NAME = "ATAV (Analysis Tool for Annotated Variants)";
public static String VERSION = "trunk";
public static String userName = System.getProperty("user.name");
// atav home path (location of executable jar file, config dir, data dir, lib dir etc.)
public static String ATAV_HOME = System.getenv().getOrDefault("ATAV_HOME", "");
// system config file path
public static final String SYSTEM_CONFIG = Data.ATAV_HOME + "config/atav.dragen.system.config.properties";
public static final String SYSTEM_CONFIG_FOR_DEBUG = Data.ATAV_HOME + "config/atav.dragen.debug.system.config.properties";
// system default values
public static final int NO_FILTER = Integer.MAX_VALUE;
public static final String NO_FILTER_STR = "";
public static final byte BYTE_NA = Byte.MIN_VALUE;
public static final short SHORT_NA = Short.MIN_VALUE;
public static final int INTEGER_NA = Integer.MIN_VALUE;
public static final float FLOAT_NA = Float.MIN_VALUE;
public static final double DOUBLE_NA = Double.MIN_VALUE;
public static String STRING_NA = "NA";
public static String VCF_NA = ".";
public static String STRING_NAN = "NaN";
}
|
package tlc2.tool.distributed;
import java.io.EOFException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import tlc2.TLCGlobals;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.tool.TLCState;
import tlc2.tool.TLCStateVec;
import tlc2.tool.WorkerException;
import tlc2.tool.distributed.selector.IBlockSelector;
import tlc2.tool.fp.FPSet;
import tlc2.tool.queue.IStateQueue;
import tlc2.tool.queue.StateQueue;
import tlc2.util.BitVector;
import tlc2.util.IdThread;
import tlc2.util.LongVec;
public class TLCServerThread extends IdThread {
private static int COUNT = 0;
/**
* Identifies the worker
*/
private int receivedStates, sentStates;
private final IBlockSelector selector;
private final Timer keepAliveTimer;
/**
* Synchronized flag used to indicate the correct amount of workers to
* TCLGlobals.
*
* Either {@link TLCServerThread#run()} or
* {@link TLCServerThread#keepAliveTimer} will flip to false causing
* subsequent calls to
* {@link TLCServerThread#handleRemoteWorkerLost(StateQueue)} to be a noop.
*
* Synchronization is required because {@link TLCServerThread#run()} and
* {@link TLCTimerTask#run()} are executed as two separate threads.
*/
private final AtomicBoolean cleanupGlobals = new AtomicBoolean(true);
/**
* An {@link ExecutorService} used to parallelize calls to the _distributed_
* fingerprint set servers ({@link FPSet}).
* <p>
* The fingerprint space is partitioned across all {@link FPSet} servers and
* thus can be accessed concurrently.
*/
private ExecutorService executorService;
public TLCServerThread(TLCWorkerRMI worker, TLCServer tlc, ExecutorService es, IBlockSelector aSelector) {
super(COUNT++);
this.executorService = es;
this.setWorker(worker);
this.tlcServer = tlc;
this.selector = aSelector;
// schedule a timer to periodically (60s) check server aliveness
keepAliveTimer = new Timer("TLCWorker KeepAlive Timer ["
+ uri.toASCIIString() + "]", true);
keepAliveTimer.schedule(new TLCTimerTask(), 10000, 60000);
}
private TLCWorkerRMI worker;
private final TLCServer tlcServer;
private URI uri;
private long lastInvocation;
/**
* Current unit of work or null
*/
private TLCState[] states = new TLCState[0];
public final TLCWorkerRMI getWorker() {
return this.worker;
}
public final void setWorker(TLCWorkerRMI worker) {
this.worker = new TLCWorkerSmartProxy(worker);
try {
this.uri = worker.getURI();
} catch (RemoteException e) {
MP.printError(EC.GENERAL, e);
handleRemoteWorkerLost(null);
}
// update thread name
final String i = String.format("%03d", myGetId());
setName(TLCServer.THREAD_NAME_PREFIX + i + "-[" + uri.toASCIIString() + "]");
}
/**
* This method gets a state from the queue, generates all the possible next
* states of the state, checks the invariants, and updates the state set and
* state queue.
*/
public void run() {
TLCGlobals.incNumWorkers();
TLCStateVec[] newStates = null;
LongVec[] newFps = null;
final IStateQueue stateQueue = this.tlcServer.stateQueue;
try {
START: while (true) {
// blocks until more states available or all work is done
states = selector.getBlocks(stateQueue, worker);
if (states == null) {
synchronized (this.tlcServer) {
this.tlcServer.setDone();
this.tlcServer.notify();
}
stateQueue.finishAll();
return;
}
// without initial states no need to bother workers
if (states.length == 0) {
continue;
}
// count statistics
sentStates += states.length;
// real work happens here:
// worker computes next states for states
boolean workDone = false;
while (!workDone) {
try {
final Object[] res = this.worker.getNextStates(states);
newStates = (TLCStateVec[]) res[0];
receivedStates += newStates[0].size();
newFps = (LongVec[]) res[1];
workDone = true;
lastInvocation = System.currentTimeMillis();
// Read remote worker cache hits which correspond to
// states skipped
tlcServer.addStatesGeneratedDelta((Long) res[3]);
} catch (RemoteException e) {
// If a (remote) {@link TLCWorkerRMI} fails due to the
// amount of new states we have sent it, try to lower
// the amount of states
// and re-send (until we just send a single state)
if (isRecoverable(e) && states.length > 1) {
MP.printMessage(
EC.TLC_DISTRIBUTED_EXCEED_BLOCKSIZE,
Integer.toString(states.length / 2));
// states[] exceeds maximum transferable size
// (add states back to queue and retry)
stateQueue.sEnqueue(states);
// half the maximum size and use it as a limit from
// now on
selector.setMaxTXSize(states.length / 2);
// go back to beginning
continue START;
} else {
// non recoverable errors, exit...
MP.printMessage(
EC.TLC_DISTRIBUTED_WORKER_DEREGISTERED,
getUri().toString());
handleRemoteWorkerLost(stateQueue);
return;
}
} catch (NullPointerException e) {
MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_LOST,
throwableToString(e));
handleRemoteWorkerLost(stateQueue);
return;
}
}
// add fingerprints to fingerprint manager (delegates to
// corresponding fingerprint server)
// (Why isn't this done by workers directly?
// -> because if the worker crashes while computing states, the
// fp set would be inconsistent => making it an "atomic"
// operation)
BitVector[] visited = this.tlcServer.fpSetManager
.putBlock(newFps, executorService);
// recreate newly computed states and add them to queue
for (int i = 0; i < visited.length; i++) {
BitVector.Iter iter = new BitVector.Iter(visited[i]);
int index;
while ((index = iter.next()) != -1) {
TLCState state = newStates[i].elementAt(index);
// write state id and state fp to .st file for
// checkpointing
long fp = newFps[i].elementAt(index);
state.uid = this.tlcServer.trace.writeState(state, fp);
// add state to state queue for further processing
stateQueue.sEnqueue(state);
}
}
}
} catch (Throwable e) {
TLCState state1 = null, state2 = null;
if (e instanceof WorkerException) {
state1 = ((WorkerException) e).state1;
state2 = ((WorkerException) e).state2;
}
if (this.tlcServer.setErrState(state1, true)) {
MP.printError(EC.GENERAL, e);
if (state1 != null) {
try {
this.tlcServer.trace.printTrace(state1, state2);
} catch (Exception e1) {
MP.printError(EC.GENERAL, e1);
}
}
stateQueue.finishAll();
synchronized (this.tlcServer) {
this.tlcServer.notify();
}
}
} finally {
keepAliveTimer.cancel();
states = new TLCState[0];
// not calling TLCGlobals#decNumWorkers here because at this point
// TLCServer is shutting down anyway
}
}
/**
* A recoverable error/exception is defined to be a case where the
* {@link TLCWorkerRMI} can continue to work if {@link TLCServer} sends less
* new states to process.
*
* @param e
* @return
*/
private boolean isRecoverable(final Exception e) {
final Throwable cause = e.getCause();
return ((cause instanceof EOFException && cause.getMessage() == null) || (cause instanceof RemoteException && cause
.getCause() instanceof OutOfMemoryError));
}
private String throwableToString(final Exception e) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
return result.toString();
}
/**
* Handles the case of a disconnected remote worker
*
* @param stateQueue
*/
private void handleRemoteWorkerLost(final IStateQueue stateQueue) {
// Cancel the keepAliveTimer which might still be running if an
// exception in the this run() method has caused handleRemoteWorkerLost
// to be called.
keepAliveTimer.cancel();
// This call has to be idempotent, otherwise we see bugs as in
// Prevent second invocation of worker de-registration which stamps from
// a race condition between the TimerTask (that periodically checks
// server aliveness) and the exception handling that kicks in when the
// run() method catches an RMI exception.
if (cleanupGlobals.compareAndSet(true, false)) {
// De-register TLCServerThread at the main server thread locally
tlcServer.removeTLCServerThread(this);
// Return the undone worklist (if any)
if (stateQueue != null) {
stateQueue.sEnqueue(states != null ? states : new TLCState[0]);
}
// Reset states to empty array to signal to TLCServer that we are not
// processing any new states. Otherwise statistics will incorrectly
// count this TLCServerThread as actively calculating states.
states = new TLCState[0];
// Before decrementing the worker count, notify all waiters on
// stateQueue to re-evaluate the while loop in isAvail(). The demise
// of this worker (who potentially was the lock owner) might causes
// another consumer to leave the while loop (become a consumer).
// This has to happen _prior_ to calling decNumWorkers. Otherwise
// we decrement the total number and the active count by one
// simultaneously, leaving isAvail without effect.
// This is to work around a design bug in
// tlc2.tool.queue.StateQueue's impl. Other IStateQueue impls should
// hopefully not be affected by calling notifyAll on them though.
synchronized (stateQueue) {
stateQueue.notifyAll();
}
TLCGlobals.decNumWorkers();
}
}
/**
* @return The current amount of states the corresponding worker is
* computing on
*/
public int getCurrentSize() {
return states.length;
}
/**
* @return the url
*/
public URI getUri() {
return this.uri;
}
/**
* @return the receivedStates
*/
public int getReceivedStates() {
return receivedStates;
}
/**
* @return the sentStates
*/
public int getSentStates() {
return sentStates;
}
private class TLCTimerTask extends TimerTask {
/*
* (non-Javadoc)
*
* @see java.util.TimerTask#run()
*/
public void run() {
long now = new Date().getTime();
if (lastInvocation == 0 || (now - lastInvocation) > 60000) {
try {
if (!worker.isAlive()) {
handleRemoteWorkerLost(tlcServer.stateQueue);
}
} catch (RemoteException e) {
handleRemoteWorkerLost(tlcServer.stateQueue);
}
}
}
}
}
|
package mjc;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.FileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.google.common.io.Files;
import mjc.lexer.Lexer;
import mjc.lexer.LexerException;
import mjc.parser.Parser;
import mjc.parser.ParserException;
import mjc.symbol.SymbolTable;
import mjc.translate.Translator;
import mjc.node.InvalidToken;
import mjc.node.Start;
import mjc.analysis.ASTGraphPrinter;
import mjc.analysis.ASTPrinter;
import mjc.analysis.SymbolTableBuilder;
import mjc.analysis.TypeChecker;
import mjc.arm.ARMFactory;
import mjc.error.MiniJavaError;
import static mjc.error.MiniJavaErrorType.LEXER_ERROR;
import static mjc.error.MiniJavaErrorType.PARSER_ERROR;
public class ARMMain {
private final static CommandLineParser commandLineParser = new GnuParser();
private final static HelpFormatter helpFormatter = new HelpFormatter();
private final static Options options = new Options();
private final ASTPrinter astPrinter = new ASTPrinter();
private final ASTGraphPrinter graphPrinter = new ASTGraphPrinter();
public ARMMain() {
Option outputFileOption = new Option("o", true, "output file");
outputFileOption.setArgName("outfile");
options.addOption("S", false, "output assembly code");
options.addOption(outputFileOption);
options.addOption("p", false, "print abstract syntax tree");
options.addOption("g", false, "print abstract syntax tree in GraphViz format");
options.addOption("s", false, "print symbol table");
options.addOption("h", false, "show help message");
helpFormatter.setOptionComparator(new OptionComparator<Option>());
}
public static void main(String[] args) {
ARMMain main = new ARMMain();
try {
// Run the compiler.
if (!main.run(args)) {
System.exit(1);
}
} catch (ParseException e) {
printHelp();
System.exit(1);
}
}
/**
* Run compiler with the given command line arguments.
*
* @param args Command line arguments.
* @return true if compilation succeeded, otherwise false.
* @throws ParseException if parsing of command line arguments failed.
*/
private boolean run(String[] args) throws ParseException {
final CommandLine commandLine = commandLineParser.parse(options, args);
if (commandLine.hasOption("h")) {
printHelp();
return true;
}
if (commandLine.getArgs().length != 1) {
printHelp();
return false;
}
Start tree = new Start();
try {
final String fileName = commandLine.getArgs()[0];
final PushbackReader reader = new PushbackReader(new FileReader(fileName));
final Parser parser = new Parser(new Lexer(reader));
tree = parser.parse();
} catch (LexerException e) {
final InvalidToken token = e.getToken();
final int line = token.getLine();
final int column = token.getPos();
System.err.println(LEXER_ERROR.on(line, column, token.getText()));
return false;
} catch (ParserException e) {
System.err.println(PARSER_ERROR.on(e.getLine(), e.getPos(), e.getError()));
return false;
} catch (IOException e) {
System.err.println(e.getMessage());
return false;
}
if (commandLine.hasOption("p"))
astPrinter.print(tree);
if (commandLine.hasOption("g"))
graphPrinter.print(tree);
// Build symbol table.
final SymbolTableBuilder builder = new SymbolTableBuilder();
final SymbolTable symbolTable = builder.build(tree);
if (builder.hasErrors()) {
for (MiniJavaError error : builder.getErrors()) {
System.err.println(error);
}
}
if (commandLine.hasOption("s"))
System.out.println(symbolTable);
// Run type-check.
final TypeChecker typeChecker = new TypeChecker();
if (!typeChecker.check(tree, symbolTable)) {
for (MiniJavaError error : typeChecker.getErrors()) {
System.err.println(error);
}
}
if (builder.hasErrors() || typeChecker.hasErrors()) {
return false; // Abort compilation.
}
// Translate to IR.
final Translator translator = new Translator();
translator.translate(tree, symbolTable, new ARMFactory());
// Just write an empty output file for now.
final Path parentPath = Paths.get(commandLine.getArgs()[0]).getParent();
final String baseName = Files.getNameWithoutExtension(commandLine.getArgs()[0]);
final Path outputPath = Paths.get(parentPath.toString(), baseName + ".s");
try {
outputPath.toFile().createNewFile();
} catch (IOException e) {
System.err.println(e.getMessage());
return false;
}
return true;
}
private static void printHelp() {
helpFormatter.printHelp("mjc <infile> [options]", options);
}
// Comparator for Options, to get them in the order we want in help output.
class OptionComparator<T extends Option> implements Comparator<T> {
private static final String ORDER = "Sopgsh";
@Override
public int compare(T option1, T option2) {
return ORDER.indexOf(option1.getOpt()) - ORDER.indexOf(option2.getOpt());
}
}
}
|
package to.etc.domui.component.misc;
import to.etc.domui.dom.html.*;
import to.etc.domui.server.*;
import to.etc.domui.state.*;
import to.etc.domui.util.*;
import to.etc.util.*;
public class ALink extends ATag {
private Class< ? extends UrlPage> m_targetClass;
private PageParameters m_targetParameters;
private WindowParameters m_newWindowParameters;
private MoveMode m_moveMode = MoveMode.SUB;
private String m_jspPageName;
public ALink() {}
/**
* Link to a new page; the new page is a SUB page (it is added to the shelve stack).
* @param targetClass
*/
public ALink(Class< ? extends UrlPage> targetClass) {
m_targetClass = targetClass;
updateLink();
}
public ALink(Class< ? extends UrlPage> targetClass, MoveMode mode) {
m_targetClass = targetClass;
m_moveMode = mode;
updateLink();
}
/**
* Link to a new page; the new page is a SUB page (it is added to the shelve stack).
* @param targetClass
* @param targetParameters
*/
public ALink(Class< ? extends UrlPage> targetClass, PageParameters targetParameters) {
m_targetClass = targetClass;
m_targetParameters = targetParameters;
updateLink();
}
public ALink(Class< ? extends UrlPage> targetClass, PageParameters targetParameters, MoveMode mode) {
m_targetClass = targetClass;
m_targetParameters = targetParameters;
m_moveMode = mode;
updateLink();
}
public ALink(Class< ? extends UrlPage> targetClass, PageParameters targetParameters, WindowParameters newWindowParameters) {
m_targetClass = targetClass;
m_targetParameters = targetParameters;
m_newWindowParameters = newWindowParameters;
}
/**
* Link to an old jsp page.
* @param jspPageName
* @param targetParameters
*/
public ALink(String jspPageName, PageParameters targetParameters, WindowParameters newWindowParameters) {
m_jspPageName = jspPageName;
m_targetParameters = targetParameters;
m_newWindowParameters = newWindowParameters;
updateLink();
}
public Class< ? extends UrlPage> getTargetClass() {
return m_targetClass;
}
public void setTargetClass(Class< ? extends UrlPage> targetClass, Object... parameters) {
// if(m_targetClass == targetClass)
// return;
m_targetClass = targetClass;
if(parameters == null || parameters.length == 0)
m_targetParameters = null;
else
m_targetParameters = new PageParameters(parameters);
updateLink();
}
public PageParameters getTargetParameters() {
return m_targetParameters;
}
public void setTargetParameters(PageParameters targetParameters) {
if(DomUtil.isEqual(m_targetParameters, targetParameters))
return;
m_targetParameters = targetParameters;
updateLink();
}
public WindowParameters getNewWindowParameters() {
return m_newWindowParameters;
}
public void setNewWindowParameters(WindowParameters newWindowParameters) {
if(DomUtil.isEqual(m_newWindowParameters, newWindowParameters))
return;
m_newWindowParameters = newWindowParameters;
updateLink();
}
public MoveMode getMoveMode() {
return m_moveMode;
}
public void setMoveMode(MoveMode moveMode) {
m_moveMode = moveMode;
}
/**
* Generate the actual link to the thing.
*/
private void updateLink() {
StringBuilder sb = new StringBuilder();
if(m_jspPageName == null || "".equals(m_jspPageName)) {
if(m_targetClass == null) {
setHref(null);
return;
}
sb.append(PageContext.getRequestContext().getRelativePath(m_targetClass.getName()));
sb.append(".ui");
// DomUtil.addUrlParameters(sb, PageContext.getRequestContext(), true);
DomUtil.addUrlParameters(sb, m_targetParameters, true);
} else {
sb.append(m_jspPageName);
}
setHref(sb.toString()); // Append URL only, without WID
if(getClicked() == null && getNewWindowParameters() != null) {
//-- Generate an onclick javascript thingy to open the window to prevent popup blockers.
//-- We need a NEW window session. Create it,
RequestContextImpl ctx = (RequestContextImpl) PageContext.getRequestContext();
//-- Send a special JAVASCRIPT open command, containing the shtuff.
sb.setLength(0);
String wid = DomUtil.generateGUID();
sb.append("return DomUI.openWindow('");
if(m_jspPageName != null || !"".equals(m_jspPageName)) {
sb.append(ctx.getRelativePath(m_jspPageName));
if(m_targetParameters != null) {
DomUtil.addUrlParameters(sb, m_targetParameters, true);
}
} else {
sb.append(ctx.getRelativePath(m_targetClass.getName()));
sb.append(".ui?");
StringTool.encodeURLEncoded(sb, Constants.PARAM_CONVERSATION_ID);
sb.append('=');
sb.append(wid);
sb.append(".x");
if(m_targetParameters != null) {
DomUtil.addUrlParameters(sb, m_targetParameters, false);
}
}
sb.append("','");
sb.append(wid);
sb.append("','");
sb.append("resizable=");
sb.append(m_newWindowParameters.isResizable() ? "yes" : "no");
sb.append(",scrollbars=");
sb.append(m_newWindowParameters.isShowScrollbars() ? "yes" : "no");
sb.append(",toolbar=");
sb.append(m_newWindowParameters.isShowToolbar() ? "yes" : "no");
sb.append(",location=");
sb.append(m_newWindowParameters.isShowLocation() ? "yes" : "no");
sb.append(",directories=");
sb.append(m_newWindowParameters.isShowDirectories() ? "yes" : "no");
sb.append(",status=");
sb.append(m_newWindowParameters.isShowStatus() ? "yes" : "no");
sb.append(",menubar=");
sb.append(m_newWindowParameters.isShowMenubar() ? "yes" : "no");
sb.append(",copyhistory=");
sb.append(m_newWindowParameters.isCopyhistory() ? "yes" : "no");
if(m_newWindowParameters.getWidth() > 0) {
sb.append(",width=");
sb.append(m_newWindowParameters.getWidth());
}
if(m_newWindowParameters.getHeight() > 0) {
sb.append(",height=");
sb.append(m_newWindowParameters.getHeight());
}
sb.append("');");
setOnClickJS(sb.toString());
}
}
/**
* Generate string link to thing.
*
* @param jspPageName
* @param pageParameters
* @return
*/
public static String generatePageUrl(String jspPageName, PageParameters pageParameters) {
StringBuilder sb = new StringBuilder();
RequestContextImpl ctx = (RequestContextImpl) PageContext.getRequestContext();
sb.append(ctx.getRelativePath(jspPageName));
if(pageParameters != null) {
DomUtil.addUrlParameters(sb, pageParameters, true);
}
return sb.toString();
}
@Override
public boolean internalNeedClickHandler() {
return getClicked() != null || getNewWindowParameters() == null;
}
/**
* Overridden click handler. If no specific onClick handler is configured we handle the click by
* moving to the specified page within the same window session.
*
* @see to.etc.domui.dom.html.NodeBase#internalOnClicked()
*/
@Override
public void internalOnClicked() throws Exception {
if(getClicked() != null) {
super.internalOnClicked();
return;
}
//-- Default action.
if(m_targetClass == null)
return;
//-- Is this a WINDOWED link?
if(m_newWindowParameters != null) {
//-- We need a NEW window session. Create it,
RequestContextImpl ctx = (RequestContextImpl) PageContext.getRequestContext();
WindowSession cm = ctx.getSession().createWindowSession();
//-- Send a special JAVASCRIPT open command, containing the shtuff.
StringBuilder sb = new StringBuilder();
sb.append("DomUI.openWindow('");
sb.append(ctx.getRelativePath(m_targetClass.getName()));
sb.append(".ui?");
StringTool.encodeURLEncoded(sb, Constants.PARAM_CONVERSATION_ID);
sb.append('=');
sb.append(cm.getWindowID());
sb.append(".x");
if(m_targetParameters != null)
DomUtil.addUrlParameters(sb, m_targetParameters, false);
sb.append("','");
sb.append(cm.getWindowID());
sb.append("','");
sb.append("resizable=");
sb.append(m_newWindowParameters.isResizable() ? "yes" : "no");
sb.append(",scrollbars=");
sb.append(m_newWindowParameters.isShowScrollbars() ? "yes" : "no");
sb.append(",toolbar=");
sb.append(m_newWindowParameters.isShowToolbar() ? "yes" : "no");
sb.append(",location=");
sb.append(m_newWindowParameters.isShowLocation() ? "yes" : "no");
sb.append(",directories=");
sb.append(m_newWindowParameters.isShowDirectories() ? "yes" : "no");
sb.append(",status=");
sb.append(m_newWindowParameters.isShowStatus() ? "yes" : "no");
sb.append(",menubar=");
sb.append(m_newWindowParameters.isShowMenubar() ? "yes" : "no");
sb.append(",copyhistory=");
sb.append(m_newWindowParameters.isCopyhistory() ? "yes" : "no");
if(m_newWindowParameters.getWidth() > 0) {
sb.append(",width=");
sb.append(m_newWindowParameters.getWidth());
}
if(m_newWindowParameters.getHeight() > 0) {
sb.append(",height=");
sb.append(m_newWindowParameters.getHeight());
}
sb.append("');");
appendJavascript(sb.toString());
return;
}
//-- Normal link; moveTo.
PageContext.getRequestContext().getWindowSession().internalSetNextPage(m_moveMode, m_targetClass, null, null, m_targetParameters);
}
}
|
package flickr.usth.edu.com;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class CameraActivity extends AppCompatActivity {
// LogCat tag
private static final String TAG = CameraActivity.class.getSimpleName();
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
private Button btnCapturePicture, btnRecordVideo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// Changing action bar background color
// These two lines are not needed
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
// Capture image onClick
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
// Record video onClick
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// record video
recordVideo();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
// Checking device has camera hardware or not
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
// Launch camera
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Store the file url as it will be null after returning from camera
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// launching upload activity
// launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// launching upload activity
// launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package vikingrobotics;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.camera.AxisCameraException;
import edu.wpi.first.wpilibj.image.NIVisionException;
/**
*
* @author Neal
*/
public class Camera implements Constants {
Robot1777 r;
AxisCamera cam;
/**
* Camera constructor
*
*/
public Camera(Robot1777 r) {
this.r = r;
}
/**
* Initialize the camera.
*
* Set brightness; Rotate the camera to 180 degrees;
* Set resolution to 640 x 480; Set white balance to automatic;
* Set Exposure Control to automatic; Set Exposure priority
* to frame rate.
*
*/
public void init() {
boolean cont = false;
Timer timer = new Timer();
timer.start();
cam = AxisCamera.getInstance();
while (!cont) {
try {
cam.getImage().free();
cont = true;
} catch (AxisCameraException e) {
if(Debug.getMode())
System.err.println("
} catch (NIVisionException e) {
if(Debug.getMode())
System.err.println("
}
}
timer.stop();
System.out.println("- Camera initialized in " + timer.get() + " seconds");
timer.reset();
timer.start();
cam.writeBrightness(50);
cam.writeRotation(AxisCamera.RotationT.k180);
cam.writeResolution(AxisCamera.ResolutionT.k640x480);
cam.writeWhiteBalance(AxisCamera.WhiteBalanceT.automatic);
cam.writeExposureControl(AxisCamera.ExposureT.automatic);
cam.writeExposurePriority(AxisCamera.ExposurePriorityT.frameRate);
timer.stop();
System.out.println("- Wrote camera settings in " + timer.get() + " seconds");
timer.reset();
}
}
|
package kbasesearchengine.test.main;
import java.util.Map;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.io.IOException;
import us.kbase.common.service.JsonClientException;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.google.common.base.Ticker;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableList;
import static kbasesearchengine.test.events.handler.WorkspaceEventHandlerTest.objTuple;
import static kbasesearchengine.test.events.handler.WorkspaceEventHandlerTest.compareObjInfo;
import static kbasesearchengine.test.events.handler.WorkspaceEventHandlerTest.compareObjInfoMap;
import static kbasesearchengine.test.common.TestCommon.set;
import kbasesearchengine.main.ObjectInfoProvider;
import kbasesearchengine.main.ObjectInfoCache;
import kbasesearchengine.test.common.TestCommon;
import us.kbase.common.service.Tuple11;
public class ObjectInfoCacheTest {
private final Tuple11<Long, String, String, String, Long, String,
Long, String, String, Long, Map<String, String>> obj_65_1_1_var1 =
objTuple(1L, "objName1", "sometype", "date1", 1L,"copier1",
65L, "wsname1", "checksum", 44, Collections.emptyMap());
private final Tuple11<Long, String, String, String, Long, String,
Long, String, String, Long, Map<String, String>> obj_65_1_1_var11 =
objTuple(1L, "objName11", "sometype", "date11", 1L, "copier11",
65L, "wsname11", "checksum", 44, Collections.emptyMap());
private final Tuple11<Long, String, String, String, Long, String,
Long, String, String, Long, Map<String, String>> obj_2_1_1_var2 =
objTuple(1L, "objName2", "sometype", "date2", 1L, "copier2",
2L, "wsname2", "checksum", 44, Collections.emptyMap());
private final Tuple11<Long, String, String, String, Long, String,
Long, String, String, Long, Map<String, String>> obj_2_1_1_var22 =
objTuple(1L, "objName22", "sometype", "date22", 1L, "copier22",
2L, "wsname22", "checksum", 44, Collections.emptyMap());
@SuppressWarnings("unchecked")
@Test
public void standardConstructorMultiLookup() throws Exception {
// test the non-test constructor
final ObjectInfoProvider wrapped = mock(ObjectInfoProvider.class);
final ObjectInfoCache cache = new ObjectInfoCache(
wrapped,
2,
10000);
when(wrapped.getObjectsInfo(set("65/1/1", "2/1/1"))).thenReturn(
ImmutableMap.of("65/1/1", obj_65_1_1_var1, "2/1/1", obj_2_1_1_var2),
ImmutableMap.of("65/1/1", obj_65_1_1_var11, "2/1/1", obj_2_1_1_var22),
null);
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"2/1/1", obj_2_1_1_var2,
"65/1/1", obj_65_1_1_var1));
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var1,
"2/1/1", obj_2_1_1_var2));
Thread.sleep(2001);
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var11,
"2/1/1", obj_2_1_1_var22));
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var11,
"2/1/1", obj_2_1_1_var22));
}
@SuppressWarnings("unchecked")
@Test
public void standardConstructorSingleLookup() throws Exception {
// test the non-test constructor
final ObjectInfoProvider wrapped = mock(ObjectInfoProvider.class);
final ObjectInfoCache cache = new ObjectInfoCache(
wrapped,
1,
10000);
when(wrapped.getObjectsInfo(ImmutableList.of("65/1/1"))).thenReturn(
ImmutableMap.of("65/1/1", obj_65_1_1_var1),
ImmutableMap.of("65/1/1", obj_65_1_1_var11),
null);
when(wrapped.getObjectInfo("65/1/1")).thenReturn(
obj_65_1_1_var1,
obj_65_1_1_var11,
null);
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var1);
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var1);
Thread.sleep(1001);
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var11);
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var11);
}
@SuppressWarnings("unchecked")
@Test
public void expiresEveryGet() throws Exception {
// test that expires the value from the cache every time
final ObjectInfoProvider wrapped = mock(ObjectInfoProvider.class);
final Ticker ticker = mock(Ticker.class);
final ObjectInfoCache cache = new ObjectInfoCache(
wrapped,
10,
10000,
ticker);
when(wrapped.getObjectsInfo(set("65/1/1", "2/1/1"))).thenReturn(
ImmutableMap.of(
"65/1/1", obj_65_1_1_var1,
"2/1/1", obj_2_1_1_var2),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var11,
"2/1/1", obj_2_1_1_var22),
null);
when(ticker.read()).thenReturn(0L, 10000000001L, 20000000001L);
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var1,
"2/1/1", obj_2_1_1_var2));
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var11,
"2/1/1", obj_2_1_1_var22));
}
@SuppressWarnings("unchecked")
@Test
public void cacheLookupException() throws Exception {
// test the non-test constructor
final ObjectInfoProvider wrapped = mock(ObjectInfoProvider.class);
final Ticker ticker = mock(Ticker.class);
final ObjectInfoCache cache = new ObjectInfoCache(
wrapped,
10,
10000,
ticker);
try {
cache.getObjectInfo("65/1/1");
fail("CacheLoader DID NOT throw an exception for a lookup of non-existing key.");
} catch (Exception e) {
assertThat(e.getMessage(), is("CacheLoader returned null for key 65/1/1."));
}
}
@SuppressWarnings("unchecked")
@Test
public void cacheAccessOnGet() throws Exception {
// test that the cache is accessed when available
final ObjectInfoProvider wrapped = mock(ObjectInfoProvider.class);
final Ticker ticker = mock(Ticker.class);
final ObjectInfoCache cache = new ObjectInfoCache(
wrapped,
10,
10000,
ticker);
when(wrapped.getObjectsInfo(ImmutableList.of("65/1/1"))).thenReturn(
ImmutableMap.of("65/1/1", obj_65_1_1_var1),
ImmutableMap.of("65/1/1", obj_65_1_1_var11),
null);
when(wrapped.getObjectInfo("65/1/1")).thenReturn(
obj_65_1_1_var1,
obj_65_1_1_var11,
null);
when(ticker.read()).thenReturn(0L, 5000000001L, 10000000001L, 15000000001L, 20000000001L);
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var1);
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var1);
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var11);
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var11);
}
@SuppressWarnings("unchecked")
@Test
public void cacheAccessOnGetMultiple() throws Exception {
// test that the cache is accessed when available
final ObjectInfoProvider wrapped = mock(ObjectInfoProvider.class);
final Ticker ticker = mock(Ticker.class);
final ObjectInfoCache cache = new ObjectInfoCache(
wrapped,
10,
10000,
ticker);
when(wrapped.getObjectsInfo(set("65/1/1", "2/1/1"))).thenReturn(
ImmutableMap.of(
"65/1/1", obj_65_1_1_var1,
"2/1/1", obj_2_1_1_var2),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var11,
"2/1/1", obj_2_1_1_var22),
null);
when(ticker.read()).thenReturn(0L, 0L, 5000000001L, 5000000001L, 10000000001L, 10000000001L,
15000000001L, 15000000001L, 20000000001L, 20000000001L);
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var1,
"2/1/1", obj_2_1_1_var2));
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var1,
"2/1/1", obj_2_1_1_var2));
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var11,
"2/1/1", obj_2_1_1_var22));
compareObjInfoMap(cache.getObjectsInfo(set("65/1/1", "2/1/1")),
ImmutableMap.of(
"65/1/1", obj_65_1_1_var11,
"2/1/1", obj_2_1_1_var22));
}
@SuppressWarnings("unchecked")
@Test
public void expiresOnSize() throws Exception {
// test that the cache expires values when it reaches the max size
final ObjectInfoProvider wrapped = mock(ObjectInfoProvider.class);
final ObjectInfoCache cache = new ObjectInfoCache(wrapped, 10000, 16);
when(wrapped.getObjectInfo("65/1/1")).thenReturn(
obj_65_1_1_var1,
obj_65_1_1_var11,
null);
when(wrapped.getObjectInfo("2/1/1")).thenReturn(
obj_2_1_1_var2,
obj_2_1_1_var22,
null);
// load 22 object infos into a max 16 cache
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var1);
// check cache access
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var1);
// force an expiration based on cache size
compareObjInfo(cache.getObjectInfo("2/1/1"), obj_2_1_1_var2);
// check that with every access, the oldest value had expired
compareObjInfo(cache.getObjectInfo("65/1/1"), obj_65_1_1_var11);
compareObjInfo(cache.getObjectInfo("2/1/1"), obj_2_1_1_var22);
}
@Test
public void constructFail() throws Exception {
final ObjectInfoProvider wrapped = mock(ObjectInfoProvider.class);
failConstruct(null, 10, 10, new NullPointerException("provider"));
failConstruct(wrapped, 0, 10,
new IllegalArgumentException("cache lifetime must be at least one second"));
failConstruct(wrapped, 10, 0,
new IllegalArgumentException("cache size must be at least one"));
}
private void failConstruct(
final ObjectInfoProvider provider,
final int lifetimeSec,
final int size,
final Exception exception) {
try {
new ObjectInfoCache(provider, lifetimeSec, size);
fail("expected exception");
} catch (Exception got) {
TestCommon.assertExceptionCorrect(got, exception);
}
}
@Test
public void getFailIOE() throws Exception {
final ObjectInfoProvider wrapped = mock(ObjectInfoProvider.class);
final ObjectInfoCache cache = new ObjectInfoCache(wrapped, 10000, 10);
when(wrapped.getObjectsInfo(set("65/1/1"))).thenThrow(new IOException("Test Exception Message"));
failFindObjectInfo(cache, ImmutableList.of("65/1/1"), new IOException("Test Exception Message"));
}
private void failFindObjectInfo(
final ObjectInfoCache cache,
final ImmutableList<String> objRefs,
final Exception expected) {
try {
cache.getObjectsInfo(objRefs);
fail("expected exception");
} catch (Exception got) {
TestCommon.assertExceptionCorrect(got, expected);
}
}
}
|
package org.jaexcel.framework.JAEX.engine;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jaexcel.framework.JAEX.annotation.XlsConfiguration;
import org.jaexcel.framework.JAEX.annotation.XlsDecorator;
import org.jaexcel.framework.JAEX.annotation.XlsDecorators;
import org.jaexcel.framework.JAEX.annotation.XlsElement;
import org.jaexcel.framework.JAEX.annotation.XlsNestedHeader;
import org.jaexcel.framework.JAEX.annotation.XlsSheet;
import org.jaexcel.framework.JAEX.configuration.Configuration;
import org.jaexcel.framework.JAEX.definition.ExceptionMessage;
import org.jaexcel.framework.JAEX.definition.ExtensionFileType;
import org.jaexcel.framework.JAEX.definition.PropagationType;
import org.jaexcel.framework.JAEX.exception.ConfigurationException;
import org.jaexcel.framework.JAEX.exception.ConverterException;
import org.jaexcel.framework.JAEX.exception.ElementException;
import org.jaexcel.framework.JAEX.exception.SheetException;
public class Engine implements IEngine {
// Workbook wb;
@Deprecated
Configuration configuration;
// CellDecorator headerDecorator;
// Map<String, CellStyle> stylesMap = new HashMap<String, CellStyle>();
// Map<String, CellDecorator> cellDecoratorMap = new HashMap<String,
// CellDecorator>();
/**
* Get the runtime class of the object passed as parameter.
*
* @param object
* the object
* @return the runtime class
* @throws ElementException
*/
private Class<?> initializeRuntimeClass(Object object) throws ElementException {
Class<?> oC = null;
try {
/* instance object class */
oC = object.getClass();
} catch (Exception e) {
throw new ElementException(ExceptionMessage.ElementException_NullObject.getMessage(), e);
}
return oC;
}
/**
* Initialize the configuration to apply at the Excel.
*
* @param oC
* the {@link Class<?>}
* @return
* @throws ConfigurationException
*/
private void initializeConfigurationData(ConfigCriteria configCriteria, Class<?> oC) throws ConfigurationException {
/* Process @XlsConfiguration */
if (oC.isAnnotationPresent(XlsConfiguration.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) oC.getAnnotation(XlsConfiguration.class);
initializeConfiguration(configCriteria, xlsAnnotation);
} else {
throw new ConfigurationException(
ExceptionMessage.ConfigurationException_XlsConfigurationMissing.getMessage());
}
/* Process @XlsSheet */
if (oC.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) oC.getAnnotation(XlsSheet.class);
initializeSheetConfiguration(configCriteria, xlsAnnotation);
} else {
throw new ConfigurationException(ExceptionMessage.ConfigurationException_XlsSheetMissing.getMessage());
}
}
/**
* Add the main xls configuration.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param annotation
* the {@link XlsConfiguration}
* @return
*/
private void initializeConfiguration(ConfigCriteria configCriteria, XlsConfiguration annotation) {
configCriteria.setFileName(annotation.nameFile());
configCriteria.setCompleteFileName(annotation.nameFile() + annotation.extensionFile().getExtension());
configCriteria.setExtension(annotation.extensionFile());
}
/**
* Add the sheet configuration.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param annotation
* the {@link XlsSheet}
* @return
*/
private void initializeSheetConfiguration(ConfigCriteria configCriteria, XlsSheet annotation) {
configCriteria.setTitleSheet(annotation.title());
configCriteria.setPropagation(annotation.propagation());
configCriteria.setStartRow(annotation.startRow());
configCriteria.setStartCell(annotation.startCell());
}
/**
* Initialize the configuration to apply at the Excel.
*
* @param oC
* the {@link Class<?>}
* @return
*/
@Deprecated
private Configuration initializeConfigurationData(Class<?> oC) {
Configuration config = null;
/* Process @XlsConfiguration */
if (oC.isAnnotationPresent(XlsConfiguration.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) oC.getAnnotation(XlsConfiguration.class);
config = initializeConfiguration(xlsAnnotation);
}
/* Process @XlsSheet */
if (oC.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) oC.getAnnotation(XlsSheet.class);
config = initializeSheetConfiguration(xlsAnnotation);
}
return config;
}
/**
* Add the main xls configuration.
*
* @param config
* the {@link XlsConfiguration}
* @return
*/
@Deprecated
private Configuration initializeConfiguration(XlsConfiguration config) {
if (configuration == null) {
configuration = new Configuration();
}
configuration.setName(config.nameFile());
configuration.setNameFile(config.nameFile() + config.extensionFile().getExtension());
configuration.setExtensionFile(config.extensionFile());
return configuration;
}
/**
* Add the sheet configuration.
*
* @param config
* the {@link XlsSheet}
* @return
*/
@Deprecated
private Configuration initializeSheetConfiguration(XlsSheet config) {
if (configuration == null) {
configuration = new Configuration();
}
configuration.setTitleSheet(config.title());
configuration.setPropagationType(config.propagation());
configuration.setStartRow(config.startRow());
configuration.setStartCell(config.startCell());
return configuration;
}
/**
* Initialize Workbook.
*
* @param type
* the {@link ExtensionFileType} of workbook
* @return the {@link Workbook}.
*/
private Workbook initializeWorkbook(ExtensionFileType type) {
if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) {
return new HSSFWorkbook();
} else {
return new XSSFWorkbook();
}
}
/**
* Initialize Workbook from FileInputStream.
*
* @param inputStream
* the file input stream
* @param type
* the {@link ExtensionFileType} of workbook
* @return the {@link Workbook} created
* @throws IOException
*/
private Workbook initializeWorkbook(FileInputStream inputStream, ExtensionFileType type) throws IOException {
if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) {
return new HSSFWorkbook(inputStream);
} else {
return new XSSFWorkbook(inputStream);
}
}
/**
* Initialize Workbook from byte[].
*
* @param byteArray
* the array of bytes
* @param type
* the {@link ExtensionFileType} of workbook
* @return the {@link Workbook} created
* @throws IOException
*/
private Workbook initializeWorkbook(byte[] byteArray, ExtensionFileType type) throws IOException {
if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) {
return new HSSFWorkbook(new ByteArrayInputStream(byteArray));
} else {
return new XSSFWorkbook(new ByteArrayInputStream(byteArray));
}
}
/**
* Initialize Sheet.
*
* @param wb
* the {@link Workbook} to use
* @param sheetName
* the name of the sheet
* @return the {@link Sheet} created
* @throws SheetException
*/
private Sheet initializeSheet(Workbook wb, String sheetName) throws SheetException {
Sheet s = null;
try {
s = wb.createSheet(sheetName);
} catch (Exception e) {
throw new SheetException(ExceptionMessage.SheetException_CreationSheet.getMessage(), e);
}
return s;
}
/**
* Validate if the nested header configuration is valid.
*
* @param isPH
* true if propagation is HORIZONTAL otherwise false to
* propagation VERTICAL
* @param annotation
* the {@link XlsNestedHeader} annotation
* @throws ConfigurationException
*/
private void isValidNestedHeaderConfiguration(boolean isPH, XlsNestedHeader annotation)
throws ConfigurationException {
if (isPH && annotation.startX() == annotation.endX()) {
throw new ConfigurationException(ExceptionMessage.ConfigurationException_Conflict.getMessage());
} else if (!isPH && annotation.startY() == annotation.endY()) {
throw new ConfigurationException(ExceptionMessage.ConfigurationException_Conflict.getMessage());
}
}
/**
* Apply merge region if necessary.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param r
* the {@link Row}
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param isPH
* true if propagation horizontally, false if propagation
* vertically
*/
private void applyMergeRegion(ConfigCriteria configCriteria, Row r, int idxR, int idxC, boolean isPH)
throws Exception {
/* Process @XlsNestedHeader */
if (configCriteria.getField().isAnnotationPresent(XlsNestedHeader.class)) {
XlsNestedHeader annotation = (XlsNestedHeader) configCriteria.getField()
.getAnnotation(XlsNestedHeader.class);
/* if row null is necessary to create it */
if (r == null) {
r = initializeRow(configCriteria.getSheet(), idxR);
}
/* validation of configuration */
isValidNestedHeaderConfiguration(isPH, annotation);
/* prepare position rows / cells */
int startRow, endRow, startCell, endCell;
if (isPH) {
startRow = endRow = idxR;
startCell = idxC + annotation.startX();
endCell = idxC + annotation.endX();
} else {
startRow = idxR + annotation.startY();
endRow = idxR + annotation.endY();
startCell = endCell = idxC;
}
/* initialize master header cell */
CellStyleUtils.initializeHeaderCell(configCriteria.getStylesMap(), r, startCell, annotation.title());
/* merge region of the master header cell */
configCriteria.getSheet().addMergedRegion(new CellRangeAddress(startRow, endRow, startCell, endCell));
}
}
/**
* Initialize an row.
*
* @param s
* the {@link Sheet} to add the row
* @param idxR
* position of the new row
* @return the {@link Row} created
*/
private Row initializeRow(Sheet s, int idxR) {
return s.createRow(idxR);
}
/**
* Initialize an cell according the type of field and the PropagationType is
* PROPAGATION_HORIZONTAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return in case of the object return the number of cell created,
* otherwise 0
* @throws Exception
*/
private int initializeCellByFieldHorizontal(ConfigCriteria configCriteria, Object o, int idxR, int idxC, int cL)
throws Exception {
int counter = 0;
// FIXME uncomment line to activate cascade level
// if (cL <= configCriteria.getCascadeLevel().getCode()) {
/* make the field accessible to recover the value */
configCriteria.getField().setAccessible(true);
Class<?> fT = configCriteria.getField().getType();
boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC);
if (!isAppliedObject && !fT.isPrimitive()) {
Object nO = configCriteria.getField().get(o);
/* manage null objects */
if (nO == null) {
nO = fT.newInstance();
}
Class<?> oC = nO.getClass();
counter = marshalAsPropagationHorizontal(configCriteria, nO, oC, idxR, idxC - 1, cL + 1);
}
// FIXME uncomment line to activate cascade level
return counter;
}
/**
* Initialize an cell according the type of field and the PropagationType is
* PROPAGATION_VERTICAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param r
* the content row
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return
* @throws Exception
*/
private int initializeCellByFieldVertical(ConfigCriteria configCriteria, Object o, Row r, int idxR, int idxC,
int cL) throws Exception {
int counter = 0;
// FIXME uncomment line to activate cascade level
// if (cL <= configCriteria.getCascadeLevel().getCode()) {
/* make the field accessible to recover the value */
configCriteria.getField().setAccessible(true);
Class<?> fT = configCriteria.getField().getType();
configCriteria.setRow(r);
boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC);
if (!isAppliedObject && !fT.isPrimitive()) {
Object nO = configCriteria.getField().get(o);
/* manage null objects */
if (nO == null) {
nO = fT.newInstance();
}
Class<?> oC = nO.getClass();
counter = marshalAsPropagationVertical(configCriteria, nO, oC, idxR - 1, idxC - 1, cL + 1);
}
// FIXME uncomment line to activate cascade level
return counter;
}
private boolean toExcel(ConfigCriteria configCriteria, Object o, Class<?> fT, int idxC)
throws IllegalArgumentException, IllegalAccessException, ConverterException, NoSuchMethodException,
SecurityException, InvocationTargetException {
/* flag which define if the cell was updated or not */
boolean isUpdated = false;
/* initialize cell */
Cell cell = null;
switch (fT.getName()) {
case CellValueUtils.OBJECT_DATE:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toDate(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_STRING:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toString(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_INTEGER:
/* falls through */
case CellValueUtils.PRIMITIVE_INTEGER:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toInteger(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_LONG:
/* falls through */
case CellValueUtils.PRIMITIVE_LONG:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toLong(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_DOUBLE:
/* falls through */
case CellValueUtils.PRIMITIVE_DOUBLE:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toDouble(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_BIGDECIMAL:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toBigDecimal(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_FLOAT:
/* falls through */
case CellValueUtils.PRIMITIVE_FLOAT:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toFloat(configCriteria, o, cell);
break;
case CellValueUtils.OBJECT_BOOLEAN:
/* falls through */
case CellValueUtils.PRIMITIVE_BOOLEAN:
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toBoolean(configCriteria, o, cell);
break;
default:
isUpdated = false;
break;
}
if (!isUpdated && fT.isEnum()) {
cell = configCriteria.getRow().createCell(idxC);
isUpdated = CellValueUtils.toEnum(configCriteria, o, cell);
}
return isUpdated;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private boolean toObject(Object o, Class<?> fT, Field f, Cell c, XlsElement xlsAnnotation)
throws IllegalArgumentException, IllegalAccessException, ConverterException {
/* flag which define if the cell was updated or not */
boolean isUpdated = false;
f.setAccessible(true);
switch (fT.getName()) {
case CellValueUtils.OBJECT_DATE:
// FIXME review the management
if (StringUtils.isBlank(xlsAnnotation.transformMask())) {
f.set(o, c.getDateCellValue());
} else {
String date = c.getStringCellValue();
if (StringUtils.isNotBlank(date)) {
String tM = xlsAnnotation.transformMask();
String fM = xlsAnnotation.formatMask();
String decorator = StringUtils.isEmpty(tM)
? (StringUtils.isEmpty(fM) ? CellStyleUtils.MASK_DECORATOR_DATE : fM) : tM;
SimpleDateFormat dt = new SimpleDateFormat(decorator);
try {
Date dateConverted = dt.parse(date);
f.set(o, dateConverted);
} catch (ParseException e) {
/*
* if date decorator do not match with a valid mask
* launch exception
*/
throw new ConverterException(ExceptionMessage.ConverterException_Date.getMessage(), e);
}
}
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_STRING:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, CellValueUtils.fromExcel(c));
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_INTEGER:
/* falls through */
case CellValueUtils.PRIMITIVE_INTEGER:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)).intValue());
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_LONG:
/* falls through */
case CellValueUtils.PRIMITIVE_LONG:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)).longValue());
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_DOUBLE:
/* falls through */
case CellValueUtils.PRIMITIVE_DOUBLE:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c).replace(",", ".")));
} else {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)));
}
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_BIGDECIMAL:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
f.set(o, BigDecimal.valueOf(Double.valueOf(CellValueUtils.fromExcel(c).replace(",", "."))));
} else {
f.set(o, BigDecimal.valueOf(Double.valueOf(CellValueUtils.fromExcel(c))));
}
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_FLOAT:
/* falls through */
case CellValueUtils.PRIMITIVE_FLOAT:
if (StringUtils.isNotBlank(CellValueUtils.fromExcel(c))) {
f.set(o, Double.valueOf(CellValueUtils.fromExcel(c)).floatValue());
}
isUpdated = true;
break;
case CellValueUtils.OBJECT_BOOLEAN:
/* falls through */
case CellValueUtils.PRIMITIVE_BOOLEAN:
String booleanValue = c.getStringCellValue();
if (StringUtils.isNotBlank(booleanValue)) {
if (StringUtils.isNotBlank(xlsAnnotation.transformMask())) {
/* apply format mask defined at transform mask */
String[] split = xlsAnnotation.transformMask().split("/");
f.set(o, StringUtils.isNotBlank(booleanValue) ? (split[0].equals(booleanValue) ? true : false)
: null);
} else {
/* locale mode */
f.set(o, StringUtils.isNotBlank(booleanValue) ? Boolean.valueOf(booleanValue) : null);
}
}
isUpdated = true;
break;
default:
isUpdated = false;
break;
}
if (!isUpdated && fT.isEnum()) {
if (StringUtils.isNotBlank(c.getStringCellValue())) {
f.set(o, Enum.valueOf((Class<Enum>) fT, c.getStringCellValue()));
}
isUpdated = true;
}
return isUpdated;
}
private int marshalAsPropagationHorizontal(ConfigCriteria configCriteria, Object o, Class<?> oC, int idxR, int idxC,
int cL) throws Exception {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* get declared fields */
List<Field> fL = Arrays.asList(oC.getDeclaredFields());
for (Field f : fL) {
/* update field at ConfigCriteria */
configCriteria.setField(f);
/* process each field from the object */
if (configCriteria.getRowHeader() != null) {
/* calculate index of the cell */
int tmpIdxRow = idxR - 3;
/* apply merge region */
applyMergeRegion(configCriteria, null, tmpIdxRow, idxC, true);
}
/* Process @XlsElement */
if (f.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);
/* update annotation at ConfigCriteria */
configCriteria.setElement(xlsAnnotation);
/* apply customized rules defined at the object */
if (StringUtils.isNotBlank(xlsAnnotation.customizedRules())) {
CellValueUtils.applyCustomizedRules(o, xlsAnnotation.customizedRules());
}
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
if (configCriteria.getRowHeader() != null) {
/* header treatment */
CellStyleUtils.initializeHeaderCell(configCriteria.getStylesMap(), configCriteria.getRowHeader(),
idxC + xlsAnnotation.position(), xlsAnnotation.title());
}
/* content treatment */
idxC += initializeCellByFieldHorizontal(configCriteria, o, idxR, idxC + xlsAnnotation.position(), cL);
}
}
return counter;
}
/**
* Convert the object to file with the PropagationType as
* PROPAGATION_VERTICAL.
*
* @param configCriteria
* the {@link ConfigCriteria}
* @param o
* the object
* @param oC
* the object class
* @param idxR
* the position of the row
* @param idxC
* the position of the cell
* @param cL
* the cascade level
* @return
* @throws Exception
*/
private int marshalAsPropagationVertical(ConfigCriteria configCriteria, Object o, Class<?> oC, int idxR, int idxC,
int cL) throws Exception {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* backup base index of the cell */
int baseIdxCell = idxC;
/* get declared fields */
List<Field> fieldList = Arrays.asList(oC.getDeclaredFields());
for (Field field : fieldList) {
/* process each field from the object */
configCriteria.setField(field);
/* restart the index of the cell */
idxC = baseIdxCell;
/* Process @XlsElement */
if (field.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) field.getAnnotation(XlsElement.class);
configCriteria.setElement(xlsAnnotation);
/* apply customized rules defined at the object */
if (StringUtils.isNotBlank(xlsAnnotation.customizedRules())) {
CellValueUtils.applyCustomizedRules(o, xlsAnnotation.customizedRules());
}
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
/* create the row */
Row row = null;
if (baseIdxCell == 1) {
int tmpIdxCell = idxC - 1;
/* initialize row */
row = initializeRow(configCriteria.getSheet(), idxR + xlsAnnotation.position());
/* apply merge region */
applyMergeRegion(configCriteria, row, idxR, tmpIdxCell, false);
/* header treatment */
CellStyleUtils.initializeHeaderCell(configCriteria.getStylesMap(), row, idxC,
xlsAnnotation.title());
} else {
row = configCriteria.getSheet().getRow(idxR + xlsAnnotation.position());
}
/* increment the cell position */
idxC++;
/* content treatment */
idxR += initializeCellByFieldVertical(configCriteria, o, row, idxR + xlsAnnotation.position(), idxC,
cL);
}
}
return counter;
}
private int unmarshalAsPropagationHorizontal(ConfigCriteria configCriteria, Object o, Class<?> oC, int idxR,
int idxC) throws IllegalAccessException, ConverterException, InstantiationException {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* get declared fields */
List<Field> fL = Arrays.asList(oC.getDeclaredFields());
for (Field f : fL) {
/* process each field from the object */
Class<?> fT = f.getType();
/* Process @XlsElement */
if (f.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
/* content row */
Row contentRow = configCriteria.getSheet().getRow(idxR + 1);
Cell contentCell = contentRow.getCell(idxC + xlsAnnotation.position());
boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation);
if (!isAppliedToBaseObject && !fT.isPrimitive()) {
Object subObjbect = fT.newInstance();
Class<?> subObjbectClass = subObjbect.getClass();
int internalCellCounter = unmarshalAsPropagationHorizontal(configCriteria, subObjbect,
subObjbectClass, idxR, idxC + xlsAnnotation.position() - 1);
/* add the sub object to the parent object */
f.set(o, subObjbect);
/* update the index */
idxC += internalCellCounter;
}
}
}
return counter;
}
private int unmarshalAsPropagationVertical(ConfigCriteria configCriteria, Object object, Class<?> oC, int idxR,
int idxC) throws IllegalAccessException, ConverterException, InstantiationException {
/* counter related to the number of fields (if new object) */
int counter = -1;
/* get declared fields */
List<Field> fL = Arrays.asList(oC.getDeclaredFields());
for (Field f : fL) {
/* process each field from the object */
Class<?> fT = f.getType();
/* Process @XlsElement */
if (f.isAnnotationPresent(XlsElement.class)) {
XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);
/*
* increment of the counter related to the number of fields (if
* new object)
*/
counter++;
/* content row */
Row contentRow = configCriteria.getSheet().getRow(idxR + xlsAnnotation.position());
Cell contentCell = contentRow.getCell(idxC + 1);
boolean isAppliedToBaseObject = toObject(object, fT, f, contentCell, xlsAnnotation);
if (!isAppliedToBaseObject && !fT.isPrimitive()) {
Object subObjbect = fT.newInstance();
Class<?> subObjbectClass = subObjbect.getClass();
int internalCellCounter = unmarshalAsPropagationVertical(configCriteria, subObjbect,
subObjbectClass, idxR + xlsAnnotation.position() - 1, idxC);
/* add the sub object to the parent object */
f.set(object, subObjbect);
/* update the index */
idxR += internalCellCounter;
}
}
}
return counter;
}
/**
* Generate file output stream.
*
* @param wb
* the {@link Workbook}
* @param name
* the name
* @return
* @throws Exception
*/
private FileOutputStream workbookFileOutputStream(Workbook wb, String name) throws Exception {
FileOutputStream output = new FileOutputStream(name);
wb.write(output);
output.close();
return output;
}
/**
* Generate the byte array.
*
* @param wb
* the {@link Workbook}
* @return the byte[]
* @throws IOException
*/
private byte[] workbookToByteAray(Workbook wb) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
wb.write(bos);
} finally {
bos.close();
}
return bos.toByteArray();
}
/**
* Generate the workbook based at the {@link ConfigCriteria} and the object
* passed as parameters.
*
* @param configCriteria
* the {@link ConfigCriteria} to use.
* @param object
* the object to apply at the workbook.
* @throws ElementException
* @throws ConfigurationException
* @throws SheetException
* @throws Exception
*/
private void marshalEngine(ConfigCriteria configCriteria, Object object)
throws ElementException, ConfigurationException, SheetException, Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
// ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/* initialize Workbook */
configCriteria.setWorkbook(initializeWorkbook(configCriteria.getExtension()));
/* initialize style cell via annotations */
if (oC.isAnnotationPresent(XlsDecorators.class)) {
XlsDecorators xlsDecorators = (XlsDecorators) oC.getAnnotation(XlsDecorators.class);
for (XlsDecorator decorator : xlsDecorators.values()) {
configCriteria.getStylesMap().put(decorator.decoratorName(),
CellStyleUtils.initializeCellStyleByXlsDecorator(configCriteria.getWorkbook(), decorator));
}
}
/* initialize style cell via default option */
configCriteria.initializeCellDecorator();
// configCriteria.setStylesMap(stylesMap);
/* initialize Sheet */
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), configCriteria.getTitleSheet()));
/* initialize Row & Cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
/* initialize rows according the PropagationType */
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++));
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
marshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell, 0);
} else {
marshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell, 0);
}
// FIXME apply the column size here - if necessary
}
/**
* Extract from the workbook based at the {@link ConfigCriteria} and the
* object passed as parameters.
*
* @param configCriteria
* the {@link ConfigCriteria} to use.
* @param object
* the object to apply at the workbook.
* @param oC
* the object class
* @throws Exception
*/
private void unmarshalEngine(ConfigCriteria configCriteria, Object object, Class<?> oC) throws Exception {
/* initialize sheet */
configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
/* initialize index row & cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
} else {
unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
}
}
/**
* Generate the sheet based at the object passed as parameter and return the
* sheet generated.
*
* @param object
* the object to apply at the workbook.
* @return the {@link Sheet} generated
*/
public Sheet marshalToSheet(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook based at the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Sheet generated */
return configCriteria.getWorkbook().getSheetAt(0);
}
/**
* Generate the sheet based at the {@link ConfigCriteria} and the object
* passed as parameters and return the sheet generated.
*
* @param configCriteria
* the {@link ConfigCriteria} to use
* @param object
* the object to apply at the workbook.
* @return the {@link Sheet} generated
*/
public Sheet marshalToSheet(ConfigCriteria configCriteria, Object object) throws Exception {
/* Generate the workbook based at the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Sheet generated */
return configCriteria.getWorkbook().getSheetAt(0);
}
/**
* Generate the workbook based at the object passed as parameter and return
* the workbook generated.
*
* @param object
* the object to apply at the workbook.
* @return the {@link Workbook} generated
*/
public Workbook marshalToWorkbook(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook based at the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Workbook generated */
return configCriteria.getWorkbook();
}
/**
* Generate the workbook based at the {@link ConfigCriteria} and the object
* passed as parameters and return the workbook generated.
*
* @param configCriteria
* the {@link ConfigCriteria} to use
* @param object
* the object to apply at the workbook.
* @return the {@link Workbook} generated
*/
public Workbook marshalToWorkbook(ConfigCriteria configCriteria, Object object) throws Exception {
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/* Return the Workbook generated */
return configCriteria.getWorkbook();
}
/**
* Generate the workbook from the object passed as parameter and return the
* respective {@link FileOutputStream}.
*
* @param object
* the object to apply at the workbook.
* @return the {@link Workbook} generated
*/
public byte[] marshalToByte(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/* Generate the byte array to return */
return workbookToByteAray(configCriteria.getWorkbook());
}
/**
* Generate the workbook based at the object passed as parameters and save
* it at the path send as parameter.
*
* @param object
* the object to apply at the workbook.
* @param pathFile
* the file path where will be the file saved
*/
public void marshalAndSave(Object object, String pathFile) throws Exception {
/* Generate the workbook from the object passed as parameter */
ConfigCriteria configCriteria = new ConfigCriteria();
marshalAndSave(configCriteria, object, pathFile);
}
/**
* Generate the workbook based at the {@link ConfigCriteria} and the object
* passed as parameters and save it at the path send as parameter.
*
* @param configCriteria
* the {@link ConfigCriteria} to use
* @param object
* the object to apply at the workbook.
* @param pathFile
* the file path where will be the file saved
*/
public void marshalAndSave(ConfigCriteria configCriteria, Object object, String pathFile) throws Exception {
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/*
* check if the path terminate with the file separator, otherwise will
* be added to avoid any problem
*/
if (!pathFile.endsWith(File.separator)) {
pathFile = pathFile.concat(File.separator);
}
/* Save the Workbook at a specified path (received as parameter) */
workbookFileOutputStream(configCriteria.getWorkbook(), pathFile + configCriteria.getCompleteFileName());
}
/**
* Generate the workbook from the collection of objects.
*
* @param collection
* the collection of objects to apply at the workbook.
* @param filename
* the file name
* @param extensionFileType
* the file extension
* @throws Exception
*/
public void marshalAsCollection(Collection<?> collection, final String filename,
final ExtensionFileType extensionFileType) throws Exception {
// Temos que iniciar o config data neste ponto porque
// como estamos na escritura de uma coleccao
// temos que ter o nome e a extensao antes de iniciar o excel
configuration = new Configuration();
configuration.setExtensionFile(extensionFileType);
configuration.setNameFile(filename);
Configuration config = configuration;
ConfigCriteria configCriteria = new ConfigCriteria();
configCriteria.setPropagation(config.getPropagationType());
configCriteria.setExtension(config.getExtensionFile());
// initialize Workbook
configCriteria.setWorkbook(initializeWorkbook(config.getExtensionFile()));
// initialize style cell via default option
configCriteria.initializeCellDecorator();
// configCriteria.setStylesMap(stylesMap);
int idxRow = 0, idxCell = 0, index = 0;
@SuppressWarnings("rawtypes")
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
Object object = iterator.next();
// We get the class of the object
Class<?> objectClass = object.getClass();
// Process @XlsSheet
if (objectClass.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) objectClass.getAnnotation(XlsSheet.class);
config = initializeSheetConfiguration(xlsAnnotation);
}
// initialize rows according the PropagationType
if (PropagationType.PROPAGATION_HORIZONTAL.equals(config.getPropagationType())) {
idxCell = config.getStartCell();
if (configCriteria.getWorkbook().getNumberOfSheets() == 0
|| configCriteria.getWorkbook().getSheet(config.getTitleSheet()) == null) {
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), config.getTitleSheet()));
idxRow = config.getStartRow();
configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++));
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
} else {
idxRow = configCriteria.getSheet().getLastRowNum() + 1;
configCriteria.setRowHeader(null);
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
}
marshalAsPropagationHorizontal(configCriteria, object, objectClass, idxRow, idxCell, 0);
} else {
idxRow = config.getStartRow();
if (configCriteria.getWorkbook().getNumberOfSheets() == 0
|| configCriteria.getWorkbook().getSheet(config.getTitleSheet()) == null) {
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), config.getTitleSheet()));
idxCell = config.getStartCell();
} else {
idxCell = index + 1;
}
marshalAsPropagationVertical(configCriteria, object, objectClass, idxRow, idxCell, 0);
index = index + 1;
}
}
// FIXME manage return value
workbookFileOutputStream(configCriteria.getWorkbook(),
"D:\\projects\\" + config.getNameFile() + config.getExtensionFile().getExtension());
}
/**
* Generate the object from the workbook passed as parameter.
*
* @param object
* the object to fill up.
* @param workbook
* the {@link Workbook} to read and pass the information to the
* object
* @return the {@link Object} filled up
* @throws ConfigurationException
*/
public Object unmarshalFromWorkbook(Object object, Workbook workbook) throws Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/* set workbook */
configCriteria.setWorkbook(workbook);
/* Extract from the workbook to the object passed as parameter */
unmarshalEngine(configCriteria, object, oC);
return object;
}
/**
* Generate the object from the path file passed as parameter.
*
* @param object
* the object to fill up.
* @param pathFile
* the path where is found the file to read and pass the
* information to the object
* @return the {@link Object} filled up
*/
public Object unmarshalFromPath(Object object, String pathFile) throws Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/*
* check if the path terminate with the file separator, otherwise will
* be added to avoid any problem
*/
if (!pathFile.endsWith(File.separator)) {
pathFile = pathFile.concat(File.separator);
}
FileInputStream input = new FileInputStream(pathFile + configCriteria.getCompleteFileName());
/* set workbook */
configCriteria.setWorkbook(initializeWorkbook(input, configCriteria.getExtension()));
/* Extract from the workbook to the object passed as parameter */
unmarshalEngine(configCriteria, object, oC);
return object;
}
/**
* Generate the object from the byte array passed as parameter.
*
* @param object
* the object to fill up.
* @param inputByte
* the byte array to read and pass the information to the object
* @return the {@link Object} filled up
*/
public Object unmarshalFromByte(Object object, byte[] byteArray) throws Exception {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/* set workbook */
configCriteria.setWorkbook(initializeWorkbook(byteArray, configCriteria.getExtension()));
/* Extract from the workbook to the object passed as parameter */
unmarshalEngine(configCriteria, object, oC);
return object;
}
private void unmarshalIntern(Object object, Class<?> oC, ConfigCriteria configCriteria, FileInputStream input)
throws IOException, IllegalAccessException, ConverterException, InstantiationException, SheetException {
configCriteria.setWorkbook(initializeWorkbook(input, configCriteria.getExtension()));
configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet()));
// FIXME add manage sheet null
if (configCriteria.getSheet() == null) {
throw new SheetException(ExceptionMessage.SheetException_CreationSheet.getMessage());
}
/* initialize index row & cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell);
} else {
unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell);
}
}
@Override
public void marshalAsCollection(Collection<?> collection) {
// TODO Auto-generated method stub
}
@Override
public Collection<?> unmarshalToCollection(Object object) {
// TODO Auto-generated method stub
return null;
}
/**
* marshal
*
* @throws Exception
*/
@Deprecated
public void marshal(Object object) throws Exception {
Class<?> objectClass = object.getClass();
ConfigCriteria configCriteria = new ConfigCriteria();
/* Process @XlsConfiguration */
if (objectClass.isAnnotationPresent(XlsSheet.class)) {
XlsConfiguration xlsAnnotation = (XlsConfiguration) objectClass.getAnnotation(XlsConfiguration.class);
initializeConfiguration(configCriteria, xlsAnnotation);
}
/* Process @XlsSheet */
if (objectClass.isAnnotationPresent(XlsSheet.class)) {
XlsSheet xlsAnnotation = (XlsSheet) objectClass.getAnnotation(XlsSheet.class);
initializeSheetConfiguration(configCriteria, xlsAnnotation);
}
/* initialize Workbook */
configCriteria.setWorkbook(initializeWorkbook(configCriteria.getExtension()));
/* initialize style cell via annotations */
if (objectClass.isAnnotationPresent(XlsDecorators.class)) {
XlsDecorators xlsDecorators = (XlsDecorators) objectClass.getAnnotation(XlsDecorators.class);
for (XlsDecorator decorator : xlsDecorators.values()) {
configCriteria.getStylesMap().put(decorator.decoratorName(),
CellStyleUtils.initializeCellStyleByXlsDecorator(configCriteria.getWorkbook(), decorator));
}
}
/* initialize style cell via default option */
configCriteria.initializeCellDecorator();
/* initialize Sheet */
// FIXME add loop if necessary
configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), configCriteria.getTitleSheet()));
/* initialize Row & Cell */
int idxRow = configCriteria.getStartRow();
int idxCell = configCriteria.getStartCell();
/* initialize rows according the PropagationType */
if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) {
configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++));
configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++));
marshalAsPropagationHorizontal(configCriteria, object, objectClass, idxRow, idxCell, 0);
} else {
marshalAsPropagationVertical(configCriteria, object, objectClass, idxRow, idxCell, 0);
}
// FIXME manage return value
workbookFileOutputStream(configCriteria.getWorkbook(), "D:\\projects\\" + configCriteria.getFileName());
}
@Deprecated
public Object unmarshal(Object object) throws IOException, IllegalArgumentException, IllegalAccessException,
ConverterException, InstantiationException, ElementException, SheetException {
/* initialize the runtime class of the object */
Class<?> oC = initializeRuntimeClass(object);
/* initialize configuration data */
Configuration config = initializeConfigurationData(oC);
FileInputStream input = new FileInputStream("D:\\projects\\" + config.getNameFile());
unmarshalIntern(object, oC, new ConfigCriteria(), input);
return object;
}
/**
* Generate the workbook from the object passed as parameter and return the
* respective {@link FileOutputStream}.
*
* @param object
* the object to apply at the workbook.
* @return the {@link FileOutputStream} generated
*/
@Override
public FileOutputStream marshalToFileOutputStream(Object object) throws Exception {
/* Initialize a basic ConfigCriteria */
ConfigCriteria configCriteria = new ConfigCriteria();
/* Generate the workbook from the object passed as parameter */
marshalEngine(configCriteria, object);
/* Generate the FileOutputStream to return */
return workbookFileOutputStream(configCriteria.getWorkbook(), configCriteria.getFileName());
}
/**
* Generate the object from the {@link FileInputStream} passed as parameter.
*
* @param object
* the object to apply at the workbook.
* @param stream
* the {@link FileInputStream} to read
* @return the {@link Object} filled up
*/
@Override
public Object unmarshalFromFileInputStream(Object object, FileInputStream stream) throws Exception {
/* instance object class */
Class<?> oC = object.getClass();
/* initialize configuration data */
ConfigCriteria configCriteria = new ConfigCriteria();
initializeConfigurationData(configCriteria, oC);
/* set workbook */
configCriteria.setWorkbook(initializeWorkbook(stream, configCriteria.getExtension()));
unmarshalEngine(configCriteria, object, oC);
return object;
}
}
|
package water;
import static water.util.Utils.contains;
import hex.ConfusionMatrix;
import hex.VarImp;
import javassist.*;
import water.api.DocGen;
import water.api.Request.API;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.TransfVec;
import water.fvec.Vec;
import water.util.*;
import water.util.Log.Tag.Sys;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
/**
* A Model models reality (hopefully).
* A model can be used to 'score' a row, or a collection of rows on any
* compatible dataset - meaning the row has all the columns with the same names
* as used to build the mode.
*/
public abstract class Model extends Lockable<Model> {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
/** Dataset key used to *build* the model, for models for which this makes
* sense, or null otherwise. Not all models are built from a dataset (eg
* artificial models), or are built from a single dataset (various ensemble
* models), so this key has no *mathematical* significance in the model but
* is handy during common model-building and for the historical record. */
@API(help="Datakey used to *build* the model")
public final Key _dataKey;
/** Columns used in the model and are used to match up with scoring data
* columns. The last name is the response column name. */
@API(help="Column names used to build the model")
public final String _names[];
/** Categorical/factor/enum mappings, per column. Null for non-enum cols.
* The last column holds the response col enums. */
@API(help="Column names used to build the model")
public final String _domains[][];
@API(help = "Relative class distribution factors in original data")
final protected float[] _priorClassDist;
@API(help = "Relative class distribution factors used for model building")
protected float[] _modelClassDist;
public void setModelClassDistribution(float[] classdist) {
_modelClassDist = classdist.clone();
}
/** Full constructor from frame: Strips out the Vecs to just the names needed
* to match columns later for future datasets. */
public Model( Key selfKey, Key dataKey, Frame fr, float[] priorClassDist ) {
this(selfKey,dataKey,fr.names(),fr.domains(),priorClassDist);
}
/** Constructor from frame (without prior class dist): Strips out the Vecs to just the names needed
* to match columns later for future datasets. */
public Model( Key selfKey, Key dataKey, Frame fr ) {
this(selfKey,dataKey,fr.names(),fr.domains(),null);
}
/** Constructor without prior class distribution */
public Model( Key selfKey, Key dataKey, String names[], String domains[][]) {
this(selfKey,dataKey,names,domains,null);
}
/** Full constructor */
public Model( Key selfKey, Key dataKey, String names[], String domains[][], float[] priorClassDist ) {
super(selfKey);
if( domains == null ) domains=new String[names.length+1][];
assert domains.length==names.length;
assert names.length > 1;
assert names[names.length-1] != null; // Have a valid response-column name?
_dataKey = dataKey;
_names = names;
_domains = domains;
_priorClassDist = priorClassDist;
}
/** Simple shallow copy constructor to a new Key */
public Model( Key selfKey, Model m ) { this(selfKey,m._dataKey,m._names,m._domains); }
/** Remove any Model internal Keys */
@Override public Futures delete_impl(Futures fs) { return fs; /* None in the default Model */ }
@Override public String errStr() { return "Model"; }
public String responseName() { return _names[ _names.length-1]; }
public String[] classNames() { return _domains[_domains.length-1]; }
public boolean isClassifier() { return classNames() != null ; }
public int nclasses() {
String cns[] = classNames();
return cns==null ? 1 : cns.length;
}
/** Returns number of input features */
public int nfeatures() { return _names.length - 1; }
/** For classifiers, confusion matrix on validation set. */
public ConfusionMatrix cm() { return null; }
/** Returns mse for validation set. */
public double mse() { return Double.NaN; }
/** Variable importance of individual input features measured by this model. */
public VarImp varimp() { return null; }
/** Bulk score for given <code>fr<code> frame.
* The frame is always adapted to this model.
*
* @param fr frame to be scored
* @return frame holding predicted values
*
* @see #score(Frame, boolean)
*/
public final Frame score(Frame fr) {
return score(fr, true);
}
/** Bulk score the frame <code>fr</code>, producing a Frame result; the 1st Vec is the
* predicted class, the remaining Vecs are the probability distributions.
* For Regression (single-class) models, the 1st and only Vec is the
* prediction value.
*
* The flat <code>adapt</code>
* @param fr frame which should be scored
* @param adapt a flag enforcing an adaptation of <code>fr</code> to this model. If flag
* is <code>false</code> scoring code expect that <code>fr</code> is already adapted.
* @return a new frame containing a predicted values. For classification it contains a column with
* prediction and distribution for all response classes. For regression it contains only
* one column with predicted values.
*/
public final Frame score(Frame fr, boolean adapt) {
int ridx = fr.find(responseName());
if (ridx != -1) { // drop the response for scoring!
fr = new Frame(fr);
fr.remove(ridx);
}
// Adapt the Frame layout - returns adapted frame and frame containing only
// newly created vectors
Frame[] adaptFrms = adapt ? adapt(fr,false) : null;
// Adapted frame containing all columns - mix of original vectors from fr
// and newly created vectors serving as adaptors
Frame adaptFrm = adapt ? adaptFrms[0] : fr;
// Contains only newly created vectors. The frame eases deletion of these vectors.
Frame onlyAdaptFrm = adapt ? adaptFrms[1] : null;
// Invoke scoring
Frame output = scoreImpl(adaptFrm);
// Be nice to DKV and delete vectors which i created :-)
if (adapt) onlyAdaptFrm.delete();
return output;
}
/** Score already adapted frame.
*
* @param adaptFrm
* @return
*/
private Frame scoreImpl(Frame adaptFrm) {
int ridx = adaptFrm.find(responseName());
assert ridx == -1 : "Adapted frame should not contain response in scoring method!";
assert nfeatures() == adaptFrm.numCols() : "Number of model features " + nfeatures() + " != number of test set columns: " + adaptFrm.numCols();
assert adaptFrm.vecs().length == _names.length-1 : "Scoring data set contains wrong number of columns: " + adaptFrm.vecs().length + " instead of " + (_names.length-1);
// Create a new vector for response
// If the model produces a classification/enum, copy the domain into the
// result vector.
Vec v = adaptFrm.anyVec().makeZero(classNames());
adaptFrm.add("predict",v);
if( nclasses() > 1 ) {
String prefix = "";
for( int c=0; c<nclasses(); c++ ) // if any class is the same as column name in frame, then prefix all classnames
if (contains(adaptFrm._names, classNames()[c])) { prefix = "class_"; break; }
for( int c=0; c<nclasses(); c++ )
adaptFrm.add(prefix+classNames()[c],adaptFrm.anyVec().makeZero());
}
new MRTask2() {
@Override public void map( Chunk chks[] ) {
double tmp [] = new double[_names.length-1]; // We do not need the last field representing response
float preds[] = new float [nclasses()==1?1:nclasses()+1];
int len = chks[0]._len;
for( int row=0; row<len; row++ ) {
float p[] = score0(chks,row,tmp,preds);
for( int c=0; c<preds.length; c++ )
chks[_names.length-1+c].set0(row,p[c]);
}
}
}.doAll(adaptFrm);
// Return just the output columns
int x=_names.length-1, y=adaptFrm.numCols();
return adaptFrm.extractFrame(x, y);
}
/** Single row scoring, on a compatible Frame. */
public final float[] score( Frame fr, boolean exact, int row ) {
double tmp[] = new double[fr.numCols()];
for( int i=0; i<tmp.length; i++ )
tmp[i] = fr.vecs()[i].at(row);
return score(fr.names(),fr.domains(),exact,tmp);
}
/** Single row scoring, on a compatible set of data. Fairly expensive to adapt. */
public final float[] score( String names[], String domains[][], boolean exact, double row[] ) {
return score(adapt(names,domains,exact),row,new float[nclasses()]);
}
/** Single row scoring, on a compatible set of data, given an adaption vector */
public final float[] score( int map[][][], double row[], float[] preds ) {
/*FIXME final int[][] colMap = map[map.length-1]; // Response column mapping is the last array
assert colMap.length == _names.length-1 : " "+Arrays.toString(colMap)+" "+Arrays.toString(_names);
double tmp[] = new double[colMap.length]; // The adapted data
for( int i=0; i<colMap.length; i++ ) {
// Column mapping, or NaN for missing columns
double d = colMap[i]==-1 ? Double.NaN : row[colMap[i]];
if( map[i] != null ) { // Enum mapping
int e = (int)d;
if( e < 0 || e >= map[i].length ) d = Double.NaN; // User data is out of adapt range
else {
e = map[i][e];
d = e==-1 ? Double.NaN : (double)e;
}
}
tmp[i] = d;
}
return score0(tmp,preds); // The results. */
return null;
}
/** Build an adaption array. The length is equal to the Model's vector length.
* Each inner 2D-array is a
* compressed domain map from data domains to model domains - or null for non-enum
* columns, or null for identity mappings. The extra final int[] is the
* column mapping itself, mapping from model columns to data columns. or -1
* if missing.
* If 'exact' is true, will throw if there are:
* any columns in the model but not in the input set;
* any enums in the data that the model does not understand
* any enums returned by the model that the data does not have a mapping for.
* If 'exact' is false, these situations will use or return NA's instead.
*/
private int[][][] adapt( String names[], String domains[][], boolean exact) {
int maplen = names.length;
int map[][][] = new int[maplen][][];
// Make sure all are compatible
for( int c=0; c<names.length;++c) {
// Now do domain mapping
String ms[] = _domains[c]; // Model enum
String ds[] = domains[c]; // Data enum
if( ms == ds ) { // Domains trivially equal?
} else if( ms == null ) {
throw new IllegalArgumentException("Incompatible column: '" + _names[c] + "', expected (trained on) numeric, was passed a categorical");
} else if( ds == null ) {
if( exact )
throw new IllegalArgumentException("Incompatible column: '" + _names[c] + "', expected (trained on) categorical, was passed a numeric");
throw H2O.unimpl(); // Attempt an asEnum?
} else if( !Arrays.deepEquals(ms, ds) ) {
map[c] = getDomainMapping(_names[c], ms, ds, exact);
} // null mapping is equal to identity mapping
}
return map;
}
/** Build an adapted Frame from the given Frame. Useful for efficient bulk
* scoring of a new dataset to an existing model. Same adaption as above,
* but expressed as a Frame instead of as an int[][]. The returned Frame
* does not have a response column.
* It returns a <b>two element array</b> containing an adapted frame and a
* frame which contains only vectors which where adapted (the purpose of the
* second frame is to delete all adapted vectors with deletion of the
* frame). */
public Frame[] adapt( final Frame fr, boolean exact) {
Frame vfr = new Frame(fr); // To avoid modification of original frame fr
int ridx = vfr.find(_names[_names.length-1]);
if(ridx != -1 && ridx != vfr._names.length-1){ // Unify frame - put response to the end
String n = vfr._names[ridx];
vfr.add(n,vfr.remove(ridx));
}
int n = ridx == -1?_names.length-1:_names.length;
String [] names = Arrays.copyOf(_names, n);
// FIXME: Replacing in non-existant columns with 0s only makes sense for sparse data (SVMLight), otherwise we should either throw an exception or use NaNs...
Frame [] subVfr = vfr.subframe(names, 0); // select only supported columns, if column is missing replace it with zeroes
vfr = subVfr[0]; // extract only subframe but keep the rest for delete later
Vec[] frvecs = vfr.vecs();
boolean[] toEnum = new boolean[frvecs.length];
if(!exact) for(int i = 0; i < n;++i)
if(_domains[i] != null && !frvecs[i].isEnum()) {// if model expects domain but input frame does not have domain => switch vector to enum
frvecs[i] = frvecs[i].toEnum();
toEnum[i] = true;
}
int[][][] map = adapt(names,vfr.domains(),exact);
assert map.length == names.length; // Be sure that adapt call above do not skip any column
ArrayList<Vec> avecs = new ArrayList<Vec>(); // adapted vectors
ArrayList<String> anames = new ArrayList<String>(); // names for adapted vector
for( int c=0; c<map.length; c++ ) // Iterate over columns
if(map[c] != null) { // Column needs adaptation
Vec adaptedVec;
if (toEnum[c]) { // Vector was flipped to column already, compose transformation
adaptedVec = TransfVec.compose( (TransfVec) frvecs[c], map[c], vfr.domains()[c], false);
} else adaptedVec = frvecs[c].makeTransf(map[c], vfr.domains()[c]);
avecs.add(frvecs[c] = adaptedVec);
anames.add(names[c]); // Collect right names
} else if (toEnum[c]) { // Vector was transformed to enum domain, but does not need adaptation we need to record it
avecs.add(frvecs[c]);
anames.add(names[c]);
}
// Fill trash bin by vectors which need to be deleted later by the caller.
Frame vecTrash = new Frame(anames.toArray(new String[anames.size()]), avecs.toArray(new Vec[avecs.size()]));
if (subVfr[1]!=null) vecTrash.add(subVfr[1], true);
return new Frame[] { new Frame(names,frvecs), vecTrash };
}
/** Returns a mapping between values of model domains (<code>modelDom</code>) and given column domain.
* @see #getDomainMapping(String, String[], String[], boolean) */
public static int[][] getDomainMapping(String[] modelDom, String[] colDom, boolean exact) {
return getDomainMapping(null, modelDom, colDom, exact);
}
/**
* Returns a mapping for given column according to given <code>modelDom</code>.
* In this case, <code>modelDom</code> is
*
* @param colName name of column which is mapped, can be null.
* @param modelDom
* @param logNonExactMapping
* @return
*/
public static int[][] getDomainMapping(String colName, String[] modelDom, String[] colDom, boolean logNonExactMapping) {
int emap[] = new int[modelDom.length];
boolean bmap[] = new boolean[modelDom.length];
HashMap<String,Integer> md = new HashMap<String, Integer>((int) ((colDom.length/0.75f)+1));
for( int i = 0; i < colDom.length; i++) md.put(colDom[i], i);
for( int i = 0; i < modelDom.length; i++) {
Integer I = md.get(modelDom[i]);
if (I == null && logNonExactMapping)
Log.warn(Sys.SCORM, "Domain mapping: target domain contains the factor '"+modelDom[i]+"' which DOES NOT appear in input domain " + (colName!=null?"(column: " + colName+")":""));
if (I!=null) {
emap[i] = I;
bmap[i] = true;
}
}
if (logNonExactMapping) { // Inform about additional values in column domain which do not appear in model domain
for (int i=0; i<colDom.length; i++) {
boolean found = false;
for (int j=0; j<emap.length; j++)
if (emap[j]==i) { found=true; break; }
if (!found)
Log.warn(Sys.SCORM, "Domain mapping: target domain DOES NOT contain the factor '"+colDom[i]+"' which appears in input domain "+ (colName!=null?"(column: " + colName+")":""));
}
}
// produce packed values
int[][] res = Utils.pack(emap, bmap);
// Sort values in numeric order to support binary search in TransfVec
Utils.sortWith(res[0], res[1]);
return res;
}
/** Bulk scoring API for one row. Chunks are all compatible with the model,
* and expect the last Chunks are for the final distribution & prediction.
* Default method is to just load the data into the tmp array, then call
* subclass scoring logic. */
protected float[] score0( Chunk chks[], int row_in_chunk, double[] tmp, float[] preds ) {
assert chks.length>=_names.length; // Last chunk is for the response
for( int i=0; i<_names.length-1; i++ ) // Do not include last value since it can contains a response
tmp[i] = chks[i].at0(row_in_chunk);
float[] scored = score0(tmp,preds);
// Correct probabilities obtained from training on oversampled data back to original distribution
if (isClassifier() && _priorClassDist != null && _modelClassDist != null) {
assert(scored.length == nclasses()+1); //1 label + nclasses probs
double probsum=0;
for( int c=1; c<scored.length; c++ ) {
final double original_fraction = _priorClassDist[c-1];
assert(original_fraction > 0);
final double oversampled_fraction = _modelClassDist[c-1];
assert(oversampled_fraction > 0);
assert(!Double.isNaN(scored[c]));
scored[c] *= original_fraction / oversampled_fraction;
probsum += scored[c];
}
for (int i=1;i<scored.length;++i) scored[i] /= probsum;
//set label based on corrected probabilities (max value wins, with deterministic tie-breaking)
scored[0] = ModelUtils.getPrediction(scored, tmp);
}
return scored;
}
/** Subclasses implement the scoring logic. The data is pre-loaded into a
* re-used temp array, in the order the model expects. The predictions are
* loaded into the re-used temp array, which is also returned. */
protected abstract float[] score0(double data[/*ncols*/], float preds[/*nclasses+1*/]);
// Version where the user has just ponied-up an array of data to be scored.
// Data must be in proper order. Handy for JUnit tests.
public double score(double [] data){ return Utils.maxIndex(score0(data,new float[nclasses()])); }
/** Return a String which is a valid Java program representing a class that
* implements the Model. The Java is of the form:
* <pre>
* class UUIDxxxxModel {
* public static final String NAMES[] = { ....column names... }
* public static final String DOMAINS[][] = { ....domain names... }
* // Pass in data in a double[], pre-aligned to the Model's requirements.
* // Jam predictions into the preds[] array; preds[0] is reserved for the
* // main prediction (class for classifiers or value for regression),
* // and remaining columns hold a probability distribution for classifiers.
* float[] predict( double data[], float preds[] );
* double[] map( HashMap<String,Double> row, double data[] );
* // Does the mapping lookup for every row, no allocation
* float[] predict( HashMap<String,Double> row, double data[], float preds[] );
* // Allocates a double[] for every row
* float[] predict( HashMap<String,Double> row, float preds[] );
* // Allocates a double[] and a float[] for every row
* float[] predict( HashMap<String,Double> row );
* }
* </pre>
*/
public String toJava() { return toJava(new SB()).toString(); }
public SB toJava( SB sb ) {
SB fileContextSB = new SB(); // preserve file context
String modelName = JCodeGen.toJavaId(_key.toString());
// HEADER
sb.p("import java.util.Map;").nl().nl();
sb.p("// AUTOGENERATED BY H2O at ").p(new Date().toString()).nl();
sb.p("// ").p(H2O.getBuildVersion().toString()).nl();
sb.p("
sb.p("// Standalone prediction code with sample test data for ").p(this.getClass().getSimpleName()).p(" named ").p(modelName).nl();
sb.p("
sb.p("// How to download, compile and execute:").nl();
sb.p("// mkdir tmpdir").nl();
sb.p("// cd tmpdir").nl();
sb.p("// curl http:/").p(H2O.SELF.toString()).p("/h2o-model.jar > h2o-model.jar").nl();
sb.p("// curl http:/").p(H2O.SELF.toString()).p("/2/").p(this.getClass().getSimpleName()).p("View.java?_modelKey=").pobj(_key).p(" > ").p(modelName).p(".java").nl();
sb.p("// javac -cp h2o-model.jar -J-Xmx2g -J-XX:MaxPermSize=128m ").p(modelName).p(".java").nl();
sb.p("// java -cp h2o-model.jar:. -Xmx2g -XX:MaxPermSize=256m -XX:ReservedCodeCacheSize=256m ").p(modelName).nl();
sb.p("
sb.p("// (Note: Try java argument -XX:+PrintCompilation to show runtime JIT compiler behavior.)").nl();
sb.nl();
sb.p("public class ").p(modelName).p(" extends water.genmodel.GeneratedModel {").nl(); // or extends GenerateModel
toJavaInit(sb, fileContextSB).nl();
toJavaNAMES(sb);
toJavaNCLASSES(sb);
toJavaDOMAINS(sb);
toJavaSuper(sb);
toJavaPredict(sb, fileContextSB);
sb.p(TOJAVA_MAP);
sb.p(TOJAVA_PREDICT_MAP);
sb.p(TOJAVA_PREDICT_MAP_ALLOC1);
sb.p(TOJAVA_PREDICT_MAP_ALLOC2);
sb.p("}").nl();
sb.p(fileContextSB).nl(); // Append file
return sb;
}
// Same thing as toJava, but as a Javassist CtClass
private CtClass makeCtClass() throws CannotCompileException {
CtClass clz = ClassPool.getDefault().makeClass(JCodeGen.toJavaId(_key.toString()));
clz.addField(CtField.make(toJavaNAMES (new SB()).toString(),clz));
clz.addField(CtField.make(toJavaNCLASSES(new SB()).toString(),clz));
toJavaInit(clz); // Model-specific top-level goodness
clz.addMethod(CtMethod.make(toJavaPredict(new SB(), new SB()).toString(),clz)); // FIX ME
clz.addMethod(CtMethod.make(TOJAVA_MAP,clz));
clz.addMethod(CtMethod.make(TOJAVA_PREDICT_MAP,clz));
clz.addMethod(CtMethod.make(TOJAVA_PREDICT_MAP_ALLOC1,clz));
clz.addMethod(CtMethod.make(TOJAVA_PREDICT_MAP_ALLOC2,clz));
return clz;
}
/** Generate implementation for super class. */
protected SB toJavaSuper( SB sb ) {
sb.nl();
sb.ii(1);
sb.i().p("public String[] getNames() { return NAMES; } ").nl();
sb.i().p("public String[][] getDomainValues() { return DOMAINS; }").nl();
sb.di(1);
return sb;
}
private SB toJavaNAMES( SB sb ) {
sb.nl();
sb.i(1).p("// Names of columns used by model.").nl();
return sb.i(1).p("public static final String[] NAMES = new String[] ").toJavaStringInit(_names).p(";").nl();
}
private SB toJavaNCLASSES( SB sb ) {
sb.nl();
sb.i(1).p("// Number of output classes included in training data response column,").nl();
return sb.i(1).p("public static final int NCLASSES = ").p(nclasses()).p(";").nl();
}
private SB toJavaDOMAINS( SB sb ) {
sb.nl();
sb.i(1).p("// Column domains. The last array contains domain of response column.").nl();
sb.i(1).p("public static final String[][] DOMAINS = new String[][] {").nl();
for (int i=0; i<_domains.length; i++) {
String[] dom = _domains[i];
sb.i(2).p("/* ").p(_names[i]).p(" */ ");
if (dom==null) sb.p("null");
else {
sb.p("new String[] {");
for (int j=0; j<dom.length; j++) {
if (j>0) sb.p(',');
sb.p('"').pj(dom[j]).p('"');
}
sb.p("}");
}
if (i!=_domains.length-1) sb.p(',');
sb.nl();
}
return sb.i(1).p("};").nl();
}
// Override in subclasses to provide some top-level model-specific goodness
protected SB toJavaInit(SB sb, SB fileContextSB) { return sb; }
protected void toJavaInit(CtClass ct) { }
// Override in subclasses to provide some inside 'predict' call goodness
// Method returns code which should be appended into generated top level class after
// predit method.
protected void toJavaPredictBody(SB bodySb, SB classCtxSb, SB fileCtxSb) {
throw new IllegalArgumentException("This model type does not support conversion to Java");
}
// Wrapper around the main predict call, including the signature and return value
private SB toJavaPredict(SB ccsb, SB fileCtxSb) { // ccsb = classContext
ccsb.nl();
ccsb.p(" // Pass in data in a double[], pre-aligned to the Model's requirements.").nl();
ccsb.p(" // Jam predictions into the preds[] array; preds[0] is reserved for the").nl();
ccsb.p(" // main prediction (class for classifiers or value for regression),").nl();
ccsb.p(" // and remaining columns hold a probability distribution for classifiers.").nl();
ccsb.p(" public final float[] predict( double[] data, float[] preds) { return predict( data, preds, "+toJavaDefaultMaxIters()+"); }").nl();
ccsb.p(" public final float[] predict( double[] data, float[] preds, int maxIters ) {").nl();
SB classCtxSb = new SB();
toJavaPredictBody(ccsb.ii(2), classCtxSb, fileCtxSb); ccsb.di(1);
ccsb.p(" return preds;").nl();
ccsb.p(" }").nl();
ccsb.p(classCtxSb);
return ccsb;
}
protected String toJavaDefaultMaxIters() { return "-1"; }
private static final String TOJAVA_MAP =
"\n"+
" // Takes a HashMap mapping column names to doubles. Looks up the column\n"+
" // names needed by the model, and places the doubles into the data array in\n"+
" // the order needed by the model. Missing columns use NaN.\n"+
" double[] map( Map<String, Double> row, double data[] ) {\n"+
" for( int i=0; i<NAMES.length-1; i++ ) {\n"+
" Double d = (Double)row.get(NAMES[i]);\n"+
" data[i] = d==null ? Double.NaN : d;\n"+
" }\n"+
" return data;\n"+
" }\n";
private static final String TOJAVA_PREDICT_MAP =
"\n"+
" // Does the mapping lookup for every row, no allocation\n"+
" float[] predict( Map<String, Double> row, double data[], float preds[] ) {\n"+
" return predict(map(row,data),preds);\n"+
" }\n";
private static final String TOJAVA_PREDICT_MAP_ALLOC1 =
"\n"+
" // Allocates a double[] for every row\n"+
" float[] predict( Map<String, Double> row, float preds[] ) {\n"+
" return predict(map(row,new double[NAMES.length]),preds);\n"+
" }\n";
private static final String TOJAVA_PREDICT_MAP_ALLOC2 =
"\n"+
" // Allocates a double[] and a float[] for every row\n"+
" float[] predict( Map<String, Double> row ) {\n"+
" return predict(map(row,new double[NAMES.length]),new float[NCLASSES+1]);\n"+
" }\n";
// Convenience method for testing: build Java, convert it to a class &
// execute it: compare the results of the new class's (JIT'd) scoring with
// the built-in (interpreted) scoring on this dataset. Throws if there
// is any error (typically an AssertionError).
public void testJavaScoring( Frame fr ) {
try {
//System.out.println(toJava());
Class clz = ClassPool.getDefault().toClass(makeCtClass());
Object modelo = clz.newInstance();
}
catch( CannotCompileException cce ) { throw new Error(cce); }
catch( InstantiationException cce ) { throw new Error(cce); }
catch( IllegalAccessException cce ) { throw new Error(cce); }
}
}
|
package com.punchline.javalib.entities;
import java.util.HashMap;
import java.util.Map;
/**
* Holds a map of {@link Component Components} with their type identifiers,
* and helpful methods for accessing and manipulating them.
* @author Nathaniel
*
*/
public abstract class ComponentManager {
private Map<Class<?>, Component> components = new HashMap<Class<?>, Component>(); //HashMap?
/**
* Adds the given component to this container.
* @param value The component to be added.
*/
public void addComponent(Component value) {
components.put(value.getClass(), value);
value.onAdd(this);
}
/**
* Removes the given component from this container.
* @param value The component to be removed.
*/
public void removeComponent(Component value) {
value.onRemove(this);
components.remove(value.getClass());
}
/**
* @param type The desired type.
* @return This container's component of that type.
*/
@SuppressWarnings("unchecked")
public <T extends Component> T getComponent(T... type) {
return (T)components.get((Class<T>) type.getClass().getComponentType());
}
/**
* @param type The desired type.
* @return Whether this container has a component of that type.
*/
public boolean hasComponent(Class<?> type){
return components.containsKey(type);
}
}
|
/*
* $Id: OJS2HtmlLinkExtractor.java,v 1.3 2013-04-22 22:27:41 pgust Exp $
*/
package org.lockss.plugin.ojs2;
import java.io.IOException;
import org.apache.oro.text.regex.*;
import org.lockss.extractor.GoslingHtmlLinkExtractor;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.util.*;
public class OJS2HtmlLinkExtractor extends GoslingHtmlLinkExtractor {
protected static Logger log = Logger.getLogger(OJS2HtmlLinkExtractor.class);
protected static final Pattern OPEN_RT_WINDOW_PATTERN =
RegexpUtil.uncheckedCompile("javascript:openRTWindow\\('([^']*)'\\);",
Perl5Compiler.READ_ONLY_MASK);
@Override
protected String extractLinkFromTag(
StringBuffer link, ArchivalUnit au, Callback cb) throws IOException {
switch (link.charAt(0)) {
case 'a':
case 'A':
if (beginsWithTag(link,"a")) {
// <a href="...">
String href = getAttributeValue(HREF, link);
if (href != null) {
// javascript:openRTWindow(url);
PatternMatcher matcher = RegexpUtil.getMatcher();
if ( OPEN_RT_WINDOW_PATTERN != null
&& matcher.contains(href, OPEN_RT_WINDOW_PATTERN)) {
String openRTWindowLink =
interpretRTOpenWindowMatch(matcher.getMatch());
return openRTWindowLink;
}
}
}
break;
case 'f':
case 'F':
if (beginsWithTag(link,"form")) {
// <form action="...">
String action = getAttributeValue("action", link);
if (action != null) {
// javascript:openRTWindow(url);
PatternMatcher matcher = RegexpUtil.getMatcher();
if ( OPEN_RT_WINDOW_PATTERN != null
&& matcher.contains(action, OPEN_RT_WINDOW_PATTERN)) {
String openRTWindowLink =
interpretRTOpenWindowMatch(matcher.getMatch());
return openRTWindowLink;
}
}
}
break;
case 'm':
case 'M':
if (beginsWithTag(link,"meta")) {
if ("refresh".equalsIgnoreCase(getAttributeValue(HTTP_EQUIV, link))) {
String value = getAttributeValue(HTTP_EQUIV_CONTENT, link);
if (value != null) {
// <meta http-equiv="refresh" content="...">
int i = value.indexOf(";url=");
if (i >= 0) {
String url = value.substring(i+5);
// javascript:openRTWindow(url);
PatternMatcher matcher = RegexpUtil.getMatcher();
if ( OPEN_RT_WINDOW_PATTERN != null
&& matcher.contains(url, OPEN_RT_WINDOW_PATTERN)) {
String openRTWindowLink =
interpretRTOpenWindowMatch(matcher.getMatch());
return openRTWindowLink;
}
}
}
}
}
break;
}
return super.extractLinkFromTag(link, au, cb);
}
private static String interpretRTOpenWindowMatch(MatchResult openRTWindowMatch) {
if ((openRTWindowMatch.groups() - 1) != 1) {
log.warning("Internal inconsistency: openRTWindow match '"
+ openRTWindowMatch.toString()
+ "' has "
+ (openRTWindowMatch.groups() - 1)
+ " proper subgroups; expected 1");
if ((openRTWindowMatch.groups() - 1) < 1) {
return null;
}
}
return openRTWindowMatch.group(1);
}
}
|
package alma.acs.nc;
/**
* @author dfugate
* @version $Id: ArchiveConsumer.java,v 1.10 2007/01/04 12:29:16 hsommer Exp $
* @since
*/
import java.lang.reflect.Method;
import org.omg.CosNotification.StructuredEvent;
import alma.acs.container.ContainerServices;
import alma.acs.exceptions.AcsJException;
/**
* ArchiveConsumer is a a Consumer-derived class designed solely for the purpose
* of processing notification channel structured events sent automatically by
* BACI properties under certain conditions. Basically all one has to do to use
* this class is create an ArchiveConsumer object providing an object with
* implements "receive(Long timeStamp, String device, String parameter, Object
* value)" and then invoke the consumerReady() method. Since archive events do
* not contain complex IDL structs, filtering using the extended trader
* constraint language should work as well.
*
* @author dfugate
*/
public class ArchiveConsumer extends Consumer {
/**
* Creates a new instance of ArchiveConsumer
*
* @param services
* This is used to access ACS logging system.
* @param receiver
* An object which implements a method called "receive". The
* "receive" method must accept four parameters which
* are: timeStamp(long), device(string), parameter(string),
* and value(Object).
* @throws AcsJException
* Thrown on any <I>really bad</I> error conditions encountered.
*/
public ArchiveConsumer(ContainerServices services, Object receiver) throws AcsJException {
// call the super.
super(alma.acscommon.ARCHIVING_CHANNEL_NAME.value, services);
// check to ensure receiver is capable to processing the event
Class receiverClass = receiver.getClass();
Method receiveMethod = null;
// receive will have four parameters
Class[] parm = { Long.class, String.class, String.class, Object.class };
// if this fails we know that the developer has not defined "receive"
// correctly at not at all. we can do nothing more
try {
receiveMethod = receiverClass.getMethod("receive", parm);
} catch (NoSuchMethodException err) {
m_logger.warning(err.getMessage());
// Well the method doesn't exist...that sucks!
String reason = "The '" + m_channelName
+ "' channel: the receiver object is incapable of handling events!";
throw new alma.ACSErrTypeJavaNative.wrappers.AcsJJavaLangEx(reason);
} catch (SecurityException err) {
m_logger.warning(err.getMessage());
// Developer has defined the method to be protected or private...this
// doesn't work either.
String reason = "The '" + m_channelName
+ "' channel: the receiver method of the object is protected/private for archive events!";
throw new alma.ACSErrTypeJavaNative.wrappers.AcsJJavaLangEx(reason);
}
// save the receive method for later use.
receiveMethod_m = receiveMethod;
// save the receiver for later use.
receiver_m = receiver;
}
/**
* Overridden
*
* @return string
*/
protected String getChannelKind() {
// because archive channels are registered differently
// in the CORBA naming service than ICD-style channels
return alma.acscommon.ARCHIVING_CHANNEL_KIND.value;
}
/**
* Overridden.
*
* @return string
*/
protected String getNotificationFactoryName() {
return alma.acscommon.ARCHIVE_NOTIFICATION_FACTORY_NAME.value;
}
/**
* Overridden
*/
protected void configSubscriptions() {
// calling addsubscription on null automatically subscribes
// to all event types.
try {
addSubscription(null);
} catch (Exception e) {
String msg = "Failed to subscribe to archive events: ";
msg = msg + e.getMessage();
m_logger.severe(msg);
}
return;
}
/**
* Overridden.
* @param structuredEvent CORBA NC StructuredEvent
* @throws Disconnected
*/
public void push_structured_event(StructuredEvent structuredEvent)
throws org.omg.CosEventComm.Disconnected {
try {
String[] eventNames = structuredEvent.header.fixed_header.event_name.split(":");
// extract the useful info
//Long timeStamp = new Long(structuredEvent.filterable_data[0].value.extract_ulonglong());
Long timeStamp = (Long) m_anyAide.corbaAnyToObject(structuredEvent.filterable_data[0].value);
Object value = m_anyAide.corbaAnyToObject(structuredEvent.filterable_data[1].value);
String device = eventNames[1];
String parameter = eventNames[2];
// String containerName = eventNames[0];
// organize it into an argument list to be sent to the receive method.
// order is critical here
Object[] arg = { timeStamp, device, parameter, value };
// try sending it to the receiver.
receiveMethod_m.invoke(receiver_m, arg);
} catch (java.lang.IllegalAccessException e) {
// should never happen...
String msg = "Failed to process an event on the '" + m_channelName + "' channel because: ";
msg = msg + e.getMessage();
m_logger.warning(msg);
} catch (java.lang.reflect.InvocationTargetException e) {
// should never happen...
String msg = "Failed to process an event on the '" + m_channelName + "' channel because: ";
msg = msg + e.getMessage();
m_logger.warning(msg);
}
}
/**
* There is exactly one receive method that will be invoked per
* ArchiveConsumer object.
*/
private Method receiveMethod_m = null;
/**
* There is exactly one receiver that will be used by each ArchiveConsumer
* object.
*/
private Object receiver_m = null;
}
|
package com.linuxzasve.mobile.rest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class LzsRestApi {
String baseUrl = "http:
/* number of posts to fetch */
Integer numberOfPosts = Integer.valueOf(10);
/* post id to fetch */
Integer postId = null;
/* list of basic fields to include */
String[] include = { "author", "url", "content", "title", "date", "author", "comment_count", "thumbnail" };
/**
*
* @return
* @throws IOException
*/
public String getRecentPosts() throws IOException {
/* prepare the query string */
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("include", generateInclude(include)));
/* generate request url */
String url = generateRequestString(baseUrl, "get_recent_posts/", nameValuePairs);
/* submit query, get json data */
String jsonResult = getContent(url);
return jsonResult;
}
/**
*
* @param search
* @return
* @throws IOException
*/
public String getSearchResult(final String search) throws IOException {
/* prepare the query string */
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("include", generateInclude(include)));
nameValuePairs.add(new BasicNameValuePair("search", search));
/* generate request url */
String url = generateRequestString(baseUrl, "get_search_results/", nameValuePairs);
/* submit query, get json data */
String jsonResult = getContent(url);
return jsonResult;
}
private String getContent(final String url) throws IOException {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
response = client.execute(request);
}
catch (URISyntaxException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getStringFromInputStream(response.getEntity().getContent());
}
private static String getStringFromInputStream(final InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
/**
* Comma separated values
*
* @param includes
* @return
*/
private String generateInclude(final String includes[]) {
String result = "";
int i;
for (i = 0; i < (includes.length - 1); i++) {
result += (includes[i] + ",");
}
result += includes[i];
return result;
}
private String generateRequestString(final String baseUrl, final String method, final List<NameValuePair> parameters) {
String url = "";
/* add base url */
url += baseUrl;
/* add method */
url += method;
/* generate query string */
String queryString = URLEncodedUtils.format(parameters, "UTF-8");
url += ("?" + queryString);
return url;
}
}
|
package com.intellij.localvcs;
import org.junit.Test;
public class SnapshotDirectoriesTest extends TestCase {
// todo test boundary conditions
@Test
public void testCeatingDirectory() {
Snapshot s = new Snapshot();
assertFalse(s.hasRevision(fn("dir")));
s.doCreateDirectory(fn("dir"));
assertTrue(s.hasRevision(fn("dir")));
assertEquals(DirectoryRevision.class, s.getRevision(fn("dir")).getClass());
assertTrue(s.getRevision(fn("dir")).getChildren().isEmpty());
}
@Test
public void testFilesUnderDirectory() {
Snapshot s = new Snapshot();
s.doCreateDirectory(fn("dir"));
s.doCreateFile(fn("dir/file"), "");
assertTrue(s.hasRevision(fn("dir")));
assertTrue(s.hasRevision(fn("dir/file")));
Revision dir = s.getRevision(fn("dir"));
Revision file = s.getRevision(fn("dir/file"));
assertEquals(1, dir.getChildren().size());
assertSame(file, dir.getChildren().get(0));
assertSame(dir, file.getParent());
}
@Test
public void testCreatingFileUnderNonExistingDirectory() {
Snapshot s = new Snapshot();
s.doCreateFile(fn("dir/file"), "");
assertTrue(s.hasRevision(fn("dir")));
assertTrue(s.hasRevision(fn("dir/file")));
Revision dir = s.getRevision(fn("dir"));
Revision file = s.getRevision(fn("dir/file"));
assertEquals(1, dir.getChildren().size());
assertSame(file, dir.getChildren().get(0));
}
@Test
public void testCreatingParentDirectoryForNewDirectory() {
Snapshot s = new Snapshot();
s.doCreateDirectory(fn("dir1/dir2"));
assertTrue(s.hasRevision(fn("dir1")));
assertTrue(s.hasRevision(fn("dir1/dir2")));
Revision dir1 = s.getRevision(fn("dir1"));
Revision dir2 = s.getRevision(fn("dir1/dir2"));
assertEquals(1, dir1.getChildren().size());
assertSame(dir2, dir1.getChildren().get(0));
}
@Test
public void testCreatingAllParentDirectories() {
Snapshot s = new Snapshot();
s.doCreateFile(fn("dir1/dir2/file"), "");
assertTrue(s.hasRevision(fn("dir1")));
assertTrue(s.hasRevision(fn("dir1/dir2")));
assertTrue(s.hasRevision(fn("dir1/dir2/file")));
}
}
|
package org.voltdb.regressionsuites;
import java.io.IOException;
import org.voltdb.BackendTarget;
import org.voltdb.VoltTable;
import org.voltdb.client.Client;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcCallException;
import org.voltdb.compiler.VoltProjectBuilder;
public class TestCRUDSuite extends RegressionSuite {
static final Class<?>[] PROCEDURES = {};
public TestCRUDSuite(String name) {
super(name);
}
public void testNegativeWrongTypeParam() throws Exception {
final Client client = this.getClient();
ClientResponse resp = client.callProcedure("P5.insert", -1000);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
resp = client.callProcedure("@AdHoc", "select * from p5;");
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults().length);
VoltTable results = resp.getResults()[0];
assertEquals(1, results.getRowCount());
assertEquals(1, results.getColumnCount());
assertEquals(-1000, results.fetchRow(0).getLong(0));
}
public void testPartitionedPkPartitionCol() throws Exception
{
final Client client = this.getClient();
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.insert", i, Integer.toHexString(i));
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults()[0].asScalarLong());
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.select", i);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
VoltTable vt = resp.getResults()[0];
assertTrue(vt.advanceRow());
assertEquals(i, vt.getLong(0));
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.update", i, "STR" + Integer.toHexString(i), i);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults()[0].asScalarLong());
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.select", i);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
VoltTable vt = resp.getResults()[0];
assertTrue(vt.advanceRow());
assertTrue(vt.getString(1).equals("STR" + Integer.toHexString(i)));
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.delete", i);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults()[0].asScalarLong());
}
ClientResponse resp = client.callProcedure("CountP1");
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(0, resp.getResults()[0].asScalarLong());
}
public void testMultiColPk() throws Exception
{
// P4(z INTEGER, x VARCHAR(10), y INTEGER,
// PRIMARY KEY(y, x, z));"
// z = i
// x = hex(i)
// y = i *100 (partition key)
final Client client = this.getClient();
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P4.insert", i, Integer.toHexString(i), i * 100); // z,x,y
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults()[0].asScalarLong());
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P4.select", i*100, Integer.toHexString(i), i); // y,x,z
VoltTable vt = resp.getResults()[0];
assertTrue(vt.advanceRow());
assertEquals(i, vt.getLong(0));
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P4.update",
i*10, "STR" + Integer.toHexString(i), i*100, // z,x,y (update / table order)
i*100, Integer.toHexString(i), i); // y,x,z (search / index order)
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults()[0].asScalarLong());
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P4.select", i*100, "STR" + Integer.toHexString(i), i*10); // y,x,z
VoltTable vt = resp.getResults()[0];
assertTrue(vt.advanceRow());
assertEquals(i*10, vt.getLong(0));
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P4.delete", i*100, "STR" + Integer.toHexString(i), i*10); // y,x,z
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults()[0].asScalarLong());
}
}
public void testPartitionedPkWithoutPartitionCol() throws Exception
{
Client client = getClient();
try {
client.callProcedure("P2.delete", 0, "ABC");
} catch (ProcCallException e) {
assertTrue(e.getMessage().contains("was not found"));
return;
}
fail();
}
public void testPartitionedPkWithoutPartitionCol2() throws Exception
{
Client client = getClient();
try {
client.callProcedure("P3.delete", 0, "ABC");
} catch (ProcCallException e) {
assertTrue(e.getMessage().contains("was not found"));
return;
}
fail();
}
public void testReplicatedTable() throws Exception
{
final Client client = this.getClient();
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("R1.insert", i, Integer.toHexString(i));
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults()[0].asScalarLong());
}
try {
client.callProcedure("R1.select", 0, "ABC");
fail();
} catch (ProcCallException e) {
assertTrue(e.getMessage().contains("was not found"));
return;
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("R1.update", i, "STR" + Integer.toHexString(i), i);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults()[0].asScalarLong());
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("R1.delete", i);
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(1, resp.getResults()[0].asScalarLong());
}
ClientResponse resp = client.callProcedure("CountR1");
assertEquals(ClientResponse.SUCCESS, resp.getStatus());
assertEquals(0, resp.getResults()[0].asScalarLong());
}
static public junit.framework.Test suite() {
VoltServerConfig config = null;
final MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestCRUDSuite.class);
final VoltProjectBuilder project = new VoltProjectBuilder();
project.addStmtProcedure("CountP1", "select count(*) from p1;");
project.addStmtProcedure("CountR1", "select count(*) from r1;");
try {
// a table that should generate procedures
// use column names such that lexical order != column order.
project.addLiteralSchema(
"CREATE TABLE p1(b1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL, PRIMARY KEY (b1));"
);
project.addPartitionInfo("p1", "b1");
// a partitioned table that should not generate procedures (no pkey)
project.addLiteralSchema(
"CREATE TABLE p2(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL); " +
"CREATE UNIQUE INDEX p2_tree_idx ON p2(a1);"
);
project.addPartitionInfo("p2", "a1");
// a partitioned table that should not generate procedures (pkey not partition key)
project.addLiteralSchema(
"CREATE TABLE p3(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL); " +
"CREATE UNIQUE INDEX p3_tree_idx ON p3(a1);"
);
project.addPartitionInfo("p3", "a2");
// a replicated table (should not generate procedures).
project.addLiteralSchema(
"CREATE TABLE r1(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL, PRIMARY KEY (a1));"
);
// table with a multi-column pkey. verify that pkey column ordering is
// in the index column order, not table order and not index column lex. order
project.addLiteralSchema(
"CREATE TABLE p4(z INTEGER NOT NULL, x VARCHAR(10) NOT NULL, y INTEGER NOT NULL, PRIMARY KEY(y,x,z));"
);
project.addPartitionInfo("p4", "y");
// table with a bigint pkey
project.addLiteralSchema(
"CREATE TABLE p5(x BIGINT NOT NULL, PRIMARY KEY(x));"
);
project.addPartitionInfo("p5", "x");
} catch (IOException error) {
fail(error.getMessage());
}
// JNI
config = new LocalCluster("sqltypes-onesite.jar", 1, 1, 0, BackendTarget.NATIVE_EE_JNI);
boolean t1 = config.compile(project);
assertTrue(t1);
builder.addServerConfig(config);
// CLUSTER
config = new LocalCluster("sqltypes-cluster.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI);
boolean t2 = config.compile(project);
assertTrue(t2);
builder.addServerConfig(config);
return builder;
}
}
|
import com.embeddedunveiled.serial.SerialComManager;
import com.embeddedunveiled.serial.nullmodem.SerialComNullModem;
import com.embeddedunveiled.serial.SerialComLineErrors;
import com.embeddedunveiled.serial.SerialComManager.BAUDRATE;
import com.embeddedunveiled.serial.SerialComManager.DATABITS;
import com.embeddedunveiled.serial.SerialComManager.FLOWCONTROL;
import com.embeddedunveiled.serial.SerialComManager.PARITY;
import com.embeddedunveiled.serial.SerialComManager.STOPBITS;
public final class ParityFrameError {
public static void main(String[] args) throws Exception {
SerialComManager scm = new SerialComManager();
final SerialComNullModem scnm = scm.getSerialComNullModemInstance();
try {
scnm.createStandardNullModemPair(-1, -1);
String[] ports = scnm.getLastNullModemDevicePairNodes();
long handle0 = scm.openComPort(ports[0], true, true, true);
scm.configureComPortData(handle0, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_ODD, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle0, FLOWCONTROL.NONE, 'x', 'x', true, true);
long handle1 = scm.openComPort(ports[1], true, true, true);
scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_ODD, BAUDRATE.B115200, 0);
scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', true, true);
byte[] buffer = new byte[100];
SerialComLineErrors lineErr = new SerialComLineErrors();
// PARITY
System.out.println("PARITY before : " + lineErr.hasParityErrorOccurred());
scnm.emulateLineError(ports[1], SerialComNullModem.ERR_PARITY);
int ret = scm.readBytes(handle1, buffer, 0, 50, -1, lineErr);
System.out.println("PARITY after : " + lineErr.hasParityErrorOccurred());
for(int x=0; x<ret; x++) {
System.out.println("PARITY after data : " + buffer[x]);
}
// OVERRUN
lineErr.resetLineErrors();
System.out.println("\nOVERRUN before : " + lineErr.hasOverrunErrorOccurred());
scnm.emulateLineError(ports[1], SerialComNullModem.ERR_OVERRUN);
int ret1 = scm.readBytes(handle1, buffer, 0, 50, -1, lineErr);
System.out.println("OVERRUN after : " + lineErr.hasOverrunErrorOccurred());
for(int x=0; x<ret1; x++) {
System.out.println("OVERRUN after data : " + buffer[x]);
}
// FRAME
lineErr.resetLineErrors();
System.out.println("\nFRAME before : " + lineErr.hasFramingErrorOccurred());
scnm.emulateLineError(ports[1], SerialComNullModem.ERR_FRAME);
int ret2 = scm.readBytes(handle1, buffer, 0, 50, -1, lineErr);
System.out.println("FRAME after : " + lineErr.hasFramingErrorOccurred());
for(int x=0; x<ret2; x++) {
System.out.println("FRAME after data : " + buffer[x]);
}
// BREAK
lineErr.resetLineErrors();
System.out.println("\nBREAK before : " + lineErr.isBreakReceived());
scnm.emulateLineError(ports[1], SerialComNullModem.RCV_BREAK);
int ret3 = scm.readBytes(handle1, buffer, 0, 50, -1, lineErr);
System.out.println("BREAK after : " + lineErr.isBreakReceived());
for(int x=0; x<ret3; x++) {
System.out.println("BREAK after data : " + buffer[x]);
}
// BREAK SEND AND RECEIVE
lineErr.resetLineErrors();
System.out.println("\nBREAK before : " + lineErr.isBreakReceived());
scm.sendBreak(handle0, 100);
int ret4 = scm.readBytes(handle1, buffer, 0, 50, -1, lineErr);
System.out.println("BREAK after : " + lineErr.isBreakReceived());
for(int x=0; x<ret4; x++) {
System.out.println("BREAK after data : " + buffer[x]);
}
scm.closeComPort(handle0);
scm.closeComPort(handle1);
//scnm.destroyAllVirtualDevices();
scnm.releaseResources();
System.out.println("Done !");
}catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.jboss.windup.ui;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.apache.commons.io.FileUtils;
import org.jboss.forge.addon.resource.DirectoryResource;
import org.jboss.forge.addon.resource.FileResource;
import org.jboss.forge.addon.resource.Resource;
import org.jboss.forge.addon.resource.ResourceFactory;
import org.jboss.forge.addon.resource.util.ResourcePathResolver;
import org.jboss.forge.addon.ui.command.UICommand;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.context.UIValidationContext;
import org.jboss.forge.addon.ui.input.InputComponent;
import org.jboss.forge.addon.ui.input.InputComponentFactory;
import org.jboss.forge.addon.ui.input.UIInput;
import org.jboss.forge.addon.ui.input.UIInputMany;
import org.jboss.forge.addon.ui.input.UISelectMany;
import org.jboss.forge.addon.ui.input.UISelectOne;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.addon.ui.progress.UIProgressMonitor;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.windup.config.ValidationResult;
import org.jboss.windup.config.WindupConfigurationOption;
import org.jboss.windup.exec.WindupProcessor;
import org.jboss.windup.exec.WindupProgressMonitor;
import org.jboss.windup.exec.configuration.WindupConfiguration;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.GraphContextFactory;
import org.jboss.windup.util.WindupPathUtil;
/**
* Provides a basic forge UI for running windup from within the Forge shell.
*
* @author jsightler <jesse.sightler@gmail.com>
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*
*/
public class WindupCommand implements UICommand
{
public static final String WINDUP_CONFIGURATION = "windupConfiguration";
@Inject
@WithAttributes(label = "Overwrite", required = false, defaultValue = "false", description = "Force overwrite of the output directory, without prompting")
private UIInput<Boolean> overwrite;
@Inject
private InputComponentFactory componentFactory;
@Inject
private GraphContextFactory graphContextFactory;
@Inject
private WindupProcessor processor;
@Inject
private ResourceFactory resourceFactory;
private List<WindupOptionAndInput> inputOptions = new ArrayList<>();
@Override
public UICommandMetadata getMetadata(UIContext ctx)
{
return Metadata.forCommand(getClass()).name("Windup Migrate App").description("Run Windup Migration Analyzer")
.category(Categories.create("Platform", "Migration"));
}
@Override
public void initializeUI(UIBuilder builder) throws Exception
{
for (WindupConfigurationOption option : WindupConfiguration.getWindupConfigurationOptions())
{
InputComponent<?, ?> inputComponent = null;
switch (option.getUIType())
{
case SINGLE:
UIInput<?> inputSingle = componentFactory.createInput(option.getName(), option.getType());
inputComponent = inputSingle;
break;
case MANY:
UIInputMany<?> inputMany = componentFactory.createInputMany(option.getName(), option.getType());
inputComponent = inputMany;
break;
case SELECT_MANY:
UISelectMany<?> selectMany = componentFactory.createSelectMany(option.getName(), option.getType());
inputComponent = selectMany;
break;
case SELECT_ONE:
UISelectOne<?> selectOne = componentFactory.createSelectOne(option.getName(), option.getType());
inputComponent = selectOne;
break;
case DIRECTORY:
UIInput<DirectoryResource> directoryInput = componentFactory.createInput(option.getName(),
DirectoryResource.class);
inputComponent = directoryInput;
break;
case FILE:
UIInput<?> fileInput = componentFactory.createInput(option.getName(), FileResource.class);
inputComponent = fileInput;
break;
case FILE_OR_DIRECTORY:
UIInput<?> fileOrDirInput = componentFactory.createInput(option.getName(), FileResource.class);
inputComponent = fileOrDirInput;
break;
}
if (inputComponent == null)
{
throw new IllegalArgumentException("Could not build input component for: " + option);
}
inputComponent.setLabel(option.getLabel());
inputComponent.setRequired(option.isRequired());
inputComponent.setDescription(option.getDescription());
builder.add(inputComponent);
inputOptions.add(new WindupOptionAndInput(option, inputComponent));
}
builder.add(overwrite);
}
@Override
public void validate(UIValidationContext context)
{
for (WindupOptionAndInput pair : this.inputOptions)
{
Object value = getValueForInput(pair.input);
ValidationResult result = pair.option.validate(value);
if (!result.isSuccess())
{
context.addValidationError(pair.input, result.getMessage());
}
}
}
private Object getValueForInput(InputComponent<?, ?> input)
{
Object value = input.getValue();
if (value == null)
{
return value;
}
if (value instanceof Resource<?>)
{
Resource<?> resourceResolved = getResourceResolved((Resource<?>) value);
return resourceResolved.getUnderlyingResourceObject();
}
return value;
}
private Resource<?> getResourceResolved(Resource<?> value) {
Resource<?> resource = (Resource<?>) value;
File file = (File) resource.getUnderlyingResourceObject();
return new ResourcePathResolver(resourceFactory, resource, file.getPath()).resolve().get(0);
}
@Override
public Result execute(UIExecutionContext context) throws Exception
{
WindupConfiguration windupConfiguration = new WindupConfiguration();
for (WindupOptionAndInput pair : this.inputOptions)
{
String key = pair.option.getName();
Object value = getValueForInput(pair.input);
windupConfiguration.setOptionValue(key, value);
}
// add dist/rules/ and ${forge.home}/rules/ to the user rules directory list
Path userRulesDir = WindupPathUtil.getWindupUserRulesDir();
if (!Files.isDirectory(userRulesDir))
{
Files.createDirectories(userRulesDir);
}
windupConfiguration.addDefaultUserRulesDirectory(userRulesDir);
Path windupHomeRulesDir = WindupPathUtil.getWindupHomeRules();
if (!Files.isDirectory(windupHomeRulesDir))
{
Files.createDirectories(windupHomeRulesDir);
}
windupConfiguration.addDefaultUserRulesDirectory(windupHomeRulesDir);
boolean overwrite = this.overwrite.getValue();
if (!overwrite && pathNotEmpty(windupConfiguration.getOutputDirectory().toFile()))
{
String promptMsg = "Overwrite all contents of \"" + windupConfiguration.getOutputDirectory().toString()
+ "\" (anything already in the directory will be deleted)?";
if (!context.getPrompt().promptBoolean(promptMsg))
{
return Results.fail("Windup execution aborted!");
}
}
// put this in the context for debugging, and unit tests (or anything else that needs it)
context.getUIContext().getAttributeMap().put(WindupConfiguration.class, windupConfiguration);
FileUtils.deleteQuietly(windupConfiguration.getOutputDirectory().toFile());
Path graphPath = windupConfiguration.getOutputDirectory().resolve("graph");
try (GraphContext graphContext = graphContextFactory.create(graphPath))
{
UIProgressMonitor uiProgressMonitor = context.getProgressMonitor();
WindupProgressMonitor progressMonitor = new WindupProgressMonitorAdapter(uiProgressMonitor);
windupConfiguration
.setProgressMonitor(progressMonitor)
.setGraphContext(graphContext);
processor.execute(windupConfiguration);
uiProgressMonitor.done();
return Results.success("Windup report created: " + windupConfiguration.getOutputDirectory().toAbsolutePath() + "/index.html");
}
}
@Override
public boolean isEnabled(UIContext context)
{
return true;
}
private boolean pathNotEmpty(File f)
{
if (f.exists() && !f.isDirectory())
{
return true;
}
if (f.isDirectory() && f.listFiles() != null && f.listFiles().length > 0)
{
return true;
}
return false;
}
private class WindupOptionAndInput
{
private WindupConfigurationOption option;
private InputComponent<?, ?> input;
public WindupOptionAndInput(WindupConfigurationOption option, InputComponent<?, ?> input)
{
this.option = option;
this.input = input;
}
}
}
|
package com.markjmind.uni;
import com.markjmind.uni.progress.ProgressBuilder;
import com.markjmind.uni.thread.aop.UniAop;
/**
* <br><br>
*
* @author (JaeWoong-Oh)
* @email markjmind@gmail.com
* @since 2016-06-23
*/
public class TaskController {
private UniTask uniTask;
private boolean isAsync = true;
private ProgressBuilder progress;
private UniInterface uniInterface;
private UniLoadFail uniLoadFail;
private UniAop uniAop;
private boolean isAnnotationMapping = false;
private UniUncaughtException uncaughtException;
void init(UniTask uniTask, boolean isAnnotationMapping){
this.uniTask = uniTask;
this.setProgress(uniTask.progress);
this.setUniInterface(uniTask.getUniInterface());
this.isAnnotationMapping = isAnnotationMapping;
}
public TaskController setAsync(boolean async) {
isAsync = async;
return this;
}
public TaskController setProgress(ProgressBuilder progress) {
this.progress = progress;
return this;
}
public TaskController setUniInterface(UniInterface uniInterface) {
this.uniInterface = uniInterface;
return this;
}
public TaskController setUniLoadFail(UniLoadFail uniLoadFail) {
this.uniLoadFail = uniLoadFail;
return this;
}
public TaskController setUniUncaughtException(UniUncaughtException uncaughtException){
this.uncaughtException = uncaughtException;
return this;
}
public UniUncaughtException getUniUncaughtException(){
return uncaughtException;
}
public TaskController setUniAop(UniAop uniAop) {
this.uniAop = uniAop;
return this;
}
public void cancel(String taskId){
uniTask.cancel(taskId);
}
public void cancelAll(){
uniTask.cancelAll();
}
public String execute(){
if(isAnnotationMapping){
uniTask.memberMapping();
}
if(isAsync) {
return uniTask.run(progress, uniInterface, uniLoadFail, false, uniAop, uncaughtException);
}else{
uniInterface.onPre();
return null;
}
}
public void notifyPre(){
uniInterface.onPre();
}
public void notifyPost(){
uniInterface.onPost();
}
public void post(){
if(isAnnotationMapping){
uniTask.memberMapping();
}
uniInterface.onPost();
}
public String reLoad(){
return uniTask.refresh(progress, uniLoadFail, uniAop, uncaughtException);
}
public String refresh(){
if(isAsync) {
return uniTask.refresh(progress, uniLoadFail, uniAop, uncaughtException);
}else{
uniInterface.onPre();
return null;
}
}
}
|
package helper;
import org.eclipse.rdf4j.rio.RDFFormat;
/**
* @author Jan Schnasse
*
*/
public class LobidLabelResolver implements LabelResolver {
final public static String id = "http://lobid.org/resources";
final public static String id2 = "https://lobid.org/resources";
public final static String DOMAIN = "lobid.org";
/**
* @param uri
* analyes data from the url to find a proper label
* @return a label
*/
public String lookup(String uri, String language) {
try {
String rdfAddress = uri;
/**
* Lobid uses http uris
*
*/
String rdfUri = uri.replaceAll("https", "http");
SparqlLookup SpL = new SparqlLookup();
String label = SpL.lookup(rdfUri, "<" + rdfUri + "#!>", "http://purl.org/dc/terms/title", language,
RDFFormat.JSONLD, "application/json");
if (rdfAddress.equals(label)) {
label = SpL.lookup(rdfUri, "<" + rdfUri + ">", "http://purl.org/dc/terms/title", language,
RDFFormat.JSONLD, "application/json");
}
return label;
} catch (Exception e) {
return uri;
}
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
|
package se.sics.mspsim.core;
import se.sics.mspsim.util.Utils;
public class Timer extends IOUnit {
public static final boolean DEBUG = false;//true;
public static final int TBIV = 0x011e;
public static final int TAIV = 0x012e;
public static final int TACCR0_VECTOR = 6;
// Other is on 5
public static final int TACCR1_VECTOR = 5;
public static final int TBCCR0_VECTOR = 13;
// Other is on 12
public static final int TBCCR1_VECTOR = 12;
public static final int TCTL = 0;
public static final int TCCTL0 = 2;
public static final int TCCTL1 = 4;
public static final int TCCTL2 = 6;
public static final int TCCTL3 = 8;
public static final int TCCTL4 = 0xa;
public static final int TCCTL5 = 0xc;
public static final int TCCTL6 = 0xe;
public static final int TR = 0x10;
public static final int TCCR0 = 0x12;
public static final int TCCR1 = 0x14;
public static final int TCCR2 = 0x16;
public static final int TCCR3 = 0x18;
public static final int TCCR4 = 0x1a;
public static final int TCCR5 = 0x1c;
public static final int TCCR6 = 0x1e;
public static final int STOP = 0;
public static final int UP = 1;
public static final int CONTIN = 2;
public static final int UPDWN = 3;
// Different capture modes...
public static final int CAP_NONE = 0;
public static final int CAP_UP = 1;
public static final int CAP_DWN = 2;
public static final int CAP_BOTH = 3;
public static final int TCLR = 0x4;
public static final int SRC_ACLK = 0;
public static final int SRC_MCLK = 1;
public static final int SRC_SMCLK = 2;
public static final int SRC_PORT = 0x100;
public static final int SRC_GND = 0x200;
public static final int SRC_VCC = 0x201;
public static final int SRC_CAOUT = 0x202; // Internal ??? What is this?
public static final int CC_IFG = 0x01; // Bit 0
public static final int CC_IE = 0x10; // Bit 4
public static final int CC_TRIGGER_INT = CC_IE | CC_IFG;
public static final int CM_NONE = 0;
public static final int CM_RISING = 1;
public static final int CM_FALLING = 2;
public static final int CM_BOTH = 3;
// Number of cycles passed since current counter value was set
// useful for setting expected compare and capture times to correct time.
// valid for timer A
private final int timerOverflow;
private long nextTimerTrigger = 0;
// this is used to create "tick" since last reset of the timer.
// it will contain the full number of ticks since that reset and
// is used to calculate the real counter value
private long counterStart = 0;
private long counterAcc;
// Counter stores the current timer counter register (TR)
private int counter = 0;
private int counterPassed = 0;
// Input map for timer A
public static final int[] TIMER_Ax149 = new int[] {
SRC_PORT + 0x10, SRC_ACLK, SRC_SMCLK, SRC_PORT + 0x21, // Timer
SRC_PORT + 0x11, SRC_PORT + 0x22, SRC_GND, SRC_VCC, // Cap 0
SRC_PORT + 0x12, SRC_CAOUT, SRC_GND, SRC_VCC, // Cap 1
SRC_PORT + 0x13, SRC_ACLK, SRC_GND, SRC_VCC // Cap 2
};
// Input map for timer B (configurable in later versions for other MSP430 versions)
public static final int[] TIMER_Bx149 = new int[] {
SRC_PORT + 0x47, SRC_ACLK, SRC_SMCLK, SRC_PORT + 0x47, // Timer
SRC_PORT + 0x40, SRC_PORT + 0x40, SRC_GND, SRC_VCC, // Cap 0
SRC_PORT + 0x41, SRC_PORT + 0x41, SRC_GND, SRC_VCC, // Cap 1
SRC_PORT + 0x42, SRC_PORT + 0x42, SRC_GND, SRC_VCC, // Cap 2
SRC_PORT + 0x43, SRC_PORT + 0x43, SRC_GND, SRC_VCC, // Cap 3
SRC_PORT + 0x44, SRC_PORT + 0x44, SRC_GND, SRC_VCC, // Cap 4
SRC_PORT + 0x45, SRC_PORT + 0x45, SRC_GND, SRC_VCC, // Cap 5
SRC_PORT + 0x46, SRC_ACLK, SRC_GND, SRC_VCC // Cap 6
};
public static final String[] capNames = new String[] {
"NONE", "RISING", "FALLING", "BOTH"
};
private final String name;
private final int tiv;
private int inputDivider = 1;
// If clocked by anything other than the SubMainClock at full
// speed this needs to be calculated for correct handling.
// Should be something like inputDivider * SMCLK_SPEED / CLK_SRC_SPEED;
private double cyclesMultiplicator = 1;
private int clockSource;
private int mode;
// The IO registers
private int tctl;
private int[] tcctl = new int[7];
private int[] tccr = new int[7];
// Support variables Max 7 compare regs for now (timer b)
private final int noCompare;
private int[] expCompare = new int[7];
private int[] expCapInterval = new int[7];
private long[] expCaptureTime = new long[7];
private int[] capMode = new int[7];
private boolean[] captureOn = new boolean[7];
private int[] inputSel = new int[7];
private int[] inputSrc = new int[7];
private boolean[] sync = new boolean[7];
private int[] outMode = new int[7];
private boolean interruptEnable = false;
private boolean interruptPending = false;
private final int ccr1Vector;
private final int ccr0Vector;
private final MSP430Core core;
private TimeEvent timerTrigger = new TimeEvent(0) {
public void execute(long t) {
updateTimers(core.cycles);
}
};
private int lastTIV;
private final int[] srcMap;
private long triggerTime;
/**
* Creates a new <code>Timer</code> instance.
*
*/
public Timer(MSP430Core core, int[] srcMap, int[] memory, int offset) {
super(memory, offset);
this.srcMap = srcMap;
this.core = core;
noCompare = (srcMap.length / 4) - 1;
if (DEBUG) {
System.out.println("Timer: noComp:" + noCompare);
}
if (srcMap == TIMER_Ax149) {
name = "Timer A";
tiv = TAIV;
timerOverflow = 0x0a;
ccr0Vector = TACCR0_VECTOR;
ccr1Vector = TACCR1_VECTOR;
} else {
name = "Timer B";
tiv = TBIV;
timerOverflow = 0x0e;
ccr0Vector = TBCCR0_VECTOR;
ccr1Vector = TBCCR1_VECTOR;
}
reset(0);
}
public void reset(int type) {
for (int i = 0, n = expCompare.length; i < n; i++) {
expCompare[i] = -1;
expCaptureTime[i] = -1;
expCapInterval[i] = 0;
outMode[i] = 0;
capMode[i] = 0;
inputSel[i] = 0;
inputSrc[i] = 0;
captureOn[i] = false;
}
for (int i = 0; i < tcctl.length; i++) {
tcctl[i] = 0;
tccr[i] = 0;
}
tctl = 0;
lastTIV = 0;
interruptEnable = false;
interruptPending = false;
counter = 0;
counterPassed = 0;
counterStart = 0;
counterAcc = 0;
clockSource = 0;
cyclesMultiplicator = 1;
mode = STOP;
nextTimerTrigger = 0;
inputDivider = 1;
}
// Should handle read of byte also (currently ignores that...)
public int read(int address, boolean word, long cycles) {
if (address == TAIV || address == TBIV) {
// should clear registers for cause of interrupt (highest value)?
// but what if a higher value have been triggered since this was
// triggered??? -> does that matter???
// But this mess the TIV up too early......
// Must DELAY the reset of interrupt flags until next read...?
int val = lastTIV;
resetTIV(cycles);
return val;
}
int val = 0;
int index = address - offset;
switch(index) {
case TR:
val = updateCounter(cycles);
// System.out.println(getName() + " TR read => " + val);
break;
case TCTL:
val = tctl;
if (interruptPending) {
val |= 1;
} else {
val &= 0xfffe;
}
if (DEBUG) {
System.out.println(getName() + " Read: " +
" CTL: inDiv:" + inputDivider +
" src: " + getSourceName(clockSource) +
" IEn:" + interruptEnable + " IFG: " +
interruptPending + " mode: " + mode);
}
break;
case TCCTL0:
case TCCTL1:
case TCCTL2:
case TCCTL3:
case TCCTL4:
case TCCTL5:
case TCCTL6:
int i = (index - TCCTL0) / 2;
val = tcctl[i];
break;
case TCCR0:
case TCCR1:
case TCCR2:
case TCCR3:
case TCCR4:
case TCCR5:
case TCCR6:
i = (index - TCCR0) / 2;
val = tccr[i];
break;
default:
System.out.println("Not supported read, returning zero!!!");
}
if (DEBUG && false) {
System.out.println(getName() + ": Read " + getName(address) + "(" + Utils.hex16(address) + ") => " +
Utils.hex16(val) + " (" + val + ")");
}
// It reads the interrupt flag for capture...
return val & 0xffff;
}
private void resetTIV(long cycles) {
if (lastTIV == timerOverflow) {
interruptPending = false;
lastTIV = 0;
if (DEBUG) {
System.out.println(getName() + " Clearing TIV - overflow ");
}
triggerInterrupts(cycles);
}
if (lastTIV / 2 < noCompare) {
if (DEBUG || true) {
System.out.println(getName() + " Clearing IFG for CCR" + (lastTIV/2));
}
// Clear interrupt flags!
tcctl[lastTIV / 2] &= ~CC_IFG;
triggerInterrupts(cycles);
}
}
public void write(int address, int data, boolean word, long cycles) {
// This does not handle word/byte difference yet... assumes it gets
// all 16 bits when called!!!
int iAddress = address - offset;
switch (iAddress) {
case TR:
setCounter(data, cycles);
break;
case TCTL:
if (DEBUG) {
System.out.println(getName() + " wrote to TCTL: " + Utils.hex16(data));
}
inputDivider = 1 << ((data >> 6) & 3);
clockSource = srcMap[(data >> 8) & 3];
updateCyclesMultiplicator();
if ((data & TCLR) != 0) {
counter = 0;
resetCounter(cycles);
updateCaptures(-1, cycles);
}
int newMode = (data >> 4) & 3;
if (mode == STOP && newMode != STOP) {
// Set the initial counter to the value that counter should have after
// recalculation
resetCounter(cycles);
// Wait until full wrap before setting the IRQ flag!
nextTimerTrigger = (long) (cycles + cyclesMultiplicator * ((0xffff - counter) & 0xffff));
if (DEBUG) {
System.out.println(getName() + " Starting timer!");
}
recalculateCompares(cycles);
}
mode = newMode;
interruptEnable = (data & 0x02) > 0;
if (DEBUG) {
System.out.println(getName() + " Write: " +
" CTL: inDiv:" + inputDivider +
" src: " + getSourceName(clockSource) +
" IEn:" + interruptEnable + " IFG: " +
interruptPending + " mode: " + mode +
((data & TCLR) != 0 ? " CLR" : ""));
}
// Write to the tctl.
tctl = data;
// Clear clear bit
tctl &= ~0x04;
// Clear interrupt pending if so requested...
if ((data & 0x01) == 0) {
interruptPending = false;
}
updateCaptures(-1, cycles);
break;
case TCCTL0:
case TCCTL1:
case TCCTL2:
case TCCTL3:
case TCCTL4:
case TCCTL5:
case TCCTL6:
// Control register...
int index = (iAddress - TCCTL0) / 2;
tcctl[index] = data;
outMode[index] = (data >> 5)& 7;
boolean oldCapture = captureOn[index];
captureOn[index] = (data & 0x100) > 0;
sync[index] = (data & 0x800) > 0;
inputSel[index] = (data >> 12) & 3;
int src = inputSrc[index] = srcMap[4 + index * 4 + inputSel[index]];
capMode[index] = (data >> 14) & 3;
/* capture a port state? */
if (!oldCapture && captureOn[index] && (src & SRC_PORT) != 0) {
int port = (src & 0xff) >> 4;
int pin = src & 0x0f;
IOPort ioPort = core.getIOPort(port);
System.out.println(getName() + " Assigning Port: " + port + " pin: " + pin +
" for capture");
ioPort.setTimerCapture(this, pin);
}
updateCounter(cycles);
triggerInterrupts(cycles);
if (DEBUG) {
System.out.println(getName() + " Write: CCTL" +
index + ": => " + Utils.hex16(data) +
" CM: " + capNames[capMode[index]] +
" CCIS:" + inputSel[index] + " name: " +
getSourceName(inputSrc[index]) +
" Capture: " + captureOn[index] +
" IE: " + ((data & CC_IE) != 0));
}
updateCaptures(index, cycles);
break;
// Write to compare register!
case TCCR0:
case TCCR1:
case TCCR2:
case TCCR3:
case TCCR4:
case TCCR5:
case TCCR6:
// update of compare register
index = (iAddress - TCCR0) / 2;
updateCounter(cycles);
if (index == 0) {
// Reset the counter to bring it down to a smaller value...
// Check if up or updwn and reset if counter too high...
if (counter > data && (mode == UPDWN || mode == UP)) {
counter = 0;
}
resetCounter(cycles);
}
tccr[index] = data;
int diff = data - counter;
if (diff < 0) {
// Ok we need to wrap!
diff += 0x10000;
}
if (DEBUG) {
System.out.println(getName() +
" Write: Setting compare " + index + " to " +
Utils.hex16(data) + " TR: " +
Utils.hex16(counter) + " diff: " + Utils.hex16(diff));
}
// Use the counterPassed information to compensate the expected capture/compare time!!!
expCaptureTime[index] = cycles + (long)(cyclesMultiplicator * diff + 1) - counterPassed;
if (DEBUG && counterPassed > 0) {
System.out.println(getName() + " Comp: " + counterPassed + " cycl: " + cycles + " TR: " +
counter + " CCR" + index + " = " + data + " diff = " + diff + " cycMul: " + cyclesMultiplicator + " expCyc: " +
expCaptureTime[index]);
}
counterPassed = 0;
if (DEBUG) {
System.out.println(getName() + " Cycles: " + cycles + " expCap[" + index + "]: " + expCaptureTime[index] + " ctr:" + counter +
" data: " + data + " ~" +
(100 * (cyclesMultiplicator * diff * 1L) / 2500000) / 100.0 + " sec" +
"at cycles: " + expCaptureTime[index]);
}
calculateNextEventTime(cycles);
}
}
void updateCyclesMultiplicator() {
cyclesMultiplicator = inputDivider;
if (clockSource == SRC_ACLK) {
cyclesMultiplicator = (cyclesMultiplicator * core.smclkFrq) /
core.aclkFrq;
if (DEBUG) {
System.out.println(getName() + " setting multiplicator to: " + cyclesMultiplicator);
}
}
}
void resetCounter(long cycles) {
counterStart = cycles - counterPassed;
// set counterACC to the last returned value (which is the same
// as bigCounter except that it is "moduloed" to a smaller value
counterAcc = counter;
updateCyclesMultiplicator();
if (DEBUG)
System.out.println(getName() + " Counter reset at " + cycles + " cycMul: " + cyclesMultiplicator);
}
private void setCounter(int newCtr, long cycles) {
counter = newCtr;
resetCounter(cycles);
}
private void updateCaptures(int index, long cycles) {
int hi = noCompare;
if (index != -1) {
hi = index + 1;
}
// A hack to handle the SMCLK synchronization
for (int i = 0, n = hi; i < n; i++) {
int divisor = 1;
int frqClk = 1;
/* used to set next capture independent of counter when another clock is source
* for the capture register!
*/
boolean clkSource = false;
if (clockSource == SRC_SMCLK) {
frqClk = core.smclkFrq / inputDivider;
} else if (clockSource == SRC_ACLK) {
frqClk = core.aclkFrq / inputDivider;
}
// Handle the captures...
if (captureOn[i]) {
if (inputSrc[i] == SRC_ACLK) {
divisor = core.aclkFrq;
clkSource = true;
}
if (DEBUG) {
System.out.println(getName() + " expCapInterval[" + i + "] frq = " +
frqClk + " div = " + divisor + " SMCLK_FRQ: " + core.smclkFrq);
}
// This is used to calculate expected time before next capture of
// clock-edge to occur - including what value the compare reg. will get
expCapInterval[i] = frqClk / divisor;
// This is not 100% correct - depending on clock mode I guess...
if (clkSource) {
/* assume that this was capture recently */
// System.out.println(">>> ACLK! fixing with expCompare!!!");
expCompare[i] = (tccr[i] + expCapInterval[i]) & 0xffff;
} else {
expCompare[i] = (counter + expCapInterval[i]) & 0xffff;
}
// This could be formulated in something other than cycles...
// ...??? should be multiplied with clockspeed diff also?
expCaptureTime[i] = cycles + (long)(expCapInterval[i] * cyclesMultiplicator);
if (DEBUG) {
System.out.println(getName() +
" Expected compare " + i +
" => " + expCompare[i] + " Diff: " + expCapInterval[i]);
System.out.println(getName() +
" Expected cap time: " + expCaptureTime[i] + " cycMult: " + cyclesMultiplicator);
System.out.println("Capture: " + captureOn[i]);
}
}
}
calculateNextEventTime(cycles);
}
private int updateCounter(long cycles) {
if (mode == STOP) return counter;
// Needs to be non-integer since smclk Frq can be lower
// than aclk
double divider = 1;
if (clockSource == SRC_ACLK) {
// Should later be divided with DCO clock?
divider = 1.0 * core.smclkFrq / core.aclkFrq;
}
divider = divider * inputDivider;
// These calculations assume that we have a big counter that counts from
// last reset and upwards (without any roundoff errors).
// tick - represent the counted value since last "reset" of some kind
// counterAcc - represent the value of the counter at the last reset.
long cycctr = cycles - counterStart;
double tick = cycctr / divider;
counterPassed = (int) (divider * (tick - (long) (tick)));
long bigCounter = (long) (tick + counterAcc);
switch (mode) {
case CONTIN:
counter = (int) (bigCounter & 0xffff);
break;
case UP:
counter = (int) (bigCounter % tccr[0]);
break;
case UPDWN:
counter = (int) (bigCounter % (tccr[0] * 2));
if (counter > tccr[0]) {
// Should back down to start again!
counter = 2 * tccr[0] - counter;
}
}
// System.out.println("CounterStart: " + counterStart + " C:" + cycles + " bigCounter: " + bigCounter +
// " counter" + counter);
if (DEBUG) {
System.out.println(getName() + ": Updating counter cycctr: " + cycctr +
" divider: " + divider + " mode:" + mode + " => " + counter);
}
return counter;
}
public long ioTick(long cycles) {
System.out.println(getName() + " UNEXPECTED CALL TO IOTICK ****");
return 100000 + cycles;
}
// Only called by the interrupt handler
private void updateTimers(long cycles) {
if (mode == STOP) {
if (DEBUG) {
System.out.println("No timer running -> no interrupt can be caused -> no scheduling...");
}
return;
}
updateCounter(cycles);
if (cycles >= nextTimerTrigger) {
interruptPending = true;
// This should be updated whenever clockspeed changes...
nextTimerTrigger = (long) (nextTimerTrigger + 0x10000 * cyclesMultiplicator);
}
// This will not work very good...
// But the timer does not need to be updated this often...
// Do we need to update the counter here???
// System.out.println("Checking capture register [ioTick]: " + cycles);
for (int i = 0, n = noCompare; i < n; i++) {
if (expCaptureTime[i] != -1 && cycles >= expCaptureTime[i]) {
if (DEBUG || true) {
System.out.println(getName() + (captureOn[i] ? " CAPTURE: " : " COMPARE: ") + i +
" Cycles: " + cycles + " expCap: " +
expCaptureTime[i] +
" => ExpCR: " + Utils.hex16(expCompare[i]) +
" TR: " + counter + " CCR" + i + ": " + tccr[i]);
}
// Set the interrupt flag...
tcctl[i] |= CC_IFG;
if (captureOn[i]) {
// Write the expected capture time to the register (counter could
// differ slightly)
tccr[i] = expCompare[i];
// Update capture times... for next capture
expCompare[i] = (expCompare[i] + expCapInterval[i]) & 0xffff;
expCaptureTime[i] += expCapInterval[i] * cyclesMultiplicator;
if (DEBUG) {
System.out.println(getName() +
" setting expCaptureTime to next capture: " +
expCaptureTime[i]);
}
} else {
// Update expected compare time for this compare/cap reg.
// 0x10000 cycles... e.g. a full 16 bits wrap of the timer
expCaptureTime[i] = expCaptureTime[i] +
(long) (0x10000 * cyclesMultiplicator);
if (DEBUG) {
System.out.println(getName() +
" setting expCaptureTime to full wrap: " +
expCaptureTime[i]);
}
}
if (DEBUG) {
System.out.println("Wrote to: " +
Utils.hex16(offset + TCCTL0 + i * 2 + 1));
}
}
}
// Trigger interrupts that are up for triggering!
triggerInterrupts(cycles);
calculateNextEventTime(cycles);
}
private void recalculateCompares(long cycles) {
System.out.println("**** RECALCULATE COMPARES !!! ****");
for (int i = 0; i < expCaptureTime.length; i++) {
if (expCaptureTime[i] != 0) {
int diff = tccr[i] - counter;
if (diff < 0) {
// Wrap...
diff += 0x10000;
}
expCaptureTime[i] = cycles + (long) (diff * cyclesMultiplicator);
if (i == 0) {
System.out.println("Updating capture time for CCR0: " + expCaptureTime[0] +
" cyc: " + cycles);
}
}
}
}
private void calculateNextEventTime(long cycles) {
if (mode == STOP) {
// If nothing is "running" there is no point scheduling...
return;
}
long time = nextTimerTrigger;
// int smallest = -1;
for (int i = 0; i < noCompare; i++) {
long ct = expCaptureTime[i];
if (ct > 0 && ct < time) {
time = ct;
// smallest = i;
}
}
if (time == 0) {
time = cycles + 1000;
}
if (timerTrigger.scheduledIn == null) {
// System.out.println(getName() + " new trigger (nothing sch) ..." + time + " re:" +
// smallest + " => " + (smallest > 0 ? expCaptureTime[smallest] + " > " + expCompare[smallest]:
// nextTimerTrigger) + " C:"+ cycles);
core.scheduleCycleEvent(timerTrigger, time);
} else if (timerTrigger.time > time) {
// System.out.println(getName() + " new trigger (new time)..." + time + " C:"+ cycles);
core.scheduleCycleEvent(timerTrigger, time);
}
}
// Can be called to generate any interrupt...
// TODO: check if it is ok that this also sets the flags to false or if that must
// be done by software (e.g. firmware)
public void triggerInterrupts(long cycles) {
// First check if any capture register is generating an interrupt...
boolean trigger = false;
int tIndex = 0;
for (int i = 0, n = noCompare; i < n; i++) {
// check for both IFG and IE
boolean newTrigger = (tcctl[i] & CC_TRIGGER_INT) == CC_TRIGGER_INT;
trigger = trigger | newTrigger;
// This only triggers interrupts - reading TIV clears!??!
if (i == 0) {
// Execute the interrupt vector... the high-pri one...
if (DEBUG) {
System.out.println(getName() +" >>>> Trigger IRQ for CCR0: " + tccr[0] +
" TAR: " + counter + " cycles: " + cycles + " expCap: " + expCaptureTime[0]);
}
if (counter != tccr[0] && trigger) {
System.out.print("***** WARNING!!! CTR Err ");
System.out.println(getName() +" >>>> Trigger IRQ for CCR0: " + tccr[0] +
" TAR: " + counter + " cycles: " + cycles + " expCap: " + expCaptureTime[0]);
}
core.flagInterrupt(ccr0Vector, this, trigger);
// Trigger this!
// This is handled by its own vector!!!
if (trigger) {
lastTIV = 0;
triggerTime = cycles;
return;
}
} else {
// Which would have the highest pri? Will/should this trigger more
// than one interrupt at a time?!!?!?!
// If so, which TIV would be the correct one?
if (newTrigger) {
if (DEBUG) {
System.out.println(getName() + " >>>> Triggering IRQ for CCR" + i +
" at cycles:" + cycles + " CCR" + i + ": " + tccr[i] + " TAR: " +
counter);
}
tIndex = i;
// Lower numbers are higher priority
break;
}
}
}
if (trigger) {
// Or if other CCR execute the normal one with correct TAIV
lastTIV = memory[tiv] = tIndex * 2;
triggerTime = cycles;
if (DEBUG) System.out.println(getName() +
" >>>> Triggering IRQ for CCR" + tIndex +
" at cycles:" + cycles + " CCR" + tIndex + ": " + tccr[tIndex] + " TAR: " +
counter);
if (counter != tccr[tIndex]) {
System.out.print("***** WARNING!!! CTR Err ");
System.out.println(getName() +
" >>>> Triggering IRQ for CCR" + tIndex +
" at cycles:" + cycles + " CCR" + tIndex + ": " + tccr[tIndex] + " TAR: " +
counter + " expCap: " + expCaptureTime[tIndex]);
}
}
if (!trigger) {
if (interruptEnable && interruptPending) {
trigger = true;
lastTIV = memory[tiv] = timerOverflow;
}
}
// System.out.println(getName() +">>>> Trigger IRQ for CCR:" + tIndex);
core.flagInterrupt(ccr1Vector, this, trigger);
}
public String getSourceName(int source) {
switch (source) {
case SRC_ACLK:
return "ACLK";
case SRC_VCC:
return "VCC";
case SRC_GND:
return "GND";
case SRC_SMCLK:
return "SMCLK";
default:
if ((source & SRC_PORT) == SRC_PORT) {
return "Port " + ((source & 0xf0) >> 4) + "." +
(source & 0xf);
}
}
return "";
}
public String getName() {
return name;
}
/**
* capture - perform a capture if the timer CCRx is configured for captures
* Note: capture may only be called when value has changed
* @param ccrIndex - the capture register
* @param source - the capture source (0/1)
*/
public void capture(int ccrIndex, int source, int value) {
if (ccrIndex < noCompare && captureOn[ccrIndex] && inputSel[ccrIndex] == source) {
/* This is obviously a capture! */
boolean rise = (capMode[ccrIndex] & CM_RISING) != 0;
boolean fall = (capMode[ccrIndex] & CM_FALLING) != 0;
if ((value == IOPort.PIN_HI && rise) ||
(value == IOPort.PIN_LOW && fall)) {
// value);
// Set the interrupt flag...
tcctl[ccrIndex] |= CC_IFG;
triggerInterrupts(core.cycles);
}
}
}
// The interrupt has been serviced...
// Some flags should be cleared (the highest priority flags)?
public void interruptServiced(int vector) {
if (vector == ccr0Vector) {
// Reset the interrupt trigger in "core".
core.flagInterrupt(ccr0Vector, this, false);
// Remove the flag also...
tcctl[0] &= ~CC_IFG;
System.out.println(getName() + " >>>> CCR0 flag set to false");
}
if (MSP430Core.debugInterrupts || true) {
System.out.println(getName() + " >>>> interrupt Serviced " + lastTIV +
" at cycles: " + core.cycles + " servicing delay: " + (core.cycles - triggerTime));
}
triggerInterrupts(core.cycles);
}
public int getModeMax() {
return 0;
}
public String getName(int address) {
int reg = address - offset;
if (reg == 0) return "TCTL";
if (reg < 0x10) return "TCTL" + (reg - 2) / 2;
if (reg == 0x10) return "TR";
if (reg < 0x20) return "TCCR" + (reg - 0x12) / 2;
return " UNDEF(" + Utils.hex16(address) + ")";
}
}
|
package mondrian.test.loader;
import mondrian.olap.MondrianResource;
import mondrian.olap.Util;
import mondrian.rolap.RolapUtil;
import mondrian.rolap.sql.SqlQuery;
import java.io.*;
import java.math.BigDecimal;
//import java.math.BigDecimal;
import java.sql.*;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Utility to load the FoodMart dataset into an arbitrary JDBC database.
*
* <p>It is known to work for the following databases:<ul>
*
* <li>MySQL 3.23 using MySQL-connector/J 3.0.16
* <p>On the command line:
*
* <blockquote><code>
* $ mysqladmin create foodmart<br/>
* $ java -cp 'classes;testclasses' mondrian.test.loader.MondrianFoodMartLoader
* -verbose -tables -data -indexes -jdbcDrivers=com.mysql.jdbc.Driver
* -outputJdbcURL=jdbc:mysql://localhost/foodmart
* </code></blockquote>
* </li>
*
* <li>MySQL 4.15 using MySQL-connector/J 3.0.16</li>
*
* <li>Postgres 8.0 beta using postgresql-driver-jdbc3-74-214.jar</li>
*
* </ul>
*
* @author jhyde
* @since 23 December, 2004
* @version $Id$
*/
public class MondrianFoodMartLoader {
private String jdbcDrivers;
private String jdbcURL;
private String userName;
private String password;
private String inputJdbcURL;
private String inputUserName;
private String inputPassword;
private String inputFile;
private String outputDirectory;
private boolean tables = false;
private boolean indexes = false;
private boolean data = false;
private static final String nl = System.getProperty("line.separator");
private boolean verbose = false;
private boolean jdbcInput = false;
private boolean jdbcOutput = false;
private int inputBatchSize = 50;
private Connection connection;
private Connection inputConnection;
private FileWriter fileOutput = null;
private SqlQuery sqlQuery;
private final HashMap mapTableNameToColumns = new HashMap();
public MondrianFoodMartLoader(String[] args) {
StringBuffer errorMessage = new StringBuffer();
for ( int i=0; i<args.length; i++ ) {
if (args[i].equals("-verbose")) {
verbose = true;
} else if (args[i].equals("-tables")) {
tables = true;
} else if (args[i].equals("-data")) {
data = true;
} else if (args[i].equals("-indexes")) {
indexes = true;
} else if (args[i].startsWith("-jdbcDrivers=")) {
jdbcDrivers = args[i].substring("-jdbcDrivers=".length());
} else if (args[i].startsWith("-outputJdbcURL=")) {
jdbcURL = args[i].substring("-outputJdbcURL=".length());
} else if (args[i].startsWith("-outputJdbcUser=")) {
userName = args[i].substring("-outputJdbcUser=".length());
} else if (args[i].startsWith("-outputJdbcPassword=")) {
password = args[i].substring("-outputJdbcPassword=".length());
} else if (args[i].startsWith("-inputJdbcURL=")) {
inputJdbcURL = args[i].substring("-inputJdbcURL=".length());
} else if (args[i].startsWith("-inputJdbcUser=")) {
inputUserName = args[i].substring("-inputJdbcUser=".length());
} else if (args[i].startsWith("-inputJdbcPassword=")) {
inputPassword = args[i].substring("-inputJdbcPassword=".length());
} else if (args[i].startsWith("-inputFile=")) {
inputFile = args[i].substring("-inputFile=".length());
} else if (args[i].startsWith("-outputDirectory=")) {
outputDirectory = args[i].substring("-outputDirectory=".length());
} else if (args[i].startsWith("-outputJdbcBatchSize=")) {
inputBatchSize = Integer.parseInt(args[i].substring("-outputJdbcBatchSize=".length()));
} else {
errorMessage.append("unknown arg: " + args[i] + "\n");
}
}
if (inputJdbcURL != null) {
jdbcInput = true;
if (inputFile != null) {
errorMessage.append("Specified both an input JDBC connection and an input file");
}
}
if (jdbcURL != null && outputDirectory == null) {
jdbcOutput = true;
}
if (errorMessage.length() > 0) {
usage();
throw MondrianResource.instance().newMissingArg(errorMessage.toString());
}
}
public void usage() {
System.out.println("Usage: MondrianFoodMartLoader [-verbose] [-tables] [-data] [-indexes] -jdbcDrivers=<jdbcDriver> [-outputJdbcURL=<jdbcURL> [-outputJdbcUser=user] [-outputJdbcPassword=password] [-outputJdbcBatchSize=<batch size>] | -outputDirectory=<directory name>] [ [-inputJdbcURL=<jdbcURL> [-inputJdbcUser=user] [-inputJdbcPassword=password]] | [-inputfile=<file name>]]");
System.out.println("");
System.out.println(" <jdbcURL> JDBC connect string for DB");
System.out.println(" [user] JDBC user name for DB");
System.out.println(" [password] JDBC password for user for DB");
System.out.println(" If no source DB parameters are given, assumes data comes from file");
System.out.println(" [file name] file containing test data - INSERT statements");
System.out.println(" If no input file name or input JDBC parameters are given, assume insert statements come from demo/FoodMartData.sql file");
System.out.println(" [outputDirectory] Where FoodMartCreateTables.sql, FoodMartData.sql and FoodMartCreateIndexes.sql will be created");
System.out.println(" <batch size> size of JDBC batch updates - default to 50 inserts");
System.out.println(" <jdbcDrivers> Comma-separated list of JDBC drivers.");
System.out.println(" They must be on the classpath.");
System.out.println(" -verbose Verbose mode.");
System.out.println(" -tables If specified, drop and create the tables.");
System.out.println(" -data If specified, load the data.");
System.out.println(" -indexes If specified, drop and create the tables.");
}
public static void main(String[] args) {
System.out.println("Starting load at: " + (new Date()));
try {
new MondrianFoodMartLoader(args).load();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("Finished load at: " + (new Date()));
}
private void load() throws Exception {
RolapUtil.loadDrivers(jdbcDrivers);
if (userName == null) {
connection = DriverManager.getConnection(jdbcURL);
} else {
connection = DriverManager.getConnection(jdbcURL, userName, password);
}
if (jdbcInput) {
if (inputUserName == null) {
inputConnection = DriverManager.getConnection(inputJdbcURL);
} else {
inputConnection = DriverManager.getConnection(inputJdbcURL, inputUserName, inputPassword);
}
}
final DatabaseMetaData metaData = connection.getMetaData();
sqlQuery = new SqlQuery(metaData);
try {
createTables(); // This also initializes mapTableNameToColumns
if (data) {
if (jdbcInput) {
loadDataFromJdbcInput();
} else {
loadDataFromFile();
}
}
if (indexes) {
createIndexes();
}
} finally {
if (connection != null) {
connection.close();
connection = null;
}
if (inputConnection != null) {
inputConnection.close();
inputConnection = null;
}
if (fileOutput != null) {
fileOutput.close();
fileOutput = null;
}
}
}
private void loadDataFromFile() throws IOException, SQLException {
final InputStream is = openInputStream();
final InputStreamReader reader = new InputStreamReader(is);
final BufferedReader bufferedReader = new BufferedReader(reader);
final Pattern regex = Pattern.compile("INSERT INTO ([^ ]+)(.*)VALUES(.*)\\((.*)\\);");
String line;
int lineNumber = 0;
int tableRowCount = 0;
String prevTable = "";
String[] batch = new String[inputBatchSize];
int batchSize = 0;
while ((line = bufferedReader.readLine()) != null) {
++lineNumber;
if (line.startsWith("
continue;
}
// Split the up the line. For example,
// INSERT INTO foo VALUES (1, 'bar');
// would yield
// tableName = "foo"
// values = "1, 'bar'"
final Matcher matcher = regex.matcher(line);
if (!matcher.matches()) {
throw MondrianResource.instance().newInvalidInsertLine(
new Integer(lineNumber), line);
}
final String tableName = matcher.group(1); // e.g. "foo"
final String values = matcher.group(2); // e.g. "1, 'bar'"
Util.discard(values); // Not needed now
// If table just changed, flush the previous batch.
if (!tableName.equals(prevTable)) {
if (!prevTable.equals("")) {
System.out.println("Table " + prevTable +
": loaded " + tableRowCount + " rows.");
}
tableRowCount = 0;
writeBatch(batch, batchSize);
batchSize = 0;
prevTable = tableName;
}
// remove trailing ';'
assert line.endsWith(";");
line = line.substring(0, line.length() - 1);
// this database represents booleans as integers
if (sqlQuery.isMySQL()) {
line = line.replaceAll("false", "0")
.replaceAll("true", "1");
}
++tableRowCount;
batch[batchSize++] = line;
if (batchSize >= inputBatchSize) {
writeBatch(batch, batchSize);
batchSize = 0;
}
}
// Print summary of the final table.
if (!prevTable.equals("")) {
System.out.println("Table " + prevTable +
": loaded " + tableRowCount + " rows.");
tableRowCount = 0;
writeBatch(batch, batchSize);
batchSize = 0;
}
}
private void loadDataFromJdbcInput() throws Exception {
if (outputDirectory != null) {
fileOutput = new FileWriter(new File(outputDirectory, "createData.sql"));
}
/*
* For each input table,
* read specified columns for all rows in the input connection
*
* For each row, insert a row
*/
for (Iterator it = mapTableNameToColumns.entrySet().iterator(); it.hasNext(); ) {
Map.Entry tableEntry = (Map.Entry) it.next();
int rowsAdded = loadTable((String) tableEntry.getKey(), (Column[]) tableEntry.getValue());
System.out.println("Table " + (String) tableEntry.getKey() +
": loaded " + rowsAdded + " rows.");
}
if (outputDirectory != null) {
fileOutput.close();
}
}
private int loadTable(String name, Column[] columns) throws Exception {
int rowsAdded = 0;
StringBuffer buf = new StringBuffer();
buf.append("select ");
for (int i = 0; i < columns.length; i++) {
Column column = columns[i];
if (i > 0) {
buf.append(",");
}
buf.append(quoteId(column.name));
}
buf.append(" from ")
.append(quoteId(name));
String ddl = buf.toString();
Statement statement = inputConnection.createStatement();
if (verbose) {
System.out.println("Input table SQL: " + ddl);
}
ResultSet rs = statement.executeQuery(ddl);
String[] batch = new String[inputBatchSize];
int batchSize = 0;
while (rs.next()) {
/*
* Get a batch of insert statements, then save a batch
*/
batch[batchSize++] = createInsertStatement(rs, name, columns);
if (batchSize >= inputBatchSize) {
rowsAdded += writeBatch(batch, batchSize);
batchSize = 0;
}
}
if (batchSize > 0) {
rowsAdded += writeBatch(batch, batchSize);
}
return rowsAdded;
}
private String createInsertStatement(ResultSet rs, String name, Column[] columns) throws Exception {
StringBuffer buf = new StringBuffer();
buf.append("INSERT INTO ")
.append(quoteId(name))
.append(" ( ");
for (int i = 0; i < columns.length; i++) {
Column column = columns[i];
if (i > 0) {
buf.append(",");
}
buf.append(quoteId(column.name));
}
buf.append(" ) VALUES(");
for (int i = 0; i < columns.length; i++) {
Column column = columns[i];
if (i > 0) {
buf.append(",");
}
buf.append(columnValue(rs, column));
}
buf.append(" )");
return buf.toString();
}
private int writeBatch(String[] batch, int batchSize) throws IOException, SQLException {
if (outputDirectory != null) {
for (int i = 0; i < batchSize; i++) {
fileOutput.write(batch[i]);
fileOutput.write(";\n");
}
} else {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
if (batchSize == 1) {
// Don't use batching if there's only one item. This allows
// us to work around bugs in the JDBC driver by setting
// outputJdbcBatchSize=1.
stmt.execute(batch[0]);
} else {
for (int i = 0; i < batchSize; i++) {
stmt.addBatch(batch[i]);
}
int [] updateCounts = stmt.executeBatch();
int updates = 0;
for (int i = 0; i < updateCounts.length; updates += updateCounts[i], i++) {
if (updateCounts[i] == 0) {
System.out.println("Error in SQL: " + batch[i]);
}
}
if (updates < batchSize) {
throw new RuntimeException("Failed to execute batch: " + batchSize + " versus " + updates);
}
}
stmt.close();
connection.setAutoCommit(true);
}
return batchSize;
}
private FileInputStream openInputStream() {
final File file = (inputFile != null) ? new File(inputFile) : new File("demo", "FoodMartData.sql");
if (file.exists()) {
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
}
} else {
System.out.println("No input file: " + file);
}
return null;
}
private void createIndexes() throws Exception {
if (outputDirectory != null) {
fileOutput = new FileWriter(new File(outputDirectory, "createIndexes.sql"));
}
createIndex(true, "account", "i_account_id", new String[] {"account_id"});
createIndex(false, "account", "i_account_parent", new String[] {"account_parent"});
createIndex(true, "category", "i_category_id", new String[] {"category_id"});
createIndex(false, "category", "i_category_parent", new String[] {"category_parent"});
createIndex(true, "currency", "i_currency", new String[] {"currency_id", "date"});
createIndex(false, "customer", "i_customer_account_num", new String[] {"account_num"});
createIndex(false, "customer", "i_customer_fname", new String[] {"fname"});
createIndex(false, "customer", "i_customer_lname", new String[] {"lname"});
createIndex(false, "customer", "i_customer_children_at_home", new String[] {"num_children_at_home"});
createIndex(true, "customer", "i_customer_id", new String[] {"customer_id"});
createIndex(false, "customer", "i_customer_postal_code", new String[] {"postal_code"});
createIndex(false, "customer", "i_customer_region_id", new String[] {"customer_region_id"});
createIndex(true, "department", "i_department_id", new String[] {"department_id"});
createIndex(true, "employee", "i_employee_id", new String[] {"employee_id"});
createIndex(false, "employee", "i_employee_department_id", new String[] {"department_id"});
createIndex(false, "employee", "i_employee_store_id", new String[] {"store_id"});
createIndex(false, "employee", "i_employee_supervisor_id", new String[] {"supervisor_id"});
createIndex(true, "employee_closure", "i_employee_closure", new String[] {"supervisor_id", "employee_id"});
createIndex(false, "employee_closure", "i_employee_closure_emp", new String[] {"employee_id"});
createIndex(false, "expense_fact", "i_expense_store_id", new String[] {"store_id"});
createIndex(false, "expense_fact", "i_expense_account_id", new String[] {"account_id"});
createIndex(false, "expense_fact", "i_expense_time_id", new String[] {"time_id"});
createIndex(false, "inventory_fact_1997", "i_inv_1997_product_id", new String[] {"product_id"});
createIndex(false, "inventory_fact_1997", "i_inv_1997_store_id", new String[] {"store_id"});
createIndex(false, "inventory_fact_1997", "i_inv_1997_time_id", new String[] {"time_id"});
createIndex(false, "inventory_fact_1997", "i_inv_1997_warehouse_id", new String[] {"warehouse_id"});
createIndex(false, "inventory_fact_1998", "i_inv_1998_product_id", new String[] {"product_id"});
createIndex(false, "inventory_fact_1998", "i_inv_1998_store_id", new String[] {"store_id"});
createIndex(false, "inventory_fact_1998", "i_inv_1998_time_id", new String[] {"time_id"});
createIndex(false, "inventory_fact_1998", "i_inv_1998_warehouse_id", new String[] {"warehouse_id"});
createIndex(true, "position", "i_position_id", new String[] {"position_id"});
createIndex(false, "product", "i_product_brand_name", new String[] {"brand_name"});
createIndex(true, "product", "i_product_id", new String[] {"product_id"});
createIndex(false, "product", "i_product_class_id", new String[] {"product_class_id"});
createIndex(false, "product", "i_product_name", new String[] {"product_name"});
createIndex(false, "product", "i_product_SKU", new String[] {"SKU"});
createIndex(true, "promotion", "i_promotion_id", new String[] {"promotion_id"});
createIndex(false, "promotion", "i_promotion_district_id", new String[] {"promotion_district_id"});
createIndex(true, "reserve_employee", "i_reserve_employee_id", new String[] {"employee_id"});
createIndex(false, "reserve_employee", "i_reserve_employee_dept_id", new String[] {"department_id"});
createIndex(false, "reserve_employee", "i_reserve_employee_store_id", new String[] {"store_id"});
createIndex(false, "reserve_employee", "i_reserve_employee_super_id", new String[] {"supervisor_id"});
createIndex(false, "sales_fact_1997", "i_sales_1997_customer_id", new String[] {"customer_id"});
createIndex(false, "sales_fact_1997", "i_sales_1997_product_id", new String[] {"product_id"});
createIndex(false, "sales_fact_1997", "i_sales_1997_promotion_id", new String[] {"promotion_id"});
createIndex(false, "sales_fact_1997", "i_sales_1997_store_id", new String[] {"store_id"});
createIndex(false, "sales_fact_1997", "i_sales_1997_time_id", new String[] {"time_id"});
createIndex(false, "sales_fact_dec_1998", "i_sales_dec_1998_customer_id", new String[] {"customer_id"});
createIndex(false, "sales_fact_dec_1998", "i_sales_dec_1998_product_id", new String[] {"product_id"});
createIndex(false, "sales_fact_dec_1998", "i_sales_dec_1998_promotion_id", new String[] {"promotion_id"});
createIndex(false, "sales_fact_dec_1998", "i_sales_dec_1998_store_id", new String[] {"store_id"});
createIndex(false, "sales_fact_dec_1998", "i_sales_dec_1998_time_id", new String[] {"time_id"});
createIndex(false, "sales_fact_1998", "i_sales_1998_customer_id", new String[] {"customer_id"});
createIndex(false, "sales_fact_1998", "i_sales_1998_product_id", new String[] {"product_id"});
createIndex(false, "sales_fact_1998", "i_sales_1998_promotion_id", new String[] {"promotion_id"});
createIndex(false, "sales_fact_1998", "i_sales_1998_store_id", new String[] {"store_id"});
createIndex(false, "sales_fact_1998", "i_sales_1998_time_id", new String[] {"time_id"});
createIndex(true, "store", "i_store_id", new String[] {"store_id"});
createIndex(false, "store", "i_store_region_id", new String[] {"region_id"});
if (outputDirectory != null) {
fileOutput.close();
}
}
private void createIndex(
boolean isUnique,
String tableName,
String indexName,
String[] columnNames)
{
try {
StringBuffer buf = new StringBuffer();
buf.append(isUnique ? "CREATE UNIQUE INDEX " : "CREATE INDEX ")
.append(quoteId(indexName)).append(" ON ")
.append(quoteId(tableName)).append(" (");
for (int i = 0; i < columnNames.length; i++) {
String columnName = columnNames[i];
if (i > 0) {
buf.append(", ");
}
buf.append(quoteId(columnName));
}
buf.append(")");
final String ddl = buf.toString();
if (verbose) {
System.out.println(ddl);
}
if (jdbcOutput) {
final Statement statement = connection.createStatement();
statement.execute(ddl);
} else {
fileOutput.write(ddl);
fileOutput.write(";\n");
}
} catch (Exception e) {
throw MondrianResource.instance().newCreateIndexFailed(indexName,
tableName, e);
}
}
/**
* Also initializes mapTableNameToColumns
*
* @throws Exception
*/
private void createTables() throws Exception {
if (outputDirectory != null) {
fileOutput = new FileWriter(new File(outputDirectory, "createTables.sql"));
}
String booleanColumnType = "BIT";
if (sqlQuery.isPostgres()) {
booleanColumnType = "BOOLEAN";
}
createTable("sales_fact_1997", new Column[] {
new Column("product_id", "INTEGER", "NOT NULL"),
new Column("time_id", "INTEGER", "NOT NULL"),
new Column("customer_id", "INTEGER", "NOT NULL"),
new Column("promotion_id", "INTEGER", "NOT NULL"),
new Column("store_id", "INTEGER", "NOT NULL"),
new Column("store_sales", "DECIMAL(10,4)", "NOT NULL"),
new Column("store_cost", "DECIMAL(10,4)", "NOT NULL"),
new Column("unit_sales", "DECIMAL(10,4)", "NOT NULL"),
});
createTable("sales_fact_1998", new Column[] {
new Column("product_id", "INTEGER", "NOT NULL"),
new Column("time_id", "INTEGER", "NOT NULL"),
new Column("customer_id", "INTEGER", "NOT NULL"),
new Column("promotion_id", "INTEGER", "NOT NULL"),
new Column("store_id", "INTEGER", "NOT NULL"),
new Column("store_sales", "DECIMAL(10,4)", "NOT NULL"),
new Column("store_cost", "DECIMAL(10,4)", "NOT NULL"),
new Column("unit_sales", "DECIMAL(10,4)", "NOT NULL"),
});
createTable("sales_fact_dec_1998", new Column[] {
new Column("product_id", "INTEGER", "NOT NULL"),
new Column("time_id", "INTEGER", "NOT NULL"),
new Column("customer_id", "INTEGER", "NOT NULL"),
new Column("promotion_id", "INTEGER", "NOT NULL"),
new Column("store_id", "INTEGER", "NOT NULL"),
new Column("store_sales", "DECIMAL(10,4)", "NOT NULL"),
new Column("store_cost", "DECIMAL(10,4)", "NOT NULL"),
new Column("unit_sales", "DECIMAL(10,4)", "NOT NULL"),
});
createTable("inventory_fact_1997", new Column[] {
new Column("product_id", "INTEGER", "NOT NULL"),
new Column("time_id", "INTEGER", ""),
new Column("warehouse_id", "INTEGER", ""),
new Column("store_id", "INTEGER", ""),
new Column("units_ordered", "INTEGER", ""),
new Column("units_shipped", "INTEGER", ""),
new Column("warehouse_sales", "DECIMAL(10,4)", ""),
new Column("warehouse_cost", "DECIMAL(10,4)", ""),
new Column("supply_time", "SMALLINT", ""),
new Column("store_invoice", "DECIMAL(10,4)", ""),
});
createTable("inventory_fact_1998", new Column[] {
new Column("product_id", "INTEGER", "NOT NULL"),
new Column("time_id", "INTEGER", ""),
new Column("warehouse_id", "INTEGER", ""),
new Column("store_id", "INTEGER", ""),
new Column("units_ordered", "INTEGER", ""),
new Column("units_shipped", "INTEGER", ""),
new Column("warehouse_sales", "DECIMAL(10,4)", ""),
new Column("warehouse_cost", "DECIMAL(10,4)", ""),
new Column("supply_time", "SMALLINT", ""),
new Column("store_invoice", "DECIMAL(10,4)", ""),
});
createTable("account", new Column[] {
new Column("account_id", "INTEGER", "NOT NULL"),
new Column("account_parent", "INTEGER", ""),
new Column("account_description", "VARCHAR(30)", ""),
new Column("account_type", "VARCHAR(30)", "NOT NULL"),
new Column("account_rollup", "VARCHAR(30)", "NOT NULL"),
new Column("Custom_Members", "VARCHAR(255)", ""),
});
createTable("category", new Column[] {
new Column("category_id", "VARCHAR(30)", "NOT NULL"),
new Column("category_parent", "VARCHAR(30)", ""),
new Column("category_description", "VARCHAR(30)", "NOT NULL"),
new Column("category_rollup", "VARCHAR(30)", ""),
});
createTable("currency", new Column[] {
new Column("currency_id", "INTEGER", "NOT NULL"),
new Column("date", "DATE", "NOT NULL"),
new Column("currency", "VARCHAR(30)", "NOT NULL"),
new Column("conversion_ratio", "DECIMAL(10,4)", "NOT NULL"),
});
createTable("customer", new Column[] {
new Column("customer_id", "INTEGER", "NOT NULL"),
new Column("account_num", "BIGINT", "NOT NULL"),
new Column("lname", "VARCHAR(30)", "NOT NULL"),
new Column("fname", "VARCHAR(30)", "NOT NULL"),
new Column("mi", "VARCHAR(30)", ""),
new Column("address1", "VARCHAR(30)", ""),
new Column("address2", "VARCHAR(30)", ""),
new Column("address3", "VARCHAR(30)", ""),
new Column("address4", "VARCHAR(30)", ""),
new Column("city", "VARCHAR(30)", ""),
new Column("state_province", "VARCHAR(30)", ""),
new Column("postal_code", "VARCHAR(30)", "NOT NULL"),
new Column("country", "VARCHAR(30)", "NOT NULL"),
new Column("customer_region_id", "INTEGER", "NOT NULL"),
new Column("phone1", "VARCHAR(30)", "NOT NULL"),
new Column("phone2", "VARCHAR(30)", "NOT NULL"),
new Column("birthdate", "DATE", "NOT NULL"),
new Column("marital_status", "VARCHAR(30)", "NOT NULL"),
new Column("yearly_income", "VARCHAR(30)", "NOT NULL"),
new Column("gender", "VARCHAR(30)", "NOT NULL"),
new Column("total_children", "SMALLINT", "NOT NULL"),
new Column("num_children_at_home", "SMALLINT", "NOT NULL"),
new Column("education", "VARCHAR(30)", "NOT NULL"),
new Column("date_accnt_opened", "DATE", "NOT NULL"),
new Column("member_card", "VARCHAR(30)", ""),
new Column("occupation", "VARCHAR(30)", ""),
new Column("houseowner", "VARCHAR(30)", ""),
new Column("num_cars_owned", "INTEGER", ""),
});
createTable("days", new Column[] {
new Column("day", "INTEGER", "NOT NULL"),
new Column("week_day", "VARCHAR(30)", "NOT NULL"),
});
createTable("department", new Column[] {
new Column("department_id", "INTEGER", "NOT NULL"),
new Column("department_description", "VARCHAR(30)", "NOT NULL"),
});
createTable("employee", new Column[] {
new Column("employee_id", "INTEGER", "NOT NULL"),
new Column("full_name", "VARCHAR(30)", "NOT NULL"),
new Column("first_name", "VARCHAR(30)", "NOT NULL"),
new Column("last_name", "VARCHAR(30)", "NOT NULL"),
new Column("position_id", "INTEGER", ""),
new Column("position_title", "VARCHAR(30)", ""),
new Column("store_id", "INTEGER", "NOT NULL"),
new Column("department_id", "INTEGER", "NOT NULL"),
new Column("birth_date", "DATE", "NOT NULL"),
new Column("hire_date", "TIMESTAMP", ""),
new Column("end_date", "TIMESTAMP", ""),
new Column("salary", "DECIMAL(10,4)", "NOT NULL"),
new Column("supervisor_id", "INTEGER", ""),
new Column("education_level", "VARCHAR(30)", "NOT NULL"),
new Column("marital_status", "VARCHAR(30)", "NOT NULL"),
new Column("gender", "VARCHAR(30)", "NOT NULL"),
new Column("management_role", "VARCHAR(30)", ""),
});
createTable("employee_closure", new Column[] {
new Column("employee_id", "INTEGER", "NOT NULL"),
new Column("supervisor_id", "INTEGER", "NOT NULL"),
new Column("distance", "INTEGER", ""),
});
createTable("expense_fact", new Column[] {
new Column("store_id", "INTEGER", "NOT NULL"),
new Column("account_id", "INTEGER", "NOT NULL"),
new Column("exp_date", "TIMESTAMP", "NOT NULL"),
new Column("time_id", "INTEGER", "NOT NULL"),
new Column("category_id", "VARCHAR(30)", "NOT NULL"),
new Column("currency_id", "INTEGER", "NOT NULL"),
new Column("amount", "DECIMAL(10,4)", "NOT NULL"),
});
createTable("position", new Column[] {
new Column("position_id", "INTEGER", "NOT NULL"),
new Column("position_title", "VARCHAR(30)", "NOT NULL"),
new Column("pay_type", "VARCHAR(30)", "NOT NULL"),
new Column("min_scale", "DECIMAL(10,4)", "NOT NULL"),
new Column("max_scale", "DECIMAL(10,4)", "NOT NULL"),
new Column("management_role", "VARCHAR(30)", "NOT NULL"),
});
createTable("product", new Column[] {
new Column("product_class_id", "INTEGER", "NOT NULL"),
new Column("product_id", "INTEGER", "NOT NULL"),
new Column("brand_name", "VARCHAR(60)", ""),
new Column("product_name", "VARCHAR(60)", "NOT NULL"),
new Column("SKU", "BIGINT", "NOT NULL"),
new Column("SRP", "DECIMAL(10,4)", ""),
new Column("gross_weight", "REAL", ""),
new Column("net_weight", "REAL", ""),
new Column("recyclable_package", booleanColumnType, ""),
new Column("low_fat", booleanColumnType, ""),
new Column("units_per_case", "SMALLINT", ""),
new Column("cases_per_pallet", "SMALLINT", ""),
new Column("shelf_width", "REAL", ""),
new Column("shelf_height", "REAL", ""),
new Column("shelf_depth", "REAL", ""),
});
createTable("product_class", new Column[] {
new Column("product_class_id", "INTEGER", "NOT NULL"),
new Column("product_subcategory", "VARCHAR(30)", ""),
new Column("product_category", "VARCHAR(30)", ""),
new Column("product_department", "VARCHAR(30)", ""),
new Column("product_family", "VARCHAR(30)", ""),
});
createTable("promotion", new Column[] {
new Column("promotion_id", "INTEGER", "NOT NULL"),
new Column("promotion_district_id", "INTEGER", ""),
new Column("promotion_name", "VARCHAR(30)", ""),
new Column("media_type", "VARCHAR(30)", ""),
new Column("cost", "DECIMAL(10,4)", ""),
new Column("start_date", "TIMESTAMP", ""),
new Column("end_date", "TIMESTAMP", ""),
});
createTable("region", new Column[] {
new Column("region_id", "INTEGER", "NOT NULL"),
new Column("sales_city", "VARCHAR(30)", ""),
new Column("sales_state_province", "VARCHAR(30)", ""),
new Column("sales_district", "VARCHAR(30)", ""),
new Column("sales_region", "VARCHAR(30)", ""),
new Column("sales_country", "VARCHAR(30)", ""),
new Column("sales_district_id", "INTEGER", ""),
});
createTable("reserve_employee", new Column[] {
new Column("employee_id", "INTEGER", "NOT NULL"),
new Column("full_name", "VARCHAR(30)", "NOT NULL"),
new Column("first_name", "VARCHAR(30)", "NOT NULL"),
new Column("last_name", "VARCHAR(30)", "NOT NULL"),
new Column("position_id", "INTEGER", ""),
new Column("position_title", "VARCHAR(30)", ""),
new Column("store_id", "INTEGER", "NOT NULL"),
new Column("department_id", "INTEGER", "NOT NULL"),
new Column("birth_date", "TIMESTAMP", "NOT NULL"),
new Column("hire_date", "TIMESTAMP", ""),
new Column("end_date", "TIMESTAMP", ""),
new Column("salary", "DECIMAL(10,4)", "NOT NULL"),
new Column("supervisor_id", "INTEGER", ""),
new Column("education_level", "VARCHAR(30)", "NOT NULL"),
new Column("marital_status", "VARCHAR(30)", "NOT NULL"),
new Column("gender", "VARCHAR(30)", "NOT NULL"),
});
createTable("salary", new Column[] {
new Column("pay_date", "TIMESTAMP", "NOT NULL"),
new Column("employee_id", "INTEGER", "NOT NULL"),
new Column("department_id", "INTEGER", "NOT NULL"),
new Column("currency_id", "INTEGER", "NOT NULL"),
new Column("salary_paid", "DECIMAL(10,4)", "NOT NULL"),
new Column("overtime_paid", "DECIMAL(10,4)", "NOT NULL"),
new Column("vacation_accrued", "REAL", "NOT NULL"),
new Column("vacation_used", "REAL", "NOT NULL"),
});
createTable("store", new Column[] {
new Column("store_id", "INTEGER", "NOT NULL"),
new Column("store_type", "VARCHAR(30)", ""),
new Column("region_id", "INTEGER", ""),
new Column("store_name", "VARCHAR(30)", ""),
new Column("store_number", "INTEGER", ""),
new Column("store_street_address", "VARCHAR(30)", ""),
new Column("store_city", "VARCHAR(30)", ""),
new Column("store_state", "VARCHAR(30)", ""),
new Column("store_postal_code", "VARCHAR(30)", ""),
new Column("store_country", "VARCHAR(30)", ""),
new Column("store_manager", "VARCHAR(30)", ""),
new Column("store_phone", "VARCHAR(30)", ""),
new Column("store_fax", "VARCHAR(30)", ""),
new Column("first_opened_date", "TIMESTAMP", ""),
new Column("last_remodel_date", "TIMESTAMP", ""),
new Column("store_sqft", "INTEGER", ""),
new Column("grocery_sqft", "INTEGER", ""),
new Column("frozen_sqft", "INTEGER", ""),
new Column("meat_sqft", "INTEGER", ""),
new Column("coffee_bar", booleanColumnType, ""),
new Column("video_store", booleanColumnType, ""),
new Column("salad_bar", booleanColumnType, ""),
new Column("prepared_food", booleanColumnType, ""),
new Column("florist", booleanColumnType, ""),
});
createTable("store_ragged", new Column[] {
new Column("store_id", "INTEGER", "NOT NULL"),
new Column("store_type", "VARCHAR(30)", ""),
new Column("region_id", "INTEGER", ""),
new Column("store_name", "VARCHAR(30)", ""),
new Column("store_number", "INTEGER", ""),
new Column("store_street_address", "VARCHAR(30)", ""),
new Column("store_city", "VARCHAR(30)", ""),
new Column("store_state", "VARCHAR(30)", ""),
new Column("store_postal_code", "VARCHAR(30)", ""),
new Column("store_country", "VARCHAR(30)", ""),
new Column("store_manager", "VARCHAR(30)", ""),
new Column("store_phone", "VARCHAR(30)", ""),
new Column("store_fax", "VARCHAR(30)", ""),
new Column("first_opened_date", "TIMESTAMP", ""),
new Column("last_remodel_date", "TIMESTAMP", ""),
new Column("store_sqft", "INTEGER", ""),
new Column("grocery_sqft", "INTEGER", ""),
new Column("frozen_sqft", "INTEGER", ""),
new Column("meat_sqft", "INTEGER", ""),
new Column("coffee_bar", booleanColumnType, ""),
new Column("video_store", booleanColumnType, ""),
new Column("salad_bar", booleanColumnType, ""),
new Column("prepared_food", booleanColumnType, ""),
new Column("florist", booleanColumnType, ""),
});
createTable("time_by_day", new Column[] {
new Column("time_id", "INTEGER", "NOT NULL"),
new Column("the_date", "TIMESTAMP", ""),
new Column("the_day", "VARCHAR(30)", ""),
new Column("the_month", "VARCHAR(30)", ""),
new Column("the_year", "SMALLINT", ""),
new Column("day_of_month", "SMALLINT", ""),
new Column("week_of_year", "INTEGER", ""),
new Column("month_of_year", "SMALLINT", ""),
new Column("quarter", "VARCHAR(30)", ""),
new Column("fiscal_period", "VARCHAR(30)", ""),
});
createTable("warehouse", new Column[] {
new Column("warehouse_id", "INTEGER", "NOT NULL"),
new Column("warehouse_class_id", "INTEGER", ""),
new Column("stores_id", "INTEGER", ""),
new Column("warehouse_name", "VARCHAR(60)", ""),
new Column("wa_address1", "VARCHAR(30)", ""),
new Column("wa_address2", "VARCHAR(30)", ""),
new Column("wa_address3", "VARCHAR(30)", ""),
new Column("wa_address4", "VARCHAR(30)", ""),
new Column("warehouse_city", "VARCHAR(30)", ""),
new Column("warehouse_state_province", "VARCHAR(30)", ""),
new Column("warehouse_postal_code", "VARCHAR(30)", ""),
new Column("warehouse_country", "VARCHAR(30)", ""),
new Column("warehouse_owner_name", "VARCHAR(30)", ""),
new Column("warehouse_phone", "VARCHAR(30)", ""),
new Column("warehouse_fax", "VARCHAR(30)", ""),
});
createTable("warehouse_class", new Column[] {
new Column("warehouse_class_id", "INTEGER", "NOT NULL"),
new Column("description", "VARCHAR(30)", ""),
});
if (outputDirectory != null) {
fileOutput.close();
}
}
private void createTable(String name, Column[] columns) {
try {
// Define the table.
mapTableNameToColumns.put(name, columns);
if (!tables) {
if (data) {
// We're going to load the data without [re]creating
// the table, so let's remove the data.
final Statement statement = connection.createStatement();
try {
statement.execute("DELETE FROM " + quoteId(name));
} catch (SQLException e) {
throw MondrianResource.instance().newCreateTableFailed(name, e);
}
}
return;
}
StringBuffer buf = new StringBuffer();
buf.append("CREATE TABLE ").append(quoteId(name)).append("(");
for (int i = 0; i < columns.length; i++) {
Column column = columns[i];
if (i > 0) {
buf.append(",");
}
buf.append(nl);
buf.append(" ").append(quoteId(column.name)).append(" ")
.append(column.type);
if (!column.constraint.equals("")) {
buf.append(" ").append(column.constraint);
}
}
buf.append(")");
final String ddl = buf.toString();
if (verbose) {
System.out.println(ddl);
}
if (jdbcOutput) {
final Statement statement = connection.createStatement();
try {
statement.execute("DROP TABLE " + quoteId(name));
} catch (SQLException e) {
// ignore 'table does not exist' error
}
statement.execute(ddl);
} else {
fileOutput.write(ddl);
fileOutput.write(";\n");
}
} catch (Exception e) {
throw MondrianResource.instance().newCreateTableFailed(name, e);
}
}
private String quoteId(String name) {
return sqlQuery.quoteIdentifier(name);
}
private String columnValue(ResultSet rs, Column column) throws Exception {
String columnType = column.type;
final Pattern regex = Pattern.compile("DECIMAL\\((.*),(.*)\\)");
final DecimalFormat integerFormatter = new DecimalFormat(decimalFormat(15, 0));
if (columnType.startsWith("INTEGER")) {
Object obj = rs.getObject(column.name);
if (obj == null) {
return "NULL";
} else {
if (obj.getClass() == Double.class) {
try {
Double result = (Double) obj;
return integerFormatter.format(result.doubleValue());
} catch (ClassCastException cce) {
System.out.println("CCE: " + column.name + " to Long from: " + obj.getClass().getName() + " - " + obj.toString());
throw cce;
}
} else {
try {
Integer result = (Integer) obj;
return result.toString();
} catch (ClassCastException cce) {
System.out.println("CCE: " + column.name + " to Integer from: " + obj.getClass().getName() + " - " + obj.toString());
throw cce;
}
}
}
}
if (columnType.startsWith("SMALLINT")) {
Object obj = rs.getObject(column.name);
if (obj == null) {
return "NULL";
} else {
Integer result = (Integer) obj;
return result.toString();
}
}
if (columnType.startsWith("BIGINT")) {
Object obj = rs.getObject(column.name);
if (obj == null) {
return "NULL";
} else {
if (obj.getClass() == Double.class) {
try {
Double result = (Double) obj;
return integerFormatter.format(result.doubleValue());
} catch (ClassCastException cce) {
System.out.println("CCE: " + column.name + " to Long from: " + obj.getClass().getName() + " - " + obj.toString());
throw cce;
}
} else {
try {
Long result = (Long) obj;
return result.toString();
} catch (ClassCastException cce) {
System.out.println("CCE: " + column.name + " to Long from: " + obj.getClass().getName() + " - " + obj.toString());
throw cce;
}
}
}
}
if (columnType.startsWith("VARCHAR")) {
return embedQuotes(rs.getString(column.name));
}
if (columnType.startsWith("TIMESTAMP")) {
Timestamp ts = rs.getTimestamp(column.name);
if (ts == null) {
return "NULL";
} else {
return "'" + ts + "'" ;
}
}
if (columnType.startsWith("DATE")) {
java.sql.Date dt = rs.getDate(column.name);
if (dt == null) {
return "NULL";
} else {
return "'" + dt + "'" ;
}
}
if (columnType.startsWith("REAL")) {
Object obj = rs.getObject(column.name);
if (obj == null) {
return "NULL";
} else {
Float result = (Float) obj;
return result.toString();
}
}
if (columnType.startsWith("DECIMAL")) {
Object obj = rs.getObject(column.name);
if (obj == null) {
return "NULL";
} else {
final Matcher matcher = regex.matcher(columnType);
if (!matcher.matches()) {
throw new Exception("Bad DECIMAL column type for " + columnType);
}
DecimalFormat formatter = new DecimalFormat(decimalFormat(matcher.group(1), matcher.group(2)));
if (obj.getClass() == Double.class) {
try {
Double result = (Double) obj;
return formatter.format(result.doubleValue());
} catch (ClassCastException cce) {
System.out.println("CCE: " + column.name + " to Double from: " + obj.getClass().getName() + " - " + obj.toString());
throw cce;
}
} else {
// should be (obj.getClass() == BigDecimal.class)
try {
BigDecimal result = (BigDecimal) obj;
return formatter.format(result);
} catch (ClassCastException cce) {
System.out.println("CCE: " + column.name + " to BigDecimal from: " + obj.getClass().getName() + " - " + obj.toString());
throw cce;
}
}
}
}
if (columnType.startsWith("BOOLEAN") || columnType.startsWith("BIT")) {
Object obj = rs.getObject(column.name);
if (obj == null) {
return "NULL";
} else {
Boolean result = (Boolean) obj;
return result.toString();
}
}
throw new Exception("Unknown column type: " + columnType + " for column: " + column.name);
}
private String embedQuotes(String original) {
if (original == null) {
return "NULL";
}
StringBuffer sb = new StringBuffer();
sb.append("'");
for (int i = 0; i < original.length(); i++) {
char ch = original.charAt(i);
sb.append(ch);
if (ch == '\'') {
sb.append('\'');
}
}
sb.append("'");
return sb.toString();
}
private String decimalFormat(String lengthStr, String placesStr) {
int length = Integer.parseInt(lengthStr);
int places = Integer.parseInt(placesStr);
return decimalFormat(length, places);
}
private String decimalFormat(int length, int places) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
if ((length - i) == places) {
sb.append('.');
}
sb.append("
}
return sb.toString();
}
private static class Column {
private final String name;
private final String type;
private final String constraint;
public Column(String name, String type, String constraint) {
this.name = name;
this.type = type;
this.constraint = constraint;
}
}
}
|
package org.spine3.test;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.reflect.Invokable;
import com.google.common.reflect.Parameter;
import com.google.common.reflect.TypeToken;
import com.google.protobuf.GeneratedMessageV3;
import org.spine3.util.Exceptions;
import javax.annotation.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Lists.newLinkedList;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.primitives.Primitives.allPrimitiveTypes;
import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet;
import static javax.lang.model.SourceVersion.isName;
/**
* Serves as a helper to ensure that none of the methods of the target utility
* class accept {@code null}s as argument values.
*
* <p> The helper checks the methods with access modifiers:
* <ul>
* <li> the {@code public};
* <li> the {@code protected};
* <li> the {@code default}.
* </ul>
*
* <p> The helper does not check the methods:
* <ul>
* <li> with the {@code private} modifier;
* <li> without the {@code static} modifier;
* <li> with only the primitive parameters;
* <li> if all the parameters are marked as {@code Nullable}.
* </ul>
*
* <p> The examples of the methods which will be checked:
* <ul>
* <li> public static void method(Object obj);
* <li> protected static void method(Object first, long second);
* <li> public static void method(@Nullable Object first, Object second);
* <li> static void method(Object first, Object second).
* </ul>
*
* <p> The examples of the methods which will be ignored:
* <ul>
* <li> public void method(Object obj);
* <li> private static void method(Object obj);
* <li> public static void method(@Nullable Object obj);
* <li> protected static void method(int first, float second).
* </ul>
*
* @author Illia Shepilov
*/
public class NullToleranceTest {
private final Class targetClass;
private final Set<String> excludedMethods;
private final Map<?, ?> defaultValuesMap;
private NullToleranceTest(Builder builder) {
this.targetClass = builder.targetClass;
this.excludedMethods = builder.excludedMethods;
this.defaultValuesMap = builder.defaultValues;
}
/**
* Checks the all non-private methods in the {@code targetClass}.
*
* <p> Check is successful if each of the non-primitive method parameters is ensured to be non-null.
*
* @return {@code true} if all methods have non-null check
* for the input reference type parameters, {@code false} otherwise
*/
public boolean check() {
final DefaultValuesProvider valuesProvider = new DefaultValuesProvider(defaultValuesMap);
final Method[] accessibleMethods = getAccessibleMethods(targetClass);
final String targetClassName = targetClass.getName();
for (Method method : accessibleMethods) {
final Class[] parameterTypes = method.getParameterTypes();
final String methodName = method.getName();
final boolean excluded = excludedMethods.contains(methodName);
final boolean primitivesOnly = allPrimitiveTypes().containsAll(Arrays.asList(parameterTypes));
final boolean skipMethod = excluded || parameterTypes.length == 0 || primitivesOnly;
if (skipMethod) {
continue;
}
final MethodChecker methodChecker = new MethodChecker(method, targetClassName, valuesProvider);
final boolean passed = methodChecker.check();
if (!passed) {
return false;
}
}
return true;
}
/**
* Returns the array of the declared {@code Method}s
* in the {@code Class} which are static and non-private.
*
* @param targetClass the target class
* @return the array of the {@code Method}
*/
private static Method[] getAccessibleMethods(Class targetClass) {
final Method[] declaredMethods = targetClass.getDeclaredMethods();
final List<Method> methodList = newLinkedList();
for (Method method : declaredMethods) {
final Invokable<?, Object> invokable = Invokable.from(method);
final boolean privateMethod = invokable.isPrivate();
final boolean staticMethod = invokable.isStatic();
if (!privateMethod && staticMethod) {
methodList.add(method);
}
}
final Method[] result = methodList.toArray(new Method[methodList.size()]);
return result;
}
/**
* Creates a new builder for the {@code NullToleranceTest}.
*
* @return the {@code Builder}
*/
public static Builder newBuilder() {
return new Builder();
}
@VisibleForTesting
Class getTargetClass() {
return targetClass;
}
@VisibleForTesting
Set<String> getExcludedMethods() {
return unmodifiableSet(excludedMethods);
}
@VisibleForTesting
Map<?, ?> getDefaultValuesMap() {
return unmodifiableMap(defaultValuesMap);
}
/**
* Serves as a helper to ensure that method does not accept {@code null}s as argument values.
*/
private static class MethodChecker {
private final Method method;
private final String targetClassName;
private final DefaultValuesProvider valuesProvider;
private MethodChecker(Method method, String targetClassName, DefaultValuesProvider valuesProvider) {
this.method = method;
this.targetClassName = targetClassName;
this.valuesProvider = valuesProvider;
}
private boolean check() {
final boolean nullableOnly = hasOnlyNullableArgs();
if (nullableOnly) {
return true;
}
final Class[] parameterTypes = method.getParameterTypes();
final Object[] parameterValues = getParameterValues(parameterTypes);
final ImmutableList<Parameter> parameters = Invokable.from(method)
.getParameters();
for (int i = 0; i < parameterValues.length; i++) {
Object[] copiedParametersArray = Arrays.copyOf(parameterValues, parameterValues.length);
final boolean primitive = TypeToken.of(parameterTypes[i])
.isPrimitive();
final boolean nullableParameter = parameters.get(i)
.isAnnotationPresent(Nullable.class);
if (primitive || nullableParameter) {
continue;
}
copiedParametersArray[i] = null;
final boolean correct = invokeAndCheck(copiedParametersArray);
if (!correct) {
return false;
}
}
return true;
}
private boolean hasOnlyNullableArgs() {
final ImmutableList<Parameter> parameters = Invokable.from(method)
.getParameters();
for (Parameter parameter : parameters) {
final boolean present = parameter.isAnnotationPresent(Nullable.class);
if (!present) {
return false;
}
}
return true;
}
private Object[] getParameterValues(Class[] parameterTypes) {
final Object[] parameterValues = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
final Class type = parameterTypes[i];
final Object defaultValue = valuesProvider.getDefaultValue(type);
parameterValues[i] = defaultValue;
}
return parameterValues;
}
private boolean invokeAndCheck(Object[] params) {
try {
method.invoke(null, params);
} catch (InvocationTargetException ex) {
boolean valid = validateException(ex);
return valid;
} catch (IllegalAccessException e) {
throw Exceptions.wrappedCause(e);
}
return false;
}
private boolean validateException(InvocationTargetException ex) {
final Throwable cause = ex.getCause();
checkException(cause);
final boolean result = hasExpectedStackTrace(cause);
return result;
}
private static void checkException(Throwable cause) {
final boolean correctException = cause instanceof NullPointerException;
if (!correctException) {
throw Exceptions.wrappedCause(cause);
}
}
/**
* Checks the stack trace elements.
*
* <p> It is expected that each of the tested utility methods invokes
* {@link Preconditions}#checkNotNull(<arg types here>) as a first step of the execution.
*
* <p> Therefore the stack trace is analysed to ensure its first element references
* the {@code Preconditions#checkNotNull} and the second one references the tested method.
*
* @param cause the {@code Throwable}
* @return {@code true} if the {@code StackTraceElement}s matches the expected, {@code false} otherwise
*/
private boolean hasExpectedStackTrace(Throwable cause) {
final StackTraceElement[] stackTraceElements = cause.getStackTrace();
final StackTraceElement preconditionsElement = stackTraceElements[0];
final boolean preconditionClass = Preconditions.class.getName()
.equals(preconditionsElement.getClassName());
if (!preconditionClass) {
return false;
}
final StackTraceElement targetClassElement = stackTraceElements[1];
final String targetMethodName = targetClassElement.getMethodName();
final boolean correct = method.getName()
.equals(targetMethodName);
if (!correct) {
return false;
}
final boolean correctClass = targetClassName.equals(targetClassElement.getClassName());
return correctClass;
}
}
/**
* Provides the default values for the method arguments.
*/
private static class DefaultValuesProvider {
private static final Class[] EMPTY_PARAMETER_TYPES = {};
private static final Object[] EMPTY_ARGUMENTS = {};
private static final String METHOD_NAME = "getDefaultInstance";
private final Map<?, ?> defaultValues;
private DefaultValuesProvider(Map<?, ?> defaultValues) {
this.defaultValues = defaultValues;
}
private Object getDefaultValue(Class<?> key) {
final Class messageClass = GeneratedMessageV3.class;
final boolean messageParent = messageClass.equals(key.getSuperclass());
Object result = defaultValues.get(key);
if (result == null && messageParent) {
result = getDefaultMessageInstance(key);
}
checkState(result != null);
return result;
}
private static Object getDefaultMessageInstance(Class<?> key) {
try {
final Method method = key.getMethod(METHOD_NAME, EMPTY_PARAMETER_TYPES);
final Object defaultInstance = method.invoke(null, EMPTY_ARGUMENTS);
return defaultInstance;
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw Exceptions.wrappedCause(e);
}
}
}
/**
* A builder for producing the {@link NullToleranceTest} instance.
*/
public static class Builder {
private final Set<String> excludedMethods;
private final Map<? super Class, ? super Object> defaultValues;
private Class targetClass;
private Builder() {
defaultValues = newHashMap();
excludedMethods = newHashSet();
}
/**
* Sets the target class.
*
* @param utilClass the utility {@link Class}
* @return the {@code Builder}
*/
public Builder setClass(Class utilClass) {
this.targetClass = checkNotNull(utilClass);
return this;
}
/**
* Adds the method name which will be excluded from the check.
*
* @param methodName the name of the method to exclude
* @return the {@code Builder}
*/
@SuppressWarnings("WeakerAccess") // it is a public API.
public Builder excludeMethod(String methodName) {
checkNotNull(methodName);
final boolean validName = isName(methodName);
checkArgument(validName);
excludedMethods.add(methodName);
return this;
}
@SuppressWarnings("WeakerAccess") // it is a public API.
public <I> Builder addDefaultValue(I value) {
checkNotNull(value);
defaultValues.put(value.getClass(), value);
return this;
}
@VisibleForTesting
Class getTargetClass() {
return targetClass;
}
@VisibleForTesting
Set<String> getExcludedMethods() {
return unmodifiableSet(excludedMethods);
}
@VisibleForTesting
Map<?, ?> getDefaultValues() {
return unmodifiableMap(defaultValues);
}
/**
* Returns the constructed {@link NullToleranceTest}.
*
* @return the {@code nullToleranceTest} instance.
*/
public NullToleranceTest build() {
checkNotNull(targetClass);
putPrimitiveDefaultValues();
final NullToleranceTest result = new NullToleranceTest(this);
return result;
}
private void putPrimitiveDefaultValues() {
defaultValues.put(boolean.class, false);
defaultValues.put(byte.class, (byte) 0);
defaultValues.put(short.class, (short) 0);
defaultValues.put(int.class, 0);
defaultValues.put(long.class, 0L);
defaultValues.put(char.class, '\u0000');
defaultValues.put(float.class, 0.0f);
defaultValues.put(double.class, 0.0d);
}
}
}
|
package to.etc.domui.server;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import to.etc.domui.login.DefaultLoginDeterminator;
import to.etc.domui.login.ILoginDeterminator;
import to.etc.domui.util.DomUtil;
import to.etc.log.EtcLoggerFactory;
import to.etc.util.ClassUtil;
import to.etc.util.DeveloperOptions;
import to.etc.util.StringTool;
import to.etc.util.WrappedException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Enumeration;
public class AppFilter implements Filter {
static final Logger LOG = LoggerFactory.getLogger(AppFilter.class);
public static final String LOGCONFIG_NAME = "etclogger.config.xml";
private ConfigParameters m_config;
private String m_applicationClassName;
private boolean m_logRequest;
static private String m_appContext;
@Nullable
static private IRequestResponseWrapper m_ioWrapper;
/**
* If a reloader is needed for debug/development pps this will hold the reloader.
*/
private IContextMaker m_contextMaker;
/** If client logging is enabled this contains the registry. */
private ServerClientRegistry m_clientRegistry;
private ILoginDeterminator m_loginDeterminator;
static public synchronized void setIoWrapper(@NonNull IRequestResponseWrapper ww) {
m_ioWrapper = ww;
}
@Override
public void destroy() {
//-- Pass DESTROY on to Application, if present.
if(DomApplication.get() != null)
DomApplication.get().internalDestroy();
}
static public String minitime() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.HOUR_OF_DAY) + StringTool.intToStr(cal.get(Calendar.MINUTE), 10, 2) + StringTool.intToStr(cal.get(Calendar.SECOND), 10, 2) + "." + cal.get(Calendar.MILLISECOND);
}
@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
boolean logRequired = false;
Throwable failure = null;
String path = null;
try {
HttpServletRequest rq = (HttpServletRequest) req;
path = rq.getPathInfo();
logRequired = isLogRequired(path);
if(logRequired) {
LOG.error("ENTERED " + rq.getPathInfo());
}
if(LOG.isDebugEnabled()) {
LOG.debug("--- Request entering the server");
Enumeration<String> enu = rq.getHeaderNames();
while(enu.hasMoreElements()) {
String name = enu.nextElement();
Enumeration<String> henu = rq.getHeaders(name);
while(henu.hasMoreElements()) {
String val = henu.nextElement();
System.out.println("header: " + name + ": " + val);
}
}
LOG.debug("uri " + rq.getRequestURI());
LOG.debug("url " + rq.getRequestURL());
LOG.debug("localName " + rq.getLocalName());
}
HttpServletResponse response = (HttpServletResponse) res;
IRequestResponseWrapper ww = m_ioWrapper;
if(null != ww) {
rq = ww.getWrappedRequest(rq);
response = ww.getWrappedResponse(response);
}
String userid = m_loginDeterminator.getLoginData(rq);
if(null != userid) {
m_clientRegistry.registerRequest(rq, userid);
MDC.put(to.etc.log.EtcMDCAdapter.LOGINID, userid);
}
String id = rq.getSession().getId();
if(null != id)
MDC.put(to.etc.log.EtcMDCAdapter.SESSION, id);
//LOG.info(MarkerFactory.getMarker("request-uri"), rq.getRequestURI()); -- useful for developer controlled debugging
rq.setCharacterEncoding("UTF-8"); // FIXME jal 20080804 Encoding of input was incorrect?
// DomUtil.dumpRequest(rq);
if(m_logRequest) {
String rs = rq.getQueryString();
rs = rs == null ? "" : "?" + rs;
System.out.println(minitime() + " rq=" + rq.getRequestURI() + rs);
}
m_contextMaker.handleRequest(rq, response, chain);
} catch(RuntimeException | ServletException x) {
failure = x;
DomUtil.dumpExceptionIfSevere(x);
throw x;
} catch(IOException x) {
failure = x;
if(x.getClass().getName().endsWith("ClientAbortException")) // Do not log these.
throw x;
DomUtil.dumpExceptionIfSevere(x);
throw x;
} catch(Exception x) {
failure = x;
DomUtil.dumpExceptionIfSevere(x);
throw new WrappedException(x); // checked exceptions are idiotic
} catch(Error x) {
LOG.error("Request error: " + x, x);
failure = x;
throw x;
} finally {
if(logRequired) {
LOG.error("EXITED " + path + " exception=" + failure);
}
}
}
private boolean isLogRequired(String s) {
return s.contains("/rest/appliance2/loadResultTable");
}
//static synchronized private void initContext(ServletRequest req) {
// if(m_appContext != null || !(req instanceof HttpServletRequest))
// return;
// m_appContext = NetTools.getApplicationContext((HttpServletRequest) req);
///**
// * Do not use: does not work when hosting parties do not proxy correctly.
// */
//@Deprecated
//static synchronized public String internalGetWebappContext() {
// return m_appContext;
/**
* Initialize by reading config from the web.xml.
*/
@Override
public synchronized void init(final FilterConfig config) throws ServletException {
File approot = new File(config.getServletContext().getRealPath("/"));
initLogConfig(approot, config.getInitParameter("logpath"));
if(DeveloperOptions.isDeveloperWorkstation()) {
config.getServletContext().getSessionCookieConfig().setHttpOnly(false);
config.getServletContext().getSessionCookieConfig().setSecure(false);
}
try {
m_logRequest = DeveloperOptions.getBool("domui.logurl", false);
//-- Get the root for all files in the webapp
LOG.info("WebApp root=" + approot);
if(!approot.exists() || !approot.isDirectory())
throw new IllegalStateException("Internal: cannot get webapp root directory");
m_config = new FilterConfigParameters(config, approot);
//-- Handle application construction
m_applicationClassName = getApplicationClassName(m_config);
if(m_applicationClassName == null)
throw new UnavailableException("The application class name is not set. Use 'application' in the Filter parameters to set a main class.");
//-- Do we want session logging?
String s = config.getInitParameter("login-determinator");
if(null != s) {
m_loginDeterminator = ClassUtil.loadInstance(getClass().getClassLoader(), ILoginDeterminator.class, s);
} else {
m_loginDeterminator = new DefaultLoginDeterminator();
}
m_clientRegistry = ServerClientRegistry.getInstance();
//-- Are we running in development mode?
String domUiReload = DeveloperOptions.getString("domui.reload");
String autoload = domUiReload != null ? domUiReload : m_config.getString("auto-reload"); // Allow override of web.xml values.
//these patterns will be only watched not really reloaded. It makes sure the reloader kicks in. Found bundles and MetaData will be reloaded only.
String autoloadWatchOnly = m_config.getString("auto-reload-watch-only");
if(DeveloperOptions.isDeveloperWorkstation() && DeveloperOptions.getBool("domui.developer", true) && autoload != null && autoload.trim().length() > 0)
m_contextMaker = new ReloadingContextMaker(m_applicationClassName, m_config, autoload, autoloadWatchOnly);
else
m_contextMaker = new NormalContextMaker(m_applicationClassName, m_config);
} catch(RuntimeException x) {
DomUtil.dumpException(x);
throw x;
} catch(ServletException x) {
DomUtil.dumpException(x);
throw x;
} catch(Exception x) {
DomUtil.dumpException(x);
throw new RuntimeException(x); // checked exceptions are idiotic
} catch(Error x) {
x.printStackTrace();
throw x;
}
}
static private void initLogConfig(@Nullable File appRoot, String logConfigParameter) throws Error {
try {
if(null == appRoot) {
appRoot = new File(System.getProperty("user.home"));
} else {
appRoot = new File(appRoot, "WEB-INF");
}
//-- Prio 0: developer.properties
File writablePath = null;
File logSource = null;
String logconfig = DeveloperOptions.getString("domui.logconfig");
if(null != logconfig) {
logSource = trySource(appRoot, logconfig);
//-- Always have a writable config
writablePath = makeAbs(appRoot, logconfig);
}
//-- Prio 1: -DLOGCONFIG
logconfig = System.getProperty("LOGCONFIG");
if(null != logconfig) {
logSource = trySource(appRoot, logconfig);
writablePath = makeAbs(appRoot, logconfig);
}
//-- Prio 2: parameter - not writable
if(logSource == null && logConfigParameter != null) {
logSource = trySource(appRoot, logConfigParameter);
}
//-- Prio 3: etclogger.config.xml in web-inf
if(null == logSource) {
logSource = trySource(appRoot, LOGCONFIG_NAME);
}
//-- 2. We now have either a path or not. Load the default config.
if(logSource != null)
EtcLoggerFactory.getSingleton().initializeFromFile(logSource, writablePath);
} catch(Exception x) {
x.printStackTrace();
throw WrappedException.wrap(x);
} catch(Error x) {
x.printStackTrace();
throw x;
}
}
static private File makeAbs(File appRoot, String name) {
File f = new File(name);
if(f.isAbsolute())
return f;
return new File(appRoot, name);
}
@Nullable
static private File trySource(File appRoot, String name) {
File f = new File(name);
if(!f.isAbsolute()) {
f = new File(appRoot, name);
}
if(f.exists() && f.isFile())
return f;
return null;
}
public String getApplicationClassName(final ConfigParameters p) {
return p.getString("application");
}
}
|
package github.com.javaminusminus.simplebdd;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class Test {
protected Method before;
protected Method beforeEach;
protected Method after;
protected Method afterEach;
protected Method[] tests = new Method[0];
protected Result[] results = new Result[0];
public void run() {
Method[] methods = this.getClass().getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (method.getName().startsWith("test")) {
this.addTest(method);
} else if (method.getName().equals("before")) {
this.before = method;
} else if (method.getName().equals("beforeEach")) {
this.beforeEach = method;
} else if (method.getName().equals("after")) {
this.after = method;
} else if (method.getName().equals("afterEach")) {
this.afterEach = method;
}
}
this.executeTests();
this.report();
}
public void should(String should) {
this.resultStart();
this.results[this.results.length-1].should = should;
}
public boolean assertEqual(Object a, Object b) {
if (a.equals(b)) {
return true;
}
this.resultFailure(a, b);
return false;
}
public boolean assertNotEqual(Object a, Object b) {
if (!a.equals(b)) {
return true;
}
this.resultFailure(a, b);
return false;
}
protected void report() {
new Report(this.getClass().getName(), this.results);
int failures = 0;
for (int i = 0; i < this.results.length; i++) {
if (this.results[i].failed) {
failures++;
}
}
System.exit(failures);
}
protected void addTest(Method v) {
int len = this.tests.length;
Method[] a = new Method[len + 1];
a[len] = v;
for (int i = 0; i < len; i++ ) {
a[i] = this.tests[i];
}
this.tests = a;
}
protected void resultStart() {
int len = this.results.length;
Result[] a = new Result[len + 1];
a[len] = new Result();
for (int i = 0; i < len; i++ ) {
a[i] = this.results[i];
}
this.results = a;
}
protected void resultFailure() {
this.results[this.results.length-1].failed = true;
}
protected void resultFailure(Object a, Object b) {
this.results[this.results.length-1].expected = a;
this.results[this.results.length-1].got = b;
this.results[this.results.length-1].failed = true;
}
protected void executeTests() {
this.executeBefore();
for (int i = 0; i < this.tests.length; i++) {
this.executeTest(this.tests[i]);
}
this.executeAfter();
}
protected void executeTest(Method method) {
this.executeBeforeEach();
try {
method.invoke(this);
} catch (IllegalAccessException e) {
this.resultFailure();
System.out.println(e.getCause());
} catch (InvocationTargetException e) {
this.resultFailure();
System.out.println(e.getCause());
e.printStackTrace(System.out);
}
this.executeAfterEach();
}
protected void executeBefore() {
if (this.before == null) {
return;
}
try {
this.before.invoke(this);
} catch (IllegalAccessException e) {
System.out.println(e.getCause());
} catch (InvocationTargetException e) {
System.out.println(e.getCause());
e.printStackTrace(System.out);
}
}
protected void executeAfter() {
if (this.after == null) {
return;
}
try {
this.after.invoke(this);
} catch (IllegalAccessException e) {
System.out.println(e.getCause());
} catch (InvocationTargetException e) {
System.out.println(e.getCause());
e.printStackTrace(System.out);
}
}
protected void executeBeforeEach() {
if (this.beforeEach == null) {
return;
}
try {
this.beforeEach.invoke(this);
} catch (IllegalAccessException e) {
System.out.println(e.getCause());
} catch (InvocationTargetException e) {
System.out.println(e.getCause());
e.printStackTrace(System.out);
}
}
protected void executeAfterEach() {
if (this.afterEach == null) {
return;
}
try {
this.afterEach.invoke(this);
} catch (IllegalAccessException e) {
System.out.println(e.getCause());
} catch (InvocationTargetException e) {
System.out.println(e.getCause());
e.printStackTrace(System.out);
}
}
}
|
package com.monolith.engine;
import com.monolith.api.Application;
import com.monolith.api.CollisionSystem;
import com.monolith.api.Component;
import com.monolith.api.Debug;
import com.monolith.api.Display;
import com.monolith.api.GameObject;
import com.monolith.api.Messenger;
import com.monolith.api.Renderer;
import com.monolith.api.Time;
import com.monolith.api.TouchInput;
import com.monolith.api.components.Camera;
import com.monolith.api.external.InputMessenger;
import com.monolith.engine.config.SceneCreator;
import com.monolith.engine.config.model.debug.DebugSettingsModel;
import com.monolith.engine.config.model.initial_scene_state.ISScene;
import com.monolith.engine.config.model.scenes_config.SCScene;
import com.monolith.engine.config.model.scenes_config.SCScenes;
import com.monolith.engine.messaging.InputMessengerInternal;
import com.monolith.engine.messaging.MessengerInternal;
import com.monolith.platform.Platform;
import com.monolith.platform.TouchInputInternal;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Represents one engine instance. Engine holds everything together.
*/
public class Engine {
private Platform mPlatform;
private Application mApplication;
private InputMessengerInternal mInputMessengerInternal;
// Application objects
private FullRenderer mRenderer;
private TouchInputInternal mTouchInput;
private MeshManager mMeshManager;
private MessengerInternal mMessenger;
private TimeInternal mTime;
private CollisionSystem mCollisionSystem;
private Display mDisplay;
private List<ISystem> mInternalSystems = new ArrayList<>();
private SCScenes mScenesConfig;
// This is only used for searching in scenes List
private SCScene mDummyScene = new SCScene();
private String mCurrentSceneName;
private Scene mCurrentScene;
/**
* Constructs new Engine instance.
*
* @param startSceneName Name of the scene that this engine should show first.
* If null, engine will use the default scene as specified
* in scenes configuration file.
*/
public Engine(String startSceneName) {
mCurrentSceneName = startSceneName;
mInputMessengerInternal = new InputMessengerInternal();
mMessenger = new MessengerInternal(mInputMessengerInternal);
mTime = new TimeInternal();
mCollisionSystem = new CollisionSystem();
mInternalSystems.add(mTime);
mInternalSystems.add(mMessenger);
mInternalSystems.add(mCollisionSystem);
}
private DebugSettingsModel parseDebugSettingsFile() {
InputStream debugFileInputStream = mPlatform.getAssetFileInputStream(Config.DEBUG_FILE);
if (debugFileInputStream == null) {
return null;
} else {
Serializer serializer = new Persister();
DebugSettingsModel parsedDebugSetings;
try {
parsedDebugSetings = serializer.read(DebugSettingsModel.class, debugFileInputStream);
if (parsedDebugSetings == null) {
throw new IllegalStateException();
} else {
return parsedDebugSetings;
}
} catch (Exception e) {
throw new IllegalStateException("Error during retrieval of debug config file.", e);
}
}
}
public void insertProvidedObjects(Platform platform, FullRenderer renderer, TouchInputInternal touchInput) {
Camera camera = mRenderer != null ? mRenderer.getCamera() : null;
this.mPlatform = platform;
this.mRenderer = renderer;
mInternalSystems.remove(mTouchInput);
mInternalSystems.add(touchInput);
this.mTouchInput = touchInput;
mDisplay = mPlatform.createDisplay();
if (mApplication == null) {
mApplication = new ApplicationImpl();
}
mRenderer.setApplication(mApplication);
mRenderer.setCamera(camera);
}
// This flag ensures that engine is initialized only once (onStart method)
private boolean mInitialized = false;
// TODO validate all xml files
/**
* Must be called by platform. Initializes the engine.
* It is possible to call this method for the second time on the same object
* however second initialization is not performed.
*/
public void onStart() {
if (mInitialized) {
return;
}
loadScenesConfig();
if (mCurrentSceneName == null) {
mCurrentSceneName = mScenesConfig.defaultSceneName;
}
mApplication.changeScene(mCurrentSceneName);
mInitialized = true;
}
/**
* Loads scenes configuration file. This file contains names of all scenes together with
* paths to the files defining initial state for every scene.
*/
private void loadScenesConfig() {
Serializer serializer = new Persister();
try {
mScenesConfig = serializer.read(SCScenes.class,
mPlatform.getAssetFileInputStream(Config.SCENES_FILE));
// Sort scenes for quicker lookup of scenes during scene loading
Collections.sort(mScenesConfig.scenes);
if (mScenesConfig == null) {
throw new IllegalStateException("Error during retrieval of scenes config file.");
}
} catch (Exception e) {
throw new IllegalStateException("Error during retrieval of scenes config file.", e);
}
}
/**
* Loads scene's initial configuration and constructs {@link com.monolith.engine.Scene} object.
*
* @param sceneName Name of the scene to construct.
* @return Fully constructed {@link com.monolith.engine.Scene} object.
*/
private SceneCreator getScene(String sceneName) {
// Find the scene object in the scenes definition structure
mDummyScene.name = sceneName;
int sceneIndex = Collections.binarySearch(mScenesConfig.scenes, mDummyScene);
if (sceneIndex < 0) {
throw new IllegalStateException("Scene that was requested could not be found.");
}
String configFilePath = mScenesConfig.scenes.get(sceneIndex).sceneFilePath;
ISScene scene;
try {
scene = new Persister().read(ISScene.class,
mPlatform.getAssetFileInputStream(configFilePath));
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Error during retrieval of scene config file " + configFilePath);
}
SceneCreator sceneCreator = new SceneCreator(mApplication);
sceneCreator.create(scene);
return sceneCreator;
}
/**
* Must be called by platform every frame.
* This call is dispatched to all components which results in scene state update and rendering.
*/
public void onUpdate() {
for (int i = 0; i < mInternalSystems.size(); ++i) {
mInternalSystems.get(i).update();
}
update(mCurrentScene.gameObjects);
mRenderer.onStartRenderingFrame();
postUpdate(mCurrentScene.gameObjects);
for (int i = 0; i < mInternalSystems.size(); ++i) {
mInternalSystems.get(i).postUpdate();
}
}
/**
* Helper recursive method to call {@link Component#update()} on all
* {@link com.monolith.api.Component Components}.
*
* @param gameObjects {@link java.util.List} of top level scene objects.
*/
private void update(List<GameObject> gameObjects) {
for (int i = 0; i < gameObjects.size(); ++i) {
GameObject gameObject = gameObjects.get(i);
for (int j = 0; j < gameObject.components.size(); ++j) {
gameObject.components.get(j).update();
}
update(gameObject.children);
}
}
/**
* Helper recursive method to call {@link Component#postUpdate()} on all
* {@link com.monolith.api.Component Components}.
*
* @param gameObjects {@link java.util.List} of top level scene objects.
*/
private void postUpdate(List<GameObject> gameObjects) {
for (int i = 0; i < gameObjects.size(); ++i) {
GameObject gameObject = gameObjects.get(i);
for (int j = 0; j < gameObject.components.size(); ++j) {
gameObject.components.get(j).postUpdate();
}
postUpdate(gameObject.children);
}
}
/**
* Must be called by platform when this engine instance finishes.
* This call is dispatched to all components.
*/
public void onFinish() {
finish(mCurrentScene.gameObjects);
}
/**
* Helper recursive method to call {@link Component#finish()} on all
* {@link com.monolith.api.Component Components}.
*
* @param gameObjects {@link java.util.List} of top level scene objects.
*/
private void finish(List<GameObject> gameObjects) {
for (int i = 0; i < gameObjects.size(); ++i) {
GameObject gameObject = gameObjects.get(i);
for (int j = 0; j < gameObject.components.size(); ++j) {
gameObject.components.get(j).finish();
}
finish(gameObject.children);
}
}
public InputMessenger getInputMessenger() {
return mInputMessengerInternal.getInputMessenger();
}
private class ApplicationImpl extends Application {
private Debug mDebug;
public ApplicationImpl() {
DebugSettingsModel debugSettingsModel = parseDebugSettingsFile();
boolean debug = debugSettingsModel != null;
boolean drawColliders = debug && (debugSettingsModel.drawColliders == null || debugSettingsModel.drawColliders);
mDebug = new Debug(debug, drawColliders) {
@Override
public void log(String message) {
mPlatform.log(message);
}
};
}
@Override
public Renderer getRenderer() {
return mRenderer;
}
@Override
public TouchInput getTouchInput() {
return mTouchInput;
}
@Override
public MeshManager getModelManager() {
return mMeshManager;
}
@Override
public Messenger getMessenger() {
return mMessenger;
}
@Override
public CollisionSystem getCollisionSystem() {
return mCollisionSystem;
}
@Override
public Time getTime() {
return mTime;
}
@Override
public Debug getDebug() {
return mDebug;
}
@Override
public Display getDisplay() {
return mDisplay;
}
@Override
public void changeScene(String newSceneName) {
mMeshManager = new MeshManager(mApplication, mPlatform);
SceneCreator newSceneCreator = getScene(newSceneName);
mCurrentScene = newSceneCreator.scene;
mRenderer.setCamera(newSceneCreator.camera);
mCurrentSceneName = newSceneName;
}
@Override
public String getCurrentSceneName() {
return mCurrentSceneName;
}
}
}
|
package VASSAL.counters;
import VASSAL.build.module.Map;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.command.ChangeTracker;
import VASSAL.command.Command;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.DoubleConfigurer;
import VASSAL.configure.IntConfigurer;
import VASSAL.configure.NamedHotKeyConfigurer;
import VASSAL.configure.StringConfigurer;
import VASSAL.i18n.PieceI18nData;
import VASSAL.i18n.Resources;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.SequenceEncoder;
import VASSAL.tools.image.ImageUtils;
import VASSAL.tools.image.LabelUtils;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import javax.swing.KeyStroke;
/**
* Displays a movement trail indicating where a piece has been moved
*/
public class Footprint extends MovementMarkable {
public static final String ID = "footprint;"; //$NON-NLS-1$//
private KeyCommand[] commands;
// State Variables (Saved in logfile/sent to opponent)
protected boolean globalVisibility = false; // Shared trail visibility (if globallyVisible == true)
protected String startMapId = ""; // Map Id trail started on
// List of points
protected List<Point> pointList = new ArrayList<>();
// Type Variables (Configured in Ed)
protected NamedKeyStroke trailKey; // Control Key to invoke
protected NamedKeyStroke trailKeyOn; // Control Key to force trails on
protected NamedKeyStroke trailKeyOff; // Control Key to force trails off
protected NamedKeyStroke trailKeyClear; // Control Key to force trails clear
protected String menuCommand; // Menu Command
protected boolean initiallyVisible = false; // Are Trails initially visible?
protected boolean globallyVisible = false; // Are Trails shared between players?
protected int circleRadius; // Radius of trail point circle
protected int selectedTransparency; // Transparency of trail when unit is selected
protected int unSelectedTransparency; // Transparency of trail when unit is selected/unselected
protected Color lineColor; // Color of Trail lines
protected Color fillColor; // Color of Trail circle fill
protected int edgePointBuffer; // How far Off-map to draw trail points (pixels)?
protected int edgeDisplayBuffer; // How far Off-map to draw trail lines (pixels)?
protected String description; // Description for this movement trail
// Defaults for Type variables
protected static final char DEFAULT_TRAIL_KEY = 'T';
protected static final String DEFAULT_MENU_COMMAND = Resources.getString("Editor.Footprint.movement_trail");
protected static final Boolean DEFAULT_INITIALLY_VISIBLE = Boolean.FALSE;
protected static final Boolean DEFAULT_GLOBALLY_VISIBLE = Boolean.FALSE;
protected static final int DEFAULT_CIRCLE_RADIUS = 10;
protected static final Color DEFAULT_FILL_COLOR = Color.WHITE;
protected static final Color DEFAULT_LINE_COLOR = Color.BLACK;
protected static final int DEFAULT_SELECTED_TRANSPARENCY = 100;
protected static final int DEFULT_UNSELECTED_TRANSPARENCY = 50;
protected static final int DEFAULT_EDGE_POINT_BUFFER = 20;
protected static final int DEFAULT_EDGE_DISPLAY_BUFFER = 30;
protected static final float LINE_WIDTH = 1.0f;
// Local Variables
protected Rectangle myBoundingBox;
protected Font font;
protected double lastZoom;
protected boolean localVisibility;
protected boolean initialized = false; // Protect against multiple re-initializations
protected double lineWidth;
private KeyCommand showTrailCommand;
private KeyCommand showTrailCommandOn; // Commands to force specific trail states
private KeyCommand showTrailCommandOff;
private KeyCommand showTrailCommandClear;
public Footprint() {
super(Footprint.ID, null);
}
public Footprint(String type, GamePiece p) {
mySetType(type);
setInner(p);
}
@Override
public void mySetState(String newState) {
pointList.clear();
final SequenceEncoder.Decoder ss =
new SequenceEncoder.Decoder(newState, ';');
globalVisibility = ss.nextBoolean(initiallyVisible);
startMapId = ss.nextToken("");
final int items = ss.nextInt(0);
for (int i = 0; i < items; i++) {
final String point = ss.nextToken("");
if (point.length() != 0) {
final SequenceEncoder.Decoder sp =
new SequenceEncoder.Decoder(point, ',');
final int x = sp.nextInt(0);
final int y = sp.nextInt(0);
pointList.add(new Point(x, y));
}
}
}
@Override
public String myGetState() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(globalVisibility)
.append(startMapId)
.append(pointList.size());
for (final Point p : pointList) {
se.append(p.x + "," + p.y);
}
return se.getValue();
}
/**
* Type is the character command that toggles footprint visibility
*/
@Override
public void mySetType(String type) {
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';');
st.nextToken();
trailKey = st.nextNamedKeyStroke(DEFAULT_TRAIL_KEY);
menuCommand = st.nextToken(DEFAULT_MENU_COMMAND);
initiallyVisible = st.nextBoolean(DEFAULT_INITIALLY_VISIBLE);
globallyVisible = st.nextBoolean(DEFAULT_GLOBALLY_VISIBLE);
circleRadius = st.nextInt(DEFAULT_CIRCLE_RADIUS);
fillColor = st.nextColor(DEFAULT_FILL_COLOR);
lineColor = st.nextColor(DEFAULT_LINE_COLOR);
selectedTransparency = st.nextInt(DEFAULT_SELECTED_TRANSPARENCY);
unSelectedTransparency = st.nextInt(DEFULT_UNSELECTED_TRANSPARENCY);
edgePointBuffer = st.nextInt(DEFAULT_EDGE_POINT_BUFFER);
edgeDisplayBuffer = st.nextInt(DEFAULT_EDGE_DISPLAY_BUFFER);
lineWidth = st.nextDouble(LINE_WIDTH);
trailKeyOn = st.nextNamedKeyStroke(null);
trailKeyOff = st.nextNamedKeyStroke(null);
trailKeyClear = st.nextNamedKeyStroke(null);
description = st.nextToken("");
commands = null;
showTrailCommand = null;
showTrailCommandOn = null;
showTrailCommandOff = null;
showTrailCommandClear = null;
if (initiallyVisible) {
localVisibility = true;
globalVisibility = true;
}
}
@Override
public String myGetType() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(trailKey)
.append(menuCommand)
.append(initiallyVisible)
.append(globallyVisible)
.append(circleRadius)
.append(fillColor)
.append(lineColor)
.append(selectedTransparency)
.append(unSelectedTransparency)
.append(edgePointBuffer)
.append(edgeDisplayBuffer)
.append(lineWidth)
.append(trailKeyOn)
.append(trailKeyOff)
.append(trailKeyClear)
.append(description);
return ID + se.getValue();
}
/**
* @return a list of any Named KeyStrokes referenced in the Decorator, if any (for search)
*/
@Override
public List<NamedKeyStroke> getNamedKeyStrokeList() {
return Arrays.asList(trailKey, trailKeyOn, trailKeyOff, trailKeyClear);
}
/**
* @return a list of any Menu Text strings referenced in the Decorator, if any (for search)
*/
@Override
public List<String> getMenuTextList() {
return List.of(menuCommand);
}
@Override
public void setProperty(Object key, Object val) {
if (Properties.MOVED.equals(key)) {
setMoved(Boolean.TRUE.equals(val));
piece.setProperty(key, val); // Pass on to MovementMarkable
myBoundingBox = null;
}
else {
super.setProperty(key, val);
}
}
@Override
public Object getLocalizedProperty(Object key) {
if (Properties.MOVED.equals(key)) {
final Object value = piece.getProperty(key);
return value == null ? super.getProperty(key) : value;
}
return super.getLocalizedProperty(key);
}
@Override
public Object getProperty(Object key) {
// If this piece has a real MovementMarkable trait,
// use it to store the MOVED status
if (Properties.MOVED.equals(key)) {
final Object value = piece.getProperty(key);
return value == null ? super.getProperty(key) : value;
}
return super.getProperty(key);
}
/**
* setMoved is called with an argument of true each time the piece is moved.
* The argument is false when the unit is marked as not moved.
*/
@Override
public void setMoved(boolean justMoved) {
if (justMoved) {
recordCurrentPosition();
final Map map = getMap();
startMapId = map != null ? map.getId() : null;
}
else {
clearTrail();
}
redraw();
}
protected void recordCurrentPosition() {
final Point here = this.getPosition();
if (pointList.isEmpty() ||
!pointList.get(pointList.size() - 1).equals(here)) {
addPoint(here);
}
else {
myBoundingBox = null;
}
}
protected void clearTrail() {
myBoundingBox = null;
pointList.clear();
addPoint(getPosition());
if (!initialized) { //BR// Bug 12980 - prevent multiple re-initializations
localVisibility = initiallyVisible;
globalVisibility = initiallyVisible;
initialized = true;
}
}
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("MovementTrail.html"); //$NON-NLS-1$//
}
/**
* Add Point to list and adjust the overall boundingBox to encompass the
* trail.
*/
protected void addPoint(Point p) {
pointList.add(p);
myBoundingBox = null;
}
public void redraw() {
myBoundingBox = null;
final Map m = getMap();
if (m != null) {
m.repaint(getMyBoundingBox());
}
}
@Override
public String getDescription() {
return buildDescription("Editor.Footprint.trait_description", description);
}
// FIXME: This method is inefficient.
@Override
public void draw(Graphics g, int x, int y, Component obs, double zoom) {
piece.draw(g, x, y, obs, zoom);
final Map map = getMap();
// Do nothing when piece is not on a map, we are drawing the map
// to something other than its normal view, or the trail is invisible,
if (map == null || map.getView() != obs || !isTrailVisible()) {
return;
}
/*
* If we have changed Maps, then start a new trail. Note that this check is
* here because setMoved is called before the piece has been moved.
*/
final String currentMap = map.getId();
if (!currentMap.equals(startMapId)) {
startMapId = currentMap;
clearTrail();
return;
}
// Anything to draw?
if (pointList.isEmpty()) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
/*
* If we are asked to be drawn at a different zoom from the current map zoom
* setting, then don't draw the trail as it will be in the wrong place.
* (i.e. Mouse-over viewer)
*/
if (zoom != map.getZoom() * os_scale) {
return;
}
final boolean selected = Boolean.TRUE.equals(
Decorator.getOutermost(this).getProperty(Properties.SELECTED));
final int transparencyPercent = Math.max(0, Math.min(100,
selected ? selectedTransparency : unSelectedTransparency));
final float transparency = transparencyPercent / 100.0f;
final Composite oldComposite = g2d.getComposite();
final Stroke oldStroke = g2d.getStroke();
final Color oldColor = g2d.getColor();
/*
* newClip is an overall clipping region made up of the Map itself and a
* border of edgeDisplayBuffer pixels. No drawing at all outside this area.
* mapRect is made of the Map and a edgePointBuffer pixel border. Trail
* points are not drawn outside this area.
*/
final Dimension mapsize = map.mapSize();
final int mapHeight = mapsize.height;
final int mapWidth = mapsize.width;
final int edgeHeight =
Integer.parseInt(map.getAttributeValueString(Map.EDGE_HEIGHT));
final int edgeWidth =
Integer.parseInt(map.getAttributeValueString(Map.EDGE_WIDTH));
final int edgeClipHeight = Math.min(edgeHeight, edgeDisplayBuffer);
final int edgeClipWidth = Math.min(edgeWidth, edgeDisplayBuffer);
final int clipX = edgeWidth - edgeClipWidth;
final int clipY = edgeHeight - edgeClipHeight;
final int width = mapWidth - 2 * (edgeWidth + edgeClipWidth);
final int height = mapHeight - 2 * (edgeHeight + edgeClipHeight);
Rectangle newClip = new Rectangle(
(int) (clipX * zoom),
(int) (clipY * zoom),
(int) (width * zoom),
(int) (height * zoom)
);
final Rectangle visibleRect =
map.componentToDrawing(map.getView().getVisibleRect(), os_scale);
final Shape oldClip = g2d.getClip();
newClip = newClip.intersection(visibleRect);
if (oldClip != null) {
newClip = oldClip.getBounds().intersection(newClip);
}
g2d.setClip(newClip);
g2d.setComposite(
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency));
final float thickness = Math.max(1.0f, (float)(zoom * lineWidth));
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(lineColor);
final Rectangle circleRect = new Rectangle(
edgeWidth - edgePointBuffer,
edgeHeight - edgePointBuffer,
mapWidth + 2 * edgePointBuffer,
mapHeight + 2 * edgePointBuffer
);
/*
* Draw the tracks between trail points
*/
int x1, y1, x2, y2;
final Iterator<Point> i = pointList.iterator();
Point cur = i.next(), next;
while (i.hasNext()) {
next = i.next();
x1 = (int)(cur.x * zoom);
y1 = (int)(cur.y * zoom);
x2 = (int)(next.x * zoom);
y2 = (int)(next.y * zoom);
drawTrack(g, x1, y1, x2, y2, zoom);
cur = next;
}
final Point here = getPosition();
if (!here.equals(cur)) {
x1 = (int)(cur.x * zoom);
y1 = (int)(cur.y * zoom);
x2 = (int)(here.x * zoom);
y2 = (int)(here.y * zoom);
drawTrack(g, x1, y1, x2, y2, zoom);
}
/*
* And draw the points themselves.
*/
int elementCount = -1;
for (final Point p : pointList) {
++elementCount;
if (circleRect.contains(p) && !p.equals(here)) {
drawPoint(g, p, zoom, elementCount);
// Is there an Icon to draw in the circle?
final Image image = getTrailImage(elementCount);
x1 = (int)((p.x - circleRadius) * zoom);
y1 = (int)((p.y - circleRadius) * zoom);
if (selected && image != null) {
if (zoom == 1.0) {
g.drawImage(image, x1, y1, obs);
}
else {
final Image scaled =
ImageUtils.transform((BufferedImage) image, zoom, 0.0);
g.drawImage(scaled, x1, y1, obs);
}
}
// Or some text?
final String text = getTrailText(elementCount);
if (selected && text != null) {
if (font == null || lastZoom != zoom) {
x1 = (int)(p.x * zoom);
y1 = (int)(p.y * zoom);
final Font font =
new Font(Font.DIALOG, Font.PLAIN, (int)(circleRadius * 1.4 * zoom));
LabelUtils.drawLabel(
g, text, x1, y1,
font, LabelUtils.CENTER, LabelUtils.CENTER,
lineColor, null, null
);
}
lastZoom = zoom;
}
}
}
g2d.setComposite(oldComposite);
g2d.setStroke(oldStroke);
g2d.setColor(oldColor);
g.setClip(oldClip);
}
/**
* Draw a Circle at the given point.
* Override this method to do something different (eg. display an Icon)
*/
protected void drawPoint(Graphics g, Point p, double zoom, @SuppressWarnings("unused") int elementCount) {
final int x = (int)((p.x - circleRadius) * zoom);
final int y = (int)((p.y - circleRadius) * zoom);
final int radius = (int)(2 * circleRadius * zoom);
g.setColor(fillColor);
g.fillOval(x, y, radius, radius);
g.setColor(lineColor);
g.drawOval(x, y, radius, radius);
}
/**
* Draw a track from one Point to another.
* Don't draw under the circle as it shows
* through with transparency turned on.
*/
protected void drawTrack(Graphics g, int x1, int y1, int x2, int y2, double zoom) {
double lastSqrt = -1;
int lastDistSq = -1;
final int distSq = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
if (distSq != lastDistSq) {
lastDistSq = distSq;
lastSqrt = Math.sqrt(distSq);
}
final int xDiff = (int) ((circleRadius * (x2 - x1) * zoom) / lastSqrt);
final int yDiff = (int) ((circleRadius * (y2 - y1) * zoom) / lastSqrt);
g.drawLine(x1 + xDiff, y1 + yDiff, x2 - xDiff, y2 - yDiff);
}
/**
* Override this method to return an Image to display within each trail circle
*/
protected Image getTrailImage(@SuppressWarnings("unused")int elementCount) {
return null;
}
/**
* Override this method to return text to display within each trail circle.
* Note, there will normally be only room for 1 character.
*/
protected String getTrailText(@SuppressWarnings("unused")int elementCount) {
return null;
}
/**
* Global Visibility means all players see the same trail
* Local Visibility means each player controls their own trail visibility
*/
protected boolean isTrailVisible() {
if (globallyVisible) {
return globalVisibility || trailKey == null;
}
else {
return localVisibility || trailKey == null;
}
}
/**
* Return a bounding box covering the whole trail if it is visible, otherwise
* just return the standard piece bounding box
*/
@Override
public Rectangle boundingBox() {
return isTrailVisible() && getMap() != null ?
new Rectangle(getMyBoundingBox()) : piece.boundingBox();
}
/**
* Return the boundingBox including the trail
*/
public Rectangle getMyBoundingBox() {
if (myBoundingBox == null) {
final Rectangle bb = piece.boundingBox();
final Point pos = piece.getPosition();
bb.x += pos.x;
bb.y += pos.y;
final int circleDiameter = 2 * circleRadius;
final Rectangle pr = new Rectangle();
for (final Point p: pointList) {
pr.setBounds(
p.x - circleRadius, p.y - circleRadius, circleDiameter, circleDiameter
);
bb.add(pr);
}
bb.x -= pos.x;
bb.y -= pos.y;
myBoundingBox = bb;
}
return myBoundingBox;
}
@Override
public Shape getShape() {
return piece.getShape();
}
@Override
public String getName() {
return piece.getName();
}
@Override
public KeyCommand[] myGetKeyCommands() {
if (commands == null) {
if (trailKey != null && ! trailKey.isNull()) {
showTrailCommand = new KeyCommand(menuCommand, trailKey, Decorator.getOutermost(this), this);
}
// Key commands to force trails to specific states
if (trailKeyOn != null && !trailKeyOn.isNull()) {
showTrailCommandOn = new KeyCommand("", trailKeyOn, Decorator.getOutermost(this), this);
}
if (trailKeyOff != null && !trailKeyOff.isNull()) {
showTrailCommandOff = new KeyCommand("", trailKeyOff, Decorator.getOutermost(this), this);
}
if (trailKeyClear != null && !trailKeyClear.isNull()) {
showTrailCommandClear = new KeyCommand("", trailKeyClear, Decorator.getOutermost(this), this);
}
if (showTrailCommand != null
&& menuCommand.length() > 0) {
commands = new KeyCommand[]{showTrailCommand};
}
else {
commands = KeyCommand.NONE;
}
}
if (showTrailCommand != null) {
showTrailCommand.setEnabled(getMap() != null);
}
return commands;
}
@Override
public Command myKeyEvent(KeyStroke stroke) {
myGetKeyCommands();
if (showTrailCommand != null
&& showTrailCommand.matches(stroke)) {
final ChangeTracker tracker = new ChangeTracker(this);
initialized = true;
if (globallyVisible) {
globalVisibility = !globalVisibility;
}
else {
localVisibility = !localVisibility;
}
redraw();
return tracker.getChangeCommand();
}
// These two if blocks allow forcing the trails to a specified on or off state - much easier for a "global trails" function to keep track of.
if (showTrailCommandOn != null && showTrailCommandOn.matches(stroke)) {
final ChangeTracker tracker = new ChangeTracker(this);
initialized = true;
if (globallyVisible) {
globalVisibility = true;
}
else {
localVisibility = true;
}
redraw();
return tracker.getChangeCommand();
}
if (showTrailCommandOff != null && showTrailCommandOff.matches(stroke)) {
final ChangeTracker tracker = new ChangeTracker(this);
initialized = true;
if (globallyVisible) {
globalVisibility = false;
}
else {
localVisibility = false;
}
redraw();
return tracker.getChangeCommand();
}
// Clears the movement trail history (without being forced to do any other stuff)
if (showTrailCommandClear != null && showTrailCommandClear.matches(stroke)) {
final ChangeTracker tracker = new ChangeTracker(this);
clearTrail();
return tracker.getChangeCommand();
}
return null;
}
@Override
public PieceEditor getEditor() {
return new Ed(this);
}
@Override
public PieceI18nData getI18nData() {
final PieceI18nData data = super.getI18nData();
data.add(menuCommand, Resources.getString("Editor.Footprint.show_movement_trail_command"));
return data;
}
@Override
public boolean testEquals(Object o) {
if (! (o instanceof Footprint)) return false;
final Footprint c = (Footprint) o;
if (! Objects.equals(trailKey, c.trailKey)) return false;
if (! Objects.equals(menuCommand, c.menuCommand)) return false;
if (! Objects.equals(initiallyVisible, c.initiallyVisible)) return false;
if (! Objects.equals(globallyVisible, c.globallyVisible)) return false;
if (! Objects.equals(circleRadius, c.circleRadius)) return false;
if (! Objects.equals(fillColor, c.fillColor)) return false;
if (! Objects.equals(lineColor, c.lineColor)) return false;
if (! Objects.equals(selectedTransparency, c.selectedTransparency)) return false;
if (! Objects.equals(unSelectedTransparency, c.unSelectedTransparency)) return false;
if (! Objects.equals(edgePointBuffer, c.edgePointBuffer)) return false;
if (! Objects.equals(edgeDisplayBuffer, c.edgeDisplayBuffer)) return false;
if (! Objects.equals(lineWidth, c.lineWidth)) return false;
if (! Objects.equals(trailKeyOn, c.trailKeyOn)) return false;
if (! Objects.equals(trailKeyOff, c.trailKeyOff)) return false;
if (! Objects.equals(trailKeyClear, c.trailKeyClear)) return false;
if (! Objects.equals(description, c.description)) return false;
if (! Objects.equals(globalVisibility, c.globalVisibility)) return false;
if (! Objects.equals(startMapId, c.startMapId)) return false;
return Objects.equals(pointList, c.pointList);
}
/**
* Key Command Global Visibility Circle Radius Fill Color Line Color Selected
* Transparency Unselected Transparency Edge Buffer Display Limit Edge Buffer
* Point Limit
*/
protected static class Ed implements PieceEditor {
private final StringConfigurer desc;
private final NamedHotKeyConfigurer trailKeyInput;
private final NamedHotKeyConfigurer trailKeyOn;
private final NamedHotKeyConfigurer trailKeyOff;
private final NamedHotKeyConfigurer trailKeyClear;
private final TraitConfigPanel controls;
private final StringConfigurer mc;
private final BooleanConfigurer iv;
private final BooleanConfigurer gv;
private final IntConfigurer cr;
private final ColorConfigurer fc;
private final ColorConfigurer lc;
private final IntConfigurer st;
private final IntConfigurer ut;
private final IntConfigurer pb;
private final IntConfigurer db;
private final DoubleConfigurer lw;
public Ed(Footprint p) {
controls = new TraitConfigPanel();
desc = new StringConfigurer(p.description);
desc.setHintKey("Editor.description_hint");
controls.add("Editor.description_label", desc);
mc = new StringConfigurer(p.menuCommand);
mc.setHintKey("Editor.menu_command_hint");
controls.add("Editor.menu_command", mc);
trailKeyInput = new NamedHotKeyConfigurer(p.trailKey);
controls.add("Editor.keyboard_command", trailKeyInput);
// Trail forcing commands
trailKeyOn = new NamedHotKeyConfigurer(p.trailKeyOn);
controls.add("Editor.Footprint.turn_on_key_command", trailKeyOn);
trailKeyOff = new NamedHotKeyConfigurer(p.trailKeyOff);
controls.add("Editor.Footprint.turn_off_key_command", trailKeyOff);
trailKeyClear = new NamedHotKeyConfigurer(p.trailKeyClear);
controls.add("Editor.Footprint.clear_trail_key_command", trailKeyClear);
iv = new BooleanConfigurer(p.initiallyVisible);
controls.add("Editor.Footprint.trails_start_visible", iv);
gv = new BooleanConfigurer(p.globallyVisible);
controls.add("Editor.Footprint.trails_are_visible_to_all_players", gv);
cr = new IntConfigurer(p.circleRadius);
controls.add("Editor.Footprint.circle_radius", cr);
fc = new ColorConfigurer(p.fillColor);
controls.add("Editor.Footprint.circle_fill_color", fc);
lc = new ColorConfigurer(p.lineColor);
controls.add("Editor.Footprint.line_color", lc);
lw = new DoubleConfigurer(p.lineWidth);
controls.add("Editor.Footprint.line_thickness", lw);
st = new IntConfigurer(p.selectedTransparency);
controls.add("Editor.Footprint.selected_transparency", st);
ut = new IntConfigurer(p.unSelectedTransparency);
controls.add("Editor.Footprint.unselected_transparency", ut);
pb = new IntConfigurer(p.edgePointBuffer);
controls.add("Editor.Footprint.display_trail_points_off_map", pb);
db = new IntConfigurer(p.edgeDisplayBuffer);
controls.add("Editor.Footprint.display_trails_off_map", db);
}
@Override
public String getState() {
return gv.booleanValue() + ";;0";
}
@Override
public String getType() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(trailKeyInput.getValueString())
.append(mc.getValueString())
.append(iv.getValueString())
.append(gv.getValueString())
.append(cr.getValueString())
.append(fc.getValueString())
.append(lc.getValueString())
.append(st.getValueString())
.append(ut.getValueString())
.append(pb.getValueString())
.append(db.getValueString())
.append(lw.getValueString())
.append(trailKeyOn.getValueString())
.append(trailKeyOff.getValueString())
.append(trailKeyClear.getValueString())
.append(desc.getValueString());
return ID + se.getValue();
}
@Override
public Component getControls() {
return controls;
}
}
}
|
package exm.stc.tclbackend;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import exm.stc.common.Settings;
import exm.stc.common.exceptions.InvalidOptionException;
import exm.stc.common.exceptions.STCRuntimeError;
import exm.stc.common.lang.TaskMode;
import exm.stc.tclbackend.tree.Command;
import exm.stc.tclbackend.tree.Expression;
import exm.stc.tclbackend.tree.LiteralInt;
import exm.stc.tclbackend.tree.Sequence;
import exm.stc.tclbackend.tree.SetVariable;
import exm.stc.tclbackend.tree.Square;
import exm.stc.tclbackend.tree.TclList;
import exm.stc.tclbackend.tree.TclString;
import exm.stc.tclbackend.tree.TclTree;
import exm.stc.tclbackend.tree.Token;
import exm.stc.tclbackend.tree.Value;
/**
* Automates creation of Turbine-specific Tcl constructs
* @author wozniak
*
* This class is package-private: only TurbineGenerator uses it
* */
class Turbine
{
private static final String EXEC = "exec";
/* Names of types used by Turbine */
public static final String STRING_TYPENAME = "string";
public static final String INTEGER_TYPENAME = "integer";
public static final String VOID_TYPENAME = "void";
public static final String FLOAT_TYPENAME = "float";
public static final String BLOB_TYPENAME = "blob";
// Commonly used things:
private static final Token ALLOCATE_CONTAINER =
new Token("turbine::allocate_container");
private static final Token ALLOCATE_FILE =
new Token("turbine::allocate_file2");
private static final Token CONTAINER_INSERT =
new Token("turbine::container_insert");
private static final Token CONTAINER_F_INSERT =
new Token("turbine::container_f_insert");
private static final Token CONTAINER_F_REFERENCE =
new Token("turbine::f_reference");
private static final Token CONTAINER_REFERENCE =
new Token("adlb::container_reference");
private static final Token CONTAINER_IMMEDIATE_INSERT =
new Token("turbine::container_immediate_insert");
private static final Token CREF_F_LOOKUP =
new Token("turbine::f_cref_lookup");
private static final TclTree CREF_LOOKUP_LITERAL =
new Token("turbine::f_cref_lookup_literal");
private static final Token F_CONTAINER_CREATE_NESTED =
new Token("turbine::f_container_create_nested");
private static final Token F_CREF_CREATE_NESTED =
new Token("turbine::f_cref_create_nested");
private static final Token F_CONTAINER_CREATE_NESTED_STATIC =
new Token("turbine::container_create_nested");
private static final Token F_CREF_CREATE_NESTED_STATIC =
new Token("turbine::cref_create_nested");
private static final Token CONTAINER_SLOT_DROP =
new Token("adlb::slot_drop");
private static final Token CONTAINER_SLOT_CREATE =
new Token("adlb::slot_create");
private static final Token CONTAINER_ENUMERATE =
new Token("adlb::enumerate");
private static final Token RETRIEVE_UNTYPED =
new Token("turbine::retrieve");
private static final Token RETRIEVE_INTEGER =
new Token("turbine::retrieve_integer");
private static final Token RETRIEVE_FLOAT =
new Token("turbine::retrieve_float");
private static final Token RETRIEVE_STRING =
new Token("turbine::retrieve_string");
private static final Token RETRIEVE_BLOB = new Token("turbine::retrieve_blob");
private static final Token STACK_LOOKUP =
new Token("turbine::stack_lookup");
static final String LOCAL_STACK_NAME = "stack";
static final String PARENT_STACK_NAME = "stack";
private static final Value STACK = new Value(LOCAL_STACK_NAME);
private static final Value PARENT_STACK =
new Value(PARENT_STACK_NAME);
private static final Token PARENT_STACK_ENTRY =
new Token("_parent");
private static final Token RULE = new Token("turbine::c::rule");
private static final Token NO_STACK = new Token("no_stack");
private static final Token DEREFERENCE_INTEGER =
new Token("turbine::f_dereference_integer");
private static final Token DEREFERENCE_FLOAT =
new Token("turbine::f_dereference_float");
private static final Token DEREFERENCE_STRING =
new Token("turbine::f_dereference_string");
private static final Token DEREFERENCE_BLOB =
new Token("turbine::f_dereference_blob");
private static final Token DEREFERENCE_FILE =
new Token("turbine::f_dereference_file");
private static final Token TURBINE_LOG =
new Token("turbine::c::log");
private static final Token ALLOCATE = new Token("turbine::allocate");
private static final Token DIVIDE_INTEGER =
new Token("turbine::divide_integer_impl");
private static final Token MOD_INTEGER =
new Token("turbine::mod_integer_impl");
static final Token CONTAINER_LOOKUP =
new Token("turbine::container_lookup");
static final Token CONTAINER_LOOKUP_CHECKED =
new Token("turbine::container_lookup_checked");
private static final Token STORE_INTEGER =
new Token("turbine::store_integer");
private static final Token STORE_VOID =
new Token("turbine::store_void");
private static final Token STORE_FLOAT =
new Token("turbine::store_float");
private static final Token STORE_STRING =
new Token("turbine::store_string");
private static final Token STORE_BLOB = new Token("turbine::store_blob");
private static final Token INIT_UPD_FLOAT =
new Token("turbine::init_updateable_float");
private static final Token CONTAINER_DEREF_INSERT =
new Token("turbine::container_deref_insert");
private static final Token CONTAINER_F_DEREF_INSERT =
new Token("turbine::container_f_deref_insert");
private static final Token CALL_FUNCTION =
new Token("turbine::call_composite");
private static final Token UNCACHED_MODE = new Token("UNCACHED");
private static final Token FREE_BLOB = new Token("turbine::free_blob");
private static final Token FREE_LOCAL_BLOB =
new Token("turbine::free_local_blob");
public static final LiteralInt VOID_DUMMY_VAL = new LiteralInt(12345);
private static final Token REFCOUNT_INCR = new Token("turbine::read_refcount_incr");
private static final Token REFCOUNT_DECR = new Token("turbine::read_refcount_decr");
private static final Token FILE_REFCOUNT_INCR = new Token("turbine::file_read_refcount_incr");
private static final Token FILE_REFCOUNT_DECR = new Token("turbine::file_read_refcount_decr");
public enum StackFrameType {
MAIN,
FUNCTION,
NESTED
}
/**
* Used to specify what caching is allowed for retrieve
* @author tga
*/
public enum CacheMode {
CACHED,
UNCACHED
}
public Turbine()
{}
public static TclTree[] createStackFrame(StackFrameType type)
{
TclTree[] result;
// Index into result
int index = 0;
if (type == StackFrameType.MAIN)
result = new TclTree[1];
else
result = new TclTree[3];
if (type == StackFrameType.NESTED || type == StackFrameType.FUNCTION) {
// Make sure that there is a variable in scope called parent
// (parent is passed in as an argument)
result[index++] = new SetVariable("parent", STACK);
}
result[index++] = allocateContainer(LOCAL_STACK_NAME, STRING_TYPENAME);
if (type != StackFrameType.MAIN) {
// main is the only procedure without a parent stack frame
result[index++] = new Command(CONTAINER_INSERT, STACK,
PARENT_STACK_ENTRY, PARENT_STACK);
}
return result;
}
public static TclTree createDummyStackFrame() {
return new SetVariable(LOCAL_STACK_NAME, new LiteralInt(0));
}
public static Command storeInStack(String stackVarName, String tclVarName)
{
Token name = new Token(stackVarName);
Value value = new Value(tclVarName);
Command result =
new Command(CONTAINER_INSERT, STACK, name, value);
return result;
}
public static TclTree allocate(String tclName, String typePrefix,
boolean updateable) {
return new Command(ALLOCATE,
new Token(tclName), new Token(typePrefix),
LiteralInt.boolValue(updateable));
}
public static TclTree allocateContainer(String name,
String indexType) {
return new Command(ALLOCATE_CONTAINER,
new Token(name), new Token(indexType));
}
public static TclTree allocateFile(Value mapVar, String tclName) {
if (mapVar != null) {
return new Command(ALLOCATE_FILE,
new Token(tclName), mapVar);
} else {
return new Command(ALLOCATE_FILE,
new Token(tclName));
}
}
public static SetVariable stackLookup(String stackName,
String tclVarName, String containerVarName) {
Token v = new Token(containerVarName);
Square square = new Square(STACK_LOOKUP,
new Value(stackName), v);
SetVariable sv = new SetVariable(tclVarName, square);
return sv;
}
public static SetVariable lookupParentStack(String parentScope,
String childScope) {
Square square = new Square(STACK_LOOKUP,
new Value(childScope),
PARENT_STACK_ENTRY);
SetVariable sv = new SetVariable(parentScope, square);
return sv;
}
/**
Do a data get operation to load the value from the TD
*/
public static SetVariable integerGet(String target, Value variable) {
return new SetVariable(target, new Square(RETRIEVE_INTEGER, variable));
}
public static SetVariable refGet(String target, Value variable) {
return new SetVariable(target, new Square(RETRIEVE_UNTYPED, variable));
}
public static Command stringSet(Value turbineDstVar, Expression src) {
return new Command(STORE_STRING, turbineDstVar, src);
}
public static Command integerSet(Value turbineDstVar, Expression src) {
return new Command(STORE_INTEGER, turbineDstVar, src);
}
public static TclTree voidSet(Value voidVar) {
return new Command(STORE_VOID, voidVar);
}
public static Command floatSet(Value turbineDstVar, Expression src) {
return new Command(STORE_FLOAT, turbineDstVar, src);
}
public static Command updateableFloatInit(Value turbineDstVar, Expression src) {
return new Command(INIT_UPD_FLOAT, turbineDstVar, src);
}
public static SetVariable floatGet(String target, Value variable) {
return floatGet(target, variable, CacheMode.CACHED);
}
public static SetVariable floatGet(String target, Value variable,
CacheMode caching) {
if (caching == CacheMode.CACHED) {
return new SetVariable(target,
new Square(RETRIEVE_FLOAT, variable));
} else {
assert(caching == CacheMode.UNCACHED);
return new SetVariable(target,
new Square(RETRIEVE_FLOAT, variable, UNCACHED_MODE));
}
}
/**
* Do a data get operation to load the value from the TD
*/
public static SetVariable stringGet(String target, Value variable) {
return new SetVariable(target, new Square(RETRIEVE_STRING, variable));
}
public static SetVariable blobGet(String target, Value var) {
return new SetVariable(target, new Square(RETRIEVE_BLOB, var));
}
public static Command freeBlob(Value var) {
return new Command(FREE_BLOB, var);
}
public static Command freeLocalBlob(Value var) {
return new Command(FREE_LOCAL_BLOB, var);
}
public static Command blobSet(Value target, Expression src) {
// Calling convention requires separate pointer and length args
return new Command(STORE_BLOB, target, src);
}
private static Value tclRuleType (TaskMode t) {
switch (t) {
case LOCAL:
return new Value("turbine::LOCAL");
case CONTROL:
return new Value("turbine::CONTROL");
case LEAF:
return new Value("turbine::WORK");
default:
throw new STCRuntimeError("Unexpected rule type: " + t);
}
}
/**
* Generate code for a rule
* @param symbol
* @param inputs
* @param action the action, using a tcl list to ensure proper escaping
* @param type
* @return
*/
private static Sequence ruleHelper(String symbol,
List<? extends Expression> inputs,
TclList action, TaskMode type) {
Sequence result = new Sequence();
Token s = new Token(symbol);
TclList i = new TclList(inputs);
Command r = new Command(RULE, s, i, tclRuleType(type), action);
result.add(r);
return result;
}
/**
* Same as rule, but store the rule ID into the TCL variable named by
* ruleIDVarName so that it can be provided as an argument to the procedure
* @param symbol
* @param blockOn
* @param action
* @param mode
* @return
*/
public static Sequence rule(String symbol,
List<? extends Expression> blockOn, TclList action, TaskMode mode) {
return ruleHelper(symbol, blockOn, action, mode);
}
public static Sequence loopRule(String symbol,
List<Value> args, List<? extends Expression> blockOn) {
List<Expression> actionElems = new ArrayList<Expression>();
actionElems.add(new Token(symbol));
for (Value arg: args) {
actionElems.add(arg);
}
TclList action = new TclList(actionElems);
return ruleHelper(symbol, blockOn, action, TaskMode.CONTROL);
}
public static TclTree allocateStruct(String tclName) {
Square createExpr = new Square(new Token("dict"), new Token("create"));
return new SetVariable(tclName, createExpr);
}
/**
* Insert src into struct at container.field
* @param container
* @param field
* @param src
*/
public static Sequence structInsert(String container, String field,
String src) {
Sequence result = new Sequence();
Command storeCmd = new Command(
new Token("dict"), new Token("set"),
new Token(container), new TclString(field, true), new Value(src));
result.add(storeCmd);
return result;
}
public static Sequence structLookupFieldID(String structName, String structField,
String resultVar) {
Sequence result = new Sequence();
Square containerGet = new Square(new Token("dict"), new Token("get"),
new Value(structName), new TclString(structField, true));
SetVariable loadCmd = new SetVariable(resultVar, containerGet);
result.add(loadCmd);
return result;
}
public static Command structRefLookupFieldID(String structName, String structField,
String resultVar, String resultTypeName) {
Command lookup = new Command(new Token("turbine::struct_ref_lookup"),
new Value(structName), new TclString(structField, true),
new Value(resultVar), new TclString(resultTypeName, true));
return lookup;
}
/**
* Put reference to arrayVar[arrayIndex] into refVar once it is ready
* @param refVar
* @param arrayIndex
* @param isArrayRef
* @return
*/
public static Command arrayLookupImmIx(String refVar,
boolean refIsString, String arrayVar,
Expression arrayIndex, boolean isArrayRef) {
Token refType = refIsString ? new Token(STRING_TYPENAME)
: new Token(INTEGER_TYPENAME);
// set up reference to point to array data
if (isArrayRef) {
return new Command(CREF_LOOKUP_LITERAL, NO_STACK,
new TclList(), new TclList(new Value(arrayVar),
arrayIndex, new Value(refVar), refType));
} else {
return new Command(CONTAINER_REFERENCE, new Value(arrayVar),
arrayIndex, new Value(refVar), refType);
}
}
/**
* Lookup arrayVar[arrayIndex] right away, regardless of whether
* it is closed
*/
public static SetVariable arrayLookupImm(String dst, String arrayVar,
Expression arrayIndex) {
return new SetVariable(dst,
new Square(CONTAINER_LOOKUP_CHECKED, new Value(arrayVar), arrayIndex));
}
/**
* Put a reference to arrayVar[indexVar] into refVar
* @param refVar
* @param arrayVar
* @param indexVar
* @param isArrayRef
* @return
*/
public static Command arrayLookupComputed(String refVar,
boolean refIsString,
String arrayVar,
String indexVar, boolean isArrayRef) {
Token refType = refIsString ? new Token(STRING_TYPENAME)
: new Token(INTEGER_TYPENAME);
if (isArrayRef) {
return new Command(CREF_F_LOOKUP, NO_STACK,
new TclList(), new TclList(new Value(arrayVar), new Value(indexVar),
new Value(refVar), refType));
} else {
return new Command(CONTAINER_F_REFERENCE, NO_STACK,
new TclList(), new TclList(new Value(arrayVar), new Value(indexVar),
new Value(refVar), refType));
}
}
public static Command dereferenceInteger(Value dstVar, Value refVar) {
return new Command(DEREFERENCE_INTEGER, NO_STACK, dstVar, refVar);
}
public static Command dereferenceFloat(Value dstVar, Value refVar) {
return new Command(DEREFERENCE_FLOAT, NO_STACK, dstVar, refVar);
}
public static Command dereferenceString(Value dstVar, Value refVar) {
return new Command(DEREFERENCE_STRING, NO_STACK,
dstVar, refVar);
}
public static Command dereferenceBlob(Value dstVar, Value refVar) {
return new Command(DEREFERENCE_BLOB, NO_STACK, dstVar, refVar);
}
public static Command dereferenceFile(Value dstVar, Value refVar) {
return new Command(DEREFERENCE_FILE, NO_STACK, dstVar, refVar);
}
public static Command arrayStoreImmediate(String srcVar, String arrayVar,
Expression arrayIndex) {
return new Command(CONTAINER_IMMEDIATE_INSERT,
new Value(arrayVar), arrayIndex, new Value(srcVar));
}
public static Command arrayDerefStore(String srcRefVar, String arrayVar,
Expression arrayIndex) {
Square outputs = new TclList();
Square inputs = new TclList(new Value(arrayVar),
arrayIndex, new Value(srcRefVar));
return new Command(CONTAINER_DEREF_INSERT, NO_STACK, outputs, inputs);
}
public static Command arrayDerefStoreComputed(String srcRefVar, String arrayVar,
String indexVar) {
Square outputs = new TclList();
Square inputs = new TclList(new Value(arrayVar), new Value(indexVar),
new Value(srcRefVar));
return new Command(CONTAINER_F_DEREF_INSERT, NO_STACK, outputs, inputs);
}
public static Command arrayStoreComputed(String srcVar, String arrayVar,
String indexVar) {
Square outputs = new TclList();
Square inputs = new TclList(new Value(arrayVar), new Value(indexVar),
new Value(srcVar));
return new Command(CONTAINER_F_INSERT, NO_STACK, outputs, inputs);
}
public static Command arrayRefStoreImmediate(String srcVar, String arrayVar,
Expression arrayIndex, String outerArray) {
return new Command(new Token("turbine::cref_insert"),
NO_STACK, new TclList(), new TclList(
new Value(arrayVar), arrayIndex, new Value(srcVar),
new Value(outerArray)));
}
public static Command arrayRefStoreComputed(String srcVar, String arrayVar,
String indexVar, String outerArray) {
Square outputs = new TclList();
Square inputs = new TclList(new Value(arrayVar), new Value(indexVar),
new Value(srcVar), new Value(outerArray));
return new Command(new Token("turbine::f_cref_insert"),
NO_STACK, outputs, inputs);
}
public static Command arrayRefDerefStore(String srcRefVar, String arrayVar,
Expression arrayIndex, String outerArrayVar) {
Square outputs = new TclList();
Square inputs = new TclList(new Value(arrayVar),
arrayIndex, new Value(srcRefVar), new Value(outerArrayVar));
return new Command(new Token("turbine::cref_deref_insert"),
NO_STACK, outputs, inputs);
}
public static Command arrayRefDerefStoreComputed(String srcRefVar, String arrayVar,
String indexVar, String outerArrayVar) {
Square outputs = new TclList();
Square inputs = new TclList(new Value(arrayVar), new Value(indexVar),
new Value(srcRefVar), new Value(outerArrayVar));
return new Command(new Token("turbine::cref_f_deref_insert"),
NO_STACK, outputs, inputs);
}
public static TclTree containerCreateNested(String resultVar,
String containerVar, String indexVar) {
return new Command(F_CONTAINER_CREATE_NESTED,
new Token(resultVar), new Value(containerVar),
new Value(indexVar), new Token(INTEGER_TYPENAME));
}
public static TclTree containerRefCreateNested(String resultVar,
String containerVar, String indexVar) {
return new Command(F_CREF_CREATE_NESTED,
new Token(resultVar), new Value(containerVar),
new Value(indexVar), new Token(INTEGER_TYPENAME));
}
public static TclTree containerRefCreateNestedImmIx(String resultVar,
String containerVar, Expression arrIx) {
return new Command(F_CREF_CREATE_NESTED_STATIC,
new Token(resultVar), new Value(containerVar),
arrIx, new Token(INTEGER_TYPENAME));
}
public static TclTree containerCreateNestedImmIx(String resultVar,
String containerVar, Expression arrIx) {
return new SetVariable(resultVar,
new Square(F_CONTAINER_CREATE_NESTED_STATIC,
new Value(containerVar), arrIx, new Token(INTEGER_TYPENAME)));
}
public static TclTree containerSlotCreate(Value arr) {
return new Command(CONTAINER_SLOT_CREATE, arr);
}
public static TclTree containerSlotCreate(Value arr, Expression incr) {
return new Command(CONTAINER_SLOT_CREATE, arr, incr);
}
public static TclTree decrArrayWriters(Value arr) {
return new Command(CONTAINER_SLOT_DROP, arr);
}
public static TclTree containerSlotDrop(Value arr, Expression decr) {
return new Command(CONTAINER_SLOT_DROP, arr, decr);
}
public static Command enableReferenceCounting() {
return new Command("turbine::enable_read_refcount");
}
/**
* Modify reference count by amount
* @param var
* @param change
* @return
*/
public static TclTree incrRef(Expression var, Expression change) {
try {
if (Settings.getBoolean(Settings.EXPERIMENTAL_REFCOUNTING)) {
if (change == null) {
return new Command(REFCOUNT_INCR, var);
} else {
return new Command(REFCOUNT_INCR, var, change);
}
} else {
return new Token("");
}
} catch (InvalidOptionException e) {
throw new STCRuntimeError(e.getMessage());
}
}
/**
* Modify reference count by amount
* @param var
* @param change
* @return
*/
public static TclTree decrRef(Expression var, Expression change) {
try {
if (Settings.getBoolean(Settings.EXPERIMENTAL_REFCOUNTING)) {
if (change == null) {
return new Command(REFCOUNT_DECR, var);
} else {
return new Command(REFCOUNT_DECR, var, change);
}
} else {
return new Token("");
}
} catch (InvalidOptionException e) {
throw new STCRuntimeError(e.getMessage());
}
}
public static TclTree incrRef(Value var) {
return incrRef(var, new LiteralInt(1));
}
public static TclTree decrRef(Value var) {
return decrRef(var, new LiteralInt(1));
}
/**
* Modify reference count by amount
* @param var
* @param change
* @return
*/
public static TclTree incrFileRef(Expression var, Expression change) {
try {
if (Settings.getBoolean(Settings.EXPERIMENTAL_REFCOUNTING)) {
if (change == null) {
return new Command(FILE_REFCOUNT_INCR, var);
} else {
return new Command(FILE_REFCOUNT_INCR, var, change);
}
} else {
return new Token("");
}
} catch (InvalidOptionException e) {
throw new STCRuntimeError(e.getMessage());
}
}
public static TclTree decrFileRef(Expression var, Expression change) {
try {
if (Settings.getBoolean(Settings.EXPERIMENTAL_REFCOUNTING)) {
if (change == null) {
return new Command(FILE_REFCOUNT_DECR, var);
} else {
return new Command(FILE_REFCOUNT_DECR, var, change);
}
} else {
return new Token("");
}
} catch (InvalidOptionException e) {
throw new STCRuntimeError(e.getMessage());
}
}
/**
* Get entire contents of container
* @param resultVar
* @param arr
* @param includeKeys
* @return
*/
public static SetVariable containerContents(String resultVar,
Value arr, boolean includeKeys) {
Token mode = includeKeys ? new Token("dict") : new Token("members");
return new SetVariable(resultVar, new Square(
CONTAINER_ENUMERATE, arr, mode, new Token("all"),
new LiteralInt(0)));
}
/**
* Return the size of a container
* @param resultVar
* @param arr
* @return
*/
public static SetVariable containerSize(String resultVar,
Value arr) {
return new SetVariable(resultVar, new Square(
CONTAINER_ENUMERATE, arr, new Token("count"), new Token("all"),
new LiteralInt(0)));
}
/**
* Retrieve partial contents of container from start to end inclusive
* start to end are not the logical array indices, but rather physical indices
* @param resultVar
* @param arr
* @param includeKeys
* @param start
* @param len
* @return
*/
public static SetVariable containerContents(String resultVar,
Value arr, boolean includeKeys, Expression start, Expression len) {
Token mode = includeKeys ? new Token("dict") : new Token("members");
return new SetVariable(resultVar, new Square(
CONTAINER_ENUMERATE, arr, mode, start, len));
}
public static Command turbineLog(String msg) {
return new Command(TURBINE_LOG, new TclString(msg, true));
}
public static Command turbineLog(String... tokens) {
return new Command(TURBINE_LOG, new TclList(tokens));
}
public static TclTree turbineLog(List<Expression> logMsg) {
return new Command(TURBINE_LOG, new TclList(logMsg));
}
public static TclTree declareReference(String refVarName) {
return allocate(refVarName, INTEGER_TYPENAME, false);
}
public static TclTree callFunction(String function, TclList oList,
TclList iList, TclList blockOn) {
return new Command(CALL_FUNCTION,
new Value(Turbine.LOCAL_STACK_NAME), new Token(function),
oList, iList, blockOn);
}
public static TclTree callFunctionSync(String function, TclList oList,
TclList iList) {
return new Command(new Token(function), new Value(Turbine.LOCAL_STACK_NAME),
oList, iList);
}
public static Command makeTCLGlobal(String tclName) {
return new Command(new Token("global"), new Token(tclName));
}
public static Square modInteger(Expression a, Expression b) {
return new Square(new Expression[] {MOD_INTEGER, a, b});
}
public static Square divideInteger(Expression a, Expression b) {
return new Square(new Expression[] {DIVIDE_INTEGER, a, b});
}
/**
* @param cmd
* @param args
* @return Tcl code to execute external executable
*/
public static Command exec(String cmd, List<Expression> args) {
ArrayList<Expression> args2 = new ArrayList<Expression>(args.size() + 3);
args2.add(new TclString(cmd, true));
args2.addAll(args);
args2.add(new Token(">@stdout"));
args2.add(new Token("2>@stderr"));
return new Command(EXEC, args2);
}
/**
* Expression that extracts the void status variable for
* a file variable
* @param fileVar
* @return
*/
public static Expression getFileStatus(Value fileVar) {
return new Square(new Token("turbine::get_file_status"), fileVar);
}
/**
* Expression that extracts the filename string future
* a file variable
* @param fileVar
* @param initUnmapped
* @return
*/
public static Expression getFileName(Value fileVar, boolean initUnmapped) {
if (initUnmapped) {
return new Square(new Token("turbine::get_file_path"), fileVar);
} else {
return new Square(new Token("turbine::get_output_file_path"), fileVar);
}
}
/**
* Command to clsoe a file
* @param fileVar
* @return
*/
public static Command closeFile(Value fileVar) {
return new Command(new Token("turbine::close_file"), fileVar);
}
public static TclTree resetPriority() {
return new Command("turbine::reset_priority");
}
public static TclTree setPriority(Expression priority) {
return new Command("turbine::set_priority", Arrays.asList(priority));
}
public static Command makePermanent(Value value) {
return new Command("adlb::permanent", Arrays.asList(value));
}
}
|
package org.jboss.as.web;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ServiceVerificationHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.services.path.AbstractPathService;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.web.deployment.EarContextRootProcessor;
import org.jboss.as.web.deployment.JBossWebParsingDeploymentProcessor;
import org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor;
import org.jboss.as.web.deployment.TldParsingDeploymentProcessor;
import org.jboss.as.web.deployment.WarAnnotationDeploymentProcessor;
import org.jboss.as.web.deployment.WarClassloadingDependencyProcessor;
import org.jboss.as.web.deployment.WarDeploymentInitializingProcessor;
import org.jboss.as.web.deployment.WarDeploymentProcessor;
import org.jboss.as.web.deployment.WarMetaDataProcessor;
import org.jboss.as.web.deployment.WarStructureDeploymentProcessor;
import org.jboss.as.web.deployment.WebFragmentParsingDeploymentProcessor;
import org.jboss.as.web.deployment.WebInitializeInOrderProcessor;
import org.jboss.as.web.deployment.WebParsingDeploymentProcessor;
import org.jboss.as.web.deployment.component.WebComponentProcessor;
import org.jboss.as.web.deployment.jsf.JsfAnnotationProcessor;
import org.jboss.as.web.deployment.jsf.JsfManagedBeanProcessor;
import org.jboss.as.web.deployment.jsf.JsfVersionProcessor;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder.DependencyType;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import javax.management.MBeanServer;
import java.util.List;
/**
* Adds the web subsystem.
*
* @author Emanuel Muckenhuber
* @author Tomaz Cerar
*/
class WebSubsystemAdd extends AbstractBoottimeAddStepHandler {
static final WebSubsystemAdd INSTANCE = new WebSubsystemAdd();
private static final String TEMP_DIR = "jboss.server.temp.dir";
private WebSubsystemAdd() {
}
@Override
protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
WebDefinition.DEFAULT_VIRTUAL_SERVER.validateAndSet(operation, model);
WebDefinition.NATIVE.validateAndSet(operation, model);
WebDefinition.INSTANCE_ID.validateAndSet(operation, model);
}
@Override
protected void performBoottime(OperationContext context, ModelNode baseOperation, ModelNode model,
ServiceVerificationHandler verificationHandler,
List<ServiceController<?>> newControllers) throws OperationFailedException {
ModelNode fullModel = Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS));
final ModelNode config = resolveConfiguration(context, fullModel.get(Constants.CONFIGURATION));
final String defaultVirtualServer = WebDefinition.DEFAULT_VIRTUAL_SERVER.resolveModelAttribute(context, fullModel).asString();
final boolean useNative = WebDefinition.NATIVE.resolveModelAttribute(context, fullModel).asBoolean();
final ModelNode instanceIdModel = WebDefinition.INSTANCE_ID.resolveModelAttribute(context, fullModel);
final String instanceId = instanceIdModel.isDefined() ? instanceIdModel.asString() : null;
context.addStep(new AbstractDeploymentChainStep() {
@Override
protected void execute(DeploymentProcessorTarget processorTarget) {
final SharedWebMetaDataBuilder sharedWebBuilder = new SharedWebMetaDataBuilder(config.clone());
final SharedTldsMetaDataBuilder sharedTldsBuilder = new SharedTldsMetaDataBuilder(config.clone());
processorTarget.addDeploymentProcessor(Phase.STRUCTURE, Phase.STRUCTURE_WAR_DEPLOYMENT_INIT, new WarDeploymentInitializingProcessor());
processorTarget.addDeploymentProcessor(Phase.STRUCTURE, Phase.STRUCTURE_WAR, new WarStructureDeploymentProcessor(sharedWebBuilder.create(), sharedTldsBuilder));
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WEB_DEPLOYMENT, new WebParsingDeploymentProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WEB_DEPLOYMENT_FRAGMENT, new WebFragmentParsingDeploymentProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_JSF_VERSION, new JsfVersionProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_JBOSS_WEB_DEPLOYMENT, new JBossWebParsingDeploymentProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_TLD_DEPLOYMENT, new TldParsingDeploymentProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_ANNOTATION_WAR, new WarAnnotationDeploymentProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WEB_COMPONENTS, new WebComponentProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_EAR_CONTEXT_ROOT, new EarContextRootProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WEB_MERGE_METADATA, new WarMetaDataProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.POST_MODULE_JSF_MANAGED_BEANS, new JsfManagedBeanProcessor());
processorTarget.addDeploymentProcessor(Phase.PARSE, Phase.PARSE_WEB_INITIALIZE_IN_ORDER, new WebInitializeInOrderProcessor(defaultVirtualServer));
processorTarget.addDeploymentProcessor(Phase.DEPENDENCIES, Phase.DEPENDENCIES_WAR_MODULE, new WarClassloadingDependencyProcessor());
processorTarget.addDeploymentProcessor(Phase.POST_MODULE, Phase.POST_MODULE_JSF_MANAGED_BEANS, new JsfManagedBeanProcessor());
processorTarget.addDeploymentProcessor(Phase.INSTALL, Phase.INSTALL_SERVLET_INIT_DEPLOYMENT, new ServletContainerInitializerDeploymentProcessor());
processorTarget.addDeploymentProcessor(Phase.INSTALL, Phase.INSTALL_JSF_ANNOTATIONS, new JsfAnnotationProcessor());
processorTarget.addDeploymentProcessor(Phase.INSTALL, Phase.INSTALL_WAR_DEPLOYMENT, new WarDeploymentProcessor(defaultVirtualServer));
}
}, OperationContext.Stage.RUNTIME);
final WebServerService service = new WebServerService(defaultVirtualServer, useNative, instanceId);
newControllers.add(context.getServiceTarget().addService(WebSubsystemServices.JBOSS_WEB, service)
.addDependency(AbstractPathService.pathNameOf(TEMP_DIR), String.class, service.getPathInjector())
.addDependency(DependencyType.OPTIONAL, ServiceName.JBOSS.append("mbean", "server"), MBeanServer.class, service.getMbeanServer())
.setInitialMode(Mode.ON_DEMAND)
.install());
}
@Override
protected boolean requiresRuntimeVerification() {
return false;
}
private ModelNode resolveConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
ModelNode res = new ModelNode();
ModelNode unresolvedContainer = model.get(Constants.CONTAINER);
for (AttributeDefinition attr : WebContainerDefinition.CONTAINER_ATTRIBUTES) {
res.get(Constants.CONTAINER).get(attr.getName()).set(attr.resolveModelAttribute(context, unresolvedContainer));
}
ModelNode unresolvedStaticResources = model.get(Constants.STATIC_RESOURCES);
for (SimpleAttributeDefinition attr : WebStaticResources.STATIC_ATTRIBUTES) {
res.get(Constants.STATIC_RESOURCES).get(attr.getName()).set(attr.resolveModelAttribute(context, unresolvedStaticResources));
}
ModelNode unresolvedJspConf = model.get(Constants.JSP_CONFIGURATION);
for (SimpleAttributeDefinition attr : WebJSPDefinition.JSP_ATTRIBUTES) {
res.get(Constants.JSP_CONFIGURATION).get(attr.getName()).set(attr.resolveModelAttribute(context, unresolvedJspConf));
}
return res;
}
}
|
package com.thoughtworks.xstream.core;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.core.util.PresortedMap;
import com.thoughtworks.xstream.core.util.PresortedSet;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.security.AccessControlException;
import java.text.AttributedString;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
public class JVM {
private ReflectionProvider reflectionProvider;
private transient Map loaderCache = new HashMap();
private final boolean supportsAWT = loadClass("java.awt.Color") != null;
private final boolean supportsSwing = loadClass("javax.swing.LookAndFeel") != null;
private final boolean supportsSQL = loadClass("java.sql.Date") != null;
private static final boolean optimizedTreeSetAddAll;
private static final boolean optimizedTreeMapPutAll;
private static final boolean canParseUTCDateFormat;
private static final String vendor = System.getProperty("java.vm.vendor");
private static final float majorJavaVersion = getMajorJavaVersion();
private static final boolean reverseFieldOrder = isHarmony() || (isIBM() && !is15());
static final float DEFAULT_JAVA_VERSION = 1.3f;
static {
Comparator comparator = new Comparator() {
public int compare(Object o1, Object o2) {
throw new RuntimeException();
}
};
boolean test = true;
SortedMap map = new PresortedMap(comparator);
map.put("one", null);
map.put("two", null);
try {
new TreeMap(comparator).putAll(map);
} catch (RuntimeException e) {
test = false;
}
optimizedTreeMapPutAll = test;
SortedSet set = new PresortedSet(comparator);
set.addAll(map.keySet());
try {
new TreeSet(comparator).addAll(set);
test = true;
} catch (RuntimeException e) {
test = false;
}
optimizedTreeSetAddAll = test;
try {
new SimpleDateFormat("z").parse("UTC");
test = true;
} catch (ParseException e) {
test = false;
}
canParseUTCDateFormat = test;
}
/**
* Parses the java version system property to determine the major java version,
* i.e. 1.x
*
* @return A float of the form 1.x
*/
private static final float getMajorJavaVersion() {
try {
return isAndroid() ? 1.5f : Float.parseFloat(System.getProperty("java.specification.version"));
} catch ( NumberFormatException e ){
// Some JVMs may not conform to the x.y.z java.version format
return DEFAULT_JAVA_VERSION;
}
}
public static boolean is14() {
return majorJavaVersion >= 1.4f;
}
public static boolean is15() {
return majorJavaVersion >= 1.5f;
}
public static boolean is16() {
return majorJavaVersion >= 1.6f;
}
public static boolean is17() {
return majorJavaVersion >= 1.7f;
}
private static boolean isSun() {
return vendor.indexOf("Sun") != -1;
}
private static boolean isOracle() {
return vendor.indexOf("Oracle") != -1;
}
private static boolean isApple() {
return vendor.indexOf("Apple") != -1;
}
private static boolean isHPUX() {
return vendor.indexOf("Hewlett-Packard Company") != -1;
}
private static boolean isIBM() {
return vendor.indexOf("IBM") != -1;
}
private static boolean isBlackdown() {
return vendor.indexOf("Blackdown") != -1;
}
private static boolean isDiablo() {
return vendor.indexOf("FreeBSD Foundation") != -1;
}
private static boolean isHarmony() {
return vendor.indexOf("Apache Software Foundation") != -1;
}
private static boolean isAndroid() {
return vendor.indexOf("Android") != -1;
}
/*
* Support for sun.misc.Unsafe and sun.reflect.ReflectionFactory is present
* in JRockit versions R25.1.0 and later, both 1.4.2 and 5.0 (and in future
* 6.0 builds).
*/
private static boolean isBEAWithUnsafeSupport() {
// This property should be "BEA Systems, Inc."
if (vendor.indexOf("BEA") != -1) {
/*
* Recent 1.4.2 and 5.0 versions of JRockit have a java.vm.version
* string starting with the "R" JVM version number, i.e.
* "R26.2.0-38-57237-1.5.0_06-20060209..."
*/
String vmVersion = System.getProperty("java.vm.version");
if (vmVersion.startsWith("R")) {
/*
* We *could* also check that it's R26 or later, but that is
* implicitly true
*/
return true;
}
/*
* For older JRockit versions we can check java.vm.info. JRockit
* 1.4.2 R24 -> "Native Threads, GC strategy: parallel" and JRockit
* 5.0 R25 -> "R25.2.0-28".
*/
String vmInfo = System.getProperty("java.vm.info");
if (vmInfo != null) {
// R25.1 or R25.2 supports Unsafe, other versions do not
return (vmInfo.startsWith("R25.1") || vmInfo
.startsWith("R25.2"));
}
}
// If non-BEA, or possibly some very old JRockit version
return false;
}
private static boolean isHitachi() {
return vendor.indexOf("Hitachi") != -1;
}
private static boolean isSAP() {
return vendor.indexOf("SAP AG") != -1;
}
public Class loadClass(String name) {
try {
WeakReference reference = (WeakReference) loaderCache.get(name);
if (reference != null) {
Class cached = (Class) reference.get();
if (cached != null) {
return cached;
}
}
Class clazz = Class.forName(name, false, getClass().getClassLoader());
loaderCache.put(name, new WeakReference(clazz));
return clazz;
} catch (ClassNotFoundException e) {
return null;
}
}
public synchronized ReflectionProvider bestReflectionProvider() {
if (reflectionProvider == null) {
try {
String className = null;
if (canUseSun14ReflectionProvider()) {
className = "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider";
} else if (canUseHarmonyReflectionProvider()) {
className = "com.thoughtworks.xstream.converters.reflection.HarmonyReflectionProvider";
}
if (className != null) {
Class cls = loadClass(className);
if (cls != null) {
reflectionProvider = (ReflectionProvider) cls.newInstance();
}
}
if (reflectionProvider == null) {
reflectionProvider = new PureJavaReflectionProvider();
}
} catch (InstantiationException e) {
reflectionProvider = new PureJavaReflectionProvider();
} catch (IllegalAccessException e) {
reflectionProvider = new PureJavaReflectionProvider();
} catch (AccessControlException e) {
// thrown when trying to access sun.misc package in Applet context.
reflectionProvider = new PureJavaReflectionProvider();
}
}
return reflectionProvider;
}
private boolean canUseSun14ReflectionProvider() {
return (isSun()
|| isOracle()
|| isApple()
|| isHPUX()
|| isIBM()
|| isBlackdown()
|| isBEAWithUnsafeSupport()
|| isHitachi()
|| isSAP()
|| isDiablo())
&& is14()
&& loadClass("sun.misc.Unsafe") != null;
}
private boolean canUseHarmonyReflectionProvider() {
return isHarmony();
}
public static boolean reverseFieldDefinition() {
return reverseFieldOrder;
}
/**
* Checks if the jvm supports awt.
*/
public boolean supportsAWT() {
return this.supportsAWT;
}
/**
* Checks if the jvm supports swing.
*/
public boolean supportsSwing() {
return this.supportsSwing;
}
/**
* Checks if the jvm supports sql.
*/
public boolean supportsSQL() {
return this.supportsSQL;
}
/**
* Checks if TreeSet.addAll is optimized for SortedSet argument.
*
* @since upcoming
*/
public static boolean hasOptimizedTreeSetAddAll() {
return optimizedTreeSetAddAll;
}
/**
* Checks if TreeMap.putAll is optimized for SortedMap argument.
*
* @since upcoming
*/
public static boolean hasOptimizedTreeMapPutAll() {
return optimizedTreeMapPutAll;
}
public static boolean canParseUTCDateFormat() {
return canParseUTCDateFormat;
}
private Object readResolve() {
loaderCache = new HashMap();
return this;
}
public static void main(String[] args) {
boolean reverse = false;
Field[] fields = AttributedString.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName().equals("text")) {
reverse = i > 3;
break;
}
}
if (reverse) {
fields = JVM.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName().equals("reflectionProvider")) {
reverse = i > 2;
break;
}
}
}
JVM jvm = new JVM();
System.out.println("XStream JVM diagnostics");
System.out.println("java.specification.version: " + System.getProperty("java.specification.version"));
System.out.println("java.vm.vendor: " + vendor);
System.out.println("Version: " + majorJavaVersion);
System.out.println("XStream support for enhanced Mode: " + (jvm.canUseSun14ReflectionProvider() || jvm.canUseHarmonyReflectionProvider()));
System.out.println("Supports AWT: " + jvm.supportsAWT());
System.out.println("Supports Swing: " + jvm.supportsSwing());
System.out.println("Supports SQL: " + jvm.supportsSQL());
System.out.println("Optimized TreeSet.addAll: " + hasOptimizedTreeSetAddAll());
System.out.println("Optimized TreeMap.putAll: " + hasOptimizedTreeMapPutAll());
System.out.println("Can parse UTC date format: " + canParseUTCDateFormat());
System.out.println("Reverse field order detected (may have failed): " + reverse);
}
}
|
package torrent.download.peer;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import torrent.Logable;
import torrent.Manager;
import torrent.download.Torrent;
import torrent.download.files.disk.DiskJobSendBlock;
import torrent.network.ByteInputStream;
import torrent.network.ByteOutputStream;
import torrent.network.protocol.ISocket;
import torrent.network.protocol.TcpSocket;
import torrent.protocol.BitTorrent;
import torrent.protocol.IMessage;
import torrent.protocol.MessageUtils;
import torrent.protocol.messages.MessageKeepAlive;
import torrent.protocol.messages.extension.MessageExtension;
import torrent.protocol.messages.extension.MessageHandshake;
import torrent.util.ISortable;
import torrent.util.StringUtil;
public class Peer implements Logable, ISortable {
private byte[] RESERVED_EXTENTION_BYTES = new byte[8];
private InetAddress address;
private int port;
private Torrent torrent;
private ISocket socket;
private ByteOutputStream outStream;
private ByteInputStream inStream;
private boolean crashed;
/**
* Client information about the connected peer
*/
private Client peerClient;
/**
* Client information about me retrieved from the connected peer
*/
private Client myClient;
/**
* The current Threads status
*/
private String status;
/**
* The message queue
*/
private ArrayList<IMessage> messageQueue;
/**
* The last time this connection showed any form of activity<br/>
* <i>Values are System.currentMillis()</i>
*/
private long lastActivity;
private int downloadRate;
private int uploadRate;
private boolean passedHandshake;
private String clientName;
/**
* The count of messages which are still being processed by the IOManager
*/
private int pendingMessages;
/**
* The amount of errors the client made<br/>
* If the amount reaches 5 the client will be disconnected on the next peerCheck
*/
private int strikes;
public Peer() {
crashed = false;
peerClient = new Client();
myClient = new Client();
status = "";
clientName = "pending";
messageQueue = new ArrayList<>();
RESERVED_EXTENTION_BYTES[5] |= 0x10; // Extended Messages
lastActivity = System.currentTimeMillis();
passedHandshake = false;
}
public Peer(Torrent torrent) {
this();
this.torrent = torrent;
}
public void connect() {
setStatus("Connecting...");
if (socket != null) {
setStatus("Connected (Outside request)");
return;
}
socket = new TcpSocket();
while(socket != null && (socket.isClosed() || socket.isConnecting())) {
try {
socket.connect(new InetSocketAddress(address, port));
inStream = new ByteInputStream(this, socket.getInputStream());
outStream = new ByteOutputStream(socket.getOutputStream());
} catch (IOException e) {
if(socket.canFallback()) {
socket = socket.getFallbackSocket();
} else {
crashed = true;
socket = null;
}
}
}
}
/**
* Send all extension handshakes
*/
private void sendExtensionMessage() {
if (peerClient.supportsExtention(5, 0x10)) { // EXTENDED_MESSAGE
if (torrent.getDownloadStatus() == Torrent.STATE_DOWNLOAD_METADATA)
addToQueue(new MessageExtension(BitTorrent.EXTENDED_MESSAGE_HANDSHAKE, new MessageHandshake()));
else
addToQueue(new MessageExtension(BitTorrent.EXTENDED_MESSAGE_HANDSHAKE, new MessageHandshake(torrent.getFiles().getMetadataSize())));
}
}
/**
* Send have messages or bitfield
*/
private void sendHaveMessages() {
if (torrent.getDownloadStatus() == Torrent.STATE_DOWNLOAD_DATA) {
ArrayList<IMessage> messages = torrent.getFiles().getBitfield().getBitfieldMessage();
for (int i = 0; i < messages.size(); i++) {
addToQueue(messages.get(i));
}
}
}
public void setSocket(ISocket socket) {
this.socket = socket;
try {
inStream = new ByteInputStream(this, socket.getInputStream());
outStream = new ByteOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
log(e.getMessage(), true);
}
}
public void setSocketInformation(InetAddress address, int port) {
this.address = address;
this.port = port;
}
public void sendHandshake() throws IOException {
setStatus("Sending Handshake"); // Not making this more OO because it's not within the message-flow
outStream.writeByte(0x13);
outStream.writeString("BitTorrent protocol");
outStream.write(RESERVED_EXTENTION_BYTES);
outStream.write(torrent.getHashArray());
outStream.write(Manager.getPeerId());
outStream.flush();
setStatus("Awaiting Handshake response");
}
public void processHandshake() throws IOException {
status = "Verifying handshake";
int protocolLength = inStream.read();
if (protocolLength != 0x13) {
socket.close();
crashed = true;
return;
} else {
String protocol = inStream.readString(0x13);
if ("BitTorrent protocol".equals(protocol)) {
peerClient.setReservedBytes(inStream.readByteArray(8));
byte[] torrentHash = inStream.readByteArray(20);
if (torrent == null) {
Torrent torrent = Manager.getManager().getTorrent(StringUtil.byteArrayToString(torrentHash));
if (torrent == null) {
return;
}
this.torrent = torrent;
}
if (torrentHash != torrent.getHashArray()) {
inStream.readByteArray(20);
if (torrent.getDownloadStatus() == Torrent.STATE_DOWNLOAD_DATA)
peerClient.getBitfield().setBitfieldSize(torrent.getFiles().getBitfieldSize());
setStatus("Awaiting Orders");
passedHandshake = true;
} else {
socket.close();
crashed = true;
return;
}
} else {
crashed = true;
socket.close();
return;
}
}
sendExtensionMessage();
sendHaveMessages();
}
public boolean canReadMessage() throws IOException {
if (!passedHandshake) {
return inStream.available() >= 68;
}
return MessageUtils.getUtils().canReadMessage(inStream, this);
}
public void readMessage() throws IOException {
if (!passedHandshake) {
processHandshake();
return;
}
IMessage message = MessageUtils.getUtils().readMessage(inStream, this);
message.process(this);
lastActivity = System.currentTimeMillis();
}
public void sendMessage() throws IOException {
if (messageQueue.size() > 0) {
IMessage message = messageQueue.remove(0);
if (message == null)
return;
setStatus("Sending Message: " + message);
MessageUtils.getUtils().writeMessage(outStream, message);
setStatus("Sended Message: " + message);
} else {
if (peerClient.getQueueSize() > 0 && pendingMessages == 0) {
Job request = peerClient.getNextJob();
peerClient.removeJob(request);
addToPendingMessages(1);
torrent.addDiskJob(new DiskJobSendBlock(this, request.getPieceIndex(), request.getBlockIndex(), request.getLength()));
}
}
}
public void checkDisconnect() {
if (strikes >= 5) {
close();
return;
}
int inactiveSeconds = (int) ((System.currentTimeMillis() - lastActivity) / 1000);
if (inactiveSeconds > 30) {
if (myClient.getQueueSize() > 0) { // We are not receiving a single byte in the last 30(!) seconds
// Let's try (max twice) if we can wake'm up by sending them a keepalive
addStrike(2);
addToQueue(new MessageKeepAlive());
updateLastActivity();
return;
} else if (torrent.getDownloadStatus() == Torrent.STATE_DOWNLOAD_METADATA) {
updateLastActivity();
}
}
if (inactiveSeconds > 60) {
if(myClient.isInterested() && myClient.isChoked()) {
addStrike(2);
updateLastActivity();
}
}
if (inactiveSeconds > 90) {// 1.5 Minute, We are getting close to timeout D:
if (myClient.isInterested()) {
addToQueue(new MessageKeepAlive());
}
}
if (inactiveSeconds > 180) {// 3 Minutes, We've hit the timeout mark
close();
}
}
/**
* Add a value to the pending Messages count
*
* @param i The count to add
*/
public synchronized void addToPendingMessages(int i) {
pendingMessages += i;
}
/**
* Checks if the connection is/should be closed
*
* @return If the connection should be/is closed
*/
public boolean closed() {
if (crashed)
return true;
if (socket == null)
return false;
return socket.isClosed();
}
/**
* Get this peer's socket
* @return The socket of this peer
*/
public ISocket getSocket() {
return socket;
}
@Override
public String toString() {
if (socket != null) {
return socket.toString();
} else {
return "UNCONNECTED";
}
}
@Override
public void log(String s, boolean error) {
s = "[" + toString() + "] " + s;
if (error)
System.err.println(s);
else
System.out.println(s);
}
@Override
public void log(String s) {
log(s, false);
}
public void setStatus(String s) {
status = s;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientName() {
return clientName;
}
@Override
public String getStatus() {
return status;
}
public void updateLastActivity() {
lastActivity = System.currentTimeMillis();
}
/**
* Gets the amount of messages waiting to be send
*
* @return
*/
public boolean isWorking() {
return getWorkQueueSize() > 0;
}
public int getFreeWorkTime() {
return (getWorkQueueSize() >= myClient.getMaxRequests()) ? 0 : myClient.getMaxRequests() - getWorkQueueSize();
}
public int getWorkQueueSize() {
return myClient.getQueueSize();
}
public int getMaxWorkLoad() {
return myClient.getMaxRequests();
}
public void addToQueue(IMessage m) {
messageQueue.add(m);
}
public Client getClient() {
return peerClient;
}
public Client getMyClient() {
return myClient;
}
public void pollRates() {
if (inStream != null) {
downloadRate = inStream.getSpeed();
inStream.reset(downloadRate);
}
if (outStream != null) {
uploadRate = outStream.getSpeed();
outStream.reset(uploadRate);
}
}
public int getDownloadRate() {
return downloadRate;
}
public int getUploadRate() {
return uploadRate;
}
/**
* Cancels all pieces
*/
public void cancelAllPieces() {
synchronized (this) {
if (getWorkQueueSize() > 0) {
Object[] keys = myClient.getKeySet().toArray();
for (int i = 0; i < keys.length; i++) {
Job job = (Job) keys[i];
torrent.getFiles().getPiece(job.getPieceIndex()).reset(job.getBlockIndex());
}
myClient.clearJobs();
}
}
}
public void forceClose() {
crashed = true;
}
/**
* Gracefully close the connection with this peer
*/
public void close() {
try {
if (socket != null) {
if (!socket.isClosed()) {
socket.close();
}
}
} catch (IOException e) {
e.printStackTrace();
forceClose();
}
}
public boolean getPassedHandshake() {
return passedHandshake;
}
public long getLastActivity() {
return lastActivity;
}
public Torrent getTorrent() {
return torrent;
}
@Override
public int getValue() {
return (getWorkQueueSize() * 5000) + peerClient.getBitfield().hasPieceCount() + downloadRate;
}
/**
* Adds an amount of strikes to the peer
*
* @param i
*/
public synchronized void addStrike(int i) {
if (strikes + i < 0) {
strikes = 0;
} else {
strikes += i;
}
}
@Override
public boolean equals(Object o) {
if(o instanceof Peer) {
Peer p = (Peer)o;
return (p.toString().equals(toString()));
} else {
return false;
}
}
}
|
package mathsquared.resultswizard2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* @author MathSquared
*
*/
public class FractionTest {
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#Fraction(int)}.
*/
@Test
public void testFractionInt () {
Fraction four = new Fraction(4);
assertEquals("Not stupid", four, new Fraction(4, 1));
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#Fraction(int, int)}.
*/
@Test
public void testFractionIntInt () {
Fraction twoFourths = new Fraction(2, 4);
assertTrue("Canonical: Simplification", twoFourths.getUnit() == 0 && twoFourths.getNumerator() == 1 && twoFourths.getDenominator() == 2);
Fraction zero = new Fraction(0, 3);
assertTrue("Canonical: 0/n", zero.getUnit() == 0 && zero.getNumerator() == 0 && zero.getDenominator() == 1);
Fraction sevenFifths = new Fraction(7, 5);
assertTrue("Canonical: Unit calculation", sevenFifths.getUnit() == 1 && sevenFifths.getNumerator() == 2 && sevenFifths.getDenominator() == 5);
Fraction twoNegativeThirds = new Fraction(2, -3);
assertTrue("Canonical: Negative numerator", twoNegativeThirds.getUnit() == 0 && twoNegativeThirds.getNumerator() == -2 && twoNegativeThirds.getDenominator() == 3);
Fraction negativeEightSixths = new Fraction(-8, 6);
assertTrue("Canonical: Evil simplification", negativeEightSixths.getUnit() == -1 && negativeEightSixths.getNumerator() == -1 && negativeEightSixths.getDenominator() == 3);
Fraction negativeThreeNegativeSevenths = new Fraction(-3, -7);
assertTrue("Canonical: Double negative", negativeThreeNegativeSevenths.getUnit() == 0 && negativeThreeNegativeSevenths.getNumerator() == 3 && negativeThreeNegativeSevenths.getDenominator() == 7);
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#getUnit()}, {@link mathsquared.resultswizard2.Fraction#extractUnit()}, and {@link mathsquared.resultswizard2.Fraction#isUnitValid()}.
*/
@Test
public void testExtractUnit () {
Fraction sevenThirds = new Fraction(7, 3);
int unit = sevenThirds.getUnit();
assertTrue("Correctness", sevenThirds.getUnit() == 7 / 3);
Fraction sevenNegativeThirds = new Fraction(7, -3);
assertTrue("Negativity", sevenNegativeThirds.getUnit() == 7 / -3);
assertTrue("Correctly flagged", sevenThirds.isUnitValid());
int extract = sevenThirds.extractUnit();
assertTrue("Extracted is same", unit == extract);
assertFalse("Invalidation", sevenThirds.isUnitValid());
assertTrue("Zeroing", sevenThirds.getUnit() == 0);
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#getImproperNumerator()}.
*/
@Test
public void testGetImproperNumerator () {
assertTrue("Basic", new Fraction(3, 2).getImproperNumerator() == 3);
assertTrue("Zero", new Fraction(0).getImproperNumerator() == 0);
assertTrue("Negative", new Fraction(4, -3).getImproperNumerator() == -4);
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#negative()}.
*/
@Test
public void testNegative () {
assertTrue("Proper", new Fraction(2, 3).negative().equals(new Fraction(-2, 3)));
assertTrue("Improper", new Fraction(5, 4).negative().equals(new Fraction(-5, 4)));
assertTrue("Zero", new Fraction(0).negative().equals(new Fraction(0)));
assertTrue("Perfect unit", new Fraction(3).negative().equals(new Fraction(-3)));
assertTrue("Already negative improper", new Fraction(-10, 7).negative().equals(new Fraction(10, 7)));
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#multiply(int)}.
*/
@Test
public void testMultiplyInt () {
assertTrue("Proper to proper", new Fraction(1, 3).multiply(2).equals(new Fraction(2, 3)));
assertTrue("Proper to improper", new Fraction(2, 7).multiply(5).equals(new Fraction(10, 7)));
assertTrue("Improper to improper", new Fraction(7, 4).multiply(3).equals(new Fraction(21, 4)));
assertTrue("Perfect unit", new Fraction(7).multiply(2).equals(new Fraction(14)));
assertTrue("Zero multiplier", new Fraction(4, 5).multiply(0).equals(new Fraction(0)));
assertTrue("Negative multiplicand", new Fraction(-3, 5).multiply(3).equals(new Fraction(-9, 5)));
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#multiply(mathsquared.resultswizard2.Fraction)}.
*/
@Test
public void testMultiplyFraction () {
assertTrue("Proper to proper", new Fraction(1, 3).multiply(new Fraction(2, 5)).equals(new Fraction(2, 15)));
assertTrue("Proper times improper", new Fraction(2, 3).multiply(new Fraction(4, 3)).equals(new Fraction(8, 9)));
assertTrue("Improper times proper", new Fraction(4, 3).multiply(new Fraction(2, 3)).equals(new Fraction(8, 9)));
assertTrue("Perfect unit times proper", new Fraction(6).multiply(new Fraction(2, 5)).equals(new Fraction(12, 5)));
assertTrue("Negative handling", new Fraction(-4, 3).multiply(new Fraction(2, -5)).equals(new Fraction(8, 15)));
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#divide(int)}.
*/
@Test(expected = ArithmeticException.class)
public void testDivideInt () {
assertTrue("Proper to proper", new Fraction(4, 5).divide(3).equals(new Fraction(4, 15)));
assertTrue("Improper to proper", new Fraction(7, 3).divide(8).equals(new Fraction(7, 24)));
assertTrue("Improper to improper", new Fraction(15, 7).divide(2).equals(new Fraction(15, 14)));
assertTrue("Perfect unit and simplification", new Fraction(16).divide(4).equals(new Fraction(4)));
assertTrue("Zero multiplier", new Fraction(0).divide(57).equals(0));
assertTrue("Negative over negative", new Fraction(-3, 5).divide(-2).equals(new Fraction(3, 10)));
// exception
new Fraction(4, 7).divide(0);
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#divide(mathsquared.resultswizard2.Fraction)}.
*/
@Test(expected = ArithmeticException.class)
public void testDivideFraction () {
assertTrue("Proper over proper", new Fraction(3, 4).divide(new Fraction(2, 5)).equals(new Fraction(15, 8)));
assertTrue("Proper over improper and simp.", new Fraction(4, 7).divide(new Fraction(6, 5)).equals(new Fraction(10, 21)));
assertTrue("Improper over proper", new Fraction(8, 5).divide(new Fraction(3, 4)).equals(new Fraction(32, 15)));
assertTrue("Two perfect units", new Fraction(5).divide(new Fraction(2)).equals(new Fraction(5, 2)));
assertTrue("Negative handling", new Fraction(9, -5).divide(new Fraction(-7, 4)).equals(new Fraction(36, 35)));
// exception
new Fraction(8, 5).divide(new Fraction(0, 17));
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#pow(int)}.
*/
@Test
public void testPow () {
Fraction negativeTwoThirds = new Fraction(-2, 3);
Fraction fourNinths = new Fraction(4, 9);
Fraction negativeEightTwentySevenths = new Fraction(-8, 27);
Fraction negativeThreeHalves = new Fraction(-3, 2);
Fraction nineFourths = new Fraction(9, 4);
assertEquals("^2", negativeTwoThirds.pow(2), fourNinths);
assertEquals("^3", negativeTwoThirds.pow(3), negativeEightTwentySevenths);
assertEquals("^-1", negativeTwoThirds.pow(-1), negativeThreeHalves);
assertEquals("^-2", negativeTwoThirds.pow(-2), nineFourths);
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#reciprocal()}.
*/
@Test(expected = ArithmeticException.class)
public void testReciprocal () {
Fraction threeFourths = new Fraction(3, 4);
assertEquals("3/4", threeFourths.reciprocal(), new Fraction(4, 3));
Fraction zero = new Fraction(0);
zero.reciprocal(); // throws ArithmeticException
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#add(int)}. Negative arguments to <code>add(int)</code> are tested in {@link #testSubtractInt()}.
*/
@Test
public void testAddInt () {
assertTrue("Proper", new Fraction(2, 3).add(1).equals(new Fraction(5, 3)));
assertTrue("Improper", new Fraction(7, 5).add(3).equals(new Fraction(7 + 15, 5)));
assertTrue("Perfect unit", new Fraction(3).add(1).equals(4));
assertTrue("Proper neg+pos", new Fraction(-3, 4).add(1).equals(new Fraction(1, 4)));
assertTrue("Improper neg+pos->neg", new Fraction(-9, 4).add(1).equals(new Fraction(-5, 4)));
assertTrue("Improper neg+pos->pos", new Fraction(-5, 3).add(3).equals(new Fraction(4, 3)));
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#add(mathsquared.resultswizard2.Fraction)} and {@link mathsquared.resultswizard2.Fraction#subtract(mathsquared.resultswizard2.Fraction)}.
*/
@Test
public void testAddFraction () {
/*
* To make log output more concise, these tests are signaled by a scheme of unique codes.
*
* Legend of codes used in the tests:
*
* Three-letter codes represent descriptors for the addend, augend, and sum (if ambiguous).
*
* First: proper/improper: P = proper, I = improper
*
* Second: simplification: B = same denominator, S1 = one denominator is a factor of another, RP = both denominators are relatively prime [TODO add cases where both fractions need unsimplification, but are not relatively prime]
*
* Third: sign: + = positive, - = negative
*/
assertEquals("PPP, B, ++", new Fraction(1, 5).add(new Fraction(2, 5)), new Fraction(3, 5));
assertEquals("PPP, S1, ++", new Fraction(1, 4).add(new Fraction(1, 2)), new Fraction(3, 4));
assertEquals("PPP, S2, ++", new Fraction(3, 4).add(new Fraction(1, 6)), new Fraction(22, 24));
assertEquals("PPP, RP, ++", new Fraction(2, 5).add(new Fraction(3, 7)), new Fraction(2 * 7 + 3 * 5, 5 * 7));
assertEquals("PPI, B, ++", new Fraction(5, 7).add(new Fraction(3, 7)), new Fraction(8, 7));
assertEquals("PPI, S2, ++", new Fraction(3, 10).add(new Fraction(7, 15)), new Fraction(10 * 7 + 3 * 15, 150));
assertEquals("PPI, RP, ++", new Fraction(4, 5).add(new Fraction(3, 7)), new Fraction(4 * 7 + 5 * 3, 5 * 7));
assertEquals("IP, B, ++", new Fraction(6, 5).add(new Fraction(2, 5)), new Fraction(8, 5));
assertEquals("PI, B, ++", new Fraction(2, 5).add(new Fraction(6, 5)), new Fraction(8, 5));
assertEquals("IP, RP, ++", new Fraction(7, 3).add(new Fraction(4, 5)), new Fraction(7 * 5 + 3 * 4, 3 * 5));
assertEquals("II, B, ++", new Fraction(6, 5).add(new Fraction(7, 5)), new Fraction(13, 5));
assertEquals("II, RP, ++", new Fraction(7, 3).add(new Fraction(9, 4)), new Fraction(7 * 4 + 9 * 3, 3 * 4));
// Test neg+neg for differences from pos+pos (existing tests)
assertEquals("PPP, RP, --", new Fraction(-2, 5).add(new Fraction(-3, 7)), new Fraction(2 * 7 + 3 * 5, -5 * 7));
assertEquals("PPI, RP, --", new Fraction(-4, 5).add(new Fraction(-3, 7)), new Fraction(4 * 7 + 5 * 3, -5 * 7));
assertEquals("IP, RP, --", new Fraction(-7, 3).add(new Fraction(-4, 5)), new Fraction(7 * 5 + 3 * 4, -3 * 5));
assertEquals("II, RP, --", new Fraction(-7, 3).add(new Fraction(-9, 4)), new Fraction(7 * 4 + 9 * 3, -3 * 4));
// All right, time's up, let's do this. (mismatched signs PPP)
assertEquals("PPP, B, +-+", new Fraction(4, 7).add(new Fraction(-3, 7)), new Fraction(1, 7));
assertEquals("PPP, S2, +-+", new Fraction(5, 6).add(new Fraction(-2, 9)), new Fraction(33, 54));
assertEquals("PPP, RP, +-+", new Fraction(6, 7).add(new Fraction(-2, 3)), new Fraction(4, 21));
assertEquals("PPP, RP, -++", new Fraction(-2, 3).add(new Fraction(6, 7)), new Fraction(4, 21));
assertEquals("PPP, B, +--", new Fraction(1, 7).add(new Fraction(-4, 7)), new Fraction(-3, 7));
assertEquals("PPP, RP, +--", new Fraction(2, 5).add(new Fraction(-5, 6)), new Fraction(-13, 30));
assertEquals("PPP, RP, -+-", new Fraction(-5, 6).add(new Fraction(2, 5)), new Fraction(-13, 30));
// LEEROY JENKINS! (mismatched signs IP)
assertEquals("IPI, B, +-+", new Fraction(13, 5).add(new Fraction(-2, 5)), new Fraction(11, 5));
assertEquals("IPI, S2, +-+", new Fraction(37, 21).add(new Fraction(-9, 14)), new Fraction(37 * 14 - 21 * 9, 21 * 14));
assertEquals("IPI, RP, +-+", new Fraction(17, 8).add(new Fraction(-5, 6)), new Fraction(62, 48));
assertEquals("IPP, B, +-+", new Fraction(23, 7).add(new Fraction(-19, 7)), new Fraction(4, 7));
assertEquals("IPP, RP, +-+", new Fraction(8, 7).add(new Fraction(-1, 4)), new Fraction(25, 28));
// Existing IP +-+ tests with args swapped around
assertEquals("PII, RP, -++", new Fraction(-5, 6).add(new Fraction(17, 8)), new Fraction(62, 48));
assertEquals("PIP, RP, -++", new Fraction(-1, 4).add(new Fraction(8, 7)), new Fraction(25, 28));
// Existing IP +-+ and PI -++ tests with negation applied
assertEquals("IPI, RP, -+-", new Fraction(-17, 8).add(new Fraction(5, 6)), new Fraction(-62, 48));
assertEquals("IPP, RP, -+-", new Fraction(-8, 7).add(new Fraction(1, 4)), new Fraction(-25, 28));
assertEquals("PII, RP, +--", new Fraction(5, 6).add(new Fraction(-17, 8)), new Fraction(-62, 48));
assertEquals("PIP, RP, +--", new Fraction(1, 4).add(new Fraction(-8, 7)), new Fraction(-25, 28));
// ...at least I got chicken. (mismatched signs II; letting up on RP tests because I've probably stressed that logic enough)
assertEquals("III, B, +-+", new Fraction(25, 3).add(new Fraction(-17, 3)), new Fraction(8, 3));
assertEquals("III, RP, +-+", new Fraction(10, 3).add(new Fraction(-3, 2)), new Fraction(11, 6));
assertEquals("IIP, B, +-+", new Fraction(16, 5).add(new Fraction(-13, 5)), new Fraction(3, 5));
assertEquals("IIP, B, +--", new Fraction(13, 7).add(new Fraction(-17, 7)), new Fraction(-4, 7));
assertEquals("IIP, RP, +--", new Fraction(7, 3).add(new Fraction(-20, 7)), new Fraction(-11, 21));
assertEquals("III, B, +--", new Fraction(28, 9).add(new Fraction(-41, 9)), new Fraction(-13, 9));
// Selected existing II +- tests with args swapped
assertEquals("III, B, -++", new Fraction(-17, 3).add(new Fraction(25, 3)), new Fraction(8, 3));
assertEquals("III, RP, -++", new Fraction(-3, 2).add(new Fraction(10, 3)), new Fraction(11, 6));
assertEquals("IIP, B, -++", new Fraction(-13, 5).add(new Fraction(16, 5)), new Fraction(3, 5));
assertEquals("IIP, B, -+-", new Fraction(-17, 7).add(new Fraction(13, 7)), new Fraction(-4, 7));
assertEquals("IIP, RP, -+-", new Fraction(-20, 7).add(new Fraction(7, 3)), new Fraction(-11, 21));
assertEquals("III, B, -+-", new Fraction(-41, 9).add(new Fraction(28, 9)), new Fraction(-13, 9));
// These also have the effect of mimicking negation applied (compare the codes)
// SPECIAL CASES
// Perfect units
assertEquals("Perfect units, ++", new Fraction(4).add(new Fraction(3)), new Fraction(7));
assertEquals("Perfect units, +-+", new Fraction(5).add(new Fraction(-2)), new Fraction(3));
assertEquals("Perfect units, -++", new Fraction(-5).add(new Fraction(8)), new Fraction(3));
assertEquals("Perfect units, +--", new Fraction(3).add(new Fraction(-4)), new Fraction(-1));
assertEquals("Perfect units, -+-", new Fraction(-6).add(new Fraction(2)), new Fraction(-4));
assertEquals("Perfect units, --", new Fraction(-2).add(new Fraction(-6)), new Fraction(-8));
// Identity
assertEquals("+0", new Fraction(7, 5).add(new Fraction(0)), new Fraction(7, 5));
assertEquals("0+", new Fraction(0).add(new Fraction(8, 3)), new Fraction(8, 3));
assertEquals("-0", new Fraction(-6, 5).add(new Fraction(0)), new Fraction(-6, 5));
assertEquals("0-", new Fraction(0).add(new Fraction(-11, 4)), new Fraction(-11, 4));
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#subtract(int)}. Negative arguments to <code>subtract(int)</code> are tested in {@link #testAddInt()}.
*/
@Test
public void testSubtractInt () {
assertTrue("Proper neg+neg", new Fraction(-1, 4).subtract(3).equals(new Fraction(-13, 4)));
assertTrue("Improper neg+neg", new Fraction(-8, 5).subtract(1).equals(new Fraction(-13, 5)));
assertTrue("Perfect unit neg", new Fraction(-4).subtract(2).equals(new Fraction(-6)));
assertTrue("Proper pos+neg", new Fraction(5, 7).subtract(2).equals(new Fraction(-9, 7)));
assertTrue("Improper pos+neg->pos", new Fraction(13, 6).subtract(1).equals(new Fraction(7, 6)));
assertTrue("Improper pos+neg->neg", new Fraction(10, 7).subtract(4).equals(new Fraction(-18, 7)));
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#toDouble()}.
*/
@Test
public void testToDouble () {
Fraction half = new Fraction(1, 2);
assertTrue("1/2", half.toDouble() == 1.0 / 2);
Fraction fiveThirds = new Fraction(5, 3);
assertTrue("5/3", fiveThirds.toDouble() == 5.0 / 3);
}
/**
* Test method for {@link mathsquared.resultswizard2.Fraction#equals(java.lang.Object)}.
*/
@Test
public void testEqualsObject () {
Fraction f1 = new Fraction(2, 4);
Fraction f2 = new Fraction(1, 2);
assertEquals("Simplification", f1, f2);
Fraction f3 = new Fraction(3);
Fraction f4 = new Fraction(3, 1);
assertEquals("Different constructors", f3, f4);
Fraction f5 = new Fraction(7, 5);
Fraction f6 = new Fraction(7, 5);
Fraction f7 = new Fraction(14, 10);
assertEquals("Improper", f5, f6);
assertEquals("Improper uncanonical", f5, f7);
assertEquals("Double", f2, 1.0 / 2);
assertEquals("Int", f3, 3);
}
}
|
import java.awt.*;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
public class UTTT{
public static final int WIDTH = 800;
public static final int HEIGHT = 900;
public static final String TITLE = "Ultamite Tic Tac Toe!";
public static Box newBoxes[][][][] = new Box[3][3][3][3];
public static Box boxes[][][][] = new Box[3][3][3][3];
public static Box big_boxes[][] = new Box[3][3];
//Variables used for drawing
public static List<Line2D> drawLines = new ArrayList<Line2D>();
public static Box hoverBox;
public static List<Box> availableToPlay = new ArrayList<Box>();
public static List<Ellipse2D> o_moves = new ArrayList<Ellipse2D>();
public static List<Ellipse2D> big_o_moves = new ArrayList<Ellipse2D>();
public static List<Line2D> x_moves = new ArrayList<Line2D>();
public static List<Line2D> big_x_moves = new ArrayList<Line2D>();
public static Boolean off_on = true;
public static String message = "Welcome to UTTT";
public static void main(String[] args){
initilizeLines();
setupJFrame();
}
class Box {
private int x, y, height, width, big_row, big_col, little_row, little_col;
private Color color;
Box(int x, int y, int width, int height, int big_row, int big_col, int little_row, int little_col) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.big_row = big_row;
this.big_col = big_col;
this.little_row = little_row;
this.little_col = little_col;
//System.out.println("("+x+", "+y+", "+(x+width)+", "+(y+height)+")");
}
// Screw setters. Getters are what it's all about
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getHeight(){
return height;
}
public int getWidth(){
return width;
}
public int getBigRow(){
return big_row;
}
public int getBigCol(){
return big_col;
}
public int getLittleRow(){
return little_row;
}
public int getLittleCol(){
return little_col;
}
public Color getColor(){
return color;
}
// Ok, technically this is a setter, but it isn't called setColor, so it doesn't count
public void changeColor(Color new_color){
//Add this box to the drawHoverBoxes list
color = new_color;
}
}
public static Box findBox(int x, int y) { //We use this process quite a bit, so it makes sense to make it a function
Boolean found = false;
for (int i = 0; i<3; i++){
for (int j = 0; j<3; j++){
for (int k = 0; k<3; k++){
for (int l = 0;l<3; l++){
double top = boxes[i][j][k][l].getY();
double bottom = top + boxes[i][j][k][l].getHeight();
double left = boxes[i][j][k][l].getX();
double right = left + boxes[i][j][k][l].getWidth();
//System.out.println(i+":"+j+" (" + (int) left + ", "+(int) top+", "+(int) right+", "+(int) bottom+")");
if (y > top && y < bottom && x > left && x < right) {
//System.out.println("Correct Location: " + (i+1) + ","+(j+1) + ","+(k+1)+","+(l+1));
found = true;
return boxes[i][j][k][l];
}
}
}
}
}
return null;
}
/* Find what box we're pointing at. If it's not a box, it returns null
** If we're still pointing at the same box, there's no need to repaint the screen,
** so only repaint if the old_box is different from the new box.
*/
public static void highlightBox(int x, int y, Color new_color, Container cp) {
Box old_box = hoverBox;
hoverBox = findBox(x,y);
if (old_box != hoverBox) {
if (hoverBox != null) {
hoverBox.changeColor(new_color);
//System.out.println(hoverBox.getBigRow()+", " + hoverBox.getBigCol()+ "| " + hoverBox.getLittleRow()+ ", "+ hoverBox.getLittleCol());
//if (hoverBox.getBigRow() != 2 || hoverBox.getBigCol() != 2) { //Demoing out how we can restrict them to play in the correct spot on the board
// hoverBox = null;
}
cp.repaint();
}
}
public static void selectBox(int x, int y, Color new_color, Container cp) {
Box temp = findBox(x,y);
if (temp != null) {
if (off_on) {
//o_moves.add(new Ellipse2D.Double(temp.getX()+5, temp.getY()+5, temp.getWidth()-10, temp.getHeight()-10));
temp = big_boxes[temp.getBigRow()-1][temp.getBigCol()-1];
big_x_moves.add(new Line2D.Float(temp.getX()+5, temp.getY()+5, temp.getX()+temp.getWidth()-5, temp.getY()+temp.getHeight()-5));
big_x_moves.add(new Line2D.Float(temp.getX()+5, temp.getY()+temp.getHeight()-5, temp.getX()+temp.getWidth()-5, temp.getY()+5));
message = "X's TURN";
} else {
/*x_moves.add(new Line2D.Float(temp.getX()+5, temp.getY()+5, temp.getX()+temp.getWidth()-5, temp.getY()+temp.getHeight()-5));
x_moves.add(new Line2D.Float(temp.getX()+5, temp.getY()+temp.getHeight()-5, temp.getX()+temp.getWidth()-5, temp.getY()+5));*/
temp = big_boxes[temp.getBigRow()-1][temp.getBigCol()-1];
big_o_moves.add(new Ellipse2D.Double(temp.getX()+5, temp.getY()+5, temp.getWidth()-10, temp.getHeight()-10));
message = "O's TURN";
}
off_on = !off_on;
cp.repaint();
}
}
/*Sends box position to the server
* Returns string for server to receive
*/
public static String sendBoxPosition(int x, int y) {
Box temp = findBox(x,y);
if (temp != null) { //if temp is not null, then display the position of the mouse
return (temp.getBigRow()+", " + temp.getBigCol()+ "| " + temp.getLittleRow()+ ", "+ temp.getLittleCol());
} else { //otherwise return nothing (empty string)
return "";
}
}
public static void initilizeLines(){
UTTT uttt = new UTTT();
// everything is based off of these start and offset points,
// which makes it easy to move everything if we want to
int x_start = 45;
int y_start = 145;
int y_offset = 230;
int x_offset = 230;
drawLines.add(new Line2D.Float(x_start+223, y_start+5, x_start+223, y_start+670));
drawLines.add(new Line2D.Float(x_start+453, y_start+5, x_start+453, y_start+670));
drawLines.add(new Line2D.Float(x_start+5, y_start+223, x_start+670, y_start+223));
drawLines.add(new Line2D.Float(x_start+5, y_start+453, x_start+670, y_start+453));
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
drawLines.add(new Line2D.Float(x_start+79+(j*x_offset), y_start+28+(i*y_offset), x_start+79+(j*x_offset), y_start+186+(i*y_offset)));
drawLines.add(new Line2D.Float(x_start+134+(j*x_offset), y_start+28+(i*y_offset), x_start+134+(j*x_offset), y_start+186+(i*y_offset)));
drawLines.add(new Line2D.Float(x_start+28+(j*x_offset), y_start+80+(i*y_offset), x_start+186+(j*x_offset), y_start+80+(i*y_offset)));
drawLines.add(new Line2D.Float(x_start+28+(j*x_offset), y_start+135+(i*y_offset), x_start+186+(j*x_offset), y_start+135+(i*y_offset)));
}
}
//uttt.new MoveSymbol(90,90,120,30, 120, 60, 90,180);
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
for (int k=0;k<3;k++){
for (int l=0;l<3;l++){
boxes[i][j][k][l] = uttt.new Box((x_start+27+(55*l + j*x_offset)), (y_start+27+(55*k + i*y_offset)), 50, 50, i+1, j+1, k+1, l+1);
}
}
big_boxes[i][j] = uttt.new Box(x_start+(j*x_offset),y_start+(i*y_offset),215,215, i+1, j+1, 0, 0);
}
}
}
public static void setupJFrame() {
// Now the fun part
JFrame jf = new JFrame(TITLE);
Container cp = jf.getContentPane();
cp.add(new JComponent() { //Our lovely component that does all the work
public void paintComponent(Graphics g) {
/*Basically, we have 1 paint statement, and it draws things that are
** in the lists. This way, when we want to draw something new to the screen
** we just add it to its appropriate list, and then repaint */
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (int i=0;i<availableToPlay.size();i++){
Box temp = availableToPlay.get(i);
g.setColor(temp.getColor());
g2.fillRect(temp.getX(), temp.getY(), temp.getWidth(), temp.getHeight());
}
/*g.setColor(new_color);
g2.fillRect(x, y, width, height);*/
if (hoverBox != null) {
g.setColor(hoverBox.getColor());
g2.fillRect(hoverBox.getX(), hoverBox.getY(), hoverBox.getWidth(), hoverBox.getHeight());
}
g2.setStroke(new BasicStroke(10));
g.setColor(new Color(75,75,75));
for (int i=0;i<drawLines.size();i++){
if (i == 4) {
g2.setStroke(new BasicStroke(2));
}
g2.draw(drawLines.get(i));
}
g2.setStroke(new BasicStroke(5));
g.setColor(new Color(0,0,0));
for (int i=0;i<o_moves.size();i++){
g2.draw(o_moves.get(i));
}
for (int i=0;i<x_moves.size();i++){
g2.draw(x_moves.get(i));
}
g2.setStroke(new BasicStroke(8));
g.setColor(new Color(0,0,0));
for (int i=0;i<big_o_moves.size();i++){
g2.draw(big_o_moves.get(i));
}
for (int i=0;i<big_x_moves.size();i++){
g2.draw(big_x_moves.get(i));
}
g.setColor(new Color(185,75,255));
Font font = new Font("Serif", Font.PLAIN, 96);
g2.setFont(font);
g2.drawString(message, 300 -(message.length() *18) ,100);
}
});
// Now we add MouseListeners to that component
cp.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
//Display mouse click position and "send" to server
//System.out.println(sendBoxPosition(e.getX(), e.getY()));
//changes box color to blue
/* Hard coding for mouse clicks
int x_start = 45;
int y_start = 45;
int y_offset = 230;
int x_offset = 230;
//create variables for big box and small box sizes
int x = (e.getX() - x_start) / x_offset;
int y = (e.getY() - y_start) / y_offset;
int mx = e.getX() - x * x_offset - x_start;
int my = e.getY() - y * y_offset - y_start;
int little_x = (mx - 27) / 55;
int little_y = (my - 27) / 55;
//display exact location of mouse click within big box and little box
System.out.println("Mouse click location: " + (y+1) + ","+ (x+1) + "," + (little_y+1) + "," + (little_x+1));
*/
}
//Unused methods, but still need to override them
@Override
public void mouseEntered(MouseEvent e) { }
@Override
public void mouseExited(MouseEvent e) { }
@Override
public void mouseReleased(MouseEvent e) { }
@Override
public void mousePressed(MouseEvent e) {
selectBox(e.getX(), e.getY(), new Color(0,0,255), cp);
}
});
cp.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
highlightBox(e.getX(), e.getY(), new Color(255,0,0), cp);
}
@Override
public void mouseDragged(MouseEvent e) { }
});
jf.setSize(WIDTH, HEIGHT);
jf.setVisible(true);
}
}
|
class Word implements Comparable<Word>
{
private String word;
private String backwards;
private int length;
// Constructor
public Word(String word)
{
this.word = word;
backwards = reverse(word);
length = word.length();
}
// Necessary for sorting by length:
public int compareTo(Word w)
{
if (w.getLength() > length)
return -1;
if (w.getLength() < length)
return 1;
return 0;
}
public boolean isPalindrome()
{
if (length == 0 || length == 1)
return true;
if (word.charAt(0) != word.charAt(length - 1))
return false;
return (new Word(word.substring(1, length - 1)).isPalindrome());
}
public String reverse(String string)
{
StringBuilder sb = new StringBuilder(string);
return sb.reverse().toString();
}
// Assessors
public String getWord() {return word;}
public String getBackwards() {return backwards;}
public int getLength() {return length;}
}
|
// MT.java
package ed.db.migrate;
import java.sql.*;
import ed.db.*;
import ed.js.*;
public class MT {
static {
Drivers.init();
}
public static void migrate( Connection conn , DBBase db )
throws Exception {
DBCollection coll = db.getCollection( "posts" );
Statement stmt = conn.createStatement();
ResultSet res = stmt.executeQuery( "SELECT * FROM mt_entry , mt_author WHERE entry_author_id = author_id ORDER BY entry_id DESC " );
Statement commentsStmt = conn.createStatement();
ResultSet comments = commentsStmt.executeQuery( "SELECT * FROM mt_comment WHERE comment_visible = 1 ORDER BY comment_entry_id DESC" );
comments.next();
boolean moreComments = true;
while ( res.next() ){
System.out.println( res.getString("entry_title" ) );
JSObject o = new JSObjectBase();
JSDate d = new JSDate( res.getTimestamp( "entry_authored_on" ).getTime() );
o.set( "name" , d.getYear() + "/" + d.getMonth() + "/" + res.getString("entry_basename") );
o.set( "title" , res.getString("entry_title") );
o.set( "content" , res.getString( "entry_text" ) + "\n\n
o.set( "author" , res.getString( "author_name" ) );
o.set( "ts" , d );
o.set( "live" , res.getInt( "entry_status" ) == 2 );
while ( moreComments && comments.getInt( "comment_entry_id" ) > res.getInt( "entry_id" ) ){
if ( ! comments.next() )
moreComments = false;
}
JSArray ca = null;
while ( moreComments && comments.getInt( "comment_entry_id" ) == res.getInt( "entry_id" ) ){
System.out.println( "\t found a comment" );
if ( ca == null ){
ca = new JSArray();
o.set( "comments" , ca );
}
JSObject c = new JSObjectBase();
c.set( "author" , comments.getString( "comment_author" ) );
c.set( "email" , comments.getString( "comment_email" ) );
c.set( "ip" , comments.getString( "comment_ip" ) );
c.set( "text" , comments.getString( "comment_text" ) );
c.set( "ts" , new JSDate( comments.getTimestamp( "comment_created_on" ).getTime() ) );
ca.add( c );
if ( ! comments.next() )
moreComments = false;
}
//System.out.println( JSON.serialize( o ) );
coll.save( o );
}
res.close();
stmt.close();
}
public static void main( String args[] )
throws Exception {
migrate( DriverManager.getConnection( "jdbc:mysql:
DBJni.get( "alleyinsider" ) );
}
}
|
package com.wegas.core.ejb;
import com.wegas.core.Delay;
import com.wegas.core.Helper;
import com.wegas.core.api.DelayedScriptEventFacadeI;
import com.wegas.core.api.GameModelFacadeI;
import com.wegas.core.api.I18nFacadeI;
import com.wegas.core.api.IterationFacadeI;
import com.wegas.core.api.QuestionDescriptorFacadeI;
import com.wegas.core.api.RequestManagerI;
import com.wegas.core.api.ResourceFacadeI;
import com.wegas.core.api.ReviewingFacadeI;
import com.wegas.core.api.ScriptEventFacadeI;
import com.wegas.core.api.StateMachineFacadeI;
import com.wegas.core.api.VariableDescriptorFacadeI;
import com.wegas.core.api.VariableInstanceFacadeI;
import com.wegas.core.ejb.nashorn.JSTool;
import com.wegas.core.ejb.nashorn.JavaObjectInvocationHandler;
import com.wegas.core.ejb.nashorn.NHClassFilter;
import com.wegas.core.ejb.nashorn.NHClassLoader;
import com.wegas.core.ejb.statemachine.StateMachineFacade;
import com.wegas.core.exception.WegasErrorMessageManager;
import com.wegas.core.exception.client.WegasErrorMessage;
import com.wegas.core.exception.client.WegasRuntimeException;
import com.wegas.core.exception.client.WegasScriptException;
import com.wegas.core.i18n.ejb.I18nFacade;
import com.wegas.core.persistence.AbstractEntity;
import com.wegas.core.persistence.game.GameModel;
import com.wegas.core.persistence.game.GameModelContent;
import com.wegas.core.persistence.game.Player;
import com.wegas.core.persistence.game.Populatable;
import com.wegas.core.persistence.game.Script;
import com.wegas.core.persistence.variable.VariableDescriptor;
import com.wegas.core.persistence.variable.statemachine.AbstractTransition;
import com.wegas.core.security.util.ActAsPlayer;
import com.wegas.log.xapi.Xapi;
import com.wegas.log.xapi.XapiI;
import com.wegas.mcq.ejb.QuestionDescriptorFacade;
import com.wegas.resourceManagement.ejb.IterationFacade;
import com.wegas.resourceManagement.ejb.ResourceFacade;
import com.wegas.reviewing.ejb.ReviewingFacade;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.inject.Inject;
import javax.script.*;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Francois-Xavier Aeberhard (fx at red-agent.com)
*/
@Stateless
@LocalBean
public class ScriptFacade extends WegasAbstractFacade {
private static final Logger logger = LoggerFactory.getLogger(ScriptFacade.class);
/**
* Stops script after a given delay. (ms)
*/
private static final long SCRIPT_DELAY = 1000L;
/**
* name
*/
/* package */ static final String CONTEXT = "currentDescriptor";
/**
* A single, thread safe, javascript engine (only language currently supported)
*/
private static final ScriptEngine engine;
/**
* Pre-compiled script. nashorn specific __noSuchProperty__ hijacking : find a
* variableDescriptor's scriptAlias. Must be included in each Bindings.
*/
private static final CompiledScript noSuchProperty;
/**
* Keep static scripts pre-compiled
*/
private static final Helper.LRUCache<String, CachedScript> staticCache = new Helper.LRUCache<>(250);
private static class CachedScript {
private CompiledScript script;
private String version;
private String language;
private String name;
public CachedScript(CompiledScript script, String name, String version, String language) {
this.name = name;
this.script = script;
this.version = version;
this.language = language;
}
}
/*
* Initialize noSuchProperty and other nashorn stuff
*/
static {
//engine = new ScriptEngineManager().getEngineByName("JavaScript");
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
//engine = factory.getScriptEngine(new NHClassLoader());
engine = factory.getScriptEngine(new String[0], new NHClassLoader(), new NHClassFilter());
//engine = factory.getScriptEngine(new String[] {} , new NHClassLoader(), new NHClassFilter());
CompiledScript compile = null;
try {
compile = ((Compilable) engine).compile(
"(function(global){"
+ " var defaultNoSuchProperty = global.__noSuchProperty__;" // Store nashorn's implementation
+ " Object.defineProperty(global, '__noSuchProperty__', {"
+ " value: function(prop){"
+ " if (prop === 'engine'){"
+ " return null;"
+ " }"
+ " try{"
+ " var ret = Variable.find(gameModel, prop).getInstance(self);"
+ " print('SCRIPT_ALIAS_CALL: [GM]' + gameModel.getId() + ' [alias]' + prop);" // log usage if var exists
+ " return ret;" // Try to find a VariableDescriptor's instance for that given prop
+ " }catch(e){"
+ " return defaultNoSuchProperty.call(global, prop);" // Use default implementation if no VariableDescriptor
+ " }}"
+ " });"
+ " if (!Math._random) { Math._random = Math.random; Math.random = function random(){if (RequestManager.isTestEnv()) {return 0} else {return Math._random()} }}"
+ "})(this);"); // Run on Bindings
} catch (ScriptException e) {
logger.error("noSuchProperty script compilation failed", e);
}
noSuchProperty = compile;
}
@Inject
private PlayerFacade playerFacade;
@Inject
private GameModelFacade gameModelFacade;
@Inject
private VariableDescriptorFacade variableDescriptorFacade;
@Inject
private VariableInstanceFacade variableInstanceFacade;
@Inject
private ResourceFacade resourceFacade;
@Inject
private IterationFacade iterationFacade;
@Inject
private QuestionDescriptorFacade questionDescriptorFacade;
@Inject
private StateMachineFacade stateMachineFacade;
@Inject
private ReviewingFacade reviewingFacade;
@Inject
private I18nFacade i18nFacade;
@Inject
private ScriptEventFacade event;
@Inject
private DelayedScriptEventFacade delayedEvent;
@Inject
private RequestManager requestManager;
@Inject
private Xapi xapi;
@Resource(lookup = "timeoutExecutorService")
private ManagedExecutorService timeoutExecutorService;
public ScriptContext instantiateScriptContext(Player player, String language) {
final ScriptContext currentContext = requestManager.getCurrentScriptContext();
if (currentContext == null) {
final ScriptContext scriptContext = this.populate(player);
requestManager.setCurrentScriptContext(scriptContext);
return scriptContext;
}
return currentContext;
}
private <T> void putBinding(Bindings bindings, String name, Class<T> klass, T object) {
bindings.put(name, JavaObjectInvocationHandler.wrap(object, klass));
}
private ScriptContext populate(Player player) {
final Bindings bindings = engine.createBindings();
if (player == null) {
throw WegasErrorMessage.error("ScriptFacade.populate requires a player !!!");
}
if (player.getStatus() != Populatable.Status.LIVE
&& player.getStatus() != Populatable.Status.INITIALIZING
&& player.getStatus() != Populatable.Status.SURVEY) {
throw WegasErrorMessage.error("ScriptFacade.populate requires a LIVE player !!!");
}
bindings.put("self", player); // Inject current player
bindings.put("gameModel", player.getGameModel()); // Inject current gameModel
putBinding(bindings, "GameModelFacade", GameModelFacadeI.class, gameModelFacade);
putBinding(bindings, "I18nFacade", I18nFacadeI.class, i18nFacade);
putBinding(bindings, "Variable", VariableDescriptorFacadeI.class, variableDescriptorFacade);
putBinding(bindings, "VariableDescriptorFacade", VariableDescriptorFacadeI.class, variableDescriptorFacade);
putBinding(bindings, "Instance", VariableInstanceFacadeI.class, variableInstanceFacade);
putBinding(bindings, "ResourceFacade", ResourceFacadeI.class, resourceFacade);
putBinding(bindings, "IterationFacade", IterationFacadeI.class, iterationFacade);
putBinding(bindings, "QuestionFacade", QuestionDescriptorFacadeI.class, questionDescriptorFacade);
putBinding(bindings, "StateMachineFacade", StateMachineFacadeI.class, stateMachineFacade);
putBinding(bindings, "ReviewingFacade", ReviewingFacadeI.class, reviewingFacade);
putBinding(bindings, "RequestManager", RequestManagerI.class, requestManager);
putBinding(bindings, "Event", ScriptEventFacadeI.class, event);
putBinding(bindings, "DelayedEvent", DelayedScriptEventFacadeI.class, delayedEvent);
putBinding(bindings, "xapi", XapiI.class, xapi);
bindings.put("ErrorManager", new WegasErrorMessageManager()); // Inject the MessageErrorManager
bindings.remove("exit");
bindings.remove("quit");
bindings.remove("loadWithNewGlobal");
event.detachAll();
ScriptContext ctx = new SimpleScriptContext();
ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
try {
noSuchProperty.eval(bindings);
} catch (ScriptException e) {
logger.error("noSuchProperty injection", e);
}
/**
* Inject hard server scripts first
*/
this.injectStaticScript(ctx, player.getGameModel());
/**
* Then inject soft ones. It means a soft script may override methods defined in a hard
* coded one
*/
for (GameModelContent script : player.getGameModel().getScriptLibraryList()) {
ctx.setAttribute(ScriptEngine.FILENAME, "Server script " + script.getContentKey(), ScriptContext.ENGINE_SCOPE);
String cacheFileName = "soft:" + player.getGameModel().getId() + ":" + script.getContentKey();
String version = script.getVersion().toString();
CachedScript cached = getCachedScript(cacheFileName, version, script.getContent());
try {
cached.script.eval(ctx);
} catch (ScriptException ex) { // script exception (Java -> JS -> throw)
throw new WegasScriptException("Server script " + script.getContentKey(), ex.getLineNumber(), ex.getMessage());
} catch (Exception ex) { // Java exception (Java -> JS -> Java -> throw)
throw new WegasScriptException("Server script " + script.getContentKey(), ex.getMessage());
}
}
return ctx;
}
private CachedScript getCachedScript(String name, String version, String script) {
CachedScript cached = staticCache.get(name);
if (cached == null) {
// since putIfAbsent is synchronised, check existence first to reduce locking
cached = staticCache.putIfAbsentAndGet(name, new CachedScript(null, name, version, "JavaScript"));
}
if (cached.version == null
|| !cached.version.equals(version)
|| cached.script == null) {
CompiledScript compile;
try {
compile = ((Compilable) engine).compile(script);
} catch (ScriptException ex) {
throw new WegasScriptException(name, ex.getLineNumber(), ex.getMessage());
}
cached.script = compile;
cached.version = version;
}
return cached;
}
/**
* Eval without any player related context (no server scripts, no API, etc)
*
* @param script
* @param args
*
* @return
*
* @throws ScriptException
*/
public Object nakedEval(String script, Map<String, Object> args, ScriptContext ctx) throws ScriptException {
if (ctx == null) {
ctx = new SimpleScriptContext();
}
if (args != null) {
for (Entry<String, Object> arg : args.entrySet()) {
if (arg.getValue() != null) {
ctx.getBindings(ScriptContext.ENGINE_SCOPE).put(arg.getKey(), arg.getValue());
}
}
}
return engine.eval(script, ctx);
}
public Object nakedEval(CompiledScript script, Map<String, Object> args, ScriptContext ctx) throws ScriptException {
if (ctx == null) {
ctx = new SimpleScriptContext();
}
if (args != null) {
for (Entry<String, Object> arg : args.entrySet()) {
if (arg.getValue() != null) {
ctx.getBindings(ScriptContext.ENGINE_SCOPE).put(arg.getKey(), arg.getValue());
}
}
}
return script.eval(ctx);
}
/**
* Inject script files specified in GameModel's property scriptFiles into engine
*
* @param ctx ScriptContext to populate
* @param gm GameModel from which scripts are taken
*/
private void injectStaticScript(ScriptContext ctx, GameModel gm) {
String scriptURI = gm.getProperties().getScriptUri();
if (scriptURI == null || scriptURI.equals("")) {
return;
}
String currentPath = getClass().getProtectionDomain().getCodeSource().getLocation().toString();
Integer index = currentPath.indexOf("/WEB-INF");
String root;
if (index < 1) {
// Seems we're not on a real deployed application
// smells like such an integration test
root = Helper.getWegasRootDirectory();
if (root == null) {
logger.error("Wegas Lost In The Sky... [Static Script Injection Not Available] -> {}", currentPath);
return;
}
} else {
root = currentPath.substring(0, index);
}
String cacheFileName;
String version;
try {
for (Path path : getJavaScriptsRecursively(root, scriptURI.split(";"))) {
cacheFileName = "hard:" + path;
version = Long.toString(Files.getLastModifiedTime(path).toMillis());
CachedScript cached = staticCache.get(cacheFileName);
if (cached == null) {
// since putIfAbsent is synchronised, check existence first to reduce locking
cached = staticCache.putIfAbsentAndGet(cacheFileName, new CachedScript(null, cacheFileName, version, "JavaScript"));
}
if (cached.version == null
|| !cached.version.equals(version)
|| cached.script == null) {
try (BufferedReader reader = Files.newBufferedReader(path)) {
cached.script = this.compile(reader);
cached.version = version;
} catch (ScriptException ex) {
throw new WegasScriptException(path.toString(), ex.getLineNumber(), ex.getMessage());
}
}
try {
ctx.setAttribute(ScriptEngine.FILENAME, "Static Scripts " + path, ScriptContext.ENGINE_SCOPE);
cached.script.eval(ctx);
logger.info("File {} successfully injected", path);
} catch (ScriptException ex) { // script exception (Java -> JS -> throw)
throw new WegasScriptException(scriptURI, ex.getLineNumber(), ex.getMessage());
} catch (RuntimeException ex) { // Unwrapped Java exception (Java -> JS -> Java -> throw)
throw new WegasScriptException(scriptURI, ex.getMessage());
}
}
} catch (IOException | URISyntaxException ex) {
logger.warn("Unable to read hard coded server scripts");
}
}
public CompiledScript compile(Reader script) throws ScriptException {
return ((Compilable) engine).compile(script);
}
public void clearCache() {
staticCache.clear();
}
/**
* Instantiate script context, inject arguments and eval the given script
*
* @param script
* @param arguments
*
* @return whatever the script has returned
*/
private Object eval(Script script, Map<String, AbstractEntity> arguments) throws WegasScriptException {
if (script == null) {
return null;
}
ScriptContext ctx = instantiateScriptContext(requestManager.getPlayer(), script.getLanguage());
for (Entry<String, AbstractEntity> arg : arguments.entrySet()) { // Inject the arguments
if (arg.getValue() != null) {
ctx.getBindings(ScriptContext.ENGINE_SCOPE).put(arg.getKey(), arg.getValue());
}
}
try {
ctx.setAttribute(ScriptEngine.FILENAME, script.getContent(), ScriptContext.ENGINE_SCOPE);
return engine.eval(script.getContent(), ctx);
} catch (ScriptException ex) {
logger.error("ScriptException: {}", ex);
throw new WegasScriptException(script.getContent(), ex.getLineNumber(), ex.getMessage(), ex);
} catch (WegasRuntimeException ex) { // throw our exception as-is
logger.error("ScriptException: {}", ex);
throw ex;
} catch (UndeclaredThrowableException ex) { // Java exception (Java -> JS -> Java -> throw)
Throwable cause = ex.getCause();
if (cause instanceof InvocationTargetException) {
Throwable subCause = cause.getCause();
if (subCause instanceof WegasRuntimeException) {
throw (WegasRuntimeException) subCause;
} else {
if (subCause != null) {
throw new WegasScriptException(script.getContent(), subCause.getMessage(), ex);
} else {
throw new WegasScriptException(script.getContent(), cause.getMessage(), ex);
}
}
} else {
throw new WegasScriptException(script.getContent(), ex.getMessage(), ex);
}
} catch (RuntimeException ex) { // Java exception (Java -> JS -> Java -> throw)
logger.error("ScriptException: {}", ex);
throw new WegasScriptException(script.getContent(), ex.getMessage(), ex);
}
}
private Object eval(CachedScript cachedScript, Map<String, AbstractEntity> arguments) throws WegasScriptException {
if (cachedScript == null) {
return null;
}
ScriptContext ctx = instantiateScriptContext(requestManager.getPlayer(), cachedScript.language);
for (Entry<String, AbstractEntity> arg : arguments.entrySet()) { // Inject the arguments
if (arg.getValue() != null) {
ctx.getBindings(ScriptContext.ENGINE_SCOPE).put(arg.getKey(), arg.getValue());
}
}
try {
ctx.setAttribute(ScriptEngine.FILENAME, cachedScript.name, ScriptContext.ENGINE_SCOPE);
return cachedScript.script.eval(ctx);
} catch (ScriptException ex) {
logger.error("ScriptException: {}", ex);
throw new WegasScriptException(cachedScript.name, ex.getLineNumber(), ex.getMessage(), ex);
} catch (WegasRuntimeException ex) { // throw our exception as-is
logger.error("ScriptException: {}", ex);
throw ex;
} catch (UndeclaredThrowableException ex) { // Java exception (Java -> JS -> Java -> throw)
Throwable cause = ex.getCause();
if (cause instanceof InvocationTargetException) {
Throwable subCause = cause.getCause();
if (subCause instanceof WegasRuntimeException) {
throw (WegasRuntimeException) subCause;
} else {
if (subCause != null) {
throw new WegasScriptException(cachedScript.name, subCause.getMessage(), ex);
} else {
throw new WegasScriptException(cachedScript.name, cause.getMessage(), ex);
}
}
} else {
throw new WegasScriptException(cachedScript.name, ex.getMessage(), ex);
}
} catch (RuntimeException ex) { // Java exception (Java -> JS -> Java -> throw)
logger.error("ScriptException: {}", ex);
throw new WegasScriptException(cachedScript.name, ex.getMessage(), ex);
}
}
/**
* extract all javascript files from the files list. If one of the files is a directory, recurse
* through it and fetch *.js.
* <p>
* Note: When iterating, if a script and its minified version stands in the directory, the
* minified is ignored (debugging purpose)
*
* @param root
* @param files
*
* @return javascript file collection
*/
private Collection<Path> getJavaScriptsRecursively(String root, String[] files) throws IOException, URISyntaxException {
List<Path> queue = new LinkedList<>();
for (String file : files) {
if (!Helper.isNullOrEmpty(file.trim())) {
queue.add(Paths.get(new URI(root + "/" + file)));
}
}
List<Path> result = new LinkedList<>();
while (!queue.isEmpty()) {
Path current = queue.remove(0);
if (!Files.isSymbolicLink(current) && Files.isReadable(current)) {
if (Files.isDirectory(current)) {
try (Stream<Path> children = Files.list(current)) {
// queue children
children.collect(Collectors.toCollection(() -> queue));
}
} else if (Files.isRegularFile(current)
&& current.toString().endsWith(".js")) {
// collect all .js
result.add(current);
}
}
}
// at this point, result may contains plain and minified versions of the very same script
return result.stream().filter(p -> shouldKeep(p, result)).collect(Collectors.toList());
}
/**
* Keep all file but minified which have non-minified version in the list
*
* @param path
* @param paths
*
* @return
*/
private static boolean shouldKeep(Path path, List<Path> paths) {
String toString = path.toString();
if (toString.endsWith("-min.js")) {
String nonMin = toString.replaceAll("-min.js$", ".js");
return !paths.stream().anyMatch(p -> nonMin.equals(p.toString()));
}
return true;
}
/**
* Runs a script with a delay ({@value #SCRIPT_DELAY} ms)
*
* @param playerId player to run script as
* @param script script
*
* @return script result
*
* @throws WegasScriptException when an error occurred
* @see #eval(Script, Map)
*/
public Object timeoutEval(Long playerId, Script script) throws WegasScriptException {
final Player player = playerFacade.find(playerId);
try (ActAsPlayer a = requestManager.actAsPlayer(player)) {
final ScriptContext scriptContext = this.instantiateScriptContext(player, script.getLanguage());
final Script scriptCopy = new Script();
scriptCopy.setContent(JSTool.sanitize(script.getContent(), "$$internal$delay.poll();"));
scriptCopy.setLanguage(script.getLanguage());
scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(JSTool.JS_TOOL_INSTANCE_NAME,
new JSTool.JSToolInstance());
try (Delay delay = new Delay(SCRIPT_DELAY, timeoutExecutorService)) {
scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put("$$internal$delay", delay);
return this.eval(scriptCopy, new HashMap<>());
} catch (WegasScriptException e) {
// try to restore original code
final String replaceCode = e.getMessage().replace(scriptCopy.getContent(), script.getContent());
throw new WegasScriptException(script.getContent(), replaceCode);
}
}
}
// ~~~ Sugar ~~~
/**
* Concatenate scripts
*
* @param scripts
* @param arguments
*
* @return eval result
*/
private Object eval(Player player, List<Script> scripts, Map<String, AbstractEntity> arguments) throws WegasScriptException {
if (scripts.isEmpty()) {
return null;
}
StringBuilder buf = new StringBuilder();
for (Script s : scripts) { // concatenate all scripts
if (s != null && !Helper.isNullOrEmpty(s.getContent())) {
buf.append(s.getContent()).append(';').append(System.lineSeparator());
}
}
return this.eval(player, new Script(buf.toString()), arguments);
}
public Object eval(Player player, List<Script> scripts, VariableDescriptor context) {
Map<String, AbstractEntity> arguments = new HashMap<>();
arguments.put(ScriptFacade.CONTEXT, context);
return this.eval(player, scripts, arguments);
}
@Deprecated
public Object evalDoNotUse(Player p, AbstractTransition transition, VariableDescriptor context) throws WegasScriptException {
String name = "transition:" + transition.getId();
CachedScript cached = getCachedScript(name, transition.getVersion().toString(), transition.getTriggerCondition().getContent());
Map<String, AbstractEntity> arguments = new HashMap<>();
arguments.put(ScriptFacade.CONTEXT, context);
return this.eval(p, cached, arguments);
}
private Object eval(Player player, CachedScript s, Map<String, AbstractEntity> arguments) throws WegasScriptException {
try (ActAsPlayer a = requestManager.actAsPlayer(player)) {
return this.eval(s, arguments);
}
}
/**
* @param p
* @param s
* @param context
*
* @return eval result
*/
public Object eval(Player p, Script s, VariableDescriptor context) throws WegasScriptException {
Map<String, AbstractEntity> arguments = new HashMap<>();
arguments.put(ScriptFacade.CONTEXT, context);
return this.eval(p, s, arguments);
}
/**
* @param player
* @param s
* @param arguments
*
* @return eval result
*/
private Object eval(Player player, Script s, Map<String, AbstractEntity> arguments) throws WegasScriptException {
try (ActAsPlayer a = requestManager.actAsPlayer(player)) {
return this.eval(s, arguments);
}
}
/**
* @param playerId
* @param s
* @param context
*
* @return eval result
*
* @throws WegasScriptException
*/
public Object eval(Long playerId, Script s, VariableDescriptor context) throws WegasScriptException { // ICI CONTEXT
Map<String, AbstractEntity> arguments = new HashMap<>();
arguments.put(ScriptFacade.CONTEXT, context);
return this.eval(playerFacade.find(playerId), s, arguments);
}
}
|
// JSFunction.java
package ed.js;
import java.util.*;
import java.util.concurrent.*;
import ed.lang.*;
import ed.util.*;
import ed.appserver.*;
import ed.js.func.*;
import ed.js.engine.Scope;
/** @expose */
public abstract class JSFunction extends JSFunctionBase {
final static int CACHE_SIZE = 100;
static {
JS._debugSIStart( "JSFunction" );
}
/** "JSFunction : " */
public static final String TO_STRING_PREFIX = "JSFunction : ";
/** Initialize this function with a default scope and name.
* @param num The number of parameters.
*/
public JSFunction( int num ){
this( null , null , num );
}
/** Initialize this function with a given scope, name, and number of parameters.
* @param scope Scope in which this function should run.
* @param name This function's name.
* @param num The number of parameters.
*/
public JSFunction( Scope scope , String name , int num ){
super( num );
_scope = scope;
_name = name;
_prototype = new JSObjectBase( this );
set( "prototype" , _prototype );
set( "length" , num );
setProperties( "length" , JSObjectBase.LOCK );
init();
}
/** Returns the number of parameters taken by this function.
* @return The number of parameters taken by this function.
*/
public int getNumParameters(){
return _num;
}
/** Set a property or the prototype object of this function.
* @param n The key to set. Oddly, n can be null and it will just set the property "null". If <tt>n</tt> is "prototype", this function's prototype object will be set to <tt>b</tt>.
* @param b The value to set.
* @return <tt>b</tt>
*/
public Object set( Object n , Object b ){
if ( n != null && "prototype".equals( n.toString() ) )
_prototype = (JSObjectBase)b;
return super.set( n , b );
}
/** Creates a new object with this function as its constructor.
* @return The newly created object.
*/
public JSObject newOne(){
return new JSObjectBase( this );
}
/** Initializes this function. Empty method at present. */
protected void init(){}
/** Returns a value with a given key from this function object or this function's prototype object.
* @param n Object to find.
* @returns The value corresponding to the key <tt>n</tt>.
*/
public Object get( Object n ){
Object foo = super.get( n );
if ( foo != null )
return foo;
if ( _prototype != null ){
foo = _prototype.get( n );
if ( foo != null )
return foo;
}
foo = _staticFunctions.get( n );
if ( foo != null )
return foo;
return null;
}
public JSFunction getFunction( String name , boolean tryLower ){
Object blah = _prototype.get( name );
if ( blah == null && tryLower )
blah = _prototype.get( name.toLowerCase() );
if ( blah == null )
return null;
if ( ! ( blah instanceof JSFunction ) )
return null;
return (JSFunction)blah;
}
/** Set this function's name.
* @param name Set this function's name.
*/
public void setName( String name ){
_name = name;
}
/** Returns this function's name when it has been compiled into Java.
* @return This function's name.
*/
public String getName(){
return _name;
}
/**
* this returns a Scope that is acceptable for setting this on and passing back
* if the function has a Scope, returns a child of it, otherwise just an empty scope
*/
public Scope getAScopeForThis(){
if ( _scope == null )
return new Scope();
return _scope.child();
}
/** Returns the scope in which this function is running.
*/
public Scope getScope(){
return getScope( false );
}
/** Return this function's prototype object.
* @param This function's prototype object.
*/
public JSObject getPrototype(){
return _prototype;
}
/** Returns the scope in which this function is running.
* @param threadLocal if this is true, it returns a thread local scope that you can modify for your thread
*/
public Scope getScope( boolean threadLocal ){
Scope s = null;
if ( _tlScope != null ){
s = _tlScope.get();
if ( s != null ){
return s;
}
}
if ( threadLocal ){
if ( _scope == null )
s = new Scope( "func tl scope" , null );
else
s = _scope.child( "func tl scope" );
s.setGlobal( true );
setTLScope( s );
return s;
}
return _scope;
}
/** Set the thread local scope to a given scope.
* @param tl Scope to set to.
*/
public void setTLScope( Scope tl ){
if ( _tlScope == null )
_tlScope = new ThreadLocal<Scope>();
_tlScope.set( tl );
}
/** If it exists, return the thread local scope.
* @return The thread local scope.
*/
public Scope getTLScope(){
if ( _tlScope == null )
return null;
return _tlScope.get();
}
/** Clear all objects and reset this function's scope. */
public void clearScope(){
if ( _tlScope != null ){
Scope s = _tlScope.get();
if ( s != null )
s.reset();
}
}
public String getSourceCode(){
return null;
}
/** Return a string representation of this function.
* @return A string "JSFunction : " and this function's name
*/
public String toString(){
return TO_STRING_PREFIX + _name;
}
/** Returns an array of the parameter names.
* @return An array of the parameter names.
*/
public JSArray argumentNames(){
if ( _arguments != null )
return _arguments;
JSArray temp = new JSArray();
for ( int i=0; i<_num; i++ ){
temp.add( "unknown" + i );
}
return temp;
}
/** Returns if this function is using a passed in scope.
* @return If this function is using a passed in scope.
*/
public boolean usePassedInScope(){
if ( _forceUsePassedInScope )
return true;
if ( ! _forceUsePassedInScopeTLEver )
return false;
Boolean b = _forceUsePassedInScopeTL.get();
return b == null ? false : b;
}
public void setUsePassedInScope( boolean usePassedInScope ){
_forceUsePassedInScope = usePassedInScope;
}
public Boolean setUsePassedInScopeTL( Boolean usePassedInScopeTL ){
_forceUsePassedInScopeTLEver = _forceUsePassedInScopeTLEver || usePassedInScopeTL;
Boolean old = _forceUsePassedInScopeTL.get();
_forceUsePassedInScopeTL.set( usePassedInScopeTL );
return old;
}
Object _cache( Scope s , long cacheTime , Object args[] ){
// yes, its possible for 2 threads to create their own cache and each to use a different one, but thats ok
// all that happens is that 2 threads both do the work.
// but its a race condition anyway, so behavior is a bit odd no matter what
FunctionResultCache myCache = _callCache;
if ( myCache == null ){
myCache = new FunctionResultCache();
_callCache = myCache;
}
myCache = _callCache;
final long now = System.currentTimeMillis();
final Long hash = JSInternalFunctions.hash( args );
CacheEntry entry = null;
boolean force = false;
synchronized ( myCache ){
entry = myCache.get( hash );
if ( entry != null && entry.expired( now ) ){
entry.setExpiration( now + cacheTime );
entry = null;
force = true;
}
}
if ( entry == null ){
// make sure i have a real db connection
AppRequest ar = AppRequest.getThreadLocal();
if ( ar != null )
ar.getContext().getDB().requestEnsureConnection();
final String synckey = ("function-synckey" + System.identityHashCode( this ) + ":" + hash ).intern();
synchronized( synckey ){
synchronized ( myCache ){
entry = myCache.get( hash );
}
if ( entry == null || force ){
PrintBuffer buf = new PrintBuffer();
getScope( true ).set( "print" , buf );
entry = new CacheEntry( now + cacheTime , call( s , args ) , buf.toString() );
synchronized( myCache ){
myCache.put( hash , entry );
}
clearScope();
}
}
}
JSFunction print = (JSFunction)(s.get( "print" ));
if ( print == null )
throw new JSException( "print is null" );
print.call( s , entry._print );
return entry._res;
}
public Object callAndSetThis( Scope s , Object obj , Object args[] ){
if ( s == null )
s = new Scope();
s.setThis( obj );
try {
return call( s , args );
}
finally {
s.clearThisNormal( null );
}
}
public JSFunction synchronizedVersion(){
final JSFunction t = this;
final String myLock = "some-lock-" + Math.random();
return new JSFunctionCalls0(){
public Object call( Scope s , Object args[] ){
synchronized ( myLock ){
return t.call( s , args );
}
}
};
}
public long approxSize( SeenPath seen ){
long size = super.approxSize( seen );
size += 128; // for sub-type overhead
if ( seen.shouldVisit( _prototype , this ) )
size += _prototype.approxSize( seen );
if ( seen.shouldVisit( _callCache , this ) )
size += _callCache.approxSize( seen );
if ( seen.shouldVisit( _scope , this ) )
size += _scope.approxSize( seen );
return size;
}
public Language getSourceLanguage(){
return _sourceLanguage;
}
/** The hash code value of this function.
* @return The hash code value of this function.
*/
public int hashCode( IdentitySet seen ){
return System.identityHashCode( this );
}
public boolean isCallable(){
return true;
}
/**
* @return null if we do'nt what the globals are, or an array of global strings
*/
public JSArray getGlobals(){
return _globals;
}
private final Scope _scope;
private ThreadLocal<Scope> _tlScope;
private boolean _forceUsePassedInScope = false;
private final ThreadLocal<Boolean> _forceUsePassedInScopeTL = new ThreadLocal<Boolean>();
private boolean _forceUsePassedInScopeTLEver = false;
protected JSObjectBase _prototype;
protected Language _sourceLanguage = Language.JS();
protected JSArray _arguments;
protected JSArray _globals;
protected String _name = "NO NAME SET";
private FunctionResultCache _callCache;
/** @unexpose */
public static JSFunction _call = new ed.js.func.JSFunctionCalls1(){
public Object call( Scope s , Object obj , Object[] args ){
JSFunction func = (JSFunction)s.getThis();
return func.callAndSetThis( s , obj , args );
}
};
static JSFunction _apply = new ed.js.func.JSFunctionCalls3(){
public Object call( Scope s , Object obj , Object args , Object explodeArgs , Object [] foo ){
JSFunction func = (JSFunction)s.getThis();
if ( args == null )
args = new JSArray();
if( ! (args instanceof JSArray) )
throw new RuntimeException("second argument to Function.prototype.apply must be an array not a " + args.getClass() );
JSArray jary = (JSArray)args;
if ( explodeArgs instanceof JSObject ){
if ( func._arguments == null )
throw new RuntimeException( "can't explode b/c no argument unnamed" );
JSObject explode = (JSObject)explodeArgs;
for ( int i=0; i<func._arguments.size(); i++ ){
String name = func._arguments.get(i).toString();
if ( explode.containsKey( name ) ){
if ( jary.get( i ) != null )
throw new RuntimeException( "can't have a named an array value for [" + name + "]" );
jary.set( i , explode.get( name ) );
}
}
}
s.setThis( obj );
try {
return func.call( s , jary.toArray() );
}
finally {
s.clearThisNormal( null );
}
}
};
static JSFunction _cache = new ed.js.func.JSFunctionCalls1(){
public Object call( Scope s , Object cacheTimeObj , Object[] args ){
JSFunction func = (JSFunction)s.getThis();
long cacheTime = Long.MAX_VALUE;
if ( cacheTimeObj != null && cacheTimeObj instanceof Number )
cacheTime = ((Number)cacheTimeObj).longValue();
return func._cache( s , cacheTime , args );
}
};
private static JSObjectBase _staticFunctions = new JSObjectBase();
static {
_staticFunctions.set( "wrap" , Prototype._functionWrap );
_staticFunctions.set( "bind", Prototype._functionBind );
Prototype._functionWrap.lock();
Prototype._functionBind.lock();
_staticFunctions.set( "call" , _call );
_staticFunctions.set( "apply" , _apply );
_staticFunctions.set( "cache" , _cache );
_call.lock();
_apply.lock();
_cache.lock();
}
static class CacheEntry {
CacheEntry( long expiration , Object res , String print ){
_expiration = expiration;
_res = res;
_print = print;
}
boolean expired( long now ){
return now > _expiration;
}
void setExpiration( long when ){
_expiration = when;
}
long _expiration;
final Object _res;
final String _print;
}
static class FunctionResultCache extends LinkedHashMap<Long,CacheEntry> {
public long approxSize( SeenPath seen ){
long s = 0;
synchronized ( this ){
for ( Map.Entry<Long,CacheEntry> e : entrySet() ){
CacheEntry ce = e.getValue();
s += 64 + ( ce._print.length() * 2 ) + JSObjectSize.size( ce._res , seen , this );
}
}
return s;
}
protected boolean removeEldestEntry( Map.Entry<Long,CacheEntry> eldest ){
return size() > CACHE_SIZE;
}
}
public static void _init( JSFunction fcons ){
if ( _staticFunctions == null )
return;
for ( String s : _staticFunctions.keySet() )
fcons._prototype.set( s , _staticFunctions.get( s ) );
fcons._prototype.dontEnumExisting();
}
static {
JS._debugSIDone( "JSFunction" );
}
}
|
package ru.faulab.attendence;
import com.google.inject.Guice;
import com.google.inject.Injector;
import ru.faulab.attendence.module.MainModule;
import ru.faulab.attendence.ui.MainFrame;
import javax.swing.*;
public class Runner {
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
String userHome = System.getProperty("user.home");
System.setProperty("derby.system.home", userHome);
Injector injector = Guice.createInjector(new MainModule());
MainFrame mainFrame = injector.getInstance(MainFrame.class);
mainFrame.init();
}
}
|
package org.codehaus.xfire;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.ServiceRegistry;
import org.codehaus.xfire.soap.Soap11;
import org.codehaus.xfire.soap.Soap12;
import org.codehaus.xfire.wsdl.WSDLWriter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* Contains helpful methods to test SOAP services.
*
* @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
*/
public abstract class AbstractXFireTest
extends TestCase
{
private XFire xfire;
/**
* Namespaces for the XPath expressions.
*/
private Map namespaces = new HashMap();
protected void printNode( Node node )
throws Exception
{
XMLWriter writer = new XMLWriter( OutputFormat.createPrettyPrint() );
writer.setOutputStream( System.out );
writer.write( node );
}
/**
* Invoke a service with the specified document.
*
* @param service The name of the service.
* @param document The request as an xml document in the classpath.
*/
protected Document invokeService( String service, String document )
throws Exception
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessageContext context =
new MessageContext( service,
null,
out,
null,
null );
getXFire().invoke( getResourceAsStream( document ), context );
return readDocument( out.toString() );
}
protected Document readDocument( String text )
throws DocumentException
{
try
{
SAXReader reader = new SAXReader();
return reader.read( new StringReader( text ) );
}
catch( DocumentException e )
{
System.err.println( "Could not read the document!" );
System.out.println( text );
throw e;
}
}
protected Document getWSDLDocument( String service )
throws Exception
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
getXFire().generateWSDL( service, out );
try
{
SAXReader reader = new SAXReader();
return reader.read( new StringReader( out.toString() ) );
}
catch( DocumentException e )
{
System.err.println( "Could not read the document!" );
System.out.println( out.toString() );
throw e;
}
}
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
xfire = new DefaultXFire();
addNamespace( "s", Soap11.getInstance().getNamespace() );
addNamespace( "soap12", Soap12.getInstance().getNamespace() );
}
/**
* Assert that the following XPath query selects one or more nodes.
*
* @param xpath
*/
public void assertValid( String xpath, Node node )
throws Exception
{
List nodes = createXPath( xpath ).selectNodes( node );
if( nodes.size() == 0 )
{
throw new Exception( "Failed to select any nodes for expression:.\n" +
xpath + "\n" +
node.asXML() );
}
}
/**
* Assert that the following XPath query selects no nodes.
*
* @param xpath
*/
public void assertInvalid( String xpath, Node node )
throws Exception
{
List nodes = createXPath( xpath ).selectNodes( node );
if( nodes.size() > 0 )
{
throw new Exception( "Found multiple nodes for expression:\n" +
xpath + "\n" +
node.asXML() );
}
}
/**
* Asser that the text of the xpath node retrieved is equal to the value specified.
*
* @param xpath
* @param value
* @param node
*/
public void assertXPathEquals( String xpath, String value, Node node )
throws Exception
{
String value2 = createXPath( xpath ).selectSingleNode( node ).getText().trim();
assertEquals( value, value2 );
}
public void assertNoFault( Node node )
throws Exception
{
assertInvalid( "/s:Envelope/s:Body/s:Fault", node );
}
/**
* Create the specified XPath expression with the namespaces added via addNamespace().
*/
protected XPath createXPath( String xpathString )
{
XPath xpath = DocumentHelper.createXPath( xpathString );
xpath.setNamespaceURIs( namespaces );
return xpath;
}
/**
* Add a namespace that will be used for XPath expressions.
*
* @param ns Namespace name.
* @param uri The namespace uri.
*/
public void addNamespace( String ns, String uri )
{
namespaces.put( ns, uri );
}
/**
* Get the WSDL for a service.
*
* @param service The name of the service.
*/
protected WSDLWriter getWSDL( String service )
throws Exception
{
ServiceRegistry reg = getServiceRegistry();
Service hello = reg.getService( service );
return hello.getWSDLWriter();
}
protected XFire getXFire()
{
return xfire;
}
protected ServiceRegistry getServiceRegistry()
{
return getXFire().getServiceRegistry();
}
protected InputStream getResourceAsStream( String resource )
{
return getClass().getResourceAsStream( resource );
}
protected Reader getResourceAsReader( String resource )
{
return new InputStreamReader( getResourceAsStream( resource ) );
}
public File getTestFile( String relativePath )
{
String basedir = System.getProperty( "basedir" );
if( basedir == null )
basedir = "./";
return new File( new File( basedir ), relativePath );
}
}
|
package com.mcb;
import com.mcb.owner.Application;
import com.ning.http.client.*;
import com.ning.http.client.multipart.FilePart;
import org.aeonbits.owner.ConfigFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static spark.Spark.*;
/**
* GmPoster App
*/
public class App {
Logger logger = Logger.getLogger(App.class.getName());
private final String[] args;
private final Application cfg;
public static void main(String[] args) {
Logger.getGlobal().setLevel(Level.INFO);
App app = new App(args);
app.bootstrap();
}
public App(String... args) {
this.args = args;
this.cfg = ConfigFactory.create(Application.class);
}
public void bootstrap() {
System.out.println("Server Port" + +this.cfg.port());
port(this.cfg.port());
if (!this.cfg.disableCors()) {
// Adds CORS headers
enableCORS(this.cfg.corsAllowOrigin(), this.cfg.corsRequestMethod(), this.cfg.corsAllowHeaders());
}
get("/" + this.cfg.routeName()+ "/test", (req, res) -> {
return "test request, endpoint is up";
});
get("/" + this.cfg.routeName(), (req, res) -> {
logger.log(Level.INFO, req.body());
ListenableFuture<Response> future = postIt();
if (future != null) {
Response r = future.get();
r.getCookies().stream().map(cookie -> {
res.cookie(cookie.getName(), cookie.getValue());
return res;
});
r.getHeaders().keySet().stream()
.map(h -> {
String v = r.getHeaders(h).stream().map(hv -> hv)
.collect(Collectors.joining("; "));
res.header(h, v);
return res;
});
res.status(200);
res.body(r.getResponseBody());
res.type(r.getContentType());
if (r.getStatusCode() == this.cfg.remoteStatusExpected()) {
logger.info(r.getResponseBody());
res.status(200);
} else {
logger.warning(r.getResponseBody());
res.status(r.getStatusCode());
}
return res.body();
} else {
logger.warning("no content to be processed; check if the file: " + cfg.fileToPost() + " exists and is readable.");
res.status(HttpServletResponse.SC_NO_CONTENT);
return "";
}
});
}
private void enableCORS(final String origin, final String methods, final String headers) {
before((req, res) -> {
res.header("Access-Control-Allow-Origin", origin);
res.header("Access-Control-Request-Method", methods);
res.header("Access-Control-Allow-Headers", headers);
}
);
}
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
/***
* Returns the name of the Authorization header
*
* @return String name of the Authorization Header
*/
private String getAuthHeaderName() {
return cfg.remoteAuthHeaderName();
}
/***
* Returns a Credential to be used in a designated Authorization header
* <p>
* TODO: implement other Auth types
*
* @return String value of the Authorization Header
*/
private String getAuthHeaderValue() {
return cfg.remoteAuthHeaderValue();
}
/***
* Returns a Credential to be used in a designated Authorization header
* <p>
* TODO: implement other Auth types
*
* @return @link Realm object for use in Authentication
*/
private Realm getAuthRealm() {
String type = cfg.remoteAuthType();
if (type != null) {
if ("BASIC".toLowerCase().equals(type.toLowerCase())) {
String user = cfg.remoteAuthUsername();
String pass = cfg.remoteAuthPassword();
String encoded = Base64.getEncoder().encodeToString((user + ':' + pass).getBytes(StandardCharsets.UTF_8));
Realm.RealmBuilder realm = new Realm.RealmBuilder();
realm.setPassword(pass)
.setPrincipal(user)
.setScheme(Realm.AuthScheme.BASIC)
.setUsePreemptiveAuth(true);
return realm.build();
}
if ("DIGEST".toLowerCase().equals(type.toLowerCase())) {
String user = cfg.remoteAuthUsername();
String pass = cfg.remoteAuthPassword();
String encoded = Base64.getEncoder().encodeToString((user + ':' + pass).getBytes(StandardCharsets.UTF_8));
Realm.RealmBuilder realm = new Realm.RealmBuilder();
realm.setPassword(pass)
.setPrincipal(user)
.setScheme(Realm.AuthScheme.DIGEST)
.setUsePreemptiveAuth(true);
return realm.build();
}
}
return null;
}
/***
* Posts to the indicated url
* <p>
* TODO: implement other Auth types
*
* @return a @link ListenableFuture<Response>
*/
private ListenableFuture<Response> postIt() {
File toPost = new File(cfg.fileToPost());
if (!toPost.exists()) {
return null;
}
String url = cfg.remoteUrl();
AsyncHttpClient.BoundRequestBuilder builder = asyncHttpClient.preparePost(url)
.addBodyPart(new FilePart(toPost.getName(), toPost));
Realm realm = getAuthRealm();
if (realm != null) {
builder.setRealm(realm);
} else if (getAuthHeaderValue() != null && getAuthHeaderName() != null) {
builder.addHeader(getAuthHeaderName(), getAuthHeaderValue());
}
ListenableFuture<Response> result = builder.execute(new AsyncCompletionHandler<Response>() {
@Override
public Response onCompleted(Response response) throws Exception {
return response;
}
@Override
public void onThrowable(Throwable t) {
// Something wrong happened.
if (logger.isLoggable(Level.FINER)) {
logger.log(Level.WARNING, t.getLocalizedMessage(), t);
} else {
logger.warning(t.getLocalizedMessage());
}
}
});
return result;
}
}
|
package cronapi;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import cronapi.i18n.Messages;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Var implements Comparable, JsonSerializable {
public enum Type {
STRING, INT, DOUBLE, LIST, NULL, UNKNOWN, BOOLEAN, DATETIME
};
private String id;
private Type _type;
private Object _object;
private boolean modifiable = true;
private boolean created = false;
private static final NumberFormat _formatter = new DecimalFormat("
public static final Var VAR_NULL = new Var(null, false);
public static final Var VAR_TRUE = new Var(true, false);
public static final Var VAR_FALSE = new Var(false, false);
public static final Var VAR_ZERO = new Var(0, false);
public static final Var VAR_ONE = new Var(1, false);
public static final Var VAR_NEGATIVE_ONE = new Var(-1, false);
public static final Var VAR_EMPTY = new Var("", false);
public static final Var VAR_DATE_ZERO;
static {
Calendar calendar = Calendar.getInstance();
calendar.set(1980, 1, 1, 0, 0, 0);
VAR_DATE_ZERO = new Var(calendar, false);
}
/**
* Construct a Var with an NULL type
*
*/
public Var() {
_type = Type.NULL;
created = true;
}
/**
* Construct a Var and assign its contained object to that specified.
*
* @param object The value to set this object to
*/
public Var(String id, Object object) {
this.id = id;
setObject(object);
}
/**
* Construct a Var and assign its contained object to that specified.
*
* @param object The value to set this object to
*/
public Var(Object object) {
setObject(object);
}
public Var(Object object, boolean modifiable) {
setObject(object);
this.modifiable = modifiable;
}
/**
* Construct a Var from a given Var
*
* @param var var to construct this one from
*/
public Var(Var var) {
_type = Type.UNKNOWN;
if (var!=null) {
this.id = var.id;
setObject(var.getObject());
}
}
/**
* Set the value of the underlying object. Note that the type of Var will be
* determined when setObject is called.
*
* @param val the value to set this Var to
*/
public void setObject(Object val) {
if (created && !modifiable) {
throw new RuntimeException(Messages.getString("NotModifiable"));
}
this._object = val;
inferType();
// make sure each element of List is Var if type is list
if (_type.equals(Var.Type.LIST)) {
LinkedList<Var> myList = new LinkedList<>();
for (Object obj : this.getObjectAsList()) {
myList.add(Var.valueOf(obj));
}
this._object = myList;
}
created = true;
}
/**
* Static constructor to make a var from some value.
*
* @param val some value to construct a var around
* @return the Var object
*/
public static Var valueOf(Object val) {
if (val instanceof Var)
return (Var) val;
if (val instanceof Boolean) {
if (((Boolean) val)) {
return VAR_TRUE;
} else {
return VAR_FALSE;
}
}
if (val == null) {
return VAR_NULL;
}
return new Var(val);
}
public static Var valueOf(String id, Object val) {
if (val instanceof Var && Objects.equals(((Var) val).getId(), id))
return (Var) val;
return new Var(id, val);
}
/**
* Get the type of the underlying object
*
* @return Will return the object's type as defined by Type
*/
public Type getType() {
return _type;
}
public String getId() {
return this.id;
}
/**
* Get the contained object
*
* @return the object
*/
public Object getObject() {
return _object;
}
/**
* Clone Object
*
* @return a new object equal to this one
*/
public Object cloneObject() {
Var tempVar = new Var(this);
return tempVar.getObject();
}
/**
* Get object as an int. Does not make sense for a "LIST" type object
*
* @return an integer whose value equals this object
*/
public Integer getObjectAsInt() {
switch (getType()) {
case STRING:
return Integer.parseInt(((String) getObject()));
case INT:
return ((Long) getObject()).intValue();
case BOOLEAN:
return ((Boolean) getObject()) ? 1 : 0;
case DOUBLE:
return new Double((double) getObject()).intValue();
case DATETIME:
return (int)(((Calendar) getObject()).getTimeInMillis());
case LIST:
// has no meaning
break;
default:
// has no meaning
break;
}
return 0;
}
/**
* Get object as an int. Does not make sense for a "LIST" type object
*
* @return an integer whose value equals this object
*/
public Long getObjectAsLong() {
switch (getType()) {
case STRING:
return Long.parseLong((String) getObject());
case INT:
return (Long) getObject();
case BOOLEAN:
return ((Boolean) getObject()) ? 1L : 0L;
case DOUBLE:
return new Double((double) getObject()).longValue();
case DATETIME:
return (Long)((Calendar) getObject()).getTimeInMillis();
case LIST:
// has no meaning
break;
default:
// has no meaning
break;
}
return 0L;
}
/**
* Get object as an boolean.
*
* @return an bool whose value equals this object
*/
public Calendar getObjectAsDateTime() {
switch (getType()) {
case STRING:
String s = (String) getObject();
return Utils.toCalendar(s, null);
case INT:
Calendar c = Calendar.getInstance();
c.setTimeInMillis(getObjectAsInt());
return c;
case DOUBLE:
Calendar cd = Calendar.getInstance();
cd.setTimeInMillis(getObjectAsInt());
return cd;
case DATETIME:
return (Calendar) getObject();
case LIST:
// has no meaning
break;
default:
// has no meaning
break;
}
return null;
}
/**
* Get object as an boolean.
*
* @return an bool whose value equals this object
*/
public Boolean getObjectAsBoolean() {
switch (getType()) {
case STRING:
String s = (String) getObject();
if (s.equals("1") || s.equalsIgnoreCase("true")) {
s = "true";
} else {
s = "false";
}
return Boolean.valueOf(s);
case INT:
return (Long) getObject() > 0;
case BOOLEAN:
return (boolean) getObject();
case DOUBLE:
return new Double((double) getObject()).intValue() > 0;
case DATETIME:
//has no meaning
break;
case LIST:
// has no meaning
break;
default:
// has no meaning
break;
}
return false;
}
/**
* Get object as a double. Does not make sense for a "LIST" type object.
*
* @return a double whose value equals this object
*/
public Double getObjectAsDouble() {
switch (getType()) {
case STRING:
return Double.parseDouble((String) getObject());
case INT:
return new Long((Long) getObject()).doubleValue();
case BOOLEAN:
return ((boolean) getObject()) ? 1.0 : 0.0;
case DOUBLE:
return (double) getObject();
case DATETIME:
return (double)((Calendar) getObject()).getTimeInMillis();
case LIST:
// has no meaning
break;
default:
// has no meaning
break;
}
return 0.0;
}
/**
* Get object as a string.
*
* @return The string value of the object. Note that for lists, this is a
* comma separated list of the form {x,y,z,...}
*/
public String getObjectAsString() {
return this.toString();
}
/**
* Get the object as a list.
*
* @return a LinkedList whose elements are of type Var
*/
public LinkedList<Var> getObjectAsList() {
return (LinkedList<Var>) getObject();
}
public Iterator<Var> iterator() {
return getObjectAsList().iterator();
}
/**
* If this object is a linked list, then calling this method will return the
* Var at the index indicated
*
* @param index the index of the Var to read (0 based)
* @return the Var at that index
*/
public Var get(int index) {
return ((LinkedList<Var>) getObject()).get(index);
}
/**
* If this object is a linked list, then calling this method will return the
* size of the linked list.
*
* @return size of list
*/
public int size() {
return ((LinkedList<Var>) getObject()).size();
}
public int length() {
return getObjectAsString().length();
}
public void trim() {
setObject(getObjectAsString().trim());
}
public static Var newList() {
return new Var(new LinkedList<>());
}
/**
* Set the value of of a list at the index specified. Note that this is only
* value if this object is a list and also note that index must be in
* bounds.
*
* @param index the index into which the Var will be inserted
* @param var the var to insert
*/
public void set(int index, Var var) {
((LinkedList<Var>) getObject()).add(index, var);
}
/**
* Add all values from one List to another. Both lists are Var objects that
* contain linked lists.
*
* @param var The list to add
*/
public void addAll(Var var) {
((LinkedList<Var>) getObject()).addAll(var.getObjectAsList());
}
@Override
public int hashCode() {
int hash = 5;
hash = 43 * hash + Objects.hashCode(this._type);
hash = 43 * hash + Objects.hashCode(this._object);
return hash;
}
/**
* Test to see if this object equals another one. This is done by converting
* both objects to strings and then doing a string compare.
*
* @param obj
* @return true if equals
*/
@Override
public boolean equals(Object obj) {
final Var other = Var.valueOf(obj);
if (getType() == Var.Type.NULL || other.getType() == Var.Type.NULL) {
return getType().equals(other.getType());
}
return this.toString().equals(other.toString());
}
public void inc(Object value) {
Object result = null;
switch (getType()) {
case DATETIME: {
getObjectAsDateTime().add(Calendar.DAY_OF_MONTH, Var.valueOf(value).getObjectAsInt());
break;
}
case INT: {
result = getObjectAsLong() + Var.valueOf(value).getObjectAsLong();
break;
}
default: {
result = getObjectAsDouble() + Var.valueOf(value).getObjectAsDouble();
}
}
if (result != null)
setObject(result);
}
public void multiply(Object value) {
Object result = null;
switch (getType()) {
case INT: {
result = getObjectAsLong() * Var.valueOf(value).getObjectAsLong();
break;
}
default: {
result = getObjectAsDouble() * Var.valueOf(value).getObjectAsDouble();
}
}
if (result != null)
setObject(result);
}
public Var append(Object value) {
Object result = getObjectAsString() + (value!= null?value.toString():"");
setObject(result);
return this;
}
/**
* Check to see if this Var is less than some other var.
*
* @param var the var to compare to
* @return true if it is less than
*/
public boolean lessThan(Var var) {
return this.compareTo(var) < 0;
}
/**
* Check to see if this var is less than or equal to some other var
*
* @param var the var to compare to
* @return true if this is less than or equal to var
*/
public boolean lessThanOrEqual(Var var) {
return this.compareTo(var) <= 0;
}
/**
* Check to see if this var is greater than a given var.
*
* @param var the var to compare to.
* @return true if this object is grater than the given var
*/
public boolean greaterThan(Var var) {
return this.compareTo(var) > 0;
}
/**
* Check to see if this var is greater than or equal to a given var
*
* @param var the var to compare to
* @return true if this var is greater than or equal to the given var
*/
public boolean greaterThanOrEqual(Var var) {
return this.compareTo(var) >= 0;
}
/**
* Compare this object's value to another
*
* @param val the object to compare to
* @return the value 0 if this is equal to the argument; a value less than 0
* if this is numerically less than the argument; and a value greater than 0
* if this is numerically greater than the argument (signed comparison).
*/
@Override
public int compareTo(Object val) {
// only instantiate if val is not instance of Var
Var var;
if (val instanceof Var) {
var = (Var) val;
} else {
var = new Var(val);
}
switch (getType()) {
case STRING:
return this.getObjectAsString().compareTo(var.getObjectAsString());
case INT:
if (var.getType().equals(Var.Type.INT)) {
return ((Long) this.getObjectAsLong()).compareTo(var.getObjectAsLong());
} else {
return ((Double) this.getObjectAsDouble()).compareTo(var.getObjectAsDouble());
}
case DOUBLE:
return ((Double) this.getObjectAsDouble()).compareTo(var.getObjectAsDouble());
case BOOLEAN:
return this.getObjectAsBoolean().compareTo(var.getObjectAsBoolean());
case DATETIME:
return this.getObjectAsDateTime().compareTo(var.getObjectAsDateTime());
case LIST:
// doesn't make sense
return Integer.MAX_VALUE;
default:
// doesn't make sense
return Integer.MAX_VALUE;
}
}
/**
* Convert this Var to a string format.
*
* @return the string format of this var
*/
@Override
public String toString() {
switch (getType()) {
case STRING:
return getObject().toString();
case INT:
Long i = (Long) getObject();
return i.toString();
case DOUBLE:
Double d = (double) _object;
return _formatter.format(d);
case DATETIME:
return Utils.getDateFormat().format(((Calendar)getObject()).getTime());
case LIST:
LinkedList<Var> ll = (LinkedList) getObject();
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Var v : ll) {
if (first) {
first = false;
sb.append("{");
} else {
sb.append(", ");
}
sb.append(v.toString());
}
sb.append("}");
return sb.toString();
case NULL:
return null;
default:
if (getObject() == null)
return "";
return getObject().toString();
}
}
public Var negate() {
if (getObjectAsBoolean()) {
return VAR_FALSE;
}
return VAR_TRUE;
}
/**
* Internal method for inferring the "object type" of this object. When it
* is done, it sets the private member value of _type. This will be
* referenced later on when various method calls are made on this object.
*/
private void inferType() {
if (_object == null) {
_type = Type.NULL;
} else if (_object instanceof Var) {
Var oldObj = (Var) _object;
_type = oldObj.getType();
_object = oldObj.getObject();
if (id == null)
id = oldObj.id;
} else if (_object instanceof String || _object instanceof StringBuilder || _object instanceof StringBuffer
|| _object instanceof Character) {
_type = Type.STRING;
_object = _object.toString();
} else if (_object instanceof Boolean) {
_type = Type.BOOLEAN;
} else if (_object instanceof Date) {
Date date = (Date) _object;
_type = Type.DATETIME;
_object = Calendar.getInstance();
((Calendar) _object).setTime(date);
} else if (_object instanceof Calendar) {
_type = Type.DATETIME;
} else if (_object instanceof Long) {
_type = Type.INT;
} else if (_object instanceof Integer) {
_type = Type.INT;
_object = Long.valueOf((Integer)_object);
} else if (_object instanceof Double) {
_type = Type.DOUBLE;
} else if (_object instanceof Float) {
_type = Type.DOUBLE;
_object = Double.valueOf((Float)_object);
} else if (_object instanceof BigDecimal) {
if (((BigDecimal) _object).scale() == 0) {
_type = Type.INT;
_object = ((BigDecimal) _object).longValue();
} else {
_type = Type.DOUBLE;
_object = ((BigDecimal) _object).doubleValue();
}
} else if (_object instanceof BigInteger) {
_type = Type.INT;
_object = ((BigInteger) _object).longValue();
} else if (_object instanceof LinkedList) {
_type = Type.LIST;
} else if (_object instanceof List) {
_type = Type.LIST;
_object = new LinkedList<>((List) _object);
} else {
_type = Type.UNKNOWN;
}
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (id != null) {
gen.writeStartObject();
gen.writeObjectField(id, _object);
gen.writeEndObject();
} else {
gen.writeObject(_object);
}
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
if (id != null) {
gen.writeStartObject();
gen.writeObjectField(id, _object);
gen.writeEndObject();
} else {
gen.writeObject(_object);
}
}
}
|
package org.json;
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONArray or
* JSONObject, and to covert a JSONArray or JSONObject into an XML text using
* the JsonML transform.
* @author JSON.org
* @version 2011-11-24
*/
public class JSONML {
/**
* Parse XML values and store them in a JSONArray.
* @param x The XMLTokener containing the source string.
* @param arrayForm true if array form, false if object form.
* @param ja The JSONArray that is containing the current tag or null
* if we are at the outermost level.
* @return A JSONArray if the value is the outermost tag, otherwise null.
* @throws JSONException
*/
private static Object parse(
XMLTokener x,
boolean arrayForm,
JSONArray ja
) throws JSONException {
String attribute;
char c;
String closeTag = null;
int i;
JSONArray newja = null;
JSONObject newjo = null;
Object token;
String tagName = null;
// Test for and skip past these forms:
while (true) {
if (!x.more()) {
throw x.syntaxError("Bad XML");
}
token = x.nextContent();
if (token == XML.LT) {
token = x.nextToken();
if (token instanceof Character) {
if (token == XML.SLASH) {
// Close tag </
token = x.nextToken();
if (!(token instanceof String)) {
throw new JSONException(
"Expected a closing name instead of '" +
token + "'.");
}
if (x.nextToken() != XML.GT) {
throw x.syntaxError("Misshaped close tag");
}
return token;
} else if (token == XML.BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("
}
x.back();
} else if (c == '[') {
token = x.nextToken();
if (token.equals("CDATA") && x.next() == '[') {
if (ja != null) {
ja.put(x.nextCDATA());
}
} else {
throw x.syntaxError("Expected 'CDATA['");
}
} else {
i = 1;
do {
token = x.nextMeta();
if (token == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (token == XML.LT) {
i += 1;
} else if (token == XML.GT) {
i -= 1;
}
} while (i > 0);
}
} else if (token == XML.QUEST) {
x.skipPast("?>");
} else {
throw x.syntaxError("Misshaped tag");
}
// Open tag <
} else {
if (!(token instanceof String)) {
throw x.syntaxError("Bad tagName '" + token + "'.");
}
tagName = (String)token;
newja = new JSONArray();
newjo = new JSONObject();
if (arrayForm) {
newja.put(tagName);
if (ja != null) {
ja.put(newja);
}
} else {
newjo.put("tagName", tagName);
if (ja != null) {
ja.put(newjo);
}
}
token = null;
for (;;) {
if (token == null) {
token = x.nextToken();
}
if (token == null) {
throw x.syntaxError("Misshaped tag");
}
if (!(token instanceof String)) {
break;
}
// attribute = value
attribute = (String)token;
if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
throw x.syntaxError("Reserved attribute.");
}
token = x.nextToken();
if (token == XML.EQ) {
token = x.nextToken();
if (!(token instanceof String)) {
throw x.syntaxError("Missing value");
}
newjo.accumulate(attribute, XML.stringToValue((String)token));
token = null;
} else {
newjo.accumulate(attribute, "");
}
}
if (arrayForm && newjo.length() > 0) {
newja.put(newjo);
}
// Empty tag <.../>
if (token == XML.SLASH) {
if (x.nextToken() != XML.GT) {
throw x.syntaxError("Misshaped tag");
}
if (ja == null) {
if (arrayForm) {
return newja;
} else {
return newjo;
}
}
// Content, between <...> and </...>
} else {
if (token != XML.GT) {
throw x.syntaxError("Misshaped tag");
}
closeTag = (String)parse(x, arrayForm, newja);
if (closeTag != null) {
if (!closeTag.equals(tagName)) {
throw x.syntaxError("Mismatched '" + tagName +
"' and '" + closeTag + "'");
}
tagName = null;
if (!arrayForm && newja.length() > 0) {
newjo.put("childNodes", newja);
}
if (ja == null) {
if (arrayForm) {
return newja;
} else {
return newjo;
}
}
}
}
}
} else {
if (ja != null) {
ja.put(token instanceof String
? XML.stringToValue((String)token)
: token);
}
}
}
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONArray using the JsonML transform. Each XML tag is represented as
* a JSONArray in which the first element is the tag name. If the tag has
* attributes, then the second element will be JSONObject containing the
* name/value pairs. If the tag contains children, then strings and
* JSONArrays will represent the child tags.
* Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored.
* @param string The source string.
* @return A JSONArray containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONArray toJSONArray(String string) throws JSONException {
return toJSONArray(new XMLTokener(string));
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONArray using the JsonML transform. Each XML tag is represented as
* a JSONArray in which the first element is the tag name. If the tag has
* attributes, then the second element will be JSONObject containing the
* name/value pairs. If the tag contains children, then strings and
* JSONArrays will represent the child content and tags.
* Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored.
* @param x An XMLTokener.
* @return A JSONArray containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
return (JSONArray)parse(x, true, null);
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as
* a JSONObject with a "tagName" property. If the tag has attributes, then
* the attributes will be in the JSONObject as properties. If the tag
* contains children, the object will have a "childNodes" property which
* will be an array of strings and JsonML JSONObjects.
* Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored.
* @param x An XMLTokener of the XML source text.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(XMLTokener x) throws JSONException {
return (JSONObject)parse(x, false, null);
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as
* a JSONObject with a "tagName" property. If the tag has attributes, then
* the attributes will be in the JSONObject as properties. If the tag
* contains children, the object will have a "childNodes" property which
* will be an array of strings and JsonML JSONObjects.
* Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored.
* @param string The XML source text.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
return toJSONObject(new XMLTokener(string));
}
/**
* Reverse the JSONML transformation, making an XML text from a JSONArray.
* @param ja A JSONArray.
* @return An XML string.
* @throws JSONException
*/
public static String toString(JSONArray ja) throws JSONException {
int i;
JSONObject jo;
String key;
Iterator keys;
int length;
Object object;
StringBuffer sb = new StringBuffer();
String tagName;
String value;
// Emit <tagName
tagName = ja.getString(0);
XML.noSpace(tagName);
tagName = XML.escape(tagName);
sb.append('<');
sb.append(tagName);
object = ja.opt(1);
if (object instanceof JSONObject) {
i = 2;
jo = (JSONObject)object;
// Emit the attributes
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
XML.noSpace(key);
value = jo.optString(key);
if (value != null) {
sb.append(' ');
sb.append(XML.escape(key));
sb.append('=');
sb.append('"');
sb.append(XML.escape(value));
sb.append('"');
}
}
} else {
i = 1;
}
//Emit content in body
length = ja.length();
if (i >= length) {
sb.append('/');
sb.append('>');
} else {
sb.append('>');
do {
object = ja.get(i);
i += 1;
if (object != null) {
if (object instanceof String) {
sb.append(XML.escape(object.toString()));
} else if (object instanceof JSONObject) {
sb.append(toString((JSONObject)object));
} else if (object instanceof JSONArray) {
sb.append(toString((JSONArray)object));
}
}
} while (i < length);
sb.append('<');
sb.append('/');
sb.append(tagName);
sb.append('>');
}
return sb.toString();
}
/**
* Reverse the JSONML transformation, making an XML text from a JSONObject.
* The JSONObject must contain a "tagName" property. If it has children,
* then it must have a "childNodes" property containing an array of objects.
* The other properties are attributes with string values.
* @param jo A JSONObject.
* @return An XML string.
* @throws JSONException
*/
public static String toString(JSONObject jo) throws JSONException {
StringBuffer sb = new StringBuffer();
int i;
JSONArray ja;
String key;
Iterator keys;
int length;
Object object;
String tagName;
String value;
//Emit <tagName
tagName = jo.optString("tagName");
if (tagName == null) {
return XML.escape(jo.toString());
}
XML.noSpace(tagName);
tagName = XML.escape(tagName);
sb.append('<');
sb.append(tagName);
//Emit the attributes
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
if (!"tagName".equals(key) && !"childNodes".equals(key)) {
XML.noSpace(key);
value = jo.optString(key);
if (value != null) {
sb.append(' ');
sb.append(XML.escape(key));
sb.append('=');
sb.append('"');
sb.append(XML.escape(value));
sb.append('"');
}
}
}
//Emit content in body
ja = jo.optJSONArray("childNodes");
if (ja == null) {
sb.append('/');
sb.append('>');
} else {
sb.append('>');
length = ja.length();
for (i = 0; i < length; i += 1) {
object = ja.get(i);
if (object != null) {
if (object instanceof String) {
sb.append(XML.escape(object.toString()));
} else if (object instanceof JSONObject) {
sb.append(toString((JSONObject)object));
} else if (object instanceof JSONArray) {
sb.append(toString((JSONArray)object));
} else {
sb.append(object.toString());
}
}
}
sb.append('<');
sb.append('/');
sb.append(tagName);
sb.append('>');
}
return sb.toString();
}
}
|
package example;
import org.immutables.value.Value;
class Foo {
public static void main(String[] args) {
String msg = ImmutableBar.builder().build().msg();
System.out.println(msg);
}
@Value.Immutable
public interface Bar {
@Value.Default
default String msg() {
return "bar";
}
}
}
|
package org.cache2k.benchmark;
import org.cache2k.benchmark.zoo.HashMapBenchmarkFactory;
import org.junit.Ignore;
/**
* @author Jens Wilke; created: 2013-06-13
*/
public class HashMapBenchmark extends BenchmarkCollection {
{
factory = new HashMapBenchmarkFactory();
}
@Ignore @Override
public void benchmarkMiss_500000() {}
@Ignore @Override
public void benchmarkMiss_50000() {}
}
|
package net.somethingdreadful.MAL.api.response;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.database.Cursor;
public class User {
private String name;
private String friend_since;
private Profile profile;
public static User fromCursor(Cursor c) {
return fromCursor(c, false);
}
public static User fromCursor(Cursor c, boolean friendDetails) {
User result = new User();
List<String> columnNames = Arrays.asList(c.getColumnNames());
result.setName(c.getString(columnNames.indexOf("username")));
if ( friendDetails )
result.setFriendSince(c.getString(columnNames.indexOf("friend_since")));
result.setProfile(Profile.fromCursor(c, friendDetails));
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFriendSince() {
return friend_since;
}
public void setFriendSince(String friend_since) {
this.friend_since = friend_since;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
public static boolean isDeveloperRecord(String name){
String[] developers = {
"ratan12",
"animasa",
"motokochan",
"apkawa",
"d-sko"
};
return Arrays.asList(developers).contains(name.toLowerCase(Locale.US));
}
}
|
package org.intermine.web;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Collection;
import java.util.Date;
import java.math.BigDecimal;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.AttributeDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryCollectionReference;
import org.intermine.objectstore.query.QueryEvaluable;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryFunction;
import org.intermine.objectstore.query.QueryNode;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.QueryReference;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.objectstore.query.ClassConstraint;
import org.intermine.objectstore.ObjectStore;
import org.intermine.util.TypeUtil;
import org.intermine.util.StringUtil;
import org.intermine.web.bag.InterMineBag;
import org.intermine.web.bag.InterMineIdBag;
/**
* Helper methods for main controller and main action
* @author Mark Woodbridge
*/
public class MainHelper
{
/**
* Given a path, render a set of metadata Nodes to the relevant depth
* @param path of form Gene.organism.name
* @param model the model used to resolve class names
* @return an ordered Set of nodes
*/
public static Collection makeNodes(String path, Model model) {
String className, subPath;
if (path.indexOf(".") == -1) {
className = path;
subPath = "";
} else {
className = path.substring(0, path.indexOf("."));
subPath = path.substring(path.indexOf(".") + 1);
}
Map nodes = new LinkedHashMap();
nodes.put(className, new MetadataNode(className));
makeNodes(getClassDescriptor(className, model), subPath, className, nodes);
return nodes.values();
}
/**
* Recursive method used to add nodes to a set representing a path from a given ClassDescriptor
* @param cld the root ClassDescriptor
* @param path current path prefix (eg Gene)
* @param currentPath current path suffix (eg organism.name)
* @param nodes the current Node set
*/
protected static void makeNodes(ClassDescriptor cld, String path, String currentPath,
Map nodes) {
List sortedNodes = new ArrayList();
// compare FieldDescriptors by name
Comparator comparator = new Comparator() {
public int compare(Object o1, Object o2) {
String fieldName1 = ((FieldDescriptor) o1).getName().toLowerCase();
String fieldName2 = ((FieldDescriptor) o2).getName().toLowerCase();
return fieldName1.compareTo(fieldName2);
}
};
Set attributeNodes = new TreeSet(comparator);
Set referenceAndCollectionNodes = new TreeSet(comparator);
for (Iterator i = cld.getAllFieldDescriptors().iterator(); i.hasNext();) {
FieldDescriptor fd = (FieldDescriptor) i.next();
if (!fd.isReference() && !fd.isCollection()) {
attributeNodes.add(fd);
} else {
referenceAndCollectionNodes.add(fd);
}
}
sortedNodes.addAll(attributeNodes);
sortedNodes.addAll(referenceAndCollectionNodes);
for (Iterator i = sortedNodes.iterator(); i.hasNext();) {
FieldDescriptor fd = (FieldDescriptor) i.next();
String fieldName = fd.getName();
if (fieldName.equals("id")) {
continue;
}
String head, tail;
if (path.indexOf(".") != -1) {
head = path.substring(0, path.indexOf("."));
tail = path.substring(path.indexOf(".") + 1);
} else {
head = path;
tail = "";
}
String button;
if (fieldName.equals(head)) {
button = "-";
} else if (fd.isReference() || fd.isCollection()) {
button = "+";
} else {
button = " ";
}
MetadataNode parent = (MetadataNode) nodes.get(currentPath);
MetadataNode node = new MetadataNode(parent, fieldName, button);
node.setModel(cld.getModel());
nodes.put(node.getPath(), node);
if (fieldName.equals(head)) {
ClassDescriptor refCld = ((ReferenceDescriptor) fd).getReferencedClassDescriptor();
makeNodes(refCld, tail, currentPath + "." + head, nodes);
}
}
}
/**
* Make an InterMine query from a path query
* @param query the PathQuery
* @param savedBags the current saved bags map
* @return an InterMine Query
*/
public static Query makeQuery(PathQuery query, Map savedBags, ObjectStore os) {
return makeQuery(query, savedBags, null, os);
}
/**
* Make an InterMine query from a path query
* @param query the PathQuery
* @param savedBags the current saved bags map
* @param pathToQueryNode optional parameter in which path to QueryNode map can be returned
* @param os ObjectStore from which to load objects for bags
* @return an InterMine Query
*/
public static Query makeQuery(PathQuery query, Map savedBags, Map pathToQueryNode,
ObjectStore os) {
query = (PathQuery) query.clone();
Map qNodes = query.getNodes();
List view = query.getView();
Model model = query.getModel();
//first merge the query and the view
for (Iterator i = view.iterator(); i.hasNext();) {
String path = (String) i.next();
if (!qNodes.containsKey(path)) {
query.addNode(path);
}
}
//create the real query
Query q = new Query();
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
q.setConstraint(cs);
Map queryBits = new HashMap();
//build the FROM and WHERE clauses
for (Iterator i = query.getNodes().values().iterator(); i.hasNext();) {
PathNode node = (PathNode) i.next();
String path = node.getPath();
QueryReference qr = null;
if (path.indexOf(".") == -1) {
QueryClass qc = new QueryClass(getClass(node.getType(), model));
q.addFrom(qc);
queryBits.put(path, qc);
} else {
String fieldName = node.getFieldName();
QueryClass parentQc = (QueryClass) queryBits.get(node.getPrefix());
if (node.isAttribute()) {
QueryField qf = new QueryField(parentQc, fieldName);
queryBits.put(path, qf);
} else {
if (node.isReference()) {
qr = new QueryObjectReference(parentQc, fieldName);
} else {
qr = new QueryCollectionReference(parentQc, fieldName);
}
QueryClass qc = new QueryClass(getClass(node.getType(), model));
cs.addConstraint(new ContainsConstraint(qr, ConstraintOp.CONTAINS, qc));
q.addFrom(qc);
queryBits.put(path, qc);
}
}
QueryNode qn = (QueryNode) queryBits.get(path);
for (Iterator j = node.getConstraints().iterator(); j.hasNext();) {
Constraint c = (Constraint) j.next();
if (BagConstraint.VALID_OPS.contains(c.getOp())) {
Collection bag = (Collection) savedBags.get(c.getValue());
// = ((InterMineBag) savedBags.get(c.getValue())).toObjectCollection(os);
if (bag instanceof InterMineIdBag) {
// constrain the id of the object
QueryField qf = new QueryField((QueryClass) qn, "id");
cs.addConstraint(new BagConstraint(qf, c.getOp(), bag));
} else {
cs.addConstraint(new BagConstraint(qn,
c.getOp(),
bag));
}
} else if (node.isAttribute()) { //assume, for now, that it's a SimpleConstraint
if (c.getOp() == ConstraintOp.IS_NOT_NULL
|| c.getOp() == ConstraintOp.IS_NULL) {
cs.addConstraint(new SimpleConstraint((QueryEvaluable) qn,
c.getOp()));
} else {
if (qn.getType().equals(String.class)) {
// do a case-insensitive search
QueryFunction qf = new QueryFunction((QueryField) qn,
QueryFunction.LOWER);
String lowerCaseValue = ((String) c.getValue()).toLowerCase();
cs.addConstraint(new SimpleConstraint(qf,
c.getOp(),
new QueryValue(lowerCaseValue)));
} else {
cs.addConstraint(new SimpleConstraint((QueryField) qn,
c.getOp(),
new QueryValue(c.getValue())));
}
}
} else if (node.isReference()) {
if (c.getOp() == ConstraintOp.IS_NOT_NULL
|| c.getOp() == ConstraintOp.IS_NULL) {
cs.addConstraint(
new ContainsConstraint((QueryObjectReference) qr, c.getOp()));
}
}
}
}
// Now process loop constraints. The constraint parameter refers backwards and
// forwards in the query so we can't process these in the above loop.
for (Iterator i = query.getNodes().values().iterator(); i.hasNext();) {
PathNode node = (PathNode) i.next();
String path = node.getPath();
QueryNode qn = (QueryNode) queryBits.get(path);
for (Iterator j = node.getConstraints().iterator(); j.hasNext();) {
Constraint c = (Constraint) j.next();
if (node.isReference() && c.getOp() != ConstraintOp.IS_NOT_NULL
&& c.getOp() != ConstraintOp.IS_NULL) {
QueryClass refQc = (QueryClass) queryBits.get(c.getValue());
cs.addConstraint(new ClassConstraint((QueryClass) qn, c.getOp(), refQc));
}
}
}
//build the SELECT list
for (Iterator i = view.iterator(); i.hasNext();) {
q.addToSelect((QueryNode) queryBits.get((String) i.next()));
}
//caller might want path to query node map (e.g. PrecomputeTask)
if (pathToQueryNode != null) {
pathToQueryNode.putAll(queryBits);
}
return q;
}
/**
* Instantiate a class by unqualified name
* The name should be "InterMineObject" or the name of class in the model provided
* @param className the name of the class
* @param model the Model used to resolve class names
* @return the relevant Class
*/
public static Class getClass(String className, Model model) {
if ("InterMineObject".equals(className)) {
className = "org.intermine.model.InterMineObject";
} else {
className = model.getPackageName() + "." + className;
}
try {
return Class.forName(className);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Instantiate a class by unqualified name
* The name should be "Date" or that of a primitive container class such as "Integer"
* @param className the name of the class
* @return the relevant Class
*/
public static Class getClass(String className) {
Class cls = TypeUtil.instantiate(className);
if (cls == null) {
if ("Date".equals(className)) {
cls = Date.class;
} else {
try {
cls = Class.forName("java.lang." + className);
} catch (Exception e) {
}
}
}
return cls;
}
/**
* Get the metadata for a class by unqualified name
* The name is looked up in the provided model
* @param className the name of the class
* @param model the Model used to resolve class names
* @return the relevant ClassDescriptor
*/
public static ClassDescriptor getClassDescriptor(String className, Model model) {
return model.getClassDescriptorByName(getClass(className, model).getName());
}
/**
* Take a Collection of ConstraintOps and builds a map from ConstraintOp.getIndex() to
* ConstraintOp.toString() for each
* @param ops a Collection of ConstraintOps
* @return the Map from index to string
*/
public static Map mapOps(Collection ops) {
Map opString = new LinkedHashMap();
for (Iterator iter = ops.iterator(); iter.hasNext();) {
ConstraintOp op = (ConstraintOp) iter.next();
opString.put(op.getIndex(), op.toString());
}
return opString;
}
/**
* Create constraint values for display. Returns a Map from Constraint to String
* for each Constraint in the path query.
*
* @param pathquery the PathQuery to look at
* @return Map from Constraint to displat value
*/
public static Map makeConstraintDisplayMap(PathQuery pathquery) {
Map map = new HashMap();
Iterator iter = pathquery.getNodes().values().iterator();
while (iter.hasNext()) {
PathNode node = (PathNode) iter.next();
Iterator citer = node.getConstraints().iterator();
while (citer.hasNext()) {
Constraint con = (Constraint) citer.next();
ConstraintOp op = con.getOp();
map.put(con, con.getDisplayValue(node));
}
}
return map;
}
/**
* Return the qualified name of the given unqualified class name. The className must be in the
* given model or in the java.lang package or one of java.util.Date or java.math.BigDecimal.
* @param className the name of the class
* @param model the Model used to resolve class names
* @return the fully qualified name of the class
* @throws ClassNotFoundException if the class can't be found
*/
public static String getQualifiedTypeName(String className, Model model)
throws ClassNotFoundException {
if (className.indexOf(".") != -1) {
throw new IllegalArgumentException("Expected an unqualified class name: " + className);
}
if (TypeUtil.instantiate(className) != null) {
// a primative type
return className;
} else {
if ("InterMineObject".equals(className)) {
return "org.intermine.model.InterMineObject";
} else {
try {
return Class.forName(model.getPackageName() + "." + className).getName();
} catch (ClassNotFoundException e) {
// fall through and try java.lang
}
}
if ("Date".equals(className)) {
return Date.class.getName();
}
if ("BigDecimal".equals(className)) {
return BigDecimal.class.getName();
}
return Class.forName("java.lang." + className).getName();
}
}
/**
* Given a path, find out whether it represents an attribute or a reference/collection.
*
* @param path the path
* @param pathQuery the path query
* @return true if path ends with an attribute, false if not
*/
public static boolean isPathAttribute(String path, PathQuery pathQuery) {
String classname = getTypeForPath(path, pathQuery);
return !(classname.startsWith(pathQuery.getModel().getPackageName())
|| classname.endsWith("InterMineObject"));
}
public static String getTypeForPath(String path, PathQuery pathQuery) {
// find the longest path that has a type stored in the pathQuery, then use the model to find
// the type of the last node
if (path == null) {
throw new IllegalArgumentException("path argument cannot be null");
}
if (pathQuery == null) {
throw new IllegalArgumentException("pathQuery argument cannot be null");
}
Model model = pathQuery.getModel();
PathNode testPathNode = (PathNode) pathQuery.getNodes().get(path);
if (testPathNode != null) {
try {
return getQualifiedTypeName(testPathNode.getType(), model);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("class \"" + testPathNode.getType()
+ "\" not found");
}
}
String[] bits = path.split("[.]");
List bitsList = new ArrayList(Arrays.asList(bits));
String prefix = null;
while (bitsList.size() > 0) {
prefix = StringUtil.join(bitsList, ".");
if (pathQuery.getNodes().get(prefix) != null) {
break;
}
bitsList.remove(bitsList.size() - 1);
}
// the longest path prefix that has an entry in the PathQuery
String longestPrefix = prefix;
ClassDescriptor cld;
if (bitsList.size() == 0) {
try {
cld = model.getClassDescriptorByName(getQualifiedTypeName(bits[0], model));
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("class \"" + bits[0] + "\" not found");
}
} else {
PathNode pn = (PathNode) pathQuery.getNodes().get(longestPrefix);
cld = getClassDescriptor(pn.getType(), model);
}
int startIndex = bitsList.size();
if (startIndex < 1) {
startIndex = 1;
}
for (int i = startIndex; i < bits.length; i++) {
FieldDescriptor fd = cld.getFieldDescriptorByName(bits[i]);
if (fd == null) {
throw new IllegalArgumentException("could not find descriptor for: " + bits[i]
+ " in " + cld.getName());
}
if (fd.isAttribute()) {
return ((AttributeDescriptor) fd).getType();
} else {
cld = ((ReferenceDescriptor) fd).getReferencedClassDescriptor();
}
}
return cld.getName();
}
}
|
package org.voovan.tools.collection;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
public class EventMap<K, V> implements Map {
public enum EventType {
CREATE,
GET,
PUT,
PUT_ALL,
REMOVE,
CLEAR
}
public class EventItem<K,V> {
private Map<K,V> parent;
private K key;
private V value;
private Map data;
public EventItem(Map<K,V> parent) {
this.parent = parent;
}
public EventItem(Map<K,V> parent, K key) {
this.parent = parent;
this.key = key;
}
public EventItem(Map<K,V> parent, K key, V value) {
this.parent = parent;
this.key = key;
this.value = value;
}
public EventItem(Map<K,V> parent, Map data) {
this.parent = parent;
this.data = data;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public Map getData() {
return data;
}
@Override
public String toString() {
return "EventItem{" +
"key=" + key +
", value=" + value +
", data=" + data +
'}';
}
}
private Map<K, V> conatiner;
private BiFunction<EventType, EventItem, Boolean> event;
public EventMap(Map<K, V> contianer, BiFunction<EventType, EventItem, Boolean> event) {
if(contianer == null) {
throw new NullPointerException("the contianer param is null");
}
if(event == null) {
throw new NullPointerException("the event param is null");
}
this.event = event;
if(this.event.apply(EventType.CREATE, new EventItem<K, V>(this, contianer))) {
this.conatiner = contianer;
}
}
public BiFunction<EventType, EventItem, Boolean> getEvent() {
return event;
}
public void setEvent(BiFunction<EventType, EventItem, Boolean> onEvent) {
if(event == null) {
throw new NullPointerException("the event param is null");
}
this.event = onEvent;
}
public Map<K, V> getConatiner() {
return conatiner;
}
@Override
public int size() {
return conatiner.size();
}
@Override
public boolean isEmpty() {
return conatiner.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return conatiner.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return conatiner.containsValue(value);
}
@Override
public V get(Object key) {
if(event.apply(EventType.GET, new EventItem<K, V>(this, (K)key))) {
return conatiner.get(key);
} else {
return null;
}
}
@Override
public V put(Object key, Object value) {
if(event.apply(EventType.PUT, new EventItem<K, V>(this, (K)key, (V)value))) {
return conatiner.put((K) key, (V) value);
} else {
return null;
}
}
@Override
public V remove(Object key) {
if(event.apply(EventType.REMOVE, new EventItem<K, V>(this, (K)key))) {
return conatiner.remove(key);
} else {
return null;
}
}
@Override
public void putAll(Map m) {
if(event.apply(EventType.PUT_ALL, new EventItem<K, V>(this, m))) {
conatiner.putAll(m);
}
}
@Override
public void clear() {
if(event.apply(EventType.CLEAR, new EventItem(this))) {
conatiner.clear();
}
}
@Override
public Set<K> keySet() {
return conatiner.keySet();
}
@Override
public Collection<V> values() {
return conatiner.values();
}
@Override
public Set<Entry<K,V>> entrySet() {
return conatiner.entrySet();
}
@Override
public String toString() {
return conatiner.toString();
}
}
|
package org.voovan.tools.collection;
import org.rocksdb.*;
import org.voovan.tools.TByte;
import org.voovan.tools.TFile;
import org.voovan.tools.Varint;
import org.voovan.tools.exception.ParseException;
import org.voovan.tools.exception.RocksMapException;
import org.voovan.tools.log.Logger;
import org.voovan.tools.serialize.TSerialize;
import java.io.Closeable;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
import java.util.Comparator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
public class RocksMap<K, V> implements SortedMap<K, V>, Closeable {
static {
RocksDB.loadLibrary();
}
public final static String DEFAULT_COLUMN_FAMILY_NAME = "voovan_default";
private static byte[] DATA_BYTES = "data".getBytes();
// db TransactionDB
private static Map<String, RocksDB> ROCKSDB_MAP = new ConcurrentHashMap<String, RocksDB>();
// TransactionDB
private static Map<RocksDB, List<ColumnFamilyHandle>> COLUMN_FAMILY_HANDLE_MAP = new ConcurrentHashMap<RocksDB, List<ColumnFamilyHandle>>();
private static ColumnFamilyDescriptor DEFAULE_CF_DESCRIPTOR = new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY);
private static String DEFAULT_DB_PATH = ".rocksdb"+ File.separator;
private static String DEFAULT_WAL_PATH = DEFAULT_DB_PATH + ".wal"+ File.separator;
/**
*
* @return
*/
public static String getDefaultDbPath() {
return DEFAULT_DB_PATH;
}
/**
*
* @param defaultDbPath
*/
public static void setDefaultDbPath(String defaultDbPath) {
DEFAULT_DB_PATH = defaultDbPath.endsWith(File.separator) ? defaultDbPath : defaultDbPath + File.separator;
}
/**
* WAL
* @return WAL
*/
public static String getDefaultWalPath() {
return DEFAULT_WAL_PATH;
}
/**
* WAL
* @param defaultWalPath WAL
*/
public static void setDefaultWalPath(String defaultWalPath) {
DEFAULT_WAL_PATH = defaultWalPath.endsWith(File.separator) ? defaultWalPath : defaultWalPath + File.separator;;
}
/**
*
* @param rocksDB RocksDB
* @param columnFamilyName
* @return
*/
private static ColumnFamilyHandle getColumnFamilyHandler(RocksDB rocksDB, String columnFamilyName) {
try {
for (ColumnFamilyHandle columnFamilyHandle : COLUMN_FAMILY_HANDLE_MAP.get(rocksDB)) {
if (Arrays.equals(columnFamilyHandle.getName(), columnFamilyName.getBytes())) {
return columnFamilyHandle;
}
}
return null;
} catch (RocksDBException e){
throw new RocksMapException("getColumnFamilyHandler failed, " + e.getMessage(), e);
}
}
/**
* RocksDB
* @param rocksDB RocksDB
*/
private static void closeRocksDB(RocksDB rocksDB) {
for (ColumnFamilyHandle columnFamilyHandle : COLUMN_FAMILY_HANDLE_MAP.get(rocksDB)) {
columnFamilyHandle.close();
}
rocksDB.close();
COLUMN_FAMILY_HANDLE_MAP.remove(rocksDB);
}
public DBOptions dbOptions;
public ReadOptions readOptions;
public WriteOptions writeOptions;
public ColumnFamilyOptions columnFamilyOptions;
private RocksDB rocksDB;
private ColumnFamilyDescriptor dataColumnFamilyDescriptor;
private ColumnFamilyHandle dataColumnFamilyHandle;
private ThreadLocal<Transaction> threadLocalTransaction = new ThreadLocal<Transaction>();
private ThreadLocal<Integer> threadLocalSavePointCount = ThreadLocal.withInitial(()->new Integer(0));
private ThreadLocal<StringBuilder> threadLocalBuilder = ThreadLocal.withInitial(()->new StringBuilder());
private String dbname;
private String columnFamilyName;
private Boolean readOnly;
private Boolean isDuplicate = false;
private int transactionLockTimeout = 5000;
public RocksMap() {
this(null, null, null, null, null, null, null);
}
/**
*
* @param columnFamilyName
*/
public RocksMap(String columnFamilyName) {
this(null, columnFamilyName, null, null, null, null, null);
}
/**
*
* @param dbname ,
* @param columnFamilyName
*/
public RocksMap(String dbname, String columnFamilyName) {
this(dbname, columnFamilyName, null, null, null, null, null);
}
/**
*
* @param readOnly
*/
public RocksMap(boolean readOnly) {
this(null, null, null, null, null, null, readOnly);
}
/**
*
* @param columnFamilyName
* @param readOnly
*/
public RocksMap(String columnFamilyName, boolean readOnly) {
this(null, columnFamilyName, null, null, null, null, readOnly);
}
/**
*
* @param dbname ,
* @param columnFamilyName
* @param readOnly
*/
public RocksMap(String dbname, String columnFamilyName, boolean readOnly) {
this(dbname, columnFamilyName, null, null, null, null, readOnly);
}
/**
*
* @param dbname ,
* @param columnFamilyName
* @param dbOptions DBOptions
* @param readOptions ReadOptions
* @param writeOptions WriteOptions
* @param columnFamilyOptions
* @param readOnly
*/
public RocksMap(String dbname, String columnFamilyName, ColumnFamilyOptions columnFamilyOptions, DBOptions dbOptions, ReadOptions readOptions, WriteOptions writeOptions, Boolean readOnly) {
this.dbname = dbname == null ? DEFAULT_COLUMN_FAMILY_NAME : dbname;
this.columnFamilyName = columnFamilyName == null ? "voovan_default" : columnFamilyName;
this.readOptions = readOptions == null ? new ReadOptions() : readOptions;
this.writeOptions = writeOptions == null ? new WriteOptions() : writeOptions;
this.columnFamilyOptions = columnFamilyOptions == null ? new ColumnFamilyOptions() : columnFamilyOptions;
this.readOnly = readOnly == null ? false : readOnly;
Options options = new Options();
options.setCreateIfMissing(true);
options.setCreateMissingColumnFamilies(true);
if(dbOptions == null) {
//Rocksdb
this.dbOptions = new DBOptions(options);
} else {
this.dbOptions = dbOptions;
}
this.dbOptions.useDirectIoForFlushAndCompaction();
this.dbOptions.setWalDir(DEFAULT_WAL_PATH +this.dbname);
TFile.mkdir(DEFAULT_DB_PATH + this.dbname + "/");
TFile.mkdir(this.dbOptions.walDir());
rocksDB = ROCKSDB_MAP.get(this.dbname);
try {
if (rocksDB == null || this.readOnly) {
List<ColumnFamilyDescriptor> DEFAULT_CF_DESCRIPTOR_LIST = new ArrayList<ColumnFamilyDescriptor>();
{
List<byte[]> columnFamilyNameBytes = RocksDB.listColumnFamilies(new Options(), DEFAULT_DB_PATH + this.dbname + "/");
if (columnFamilyNameBytes.size() > 0) {
for (byte[] columnFamilyNameByte : columnFamilyNameBytes) {
ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor(columnFamilyNameByte, this.columnFamilyOptions);
if (Arrays.equals(this.columnFamilyName.getBytes(), columnFamilyNameByte)) {
dataColumnFamilyDescriptor = columnFamilyDescriptor;
}
DEFAULT_CF_DESCRIPTOR_LIST.add(columnFamilyDescriptor);
}
}
if (DEFAULT_CF_DESCRIPTOR_LIST.size() == 0) {
DEFAULT_CF_DESCRIPTOR_LIST.add(DEFAULE_CF_DESCRIPTOR);
}
}
//ColumnFamilyHandle
List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<ColumnFamilyHandle>();
// Rocksdb
if (this.readOnly) {
rocksDB = TransactionDB.openReadOnly(this.dbOptions, DEFAULT_DB_PATH + this.dbname + "/", DEFAULT_CF_DESCRIPTOR_LIST, columnFamilyHandleList);
} else {
rocksDB = TransactionDB.open(this.dbOptions, new TransactionDBOptions(), DEFAULT_DB_PATH + this.dbname + "/", DEFAULT_CF_DESCRIPTOR_LIST, columnFamilyHandleList);
ROCKSDB_MAP.put(this.dbname, rocksDB);
}
COLUMN_FAMILY_HANDLE_MAP.put(rocksDB, columnFamilyHandleList);
}
choseColumnFamily(this.columnFamilyName);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap initilize failed, " + e.getMessage(), e);
}
}
private RocksMap(RocksMap<K,V> rocksMap, String columnFamilyName, boolean shareTransaction){
this.dbOptions = new DBOptions(rocksMap.dbOptions);
this.readOptions = new ReadOptions(rocksMap.readOptions);
this.writeOptions = new WriteOptions(rocksMap.writeOptions);
this.columnFamilyOptions = new ColumnFamilyOptions(rocksMap.columnFamilyOptions);
this.rocksDB = rocksMap.rocksDB;
if(shareTransaction) {
this.threadLocalTransaction = rocksMap.threadLocalTransaction;
this.threadLocalSavePointCount = rocksMap.threadLocalSavePointCount;
} else {
this.threadLocalTransaction = ThreadLocal.withInitial(()->null);
this.threadLocalSavePointCount = ThreadLocal.withInitial(()->new Integer(0));
}
this.dbname = rocksMap.dbname;
this.columnFamilyName = columnFamilyName;
this.readOnly = rocksMap.readOnly;
this.transactionLockTimeout = rocksMap.transactionLockTimeout;
this.isDuplicate = true;
this.choseColumnFamily(columnFamilyName);
}
/**
* , RocksMap
* @param cfName
* @return RocksMap
*/
public RocksMap<K,V> duplicate(String cfName){
return new RocksMap<K, V>(this, cfName, true);
}
/**
* RocksMAp
* @param cfName
* @param shareTransaction true: , false:
* @return RocksMap
*/
public RocksMap<K,V> duplicate(String cfName, boolean shareTransaction){
return new RocksMap<K, V>(this, cfName, shareTransaction);
}
public String getDbname() {
return dbname;
}
public String getColumnFamilyName() {
return columnFamilyName;
}
public Boolean getReadOnly() {
return readOnly;
}
public int savePointCount() {
return threadLocalSavePointCount.get();
}
public RocksDB getRocksDB(){
return rocksDB;
}
public int getColumnFamilyId(){
return getColumnFamilyId(this.columnFamilyName);
}
public void compact(){
try {
rocksDB.compactRange(dataColumnFamilyHandle);
} catch (RocksDBException e) {
throw new RocksMapException("compact failed", e);
}
}
/**
*
* @return
*/
public Long getLastSequence() {
return rocksDB.getLatestSequenceNumber();
}
/**
*
* @param sequenceNumber
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalSince(Long sequenceNumber, boolean withSerial) {
return getWalBetween(sequenceNumber, null, null, withSerial);
}
/**
*
* @param startSequence
* @param filter ,
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalSince(Long startSequence, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial) {
return getWalBetween(startSequence, null, filter, withSerial);
}
/**
*
* @param startSequence
* @param endSequence
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalSince(Long startSequence, Long endSequence, boolean withSerial) {
return getWalBetween(startSequence, endSequence, null, withSerial);
}
/**
*
* @param startSequence
* @param endSequence
* @param filter ,
* @param withSerial
* @return
*/
public List<RocksWalRecord> getWalBetween(Long startSequence, Long endSequence, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial) {
try (TransactionLogIterator transactionLogIterator = rocksDB.getUpdatesSince(startSequence)) {
ArrayList<RocksWalRecord> rocksWalRecords = new ArrayList<RocksWalRecord>();
if(startSequence > getLastSequence()) {
return rocksWalRecords;
}
if(endSequence!=null && startSequence > endSequence) {
throw new RocksMapException("startSequence is large than endSequence");
}
long seq = 0l;
while (transactionLogIterator.isValid()) {
TransactionLogIterator.BatchResult batchResult = transactionLogIterator.getBatch();
if (batchResult.sequenceNumber() < startSequence) {
transactionLogIterator.next();
continue;
}
// endSequence
if(endSequence!=null && batchResult.sequenceNumber() >= endSequence) {
break;
}
seq = batchResult.sequenceNumber();
List<RocksWalRecord> rocksWalRecordBySeq = RocksWalRecord.parse(ByteBuffer.wrap(batchResult.writeBatch().data()), filter, withSerial);
rocksWalRecords.addAll(rocksWalRecordBySeq);
transactionLogIterator.next();
}
if(rocksWalRecords.size() > 0)
Logger.debug("wal between: " + startSequence + "->" + endSequence + ", " + rocksWalRecords.get(0).getSequence() + "->" + rocksWalRecords.get(rocksWalRecords.size()-1).getSequence());
return rocksWalRecords;
} catch (RocksDBException e) {
throw new RocksMapException("getUpdatesSince failed, " + e.getMessage(), e);
}
}
public int getColumnFamilyId(String columnFamilyName){
ColumnFamilyHandle columnFamilyHandle = getColumnFamilyHandler(rocksDB, columnFamilyName);
if(columnFamilyHandle!=null){
return columnFamilyHandle.getID();
} else {
throw new RocksMapException("ColumnFamily [" + columnFamilyName +"] not found.");
}
}
/**
* Columnt
* @param cfName columnFamily
* @return RocksMap
*/
public RocksMap<K, V> choseColumnFamily(String cfName) {
try {
dataColumnFamilyHandle = getColumnFamilyHandler(rocksDB, cfName);
if (dataColumnFamilyHandle == null) {
dataColumnFamilyDescriptor = new ColumnFamilyDescriptor(cfName.getBytes(), columnFamilyOptions);
dataColumnFamilyHandle = rocksDB.createColumnFamily(dataColumnFamilyDescriptor);
COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).add(dataColumnFamilyHandle);
} else {
dataColumnFamilyDescriptor = new ColumnFamilyDescriptor(dataColumnFamilyHandle.getName(), columnFamilyOptions);
}
this.columnFamilyName = cfName;
return this;
} catch(RocksDBException e){
throw new RocksMapException("RocksMap initilize failed, " + e.getMessage(), e);
}
}
/**
*
* @return
*/
public int getTransactionLockTimeout() {
return transactionLockTimeout;
}
/**
*
* @param transactionLockTimeout
*/
public void setTransactionLockTimeout(int transactionLockTimeout) {
this.transactionLockTimeout = transactionLockTimeout;
}
/**
*
*
* savepoint , , , savepont
* @param transFunction , Null ,
* @param <T>
* @return null: , null:
*/
public <T> T withTransaction(Function<RocksMap<K, V>, T> transFunction) {
beginTransaction();
try {
T object = transFunction.apply(this);
if (object == null) {
rollback();
} else {
commit();
}
return object;
} catch (Exception e) {
rollback();
throw e;
}
}
/**
*
*
* : -1, :true, : false
*/
public void beginTransaction() {
beginTransaction(-1, true, false);
}
/**
*
*
*
*
* snapshot
*
* snapshotsnapshot(head)()
* @param expire
* @param deadlockDetect
* @param withSnapShot
*/
public void beginTransaction(long expire, boolean deadlockDetect, boolean withSnapShot) {
Transaction transaction = threadLocalTransaction.get();
if(transaction==null) {
transaction = createTransaction(expire, deadlockDetect, withSnapShot);
threadLocalTransaction.set(transaction);
} else {
savePoint();
}
}
private Transaction createTransaction(long expire, boolean deadlockDetect, boolean withSnapShot) {
if(readOnly){
throw new RocksMapException("RocksMap Not supported operation in read only mode");
}
TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.setExpiration(expire);
transactionOptions.setDeadlockDetect(deadlockDetect);
transactionOptions.setSetSnapshot(withSnapShot);
transactionOptions.setLockTimeout(transactionLockTimeout);
return((TransactionDB) rocksDB).beginTransaction(writeOptions, transactionOptions);
}
public Transaction getTransaction(){
Transaction transaction = threadLocalTransaction.get();
if(transaction==null){
throw new RocksMapException("RocksMap is not in transaction model");
}
return transaction;
}
private void savePoint() {
Transaction transaction = getTransaction();
try {
transaction.setSavePoint();
threadLocalSavePointCount.set(threadLocalSavePointCount.get()+1);
} catch (RocksDBException e) {
throw new RocksMapException("commit failed, " + e.getMessage(), e);
}
}
private void rollbackSavePoint(){
Transaction transaction = getTransaction();
try {
transaction.rollbackToSavePoint();
threadLocalSavePointCount.set(threadLocalSavePointCount.get()-1);
} catch (RocksDBException e) {
throw new RocksMapException("commit failed, " + e.getMessage(), e);
}
}
public void commit() {
Transaction transaction = getTransaction();
if(threadLocalSavePointCount.get() == 0) {
commit(transaction);
threadLocalTransaction.set(null);
} else {
threadLocalSavePointCount.set(threadLocalSavePointCount.get()-1);
}
}
private void commit(Transaction transaction) {
try {
if (transaction != null) {
transaction.commit();
} else {
throw new RocksMapException("RocksMap is not in transaction model");
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap commit failed, " + e.getMessage(), e);
}
}
public void rollback() {
Transaction transaction = getTransaction();
if(threadLocalSavePointCount.get()!=0) {
rollbackSavePoint();
} else {
rollback(transaction);
threadLocalTransaction.set(null);
}
}
private void rollback(Transaction transaction) {
try {
if (transaction != null) {
transaction.rollback();
} else {
throw new RocksMapException("RocksMap is not in transaction model");
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap rollback failed, " + e.getMessage(), e);
}
}
@Override
public Comparator<? super K> comparator() {
return null;
}
private RocksIterator getIterator(){
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null) {
return transaction.getIterator(readOptions, dataColumnFamilyHandle);
} else {
return rocksDB.newIterator(dataColumnFamilyHandle, readOptions);
}
}
@Override
public SortedMap<K,V> subMap(K fromKey, K toKey) {
TreeMap<K,V> subMap = new TreeMap<K,V>();
try (RocksIterator iterator = getIterator()){
byte[] fromKeyBytes = TSerialize.serialize(fromKey);
byte[] toKeyBytes = TSerialize.serialize(toKey);
if (fromKeyBytes == null) {
iterator.seekToFirst();
} else {
iterator.seek(fromKeyBytes);
}
while (iterator.isValid()) {
byte[] key = iterator.key();
if (toKey == null || !Arrays.equals(toKeyBytes, key)) {
subMap.put((K) TSerialize.unserialize(iterator.key()), (V) TSerialize.unserialize(iterator.value()));
} else {
subMap.put((K) TSerialize.unserialize(iterator.key()), (V) TSerialize.unserialize(iterator.value()));
break;
}
iterator.next();
}
return subMap;
}
}
@Override
public SortedMap<K,V> tailMap(K fromKey){
if(fromKey==null){
return null;
}
return subMap(fromKey, null);
}
@Override
public SortedMap<K,V> headMap(K toKey){
if(toKey == null){
return null;
}
return subMap(null, toKey);
}
@Override
public K firstKey() {
try (RocksIterator iterator = getIterator()) {
iterator.seekToFirst();
if (iterator.isValid()) {
return (K) TSerialize.unserialize(iterator.key());
}
return null;
}
}
@Override
public K lastKey() {
try (RocksIterator iterator = getIterator()) {
iterator.seekToLast();
if (iterator.isValid()) {
return (K) TSerialize.unserialize(iterator.key());
}
return null;
}
}
@Override
public int size() {
// try {
// return Integer.valueOf(rocksDB.getProperty(dataColumnFamilyHandle, "rocksdb.estimate-num-keys"));
// } catch (RocksDBException e) {
// e.printStackTrace();
int count = 0;
RocksIterator iterator = null;
try {
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
iterator = transaction.getIterator(readOptions, dataColumnFamilyHandle);
} else {
iterator = rocksDB.newIterator(dataColumnFamilyHandle, readOptions);
}
iterator.seekToFirst();
while (iterator.isValid()) {
iterator.next();
count++;
}
return count;
} finally {
if(iterator!=null){
iterator.close();
}
}
}
@Override
public boolean isEmpty() {
try (RocksIterator iterator = getIterator()){
iterator.seekToFirst();
return !iterator.isValid();
}
}
@Override
public boolean containsKey(Object key) {
byte[] values = null;
try {
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null) {
values = transaction.get(dataColumnFamilyHandle, readOptions, TSerialize.serialize(key));
} else {
values = rocksDB.get(dataColumnFamilyHandle, TSerialize.serialize(key));
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap containsKey " + key + " failed, " + e.getMessage(), e);
}
return values!=null;
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
/**
* ,
* @param key key
* @return key value
*/
public V lock(Object key){
return lock(key, true);
}
/**
*
* @param key key
*/
public void unlock(Object key) {
Transaction transaction = getTransaction();
transaction.undoGetForUpdate(TSerialize.serialize(key));
}
/**
*
* @param key key
* @param exclusive
* @return key value
*/
public V lock(Object key, boolean exclusive){
Transaction transaction = getTransaction();
try {
byte[] values = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, TSerialize.serialize(key), exclusive);
return values==null ? null : (V) TSerialize.unserialize(values);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap lock " + key + " failed, " + e.getMessage(), e);
}
}
private byte[] get(byte[] keyBytes) {
try {
byte[] values = null;
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
values = transaction.getForUpdate(readOptions, dataColumnFamilyHandle, keyBytes, true);
} else {
values = rocksDB.get(dataColumnFamilyHandle, readOptions, keyBytes);
}
return values;
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap get failed, " + e.getMessage(), e);
}
}
@Override
public V get(Object key) {
if(key == null){
throw new NullPointerException();
}
byte[] values = get(TSerialize.serialize(key));
return values==null ? null : (V) TSerialize.unserialize(values);
}
public List<V> getAll(Collection<K> keys) {
try {
ArrayList<byte[]> keysBytes = new ArrayList<byte[]>();
ArrayList<ColumnFamilyHandle> columnFamilyHandles = new ArrayList<ColumnFamilyHandle>();
Iterator keysIterator = keys.iterator();
for (int i = 0; i < keys.size(); i++) {
keysBytes.add(TSerialize.serialize(keysIterator.next()));
columnFamilyHandles.add(dataColumnFamilyHandle);
}
Transaction transaction = threadLocalTransaction.get();
List<byte[]> valuesBytes;
if (transaction != null) {
valuesBytes = Arrays.asList(transaction.multiGet(readOptions, columnFamilyHandles, keysBytes.toArray(new byte[0][0])));
} else {
valuesBytes = rocksDB.multiGetAsList(readOptions, columnFamilyHandles, keysBytes);
}
ArrayList<V> values = new ArrayList<V>();
for (byte[] valueByte : valuesBytes) {
values.add((V) TSerialize.unserialize(valueByte));
}
return values;
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap getAll failed, " + e.getMessage(), e);
}
}
private void put(byte[] keyBytes, byte[] valueBytes) {
try {
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
transaction.put(dataColumnFamilyHandle, keyBytes, valueBytes);
} else {
rocksDB.put(dataColumnFamilyHandle, keyBytes, valueBytes);
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap put failed, " + e.getMessage(), e);
}
}
@Override
public Object put(Object key, Object value) {
if(key == null || value == null){
throw new NullPointerException();
}
put(TSerialize.serialize(key), TSerialize.serialize(value));
return value;
}
@Override
public V putIfAbsent(K key, V value) {
byte[] keyBytes = TSerialize.serialize(key);
byte[] valueBytes = TSerialize.serialize(value);
Transaction innerTransaction = createTransaction(-1, false, false);
try {
byte[] oldValueBytes = innerTransaction.getForUpdate(readOptions, dataColumnFamilyHandle, keyBytes, true);
if(oldValueBytes == null){
innerTransaction.put(dataColumnFamilyHandle, keyBytes, valueBytes);
return null;
} else {
return (V) TSerialize.unserialize(oldValueBytes);
}
} catch (RocksDBException e) {
rollback(innerTransaction);
throw new RocksMapException("RocksMap putIfAbsent error, " + e.getMessage(), e);
} finally {
commit(innerTransaction);
}
}
/**
* key
* @param key key
* @return false key , true , key , boomfilter
*/
public boolean keyMayExists(K key) {
boolean result = rocksDB.keyMayExist(dataColumnFamilyHandle, TSerialize.serialize(key), threadLocalBuilder.get());
threadLocalBuilder.get().setLength(0);
return result;
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
byte[] keyBytes = TSerialize.serialize(key);
byte[] newValueBytes = TSerialize.serialize(newValue);
byte[] oldValueBytes = TSerialize.serialize(oldValue);
Transaction innerTransaction = createTransaction(-1, false, false);
try {
byte[] oldDbValueBytes = innerTransaction.getForUpdate(readOptions, dataColumnFamilyHandle, keyBytes, true);
if(oldDbValueBytes!=null && Arrays.equals(oldDbValueBytes, oldValueBytes)){
innerTransaction.put(dataColumnFamilyHandle, keyBytes, newValueBytes);
return true;
} else {
return false;
}
} catch (RocksDBException e) {
rollback(innerTransaction);
throw new RocksMapException("RocksMap replace failed , " + e.getMessage(), e);
} finally {
commit(innerTransaction);
}
}
/**
* key
* @param keyBytes key
* @param isRetVal value
* @return , isRetVal=false , null
*/
private byte[] remove(byte[] keyBytes, boolean isRetVal) throws RocksDBException {
if(keyBytes == null){
throw new NullPointerException();
}
byte[] valueBytes = null;
if(isRetVal) {
valueBytes = get(keyBytes);
}
if(!isRetVal || valueBytes != null) {
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null) {
transaction.delete(dataColumnFamilyHandle, keyBytes);
} else {
rocksDB.delete(dataColumnFamilyHandle, keyBytes);
}
}
return valueBytes;
}
/**
* key
* @param key key
* @param isRetVal value
* @return , isRetVal=false , null
*/
public V remove(Object key, boolean isRetVal) {
if(key == null){
throw new NullPointerException();
}
try {
byte[] valuesByte = remove(TSerialize.serialize(key), isRetVal);
return (V) TSerialize.unserialize(valuesByte);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap remove " + key + " failed", e);
}
}
@Override
public V remove(Object key) {
return remove(key, true);
}
public void removeAll(Collection<K> keys) {
if(keys == null){
throw new NullPointerException();
}
try {
Transaction transaction = threadLocalTransaction.get();
WriteBatch writeBatch = null;
if (transaction == null) {
writeBatch = THREAD_LOCAL_WRITE_BATCH.get();
writeBatch.clear();
for(K key : keys) {
if(key == null){
continue;
}
try {
writeBatch.delete(dataColumnFamilyHandle, TSerialize.serialize(key));
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll " + key + " failed", e);
}
}
rocksDB.write(writeOptions, writeBatch);
} else {
for(K key : keys) {
if(key == null){
continue;
}
try {
transaction.delete(dataColumnFamilyHandle, TSerialize.serialize(key));
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll " + key + " failed", e);
}
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll write failed", e);
}
}
/**
* Removes the database entries in the range ["beginKey", "endKey"), i.e.,
* including "beginKey" and excluding "endKey". a non-OK status on error. It
* is not an error if no keys exist in the range ["beginKey", "endKey").
* @param fromKey key
* @param toKey key
*
*/
public void removeRange(K fromKey, K toKey) {
Transaction transaction = threadLocalTransaction.get();
byte[] fromKeyBytes = TSerialize.serialize(fromKey);
byte[] toKeyBytes = TSerialize.serialize(toKey);
try {
if(transaction==null) {
rocksDB.deleteRange(dataColumnFamilyHandle, writeOptions, fromKeyBytes, toKeyBytes);
} else {
try (RocksIterator iterator = getIterator()) {
iterator.seek(fromKeyBytes);
while (iterator.isValid()) {
if (!Arrays.equals(iterator.key(), toKeyBytes)) {
transaction.delete(dataColumnFamilyHandle, iterator.key());
}
}
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap removeAll failed", e);
}
}
public static ThreadLocal<WriteBatch> THREAD_LOCAL_WRITE_BATCH = ThreadLocal.withInitial(()->new WriteBatch());
@Override
public void putAll(Map m) {
try {
Transaction transaction = threadLocalTransaction.get();
WriteBatch writeBatch = null;
if (transaction == null) {
writeBatch = THREAD_LOCAL_WRITE_BATCH.get();
writeBatch.clear();
Iterator<Entry> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
writeBatch.put(dataColumnFamilyHandle, TSerialize.serialize(key), TSerialize.serialize(value));
}
rocksDB.write(writeOptions, writeBatch);
} else {
Iterator<Entry> iterator = m.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
transaction.put(dataColumnFamilyHandle, TSerialize.serialize(key), TSerialize.serialize(value));
}
}
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap putAll failed", e);
}
}
public void flush(){
try {
rocksDB.compactRange(dataColumnFamilyHandle);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap flush failed", e);
}
}
@Override
public void clear() {
if(readOnly){
Logger.error("Clear failed, ", new RocksDBException("Not supported operation in read only mode"));
return;
}
try {
drop();
dataColumnFamilyHandle = rocksDB.createColumnFamily(dataColumnFamilyDescriptor);
COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).add(dataColumnFamilyHandle);
dataColumnFamilyHandle = getColumnFamilyHandler(rocksDB, this.columnFamilyName);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap clear failed", e);
}
}
public void drop(){
try {
rocksDB.dropColumnFamily(dataColumnFamilyHandle);
COLUMN_FAMILY_HANDLE_MAP.get(rocksDB).remove(dataColumnFamilyHandle);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap drop failed", e);
}
}
/**
* , Set Rocksdb
* @return Key set
*/
@Override
public Set keySet() {
TreeSet<K> keySet = new TreeSet<K>();
RocksIterator iterator = null;
try {
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
iterator = transaction.getIterator(readOptions, dataColumnFamilyHandle);
} else {
iterator = rocksDB.newIterator(dataColumnFamilyHandle, readOptions);
}
iterator.seekToFirst();
while (iterator.isValid()) {
K k = (K) TSerialize.unserialize(iterator.key());
keySet.add(k);
iterator.next();
}
return keySet;
} finally {
if(iterator!=null){
iterator.close();
}
}
}
@Override
public Collection values() {
ArrayList<V> values = new ArrayList<V>();
RocksIterator iterator = null;
try {
Transaction transaction = threadLocalTransaction.get();
if (transaction != null) {
iterator = transaction.getIterator(readOptions, dataColumnFamilyHandle);
} else {
iterator = rocksDB.newIterator(dataColumnFamilyHandle, readOptions);
}
iterator.seekToFirst();
while (iterator.isValid()) {
V value = (V) TSerialize.unserialize(iterator.value());
values.add(value);
iterator.next();
}
return values;
} finally {
if(iterator!=null){
iterator.close();
}
}
}
/**
* , Set Rocksdb
* @return Entry set
*/
@Override
public Set<Entry<K, V>> entrySet() {
TreeSet<Entry<K,V>> entrySet = new TreeSet<Entry<K,V>>();
try (RocksIterator iterator = getIterator()) {
iterator.seekToFirst();
while (iterator.isValid()) {
entrySet.add(new RocksMapEntry<K, V>(this, iterator.key(), iterator.value()));
iterator.next();
}
return entrySet;
}
}
/**
* key
* @param key key
* @return Map
*/
public Map<K,V> startWith(K key) {
return startWith(key, 0,0);
}
/**
* key
* @param key key
* @param skipSize
* @param size
* @return Map
*/
public Map<K,V> startWith(K key, int skipSize, int size) {
byte[] keyBytes = TSerialize.serialize(key);
TreeMap<K,V> entryMap = new TreeMap<K,V>();
try (RocksMapIterator iterator = new RocksMapIterator(this, key, null, skipSize, size)) {
while (iterator.hasNext()) {
iterator.next();
if (TByte.byteArrayStartWith(iterator.keyBytes(), keyBytes)) {
entryMap.put((K) iterator.key(), (V) iterator.value());
}
}
return entryMap;
}
}
@Override
public void close() {
Transaction transaction = threadLocalTransaction.get();
if(transaction!=null){
try {
transaction.rollback();
} catch (RocksDBException e) {
throw new RocksMapException("RocksMap rollback on close failed", e);
} finally {
transaction.close();
}
}
dbOptions.close();
readOptions.close();
writeOptions.close();
columnFamilyOptions.close();
if(!isDuplicate) {
RocksMap.closeRocksDB(rocksDB);
}
}
/**
*
* @param fromKey key
* @param toKey key
* @param size
* @param skipSize
* @param size
* @return
*/
public RocksMapIterator<K,V> iterator(K fromKey, K toKey, int skipSize, int size){
return new RocksMapIterator(this, fromKey, toKey, skipSize, size);
}
/**
*
* @param fromKey key
* @param toKey key
* @return
*/
public RocksMapIterator<K,V> iterator(K fromKey, K toKey){
return new RocksMapIterator(this, fromKey, toKey, 0, 0);
}
/**
*
* @param skipSize
* @param size
* @return
*/
public RocksMapIterator<K,V> iterator(int skipSize, int size){
return new RocksMapIterator(this, null, null, skipSize, size);
}
/**
*
* @param size
* @return
*/
public RocksMapIterator<K,V> iterator(int size){
return new RocksMapIterator(this, null, null, 0, size);
}
/**
*
* @return
*/
public RocksMapIterator<K,V> iterator(){
return new RocksMapIterator(this, null, null, 0, 0);
}
/**
*
* @param checker , true: , false:
* @param disableWal wal
*/
public void scan(Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker, boolean disableWal) {
scan(null, null, checker, disableWal);
}
/**
*
* @param fromKey key
* @param toKey key
* @param checker , true: , false:
* @param disableWal wal
*/
public void scan(K fromKey, K toKey, Function<RocksMap<K,V>.RocksMapEntry<K,V>, Boolean> checker, boolean disableWal) {
RocksMap<K,V> innerRocksMap = this.duplicate(this.getColumnFamilyName(), false);
if(disableWal) {
innerRocksMap.writeOptions.disableWAL();
}
RocksMap<K,V>.RocksMapIterator<K,V> iterator = innerRocksMap.iterator(fromKey, toKey);
while (iterator.hasNext()) {
RocksMap<K,V>.RocksMapEntry<K,V> rocksMapEntry = iterator.next();
if(rocksMapEntry==null) {
continue;
}
if(checker.apply(rocksMapEntry)) {
continue;
} else {
break;
}
}
innerRocksMap.close();
}
public class RocksMapEntry<K, V> implements Map.Entry<K, V>, Comparable<RocksMapEntry> {
private RocksMap<K,V> rocksMap;
private byte[] keyBytes;
private K k;
private byte[] valueBytes;
private V v;
protected RocksMapEntry(RocksMap<K, V> rocksMap, byte[] keyBytes, byte[] valueBytes) {
this.rocksMap = rocksMap;
this.keyBytes = keyBytes;
this.valueBytes = valueBytes;
}
@Override
public K getKey() {
if(k==null){
this.k = (K) TSerialize.unserialize(keyBytes);
}
return k;
}
@Override
public V getValue() {
if(v==null) {
this.v = (V) TSerialize.unserialize(valueBytes);
}
return v;
}
public byte[] getKeyBytes() {
return keyBytes;
}
public byte[] getValueBytes() {
return valueBytes;
}
@Override
public V setValue(V value) {
rocksMap.put(keyBytes, TSerialize.serialize(value));
return value;
}
@Override
public int compareTo(RocksMapEntry o) {
return TByte.byteArrayCompare(this.keyBytes, o.keyBytes);
}
@Override
public String toString(){
return getKey() + "=" + getValue();
}
public void remove(){
try {
rocksMap.remove(keyBytes, false);
} catch (RocksDBException e) {
throw new RocksMapException("RocksMapEntry remove failed", e);
}
}
}
public class RocksMapIterator<K,V> implements Iterator<RocksMapEntry<K,V>>, Closeable{
private RocksMap<K,V> rocksMap;
private RocksIterator iterator;
private byte[] fromKeyBytes;
private byte[] toKeyBytes;
private int skipSize;
private int size = 0;
private int count=0;
//["beginKey", "endKey")
protected RocksMapIterator(RocksMap rocksMap, K fromKey, K toKey, int skipSize, int size) {
this.rocksMap = rocksMap;
this.iterator = rocksMap.getIterator();
this.fromKeyBytes = TSerialize.serialize(fromKey);
this.toKeyBytes = TSerialize.serialize(toKey);
this.skipSize = skipSize;
this.size = size;
if(fromKeyBytes==null) {
iterator.seekToFirst();
} else {
iterator.seek(fromKeyBytes);
}
if(skipSize >0) {
for(int i=0;i<=this.skipSize;i++) {
if(!directNext()) {
break;
}
}
}
count = 0;
}
@Override
public boolean hasNext() {
if(count == 0 && iterator.isValid()) {
return true;
}
try {
iterator.next();
if (toKeyBytes == null) {
return iterator.isValid();
} else {
return iterator.isValid() && !(Arrays.equals(iterator.key(), toKeyBytes));
}
} finally {
iterator.prev();
if(size!=0 && count > size - 1){
return false;
}
}
}
/**
* Key
* @return Key
*/
public K key(){
return (K)TSerialize.unserialize(iterator.key());
}
/**
* value
* @return value
*/
public V value(){
return (V)TSerialize.unserialize(iterator.value());
}
/**
* Key
* @return Key
*/
public byte[] keyBytes(){
return iterator.key();
}
/**
* value
* @return value
*/
public byte[] valueBytes(){
return iterator.value();
}
/**
* next
* @return true: , false:
*/
public boolean directNext() {
if(count != 0) {
iterator.next();
}
if(iterator.isValid()) {
count++;
return true;
} else {
return false;
}
}
@Override
public RocksMapEntry<K,V> next() {
if(directNext()) {
return new RocksMapEntry(rocksMap, iterator.key(), iterator.value());
} else {
return null;
}
}
@Override
public void remove() {
try {
rocksMap.rocksDB.delete(rocksMap.dataColumnFamilyHandle, iterator.key());
} catch (RocksDBException e) {
throw new RocksMapException("RocksMapIterator remove failed", e);
}
}
@Override
public void forEachRemaining(Consumer<? super RocksMapEntry<K, V>> action) {
throw new UnsupportedOperationException();
}
public void close(){
iterator.close();
}
}
public static class RocksWalRecord {
// WriteBatch::rep_ :=
// sequence: fixed64
// count: fixed32
// data: record[count]
// record :=
// kTypeValue varstring varstring
// kTypeDeletion varstring
// kTypeSingleDeletion varstring
// kTypeRangeDeletion varstring varstring
// kTypeMerge varstring varstring
// kTypeColumnFamilyValue varint32 varstring varstring
// kTypeColumnFamilyDeletion varint32 varstring
// kTypeColumnFamilySingleDeletion varint32 varstring
// kTypeColumnFamilyRangeDeletion varint32 varstring varstring
// kTypeColumnFamilyMerge varint32 varstring varstring
// kTypeBeginPrepareXID varstring
// kTypeEndPrepareXID
// kTypeCommitXID varstring
// kTypeRollbackXID varstring
// kTypeBeginPersistedPrepareXID varstring
// kTypeBeginUnprepareXID varstring
// kTypeNoop
// varstring :=
// len: varint32
// data: uint8[len]
public static int TYPE_DELETION = 0x0;
public static int TYPE_VALUE = 0x1;
public static int TYPE_MERGE = 0x2;
public static int TYPE_LOGDATA = 0x3; // WAL only.
public static int TYPE_COLUMNFAMILY_DELETION = 0x4;
public static int TYPE_COLUMNFAMILY_VALUE = 0x5;
public static int TYPE_COLUMNFAMILY_MERGE = 0x6; // WAL only.
public static int TYPE_SINGLE_DELETION = 0x7;
public static int TYPE_COLUMNFAMILY_SINGLE_DELETION = 0x8; // WAL only.
public static int TYPE_BEGIN_PREPARE_XID = 0x9; // WAL only.
public static int TYPE_END_PREPARE_XID = 0xA; // WAL only.
public static int TYPE_COMMIT_XID = 0xB; // WAL only.
public static int TYPE_ROLLBACK_XID = 0xC; // WAL only.
public static int TYPE_NOOP = 0xD; // WAL only.
public static int TYPE_COLUMNFAMILY_RANGE_DELETION = 0xE; // WAL only.
public static int TYPE_RANGE_DELETION = 0xF; // meta block
public static int TYPE_COLUMNFAMILY_BLOB_INDEX = 0x10; // Blob DB only
public static int TYPE_BLOB_INDEX = 0x11; // Blob DB only
public static int TYPE_BEGIN_PERSISTED_PREPARE_XID = 0x12; // WAL only
public static int TYPE_BEGIN_UNPREPARE_XID = 0x13; // WAL only.
public static int[] TYPE_ELEMENT_COUNT = new int[]{
1, //0 kTypeDeletion varstring
2, //1 kTypeValue varstring varstring
2, //2 kTypeMerge varstring varstring
0,
1, //4 kTypeColumnFamilyDeletion varint32 varstring
2, //5 kTypeColumnFamilyValue varint32 varstring varstring
2, //6 kTypeColumnFamilyMerge varint32 varstring varstring
1, //7 kTypeSingleDeletion varstring
1, //8 kTypeColumnFamilySingleDeletion varint32 varstring
1, //9 kTypeBeginPrepareXID varstring
0, //A kTypeEndPrepareXID
1, //B kTypeCommitXID varstring
1, //C kTypeRollbackXID varstring
0, //D kTypeNoop
2, //E kTypeColumnFamilyRangeDeletion varint32 varstring varstring
0, //F kTypeRangeDeletion varstring varstring
0, //10 kTypeColumnFamilyBlobIndex
2, //11 kTypeBlobIndex varstring varstring
1, //12 kTypeBeginPersistedPrepareXID varstring
1 //13 kTypeBeginUnprepareXID varstring
};
private long sequence;
private int type;
private int columnFamilyId = 0;
private ArrayList<Object> chunks;
private RocksWalRecord(long sequence, int type, int columnFamilyId) {
this.sequence = sequence;
this.type = type;
this.columnFamilyId = columnFamilyId;
chunks = new ArrayList<Object>();
}
public long getSequence() {
return sequence;
}
private void setSequence(long sequence) {
this.sequence = sequence;
}
public int getType() {
return type;
}
private void setType(int type) {
this.type = type;
}
public int getColumnFamilyId() {
return columnFamilyId;
}
private void setColumnFamilyId(int columnFamilyId) {
this.columnFamilyId = columnFamilyId;
}
public ArrayList<Object> getChunks() {
return chunks;
}
/**
*
* @param byteBuffer
* @param withSerial
* @return
*/
public static List<RocksWalRecord> parse(ByteBuffer byteBuffer, boolean withSerial) {
return parse(byteBuffer, null, withSerial);
}
/**
*
* @param byteBuffer
* @param filter ,
* @param withSerial
* @return
*/
public static List<RocksWalRecord> parse(ByteBuffer byteBuffer, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial) {
ByteOrder originByteOrder = byteBuffer.order();
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
if(byteBuffer.remaining() < 13) {
throw new ParseException("not a correct recorder");
}
Long sequence = byteBuffer.getLong();
//Wal
int recordCount = byteBuffer.getInt();
List<RocksWalRecord> rocksWalRecords = new ArrayList<RocksWalRecord>();
for(int count=0;byteBuffer.hasRemaining();count++) {
RocksWalRecord rocksWalRecord = parseOperation(byteBuffer, sequence, filter, withSerial);
if(rocksWalRecord !=null) {
rocksWalRecords.add(rocksWalRecord);
}
}
byteBuffer.order(originByteOrder);
return rocksWalRecords;
}
/**
*
* @param byteBuffer
* @param sequence
* @param withSerial
* @return
*/
public static RocksWalRecord parseOperation(ByteBuffer byteBuffer, long sequence, boolean withSerial){
return parseOperation(byteBuffer, sequence, withSerial);
}
/**
*
* @param byteBuffer
* @param sequence
* @param filter ,
* @param withSerial
* @return
*/
public static RocksWalRecord parseOperation(ByteBuffer byteBuffer, long sequence, BiFunction<Integer, Integer, Boolean> filter, boolean withSerial){
int type = byteBuffer.get();
if (type == TYPE_NOOP) {
if(byteBuffer.hasRemaining()) {
type = byteBuffer.get();
} else {
return null;
}
}
int columnFamilyId=0;
if (type == TYPE_COLUMNFAMILY_DELETION ||
type == TYPE_COLUMNFAMILY_VALUE ||
type == TYPE_COLUMNFAMILY_MERGE ||
type == TYPE_COLUMNFAMILY_SINGLE_DELETION) {
columnFamilyId = byteBuffer.get();
}
RocksWalRecord rocksWalRecord = null;
if (type < TYPE_ELEMENT_COUNT.length) {
boolean isEnable = filter==null || filter.apply(columnFamilyId, type);
if(isEnable) {
rocksWalRecord = new RocksWalRecord(sequence, type, columnFamilyId);
}
for (int i = 0; i < TYPE_ELEMENT_COUNT[type] && byteBuffer.hasRemaining(); i++) {
int chunkSize = Varint.varintToInt(byteBuffer);
if(isEnable) {
byte[] chunkBytes = new byte[chunkSize];
byteBuffer.get(chunkBytes);
Object chunk = chunkBytes;
if (withSerial) {
chunk = TSerialize.unserialize(chunkBytes);
} else {
chunk = chunkBytes;
}
rocksWalRecord.getChunks().add(chunk);
} else {
byteBuffer.position(byteBuffer.position() + chunkSize);
}
}
}
return rocksWalRecord;
}
}
/**
* Wal, wal
*/
public static class RocksWalReader {
private Object mark;
private RocksMap rocksMap;
private Long lastSequence;
private int batchSeqsize;
private List<Integer> columnFamilys;
private List<Integer> walTypes;
public RocksWalReader(Object mark, RocksMap rocksMap, int batchSeqsize) {
this.mark = mark;
this.rocksMap = rocksMap;
this.batchSeqsize = batchSeqsize;
this.rocksMap = rocksMap;
this.lastSequence = (Long) this.rocksMap.get(mark);
this.lastSequence = this.lastSequence==null ? 0 : this.lastSequence;
Logger.debug("Start sequence: " + this.lastSequence);
}
public long getLastSequence() {
return lastSequence;
}
public List<Integer> getColumnFamily() {
return columnFamilys;
}
public void setColumnFamily(List<Integer> columnFamilys) {
this.columnFamilys = columnFamilys;
}
public int getBatchSeqsize() {
return batchSeqsize;
}
public List<Integer> getWalTypes() {
return walTypes;
}
public void setWalTypes(List<Integer> walTypes) {
this.walTypes = walTypes;
}
public void processing(RocksWalProcessor rocksWalProcessor){
//wal
Long endSequence = rocksMap.getLastSequence();
if(lastSequence + batchSeqsize < endSequence){
endSequence = lastSequence + batchSeqsize;
}
List<RocksWalRecord> rocksWalRecords = rocksMap.getWalBetween(lastSequence, endSequence, (columnFamilyId, type)-> {
return (walTypes == null ? true : walTypes.contains(type)) &&
(columnFamilys==null ? true : columnFamilys.contains(columnFamilyId));
}, true);
if(rocksWalRecords.size() > 0) {
rocksWalProcessor.process(endSequence, rocksWalRecords);
}
rocksMap.put(mark, endSequence);
lastSequence = endSequence;
}
public static interface RocksWalProcessor {
public void process(Long endSequence, List<RocksWalRecord> rocksWalRecords);
}
}
}
|
package org.jpos.iso;
import org.jpos.core.Configurable;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.iso.ISOFilter.VetoException;
import org.jpos.iso.header.BaseHeader;
import org.jpos.util.LogEvent;
import org.jpos.util.LogSource;
import org.jpos.util.Logger;
import org.jpos.util.NameRegistrar;
import java.io.*;
import java.net.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Observable;
import java.util.Vector;
/**
* ISOChannel is an abstract class that provides functionality that
* allows the transmision and reception of ISO 8583 Messages
* over a TCP/IP session.
* <p>
* It is not thread-safe, ISOMUX takes care of the
* synchronization details
* <p>
* ISOChannel is Observable in order to suport GUI components
* such as ISOChannelPanel.
* <br>
* It now support the new Logger architecture so we will
* probably setup ISOChannelPanel to be a LogListener insteado
* of being an Observer in future releases.
*
* @author Alejandro P. Revilla
* @author Bharavi Gade
* @version $Revision$ $Date$
* @see ISOMsg
* @see MUX
* @see ISOException
* @see org.jpos.iso.channel.CSChannel
* @see Logger
*
*/
public abstract class BaseChannel extends Observable
implements FilteredChannel, ClientChannel, ServerChannel, FactoryChannel,
LogSource, Configurable, BaseChannelMBean, Cloneable
{
private Socket socket;
private String host, localIface;
private String[] hosts;
int[] ports;
private int port, timeout, connectTimeout, localPort;
private int maxPacketLength = 100000;
private boolean keepAlive;
private Configuration cfg;
protected boolean usable;
protected boolean overrideHeader;
private String name;
// private int serverPort = -1;
protected DataInputStream serverIn;
protected DataOutputStream serverOut;
// The lock objects should be final, and never changed, but due to the clone() method, they must be set there.
protected Object serverInLock = new Object();
protected Object serverOutLock = new Object();
protected ISOPackager packager;
protected ServerSocket serverSocket = null;
protected Vector incomingFilters, outgoingFilters;
protected ISOClientSocketFactory socketFactory = null;
protected int[] cnt;
protected Logger logger = null;
protected String realm = null;
protected String originalRealm = null;
protected byte[] header = null;
/**
* constructor shared by server and client
* ISOChannels (which have different signatures)
*/
public BaseChannel () {
super();
cnt = new int[SIZEOF_CNT];
name = "";
incomingFilters = new Vector();
outgoingFilters = new Vector();
setHost (null, 0);
}
/**
* constructs a client ISOChannel
* @param host server TCP Address
* @param port server port number
* @param p an ISOPackager
* @see ISOPackager
*/
public BaseChannel (String host, int port, ISOPackager p) {
this();
setHost(host, port);
setPackager(p);
}
/**
* constructs a server ISOChannel
* @param p an ISOPackager
* @exception IOException on error
* @see ISOPackager
*/
public BaseChannel (ISOPackager p) throws IOException {
this();
setPackager (p);
}
/**
* constructs a server ISOChannel associated with a Server Socket
* @param p an ISOPackager
* @param serverSocket where to accept a connection
* @exception IOException on error
* @see ISOPackager
*/
public BaseChannel (ISOPackager p, ServerSocket serverSocket)
throws IOException
{
this();
setPackager (p);
setServerSocket (serverSocket);
}
/**
* initialize an ISOChannel
* @param host server TCP Address
* @param port server port number
*/
public void setHost(String host, int port) {
this.host = host;
this.port = port;
this.hosts = new String[] { host };
this.ports = new int[] { port };
}
/**
* initialize an ISOChannel
* @param iface server TCP Address
* @param port server port number
*/
public void setLocalAddress (String iface, int port) {
this.localIface = iface;
this.localPort = port;
}
/**
* @param host to connect (client ISOChannel)
*/
public void setHost (String host) {
this.host = host;
this.hosts = new String[] { host };
}
/**
* @param port to connect (client ISOChannel)
*/
public void setPort (int port) {
this.port = port;
this.ports = new int[] { port };
}
/**
* @return hostname (may be null)
*/
public String getHost() {
return host;
}
/**
* @return port number
*/
public int getPort() {
return port;
}
/**
* set Packager for channel
* @param p an ISOPackager
* @see ISOPackager
*/
public void setPackager(ISOPackager p) {
this.packager = p;
}
/**
* @return current packager
*/
public ISOPackager getPackager() {
return packager;
}
/**
* Associates this ISOChannel with a server socket
* @param sock where to accept a connection
*/
public void setServerSocket (ServerSocket sock) {
setHost (null, 0);
this.serverSocket = sock;
name = "";
}
/**
* reset stat info
*/
public void resetCounters() {
for (int i=0; i<SIZEOF_CNT; i++)
cnt[i] = 0;
}
/**
* @return counters
*/
public int[] getCounters() {
return cnt;
}
/**
* @return the connection state
*/
public boolean isConnected() {
return socket != null && usable;
}
/**
* setup I/O Streams from socket
* @param socket a Socket (client or server)
* @exception IOException on error
*/
protected void connect (Socket socket)
throws IOException
{
this.socket = socket;
applyTimeout();
setLogger(getLogger(), getOriginalRealm() +
"/" + socket.getInetAddress().getHostAddress() + ":"
+ socket.getPort()
);
synchronized (serverInLock) {
serverIn = new DataInputStream (
new BufferedInputStream (socket.getInputStream ())
);
}
synchronized (serverOutLock) {
serverOut = new DataOutputStream(
new BufferedOutputStream(socket.getOutputStream(), 2048)
);
}
postConnectHook();
usable = true;
cnt[CONNECT]++;
setChanged();
notifyObservers();
}
protected void postConnectHook() throws IOException {
// do nothing
}
/**
* factory method pattern (as suggested by Vincent.Greene@amo.com)
* @param host remote host
* @param port remote port
* @throws IOException on error
*
* Use Socket factory if exists. If it is missing create a normal socket
* @see ISOClientSocketFactory
* @return newly created socket
*/
protected Socket newSocket(String host, int port) throws IOException {
try {
if (socketFactory != null)
return socketFactory.createSocket (host, port);
else {
if (connectTimeout > 0) {
Socket s = new Socket();
s.connect (
new InetSocketAddress (host, port),
connectTimeout
);
return s;
} else if (localIface == null && localPort == 0){
return new Socket(host,port);
} else {
InetAddress addr = (localIface == null) ?
InetAddress.getLocalHost() :
InetAddress.getByName(localIface);
return new Socket(host, port, addr, localPort);
}
}
} catch (ISOException e) {
throw new IOException (e.getMessage());
}
}
protected Socket newSocket (String[] hosts, int[] ports, LogEvent evt)
throws IOException
{
Socket s = null;
for (int i=0; i<hosts.length; i++) {
try {
evt.addMessage (hosts[i]+":"+ports[i]);
s = newSocket (hosts[i], ports[i]);
break;
} catch (IOException e) {
evt.addMessage (" " + e.getMessage());
}
}
if (s == null)
throw new IOException ("Unable to connect");
return s;
}
/**
* @return current socket
*/
public Socket getSocket() {
return socket;
}
/**
* @return current serverSocket
*/
public ServerSocket getServerSocket() {
return serverSocket;
}
/**
* sets socket timeout (as suggested by
* Leonard Thomas <leonard@rhinosystemsinc.com>)
* @param timeout in milliseconds
* @throws SocketException on error
*/
public void setTimeout (int timeout) throws SocketException {
this.timeout = timeout;
applyTimeout();
}
public int getTimeout () {
return timeout;
}
protected void applyTimeout () throws SocketException {
if (timeout >= 0 && socket != null)
socket.setSoTimeout (timeout);
}
/**
* Connects client ISOChannel to server
* @exception IOException
*/
public void connect () throws IOException {
LogEvent evt = new LogEvent (this, "connect");
try {
if (serverSocket != null) {
accept(serverSocket);
evt.addMessage ("local port "+serverSocket.getLocalPort()
+" remote host "+socket.getInetAddress());
}
else {
connect(newSocket (hosts, ports, evt));
}
applyTimeout();
if (socket != null)
socket.setKeepAlive (keepAlive);
Logger.log (evt);
setChanged();
notifyObservers();
} catch (ConnectException e) {
Logger.log (new LogEvent (this, "connection-refused",
getHost()+":"+getPort())
);
} catch (IOException e) {
evt.addMessage (e.getMessage ());
Logger.log (evt);
throw e;
}
}
/**
* Accepts connection
* @exception IOException
*/
public void accept(ServerSocket s) throws IOException {
// if (serverPort > 0)
// s = new ServerSocket (serverPort);
// else
// serverPort = s.getLocalPort();
Socket ss = s.accept();
this.name = ss.getInetAddress().getHostAddress()+":"+ss.getPort();
connect(ss);
// Warning - closing here breaks ISOServer, we need an
// accept that keep ServerSocket open.
// s.close();
}
/**
* @param b - new Usable state (used by ISOMUX internals to
* flag as unusable in order to force a reconnection)
*/
public void setUsable(boolean b) {
Logger.log (new LogEvent (this, "usable", b));
usable = b;
}
/**
* allow subclasses to override default packager
* on outgoing messages
* @param m outgoing ISOMsg
* @return ISOPackager
*/
protected ISOPackager getDynamicPackager (ISOMsg m) {
return packager;
}
/**
* allow subclasses to override default packager
* on outgoing messages
* @param image incoming message image
* @return ISOPackager
*/
protected ISOPackager getDynamicPackager (byte[] image) {
return packager;
}
/**
* allow subclasses to override default packager
* on outgoing messages
* @param header message header
* @param image incoming message image
* @return ISOPackager
*/
protected ISOPackager getDynamicPackager (byte[] header, byte[] image) {
return getDynamicPackager(image);
}
/**
* Allow subclasses to override the Default header on
* incoming messages.
* @param image message image
* @return ISOHeader instance
*/
protected ISOHeader getDynamicHeader (byte[] image) {
return image != null ?
new BaseHeader (image) : null;
}
protected void sendMessageLength(int len) throws IOException { }
protected void sendMessageHeader(ISOMsg m, int len) throws IOException {
if (!isOverrideHeader() && m.getHeader() != null)
serverOut.write(m.getHeader());
else if (header != null)
serverOut.write(header);
}
/**
* @deprecated use sendMessageTrailler(ISOMsg m, byte[] b) instead.
* @param m a reference to the ISOMsg
* @param len the packed image length
* @throws IOException on error
*/
protected void sendMessageTrailler(ISOMsg m, int len) throws IOException
{
}
@SuppressWarnings ("deprecation")
protected void sendMessageTrailler(ISOMsg m, byte[] b) throws IOException
{
sendMessageTrailler (m, b.length);
}
protected void getMessageTrailler() throws IOException { }
protected void getMessage (byte[] b, int offset, int len) throws IOException, ISOException {
serverIn.readFully(b, offset, len);
}
protected int getMessageLength() throws IOException, ISOException {
return -1;
}
protected int getHeaderLength() {
return header != null ? header.length : 0;
}
protected int getHeaderLength(byte[] b) { return 0; }
protected int getHeaderLength(ISOMsg m) {
return (!overrideHeader && m.getHeader() != null) ?
m.getHeader().length : getHeaderLength();
}
protected byte[] streamReceive() throws IOException {
return new byte[0];
}
protected void sendMessage (byte[] b, int offset, int len)
throws IOException
{
serverOut.write(b, offset, len);
}
/**
* sends an ISOMsg over the TCP/IP session
* @param m the Message to be sent
* @exception IOException
* @exception ISOException
* @exception ISOFilter.VetoException;
*/
public void send (ISOMsg m)
throws IOException, ISOException
{
LogEvent evt = new LogEvent (this, "send");
try {
if (!isConnected())
throw new ISOException ("unconnected ISOChannel");
m.setDirection(ISOMsg.OUTGOING);
m = applyOutgoingFilters (m, evt);
evt.addMessage (m);
m.setDirection(ISOMsg.OUTGOING); // filter may have drop this info
m.setPackager (getDynamicPackager(m));
byte[] b = m.pack();
synchronized (serverOutLock) {
sendMessageLength(b.length + getHeaderLength(m));
sendMessageHeader(m, b.length);
sendMessage (b, 0, b.length);
sendMessageTrailler(m, b);
serverOut.flush ();
}
cnt[TX]++;
setChanged();
notifyObservers(m);
} catch (VetoException e) {
//if a filter vets the message it was not added to the event
evt.addMessage (m);
evt.addMessage (e);
throw e;
} catch (ISOException e) {
evt.addMessage (e);
throw e;
} catch (IOException e) {
evt.addMessage (e);
throw e;
} catch (Exception e) {
evt.addMessage (e);
throw new ISOException ("unexpected exception", e);
} finally {
Logger.log (evt);
}
}
/**
* sends a byte[] over the TCP/IP session
* @param b the byte array to be sent
* @exception IOException
* @exception ISOException
* @exception ISOFilter.VetoException;
*/
public void send (byte[] b)
throws IOException, ISOException
{
LogEvent evt = new LogEvent (this, "send");
try {
if (!isConnected())
throw new ISOException ("unconnected ISOChannel");
synchronized (serverOutLock) {
serverOut.write(b);
serverOut.flush();
}
cnt[TX]++;
setChanged();
} catch (Exception e) {
evt.addMessage (e);
throw new ISOException ("unexpected exception", e);
} finally {
Logger.log (evt);
}
}
/**
* Sends a high-level keep-alive message (zero length)
* @throws IOException on exception
*/
public void sendKeepAlive () throws IOException {
synchronized (serverOutLock) {
sendMessageLength(0);
serverOut.flush ();
}
}
protected boolean isRejected(byte[] b) {
// VAP Header support - see VAPChannel
return false;
}
protected boolean shouldIgnore (byte[] b) {
// VAP Header support - see VAPChannel
return false;
}
/**
* support old factory method name for backward compatibility
* @return newly created ISOMsg
*/
protected ISOMsg createMsg () {
return createISOMsg();
}
protected ISOMsg createISOMsg () {
return packager.createISOMsg ();
}
/**
* Reads in a message header.
*
* @param hLen The Length og the reader to read
* @return The header bytes that were read in
* @throws IOException on error
*/
protected byte[] readHeader(int hLen) throws IOException {
byte[] header = new byte[hLen];
serverIn.readFully(header, 0, hLen);
return header;
}
/**
* Waits and receive an ISOMsg over the TCP/IP session
* @return the Message received
* @throws IOException
* @throws ISOException
*/
public ISOMsg receive() throws IOException, ISOException {
byte[] b=null;
byte[] header=null;
LogEvent evt = new LogEvent (this, "receive");
ISOMsg m = createMsg (); // call createMsg instead of createISOMsg for
// backward compatibility
m.setSource (this);
try {
if (!isConnected())
throw new ISOException ("unconnected ISOChannel");
synchronized (serverInLock) {
int len = getMessageLength();
int hLen = getHeaderLength();
if (len == -1) {
if (hLen > 0) {
header = readHeader(hLen);
}
b = streamReceive();
}
else if (len > 0 && len <= getMaxPacketLength()) {
if (hLen > 0) {
// ignore message header (TPDU)
// Note header length is not necessarily equal to hLen (see VAPChannel)
header = readHeader(hLen);
len -= header.length;
}
b = new byte[len];
getMessage (b, 0, len);
getMessageTrailler();
}
else
throw new ISOException(
"receive length " +len + " seems strange - maxPacketLength = " + getMaxPacketLength());
}
m.setPackager (getDynamicPackager(header, b));
m.setHeader (getDynamicHeader(header));
if (b.length > 0 && !shouldIgnore (header)) // Ignore NULL messages
unpack (m, b);
m.setDirection(ISOMsg.INCOMING);
m = applyIncomingFilters (m, header, b, evt);
m.setDirection(ISOMsg.INCOMING);
evt.addMessage (m);
cnt[RX]++;
setChanged();
notifyObservers(m);
} catch (ISOException e) {
evt.addMessage (e);
if (header != null) {
evt.addMessage ("
evt.addMessage (ISOUtil.hexdump (header));
}
if (b != null) {
evt.addMessage ("
evt.addMessage (ISOUtil.hexdump (b));
}
throw e;
} catch (EOFException e) {
closeSocket();
evt.addMessage ("<peer-disconnect/>");
throw e;
} catch (SocketException e) {
closeSocket();
if (usable)
evt.addMessage ("<peer-disconnect>" + e.getMessage() + "</peer-disconnect>");
throw e;
} catch (InterruptedIOException e) {
closeSocket();
evt.addMessage ("<io-timeout/>");
throw e;
} catch (IOException e) {
closeSocket();
if (usable)
evt.addMessage (e);
throw e;
} catch (Exception e) {
evt.addMessage (m);
evt.addMessage (e);
throw new ISOException ("unexpected exception", e);
} finally {
Logger.log (evt);
}
return m;
}
/**
* Low level receive
* @param b byte array
* @throws IOException on error
* @return the total number of bytes read into the buffer,
* or -1 if there is no more data because the end of the stream has been reached.
*/
public int getBytes (byte[] b) throws IOException {
return serverIn.read (b);
}
/**
* disconnects the TCP/IP session. The instance is ready for
* a reconnection. There is no need to create a new ISOChannel<br>
* @exception IOException
*/
public void disconnect () throws IOException {
LogEvent evt = new LogEvent (this, "disconnect");
if (serverSocket != null)
evt.addMessage ("local port "+serverSocket.getLocalPort()
+" remote host "+serverSocket.getInetAddress());
else
evt.addMessage (host+":"+port);
try {
usable = false;
setChanged();
notifyObservers();
closeSocket();
if (serverIn != null) {
try {
serverIn.close();
} catch (IOException ex) { evt.addMessage (ex); }
serverIn = null;
}
if (serverOut != null) {
try {
serverOut.close();
} catch (IOException ex) { evt.addMessage (ex); }
serverOut = null;
}
} catch (IOException e) {
evt.addMessage (e);
Logger.log (evt);
throw e;
}
socket = null;
}
/**
* Issues a disconnect followed by a connect
* @exception IOException
*/
public void reconnect() throws IOException {
disconnect();
connect();
}
public void setLogger (Logger logger, String realm) {
this.logger = logger;
this.realm = realm;
if (originalRealm == null)
originalRealm = realm;
}
public String getRealm () {
return realm;
}
public Logger getLogger() {
return logger;
}
public String getOriginalRealm() {
return originalRealm == null ?
this.getClass().getName() : originalRealm;
}
/**
* associates this ISOChannel with a name using NameRegistrar
* @param name name to register
* @see NameRegistrar
*/
public void setName (String name) {
this.name = name;
NameRegistrar.register ("channel."+name, this);
}
/**
* @return this ISOChannel's name ("" if no name was set)
*/
public String getName() {
return this.name;
}
/**
* @param filter filter to add
* @param direction ISOMsg.INCOMING, ISOMsg.OUTGOING, 0 for both
*/
@SuppressWarnings ("unchecked")
public void addFilter (ISOFilter filter, int direction) {
switch (direction) {
case ISOMsg.INCOMING :
incomingFilters.add (filter);
break;
case ISOMsg.OUTGOING :
outgoingFilters.add (filter);
break;
case 0 :
incomingFilters.add (filter);
outgoingFilters.add (filter);
break;
}
}
/**
* @param filter incoming filter to add
*/
public void addIncomingFilter (ISOFilter filter) {
addFilter (filter, ISOMsg.INCOMING);
}
/**
* @param filter outgoing filter to add
*/
public void addOutgoingFilter (ISOFilter filter) {
addFilter (filter, ISOMsg.OUTGOING);
}
/**
* @param filter filter to add (both directions, incoming/outgoing)
*/
public void addFilter (ISOFilter filter) {
addFilter (filter, 0);
}
/**
* @param filter filter to remove
* @param direction ISOMsg.INCOMING, ISOMsg.OUTGOING, 0 for both
*/
public void removeFilter (ISOFilter filter, int direction) {
switch (direction) {
case ISOMsg.INCOMING :
incomingFilters.remove (filter);
break;
case ISOMsg.OUTGOING :
outgoingFilters.remove (filter);
break;
case 0 :
incomingFilters.remove (filter);
outgoingFilters.remove (filter);
break;
}
}
/**
* @param filter filter to remove (both directions)
*/
public void removeFilter (ISOFilter filter) {
removeFilter (filter, 0);
}
/**
* @param filter incoming filter to remove
*/
public void removeIncomingFilter (ISOFilter filter) {
removeFilter (filter, ISOMsg.INCOMING);
}
/**
* @param filter outgoing filter to remove
*/
public void removeOutgoingFilter (ISOFilter filter) {
removeFilter (filter, ISOMsg.OUTGOING);
}
protected ISOMsg applyOutgoingFilters (ISOMsg m, LogEvent evt)
throws VetoException
{
Iterator iter = outgoingFilters.iterator();
while (iter.hasNext())
m = ((ISOFilter) iter.next()).filter (this, m, evt);
return m;
}
protected ISOMsg applyIncomingFilters (ISOMsg m, LogEvent evt)
throws VetoException
{
return applyIncomingFilters (m, null, null, evt);
}
protected ISOMsg applyIncomingFilters (ISOMsg m, byte[] header, byte[] image, LogEvent evt)
throws VetoException
{
Iterator iter = incomingFilters.iterator();
while (iter.hasNext()) {
ISOFilter f = (ISOFilter) iter.next ();
if (image != null && (f instanceof RawIncomingFilter))
m = ((RawIncomingFilter)f).filter (this, m, header, image, evt);
else
m = f.filter (this, m, evt);
}
return m;
}
protected void unpack (ISOMsg m, byte[] b) throws ISOException {
m.unpack (b);
}
/**
* Implements Configurable<br>
* Properties:<br>
* <ul>
* <li>host - destination host (if ClientChannel)
* <li>port - port number (if ClientChannel)
* <li>local-iface - local interfase to use (if ClientChannel)
* <li>local-port - local port to bind (if ClientChannel)
* </ul>
* (host not present indicates a ServerChannel)
*
* @param cfg Configuration
* @throws ConfigurationException
*/
public void setConfiguration (Configuration cfg)
throws ConfigurationException
{
this.cfg = cfg;
String h = cfg.get ("host");
int port = cfg.getInt ("port");
maxPacketLength = cfg.getInt ("max-packet-length", 100000);
if (h != null && h.length() > 0) {
if (port == 0)
throw new ConfigurationException
("invalid port for host '"+h+"'");
setHost (h, port);
setLocalAddress (cfg.get("local-iface", null),cfg.getInt("local-port"));
String[] altHosts = cfg.getAll ("alternate-host");
int[] altPorts = cfg.getInts ("alternate-port");
hosts = new String[altHosts.length + 1];
ports = new int[altPorts.length + 1];
if (hosts.length != ports.length) {
throw new ConfigurationException (
"alternate host/port misconfiguration"
);
}
hosts[0] = host;
ports[0] = port;
System.arraycopy (altHosts, 0, hosts, 1, altHosts.length);
System.arraycopy (altPorts, 0, ports, 1, altPorts.length);
}
setOverrideHeader(cfg.getBoolean ("override-header", false));
keepAlive = cfg.getBoolean ("keep-alive", false);
if (socketFactory != this && socketFactory instanceof Configurable)
((Configurable)socketFactory).setConfiguration (cfg);
try {
setTimeout (cfg.getInt ("timeout"));
connectTimeout = cfg.getInt ("connect-timeout", timeout);
} catch (SocketException e) {
throw new ConfigurationException (e);
}
}
public Configuration getConfiguration() {
return cfg;
}
public Collection getIncomingFilters() {
return incomingFilters;
}
public Collection getOutgoingFilters() {
return outgoingFilters;
}
public void setIncomingFilters (Collection filters) {
incomingFilters = new Vector (filters);
}
public void setOutgoingFilters (Collection filters) {
outgoingFilters = new Vector (filters);
}
public void setHeader (byte[] header) {
this.header = header;
}
public void setHeader (String header) {
setHeader (header.getBytes());
}
public byte[] getHeader () {
return header;
}
public void setOverrideHeader (boolean overrideHeader) {
this.overrideHeader = overrideHeader;
}
public boolean isOverrideHeader () {
return overrideHeader;
}
/**
* @param name the Channel's name (without the "channel." prefix)
* @return ISOChannel instance with given name.
* @throws NameRegistrar.NotFoundException;
* @see NameRegistrar
*/
public static ISOChannel getChannel (String name)
throws NameRegistrar.NotFoundException
{
return (ISOChannel) NameRegistrar.get ("channel."+name);
}
/**
* Gets the ISOClientSocketFactory (may be null)
* @see ISOClientSocketFactory
* @since 1.3.3 \
* @return ISOClientSocketFactory
*/
public ISOClientSocketFactory getSocketFactory() {
return socketFactory;
}
/**
* Sets the specified Socket Factory to create sockets
* @param socketFactory the ISOClientSocketFactory
* @see ISOClientSocketFactory
* @since 1.3.3
*/
public void setSocketFactory(ISOClientSocketFactory socketFactory) {
this.socketFactory = socketFactory;
}
public int getMaxPacketLength() {
return maxPacketLength;
}
public void setMaxPacketLength(int maxPacketLength) {
this.maxPacketLength = maxPacketLength;
}
private void closeSocket() throws IOException {
if (socket != null) {
try {
socket.setSoLinger (false);
socket.shutdownOutput(); // This will force a TCP FIN to be sent.
} catch (SocketException e) {
// safe to ignore - can be closed already
// e.printStackTrace();
}
socket.close ();
socket = null;
}
}
public Object clone(){
try {
BaseChannel channel = (BaseChannel)super.clone();
channel.cnt = cnt.clone();
// The lock objects must also be cloned, and the DataStreams nullified, as it makes no sense
// to use the new lock objects to protect the old DataStreams.
// This should be safe as the only code that calls BaseChannel.clone() is ISOServer.run(),
// and it immediately calls accept(ServerSocket) which does a connect(), and that sets the stream objects.
channel.serverInLock = new Object();
channel.serverOutLock = new Object();
channel.serverIn = null;
channel.serverOut = null;
channel.usable = false;
channel.socket = null;
return channel;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
}
|
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package propsandcovariants;
import acq.AcquisitionEvent;
import coordinates.AffineUtils;
import coordinates.XYStagePosition;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.List;
import misc.Log;
import surfacesandregions.SingleResolutionInterpolation;
import surfacesandregions.SurfaceInterpolator;
/**
* Category about interpolated surface (e.g. distance below surface) to be used in
* covaried settings
*/
public class SurfaceData implements Covariant {
//all data must start with this prefix so they can be reconstructed when read from a text file on disk
public static String PREFIX = "Surface data: ";
//number of test points per dimension for finding minimum distance to surface
private static final int NUM_XY_TEST_POINTS = 9;
//number of test points per dimension for finding minimum distance to surface within angle
// private static final int NUM_XY_TEST_POINTS_ANGLE = 5;
public static String SPACER = "
public static String DISTANCE_BELOW_SURFACE_CENTER = "Vertical distance below at XY position center";
public static String DISTANCE_BELOW_SURFACE_MINIMUM = "Minimum vertical distance below at XY position";
public static String DISTANCE_BELOW_SURFACE_MAXIMUM = "Maximum vertical distance below at XY position";
public static String LN_OPTIMAL_DISTANCE_MT = "Lymph Node optimal distance Maitai";
public static String LN_OPTIMAL_DISTANCE_CHAM = "Lymph Node optimal distance Chameleon";
private String category_;
private SurfaceInterpolator surface_;
public SurfaceData(SurfaceInterpolator surface, String type) throws Exception {
category_ = type;
surface_ = surface;
if (!Arrays.asList(enumerateDataTypes()).contains(type)) {
//not a recognized type
throw new Exception();
}
}
public SurfaceInterpolator getSurface() {
return surface_;
}
public static String[] enumerateDataTypes() {
return new String[] {DISTANCE_BELOW_SURFACE_CENTER, DISTANCE_BELOW_SURFACE_MINIMUM,
DISTANCE_BELOW_SURFACE_MAXIMUM, LN_OPTIMAL_DISTANCE_MT, LN_OPTIMAL_DISTANCE_CHAM};
}
@Override
public String toString() {
return getName();
}
@Override
public String getAbbreviatedName() {
if (category_.equals(DISTANCE_BELOW_SURFACE_CENTER)) {
return "Vertical distance to " + surface_.getName();
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MINIMUM)) {
return "Min vertical distance to " + surface_.getName();
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MAXIMUM)) {
return "Min distance to " + surface_.getName();
} else if (category_.equals(LN_OPTIMAL_DISTANCE_MT)) {
return "Maitai Lymph node optimal distance for " + surface_.getName();
} else {
Log.log("Unknown Surface data type");
throw new RuntimeException();
}
}
@Override
public String getName() {
return PREFIX + surface_.getName() + SPACER + category_;
}
@Override
public boolean isValid(CovariantValue potentialValue) {
return potentialValue.getType() == CovariantType.DOUBLE;
}
@Override
public CovariantValue[] getAllowedValues() {
//not applicable because all numerical for now
return null;
}
@Override
public boolean isDiscrete() {
return false;
}
@Override
public boolean hasLimits() {
return false;
}
@Override
public CovariantValue getLowerLimit() {
return null;
}
@Override
public CovariantValue getUpperLimit() {
return null;
}
@Override
public CovariantType getType() {
return CovariantType.DOUBLE;
}
@Override
public CovariantValue getValidValue(List<CovariantValue> vals) {
double d = 0;
while (true) {
if (!vals.contains(new CovariantValue(d))) {
return new CovariantValue(d);
}
d++;
}
}
// private double lnOptimalDistanceOld(XYStagePosition xyPos, double zPosition) throws InterruptedException {
// // a special measure for curved surfaces, which gives:
// //-min distance at surface on flatter parts of curved surface (ie top)
// //-increased distance up to max distance as you go deeper
// //-higher distance at surface on side to account for curved surface blocking out some of exciation light
// //{minDistance,maxDistance, minNormalAngle, maxNormalAngle)
// double[] vals = distanceAndNormalCalc(xyPos.getFullTileCorners(), zPosition);
// double extraDistance = 0; //pretend actually deeper in LN than we are to account for blockage by curved surface
// double angleCutoff = 64; //angle cutoff is maximum nalge colletred by 1.2 NA objective
// double doublingDistance = 50;
// double angleCutoffPercent = 0;
// //twice as much power if angle goes to 0
// //doubling distance ~40-70 um when b = 0.01-0.018 i exponent
// //add extra distance to account for blockage by LN surface
// //never want to make extra distance higher than the double distance,
// //so extra power is capped at 2x
// angleCutoffPercent = Math.min(angleCutoff, vals[3]) / angleCutoff;
// extraDistance = angleCutoffPercent * doublingDistance;
// double curvatureCorrectedMin = vals[0] + extraDistance;
// double ret = Math.min(vals[1], Math.max(curvatureCorrectedMin, Math.pow(vals[0], 1.2)));
// return ret;
private double lnOptimalDistance(XYStagePosition xyPos, double zPosition, boolean maitai) throws InterruptedException {
double[] vals = distanceAndNormalCalc(xyPos.getFullTileCorners(), zPosition);
//use mindistance and max normal so as to not explode LN
double minDist = vals[0];
double maxNormal = vals[3];
//look up
int minDistIndex = (int) Math.max(0, Math.min(33, minDist / 9));
int normalIndex = (int) Math.max(0, Math.min(15, maxNormal / 5));
return maitai ? LN_DISTANCES_MT[normalIndex][minDistIndex] : LN_DISTANCES_CHAM[normalIndex][minDistIndex];
}
/**
*
* @param corners
* @param min true to get min, false to get max
* @return {minDistance,maxDistance, minNormalAngle, maxNormalAngle)
*/
private double[] distanceAndNormalCalc(Point2D.Double[] corners, double zVal) throws InterruptedException {
//check a grid of points spanning entire position
//square is aligned with axes in pixel space, so convert to pixel space to generate test points
double xSpan = corners[2].getX() - corners[0].getX();
double ySpan = corners[2].getY() - corners[0].getY();
Point2D.Double pixelSpan = new Point2D.Double();
AffineTransform transform = AffineUtils.getAffineTransform(surface_.getCurrentPixelSizeConfig(),0, 0);
try {
transform.inverseTransform(new Point2D.Double(xSpan, ySpan), pixelSpan);
} catch (NoninvertibleTransformException ex) {
Log.log("Problem inverting affine transform");
}
double minDistance = Integer.MAX_VALUE;
double maxDistance = 0;
double minNormalAngle = 90;
double maxNormalAngle = 0;
for (double x = 0; x <= pixelSpan.x; x += pixelSpan.x / (double) NUM_XY_TEST_POINTS) {
for (double y = 0; y <= pixelSpan.y; y += pixelSpan.y / (double) NUM_XY_TEST_POINTS) {
//convert these abritray pixel coordinates back to stage coordinates
double[] transformMaxtrix = new double[6];
transform.getMatrix(transformMaxtrix);
transformMaxtrix[4] = corners[0].getX();
transformMaxtrix[5] = corners[0].getY();
//create new transform with translation applied
transform = new AffineTransform(transformMaxtrix);
Point2D.Double stageCoords = new Point2D.Double();
transform.transform(new Point2D.Double(x, y), stageCoords);
//test point for inclusion of position
if (!surface_.waitForCurentInterpolation().isInterpDefined(stageCoords.x, stageCoords.y)) {
//if position is outside of convex hull, assume min distance is 0
minDistance = 0;
//get extrapolated value for max distance
float interpVal = surface_.waitForCurentInterpolation().getExtrapolatedValue(stageCoords.x, stageCoords.y);
maxDistance = Math.max(zVal - interpVal, maxDistance);
//only take actual values for normals
} else {
float interpVal = surface_.waitForCurentInterpolation().getInterpolatedValue(stageCoords.x, stageCoords.y);
float normalAngle = surface_.waitForCurentInterpolation().getNormalAngleToVertical(stageCoords.x, stageCoords.y);
minDistance = Math.min(Math.max(0,zVal - interpVal), minDistance);
maxDistance = Math.max(zVal - interpVal, maxDistance);
minNormalAngle = Math.min(minNormalAngle, normalAngle);
maxNormalAngle = Math.max(maxNormalAngle, normalAngle);
}
}
}
return new double[]{minDistance, maxDistance, minNormalAngle, maxNormalAngle};
}
@Override
public CovariantValue getCurrentValue(AcquisitionEvent event) throws Exception {
XYStagePosition xyPos = event.xyPosition_;
if (category_.equals(DISTANCE_BELOW_SURFACE_CENTER)) {
//if interpolation is undefined at position center, assume distance below is 0
Point2D.Double center = xyPos.getCenter();
SingleResolutionInterpolation interp = surface_.waitForCurentInterpolation();
if (interp.isInterpDefined(center.x, center.y)) {
return new CovariantValue( event.zPosition_ - interp.getInterpolatedValue(center.x, center.y));
}
return new CovariantValue(0.0);
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MINIMUM)) {
return new CovariantValue(distanceAndNormalCalc(xyPos.getFullTileCorners(), event.zPosition_)[0]);
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MAXIMUM)) {
return new CovariantValue(distanceAndNormalCalc(xyPos.getFullTileCorners(), event.zPosition_)[1]);
} else if (category_.equals(LN_DISTANCES_MT)) {
return new CovariantValue(lnOptimalDistance(xyPos, event.zPosition_, true));
} else if (category_.equals(LN_DISTANCES_CHAM)) {
return new CovariantValue(lnOptimalDistance(xyPos, event.zPosition_, false));
} else {
Log.log("Unknown Surface data type",true);
throw new RuntimeException();
}
}
@Override
public void updateHardwareToValue(CovariantValue dVal) {
Log.log("No hardware associated with Surface data",true);
throw new RuntimeException();
}
public static void main (String[] args) {
System.out.println();
}
private static final double[][] LN_DISTANCES_CHAM = new double[][]
{{-0.000000,9.146382,18.234974,27.266530,36.241822,45.161643,54.026803,62.838128,71.596457,80.302642,88.957547,97.562041,106.117005,114.623321,123.081877,131.493564,139.859272,148.179891,156.456312,164.689418,172.880093,181.029210,189.137641,197.206247,205.235882,213.227391,221.181608,229.099357,236.981452,244.828692,252.641867,260.421753,268.169112,275.884693},
{-0.000000,9.207467,18.345123,27.414656,36.417732,45.355985,54.231023,63.044424,71.797734,80.492472,89.130121,97.712136,106.239938,114.714918,123.138433,131.511808,139.836339,148.113288,156.343885,164.529331,172.670797,180.769420,188.826311,196.842550,204.819188,212.757250,220.657730,228.521597,236.349792,244.143232,251.902806,259.629380,267.323796,274.986870},
{-0.000000,9.404749,18.697773,27.884768,36.971114,45.961890,54.861878,63.675580,72.407225,81.060787,89.639993,98.148342,106.589117,114.965395,123.280061,131.535825,139.735228,147.880654,155.974344,164.018404,172.014814,179.965436,187.872025,195.736234,203.559625,211.343670,219.089761,226.799214,234.473277,242.113132,249.719899,257.294643,264.838376,272.352061},
{-0.000000,9.790376,19.372345,28.764980,37.985429,47.049067,55.969646,64.759452,73.429452,81.989434,90.448132,98.813350,107.092063,115.290516,123.414306,131.468463,139.457512,147.385532,155.256211,163.072891,170.838604,178.556110,186.227929,193.856365,201.443529,208.991363,216.501656,223.976059,231.416102,238.823202,246.198678,253.543758,260.859590,268.147246},
{-0.000000,10.503015,20.558682,30.241821,39.612650,48.719599,57.601695,66.290509,74.811717,83.186329,91.431665,99.562106,107.589684,115.524548,123.375321,131.149387,138.853111,146.492019,154.070944,161.594130,169.065334,176.487896,183.864799,191.198724,198.492087,205.747076,212.965681,220.149717,227.300848,234.420598,241.510374,248.571475,255.605104,262.612378},
{-0.000000,11.984941,22.690768,32.601064,41.972711,50.953196,59.633933,68.075522,76.320435,84.399784,92.337186,100.151080,107.856197,115.464528,122.985995,130.428928,137.800379,145.106403,152.352235,159.542440,166.681024,173.771531,180.817108,187.820571,194.784446,201.711014,208.602338,215.460298,222.286607,229.082832,235.850414,242.590681,249.304857,255.994076},
{1.294231,16.288229,27.001753,36.651080,45.691522,54.313270,62.621654,70.683381,78.544162,86.237027,93.786831,101.212836,108.530337,115.751726,122.887204,129.945299,136.933220,143.857122,150.722316,157.533419,164.294474,171.009048,177.680301,184.311054,190.903833,197.460914,203.984353,210.476015,216.937602,223.370665,229.776630,236.156803,242.512391,248.844490},
{5.012817,21.692950,32.820143,42.418489,51.202039,59.468169,67.371629,75.003599,82.422502,89.668292,96.769459,103.747362,110.618426,117.395618,124.089442,130.708555,137.260194,143.750494,150.184715,156.567405,162.902534,169.193591,175.443663,181.655497,187.831550,193.974029,200.084928,206.166052,212.219046,218.245407,224.246509,230.223612,236.177876,242.110371},
{9.157103,26.104313,37.458632,47.144951,55.894159,64.028282,71.724340,79.091655,86.202846,93.108671,99.845988,106.442368,112.918944,119.292262,125.575493,131.779285,137.912395,143.982083,149.994474,155.954716,161.867555,167.735986,173.564187,179.354811,185.110454,190.833415,196.525758,202.189320,207.825787,213.436656,219.023309,224.587002,230.128887,235.650024},
{13.510033,29.910306,41.100297,50.679720,59.323709,67.334129,74.880367,82.069623,88.974957,95.648967,102.130694,108.450203,114.631060,120.692103,126.648622,132.513183,138.296233,144.006543,149.651542,155.237568,160.770067,166.253752,171.692723,177.090570,182.450446,187.775141,193.067132,198.328626,203.561601,208.767833,213.948925,219.106329,224.241361,229.355225},
{17.956378,33.312456,44.001962,53.225301,61.582666,69.342758,76.657019,83.621813,90.303545,96.750424,102.998863,109.077211,115.008050,120.809706,126.497323,132.083543,137.579054,142.992955,148.333095,153.606264,158.818362,163.974588,169.079522,174.137201,179.151243,184.124842,189.060894,193.961984,198.830448,203.668385,208.477718,213.260184,218.017372,222.750731},
{22.445367,36.454511,46.386762,55.027609,62.900258,70.238595,77.174247,83.791019,90.078298,96.282991,102.231979,108.018404,113.662160,119.179505,124.584093,129.886810,135.097855,140.225332,145.276543,150.257767,155.174617,160.032027,164.834399,169.585668,174.289376,178.948711,183.566575,188.145594,192.688162,197.196470,201.672522,206.118159,210.535074,214.924830},
{26.964997,39.440850,48.427195,56.301506,63.512406,70.260494,76.658522,82.778176,88.668743,94.366008,99.897061,105.283018,110.540815,115.684242,120.724793,125.672143,130.534514,135.319069,140.032007,144.678626,149.263826,153.791889,158.266626,162.691455,167.069474,171.403498,175.696085,179.949573,184.166110,188.347664,192.496055,196.612966,200.699954,204.758462},
{31.526919,42.345342,50.245140,57.207783,63.610228,69.621362,75.336208,80.815169,86.099763,91.220115,96.198980,101.054094,105.799641,110.447179,115.006295,119.485059,123.890341,128.228052,132.503388,136.720796,140.884276,144.997365,149.063225,153.084695,157.064341,161.004491,164.907265,168.774604,172.608281,176.409929,180.181071,183.923094,187.637302,191.324912},
{36.158279,45.219329,51.918043,57.849844,63.321680,68.471592,73.377494,78.089000,82.640253,87.056054,91.355151,95.552127,99.658661,103.684271,107.636863,111.523074,115.348572,119.118119,122.836025,126.505953,130.131182,133.714608,137.258674,140.765845,144.238151,147.677547,151.085636,154.464090,157.814314,161.137640,164.435273,167.708348,170.957906,174.184878},
{40.897855,48.095654,53.482716,58.272749,62.702423,66.878934,70.863017,74.693513,78.397195,81.993603,85.497472,88.920350,92.271479,95.558382,98.787347,101.963537,105.091537,108.175171,111.217792,114.222274,117.191374,120.127223,123.031926,125.907324,128.755076,131.576685,134.373231,137.146822,139.897740,142.627322,145.336550,148.026284,150.697362,153.350573}};
private static final double[][] LN_DISTANCES_MT = new double[][]
{{-0.000000,9.124383,18.148035,27.073360,35.902862,44.639129,53.284815,61.842622,70.315290,78.705573,87.016233,95.250020,103.409667,111.497873,119.517297,127.470547,135.360178,143.188678,150.958470,158.671906,166.331262,173.938737,181.496454,189.006456,196.470706,203.891090,211.269417,218.607418,225.906750,233.168997,240.395672,247.588220,254.748020,261.876386},
{-0.000000,9.180868,18.241086,27.185799,36.019997,44.748506,53.375988,61.906929,70.345643,78.696269,86.962773,95.148950,103.258426,111.294664,119.260969,127.160489,134.996224,142.771030,150.487624,158.148590,165.756386,173.313349,180.821698,188.283542,195.700884,203.075629,210.409585,217.704468,224.961910,232.183461,239.370593,246.524704,253.647124,260.739115},
{-0.000000,9.362086,18.535053,27.535455,36.378216,45.076736,53.643016,62.087784,70.420625,78.650102,86.783872,94.828790,102.791006,110.676047,118.488894,126.234050,133.915594,141.537234,149.102351,156.614034,164.075120,171.488214,178.855723,186.179868,193.462713,200.706173,207.912033,215.081959,222.217510,229.320147,236.391242,243.432083,250.443886,257.427797},
{-0.000000,9.710525,19.079390,28.159067,36.992784,45.615983,54.057675,62.341638,70.487418,78.511155,86.426260,94.243944,101.973649,109.623388,117.200010,124.709414,132.156720,139.546403,146.882400,154.168197,161.406904,168.601305,175.753909,182.866990,189.942613,196.982645,203.988888,210.962865,217.906074,224.819877,231.705542,238.564251,245.397106,252.205138},
{-0.000000,10.330476,19.971375,29.105943,37.859353,46.317975,54.542488,62.576469,70.451969,78.193123,85.818525,93.342798,100.777664,108.132680,115.415754,122.633520,129.791606,136.894843,143.947410,150.952958,157.914700,164.835481,171.717839,178.564047,185.376155,192.155993,198.905328,205.625621,212.318311,218.984698,225.625978,232.243261,238.837574,245.409875},
{-0.000000,11.480989,21.323301,30.345825,38.866892,47.040947,54.956019,62.667979,70.214971,77.624441,84.916913,92.108222,99.210889,106.235012,113.188883,120.079407,126.912407,133.692848,140.425009,147.112603,153.758882,160.366685,166.938641,173.476933,179.983625,186.460552,192.909374,199.331600,205.728608,212.101658,218.451908,224.780425,231.088194,237.376128},
{0.735123,13.951579,23.528456,32.195357,40.338976,48.127854,55.655290,62.979645,70.140359,77.165594,84.076279,90.888468,97.614796,104.265414,110.848620,117.371302,123.839247,130.257375,136.629901,142.960507,149.252360,155.508274,161.730728,167.921931,174.083857,180.218280,186.326802,192.410874,198.471818,204.510839,210.529043,216.527445,222.506981,228.468516},
{2.847280,17.232953,26.737938,35.060609,42.782359,50.127008,57.205946,64.083795,70.802100,77.389608,83.867283,90.251021,96.553219,102.783806,108.950854,115.061048,121.119989,127.132428,133.102433,139.033520,144.928750,150.790808,156.622065,162.424622,168.200357,173.950954,179.677929,185.382652,191.066368,196.730213,202.375223,208.002347,213.612461,219.206370},
{5.201234,19.844046,29.420186,37.621411,45.097435,52.120422,58.832370,65.316678,71.626337,77.796989,83.853783,89.815113,95.694907,101.503952,107.250829,112.942497,118.584689,124.182208,129.739123,135.258922,140.744622,146.198857,151.623940,157.021922,162.394624,167.743679,173.070556,178.376574,183.662937,188.930739,194.180976,199.414563,204.632338,209.835074},
{7.673699,21.929842,31.397626,39.476758,46.784228,53.590388,60.042881,66.232682,72.219846,78.046172,83.741784,89.329077,94.825097,100.243091,105.593529,110.884824,116.123828,121.316195,126.466644,131.579154,136.657115,141.703440,146.720659,151.710962,156.676302,161.618387,166.538746,171.438745,176.319613,181.182459,186.028293,190.858030,195.672513,200.472508},
{10.199223,23.635981,32.755220,40.579795,47.660583,54.241690,60.459424,66.399663,72.120754,77.664452,83.061752,88.336336,93.506683,98.587514,103.590703,108.525961,113.401323,118.223481,122.998088,127.729934,132.423121,137.081177,141.707157,146.303722,150.873202,155.417652,159.938883,164.438510,168.917972,173.378555,177.821426,182.247628,186.658115,191.053744},
{12.748968,25.081836,33.630073,41.025947,47.748652,54.010393,59.929998,65.582763,71.020361,76.280218,81.390541,86.373205,91.245648,96.021964,100.713768,105.330665,109.881008,114.371527,118.808234,123.196259,127.540061,131.843540,136.110105,140.342789,144.544263,148.716905,152.862839,156.983967,161.082002,165.158486,169.214807,173.252229,177.271900,181.274870},
{15.316118,26.357575,34.151814,40.949689,47.161846,52.969703,58.474510,63.740347,68.811143,73.718705,78.487120,83.135095,87.677608,92.126918,96.493139,100.784797,105.009146,109.172419,113.280030,117.336703,121.346598,125.313392,129.240360,133.130429,136.986224,140.810114,144.604236,148.370534,152.110769,155.826566,159.519382,163.190574,166.841381,170.472949},
{17.907290,27.526392,34.421369,40.474591,46.031948,51.246267,56.202749,60.955157,65.540263,69.984641,74.308298,78.526859,82.652695,86.695946,90.665002,94.566923,98.407713,102.192553,105.925838,109.611805,113.253633,116.854518,120.417211,123.944207,127.437747,130.899845,134.332326,137.736997,141.115282,144.468662,147.798405,151.105747,154.391821,157.657660},
{20.537903,28.628679,34.504870,39.689398,44.465510,48.958813,53.239426,57.351636,61.325692,65.183478,68.941422,72.612307,76.206277,79.731555,83.195028,86.602430,89.958614,93.267794,96.533562,99.759084,102.947217,106.100381,109.220802,112.310473,115.371183,118.404555,121.412058,124.395051,127.354758,130.292280,133.208764,136.105091,138.982184,141.840879},
{23.229982,29.684556,34.430686,38.634626,42.516172,46.173967,49.663180,53.018800,56.264782,59.418430,62.492829,65.498080,68.442358,71.332136,74.172844,76.969011,79.724792,82.443161,85.127095,87.779137,90.401487,92.996104,95.564732,98.108937,100.630145,103.129560,105.608408,108.067034,110.508463,112.931517,115.337700,117.727757,120.102387,122.462244}};
}
|
package ml;
import org.mwg.Graph;
import org.mwg.GraphBuilder;
import org.mwg.Callback;
import org.mwg.ml.MLXPlugin;
import org.mwg.ml.algorithm.profiling.GaussianMixtureNode;
import org.mwg.core.scheduler.NoopScheduler;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
/**
* @ignore ts
*/
public class GaussianMixtureSim {
public static void main(String[] arg) {
final Graph graph = new GraphBuilder().withPlugin(new MLXPlugin()).withScheduler(new NoopScheduler()).build();
graph.connect(new Callback<Boolean>() {
@Override
public void on(Boolean result) {
boolean exit = false;
String command;
GaussianMixtureNode node1 = (GaussianMixtureNode) graph.newTypedNode(0, 0, GaussianMixtureNode.NAME);
node1.set(GaussianMixtureNode.LEVEL,2);
node1.set(GaussianMixtureNode.WIDTH,3);
while (!exit) {
Scanner scanIn = new Scanner(System.in);
command = scanIn.nextLine();
String[] args = command.split(" ");
if (args[0].equals("exit")) {
exit = true;
}
if (args[0].equals("add")) {
double[] data = new double[args.length - 1];
for (int i = 0; i < data.length; i++) {
data[i] = Double.parseDouble(args[i + 1]);
}
//to set data here
node1.learnVector(data,new Callback<Boolean>() {
@Override
public void on(Boolean result) {
}
});
long[] sublev = node1.getSubGraph();
for (int i = 0; i < sublev.length; i++) {
System.out.println("->" + sublev[i]);
}
}
if (args[0].equals("avg")) {
print(node1.getAvg());
}
if (args[0].equals("min")) {
print(node1.getMin());
}
if (args[0].equals("max")) {
print(node1.getMax());
}
if (args[0].equals("draw")) {
long[] sublev = node1.getSubGraph();
for (int i = 0; i < sublev.length; i++) {
System.out.println("->" + sublev[i]);
}
}
}
}
});
}
public static void print(double[] val) {
NumberFormat formatter = new DecimalFormat("#0.00");
if (val == null) {
return;
}
for (int i = 0; i < val.length; i++) {
System.out.print(formatter.format(val[i]) + " ");
}
System.out.println();
}
}
|
package org.pm4j.core.pm;
import java.io.Serializable;
import org.pm4j.core.exception.PmConverterException;
import org.pm4j.core.pm.annotation.PmAttrCfg;
import org.pm4j.core.pm.impl.PmAttrImpl;
/**
* Presentation model for attributes. It adds presentation logic aspects for
* attribute value handling to the base interface {@link PmObject}.
* <p>
* An attribute represents a data item that is usually represented as a data
* entry field on a form.
* <p>
* Details on how to implement application specific attribute logic see
* {@link PmAttrImpl}.
*
* @param <T> The attribute value type provided for the view.
*
* @author olaf boede
*/
public interface PmAttr<T> extends PmObject, PmDataInput {
/**
* Provides the actual value of the attribute.
* <p>
* For details on how to provide values see: {@link PmAttrImpl#getValue()}
*
* @return The attribute value.
*/
T getValue();
/**
* @param value
* The new value.
*/
void setValue(T value);
/**
* @return The string for the current value.
*/
String getValueAsString();
/**
* Sets the value with a string value.
*
* @param text
* The new value as string.
*/
void setValueAsString(String text);
/**
* Provides the set of value options the user may choose from.
* <p>
* Some attributes (e.g. attributes representing enums or references to other objects)
* usually provide an option set.
* <p>
* Most PM view components use the string value of the provided option IDs to
* set the value of the attribute using {@link #setValueAsString(String)}.<br>
* (For multiple value attribute types the PM view components usually use the
* 'setListValueAsString' method signatures to set the selected option values.)
*
* @return The attribute options.<br>
* In case of no options an empty option set.
*/
PmOptionSet getOptionSet();
/**
* Some attribute types, such as enums, may provide localized values.
* <p>
* It is sometimes useful to display in the UI rather 'Yes' and 'No' instead
* of 'TRUE' and 'FALSE'. For such situations implementations this method may
* provide the expected human readable string.<br>
* Another use case: An attribute that references a 'User' object might provide here
* the name of the referenced user.
*
* @return The localized string value for the current value.
*/
String getValueLocalized();
/**
* @return The maximum string representation length.
*/
int getMaxLen();
/**
* @return The minimal string representation length.
*/
int getMinLen();
/**
* @return <code>true</code> if the attribute value needs to be set to a value
* that is not <code>null</code>.
*/
boolean isRequired();
/**
* Reset the value to <code>null</code> or the optional default value definition.
*/
@Override
void resetPmValues();
/**
* Indicates an attribute value change.
* <p>
* Will be cleared when
* <ul>
* <li>a command that 'requiresValidValues' (e.g. a cmdSave command) gets
* successfully executed on the element the contains this attribute.</li>
* <li>{@link #resetPmValues(Object)} gets called.</li>
* <li>{@link #setPmValueChanged(Object, boolean)} gets called.</li>
* </ul>
*
* @return <code>true</code> if the attribute value was changed in the live
* time of the PM (or since the previous value or changed state
* reset).
*/
@Override
boolean isPmValueChanged();
/**
* Sets an attribute explicitly to a change or unchanged state.
* <p>
* Is usually used for the following scenarios:
* <ul>
* <li>To accept the current value as the new 'original' attribute value.</li>
* <li>To mark the PM explicitly as changed. This is usually done by
* {@link #setValue(Object)}. But in special cases {@link #setValue(Object)}
* is not used to modify the presented content. (Example: A command changes
* the domain objects behind the PM directly.) For that situation an explicit
* call to this method may inform the UI and the PM logic about the new
* changed state.</li>
* </ul>
* An event with the type-flag {@link PmEvent#VALUE_CHANGED_STATE_CHANGE}
* will be fired if the call changed this state.
*
* @param <code>true</code> marks the attribute as changed.<br>
* <code>false</code> marks the attribute as unchanged.
*/
@Override
void setPmValueChanged(boolean newChangedState);
/**
* Returns a localized format string for attribute values provided as strings.<br>
* The localized format string is based on a resource key which may be defined
* as follows:
* <ol>
* <li>You may specify it using the annotation
* {@link PmAttrCfg#formatResKey()}.</li>
* <li>You may define it within the resource file, using a resource key with a
* '_format' postfix.<br>
* Example: <code>myPm.myNumber_format=#,##0.##</code></li>
* <li>For some types such as {@link PmAttrDate} and {@link PmAttrDouble} you
* may specify default formats.<br>
* (Attribute classes may specify this by implementing
* <code>getFormatDefaultResKey()</code>.)<br>
* See: {@link PmAttrDate#RESKEY_DEFAULT_FORMAT_PATTERN} and
* {@link PmAttrDouble#RESKEY_DEFAULT_FORMAT_PATTERN}.</li>
* </ol>
* The resource key gets evaluated in the sequence specified above. The first
* resource key match wins.
*
* @return A localized format string or <code>null</code> if there is no
* format definition.
*/
String getFormatString();
/**
* Converts single values between its attribute type representation and {@link String}
* or {@link Serializable} representation.
*
* @param <T>
* The type of the items to convert.
*/
interface Converter<T> {
T stringToValue(PmAttr<?> pmAttr, String s) throws PmConverterException;
String valueToString(PmAttr<?> pmAttr, T v);
T serializeableToValue(PmAttr<?> pmAttr, Serializable s) throws PmConverterException;
Serializable valueToSerializable(PmAttr<?> pmAttr, T v);
}
/**
* Interface for the internally generated command that gets generated for each value change operation.
* <p>
* This command based value change implementation provides the basis for the features: undo and value change
* command decorator.
*
* @param <T_VALUE> The attribute value type.
*/
interface ValueChangeCommand<T_VALUE> extends PmCommand {
PmAttr<T_VALUE> getPmAttr();
T_VALUE getNewValue();
T_VALUE getOldValue();
}
}
|
package org.jpmml.xjc;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import javax.xml.namespace.QName;
import com.sun.codemodel.JAnnotatable;
import com.sun.codemodel.JAnnotationArrayMember;
import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JClassAlreadyExistsException;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JFieldRef;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JJavaName;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JMods;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JStringLiteral;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;
import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.model.CAttributePropertyInfo;
import com.sun.tools.xjc.model.CClassInfo;
import com.sun.tools.xjc.model.CClassInfoParent;
import com.sun.tools.xjc.model.CDefaultValue;
import com.sun.tools.xjc.model.CElementPropertyInfo;
import com.sun.tools.xjc.model.CPluginCustomization;
import com.sun.tools.xjc.model.CPropertyInfo;
import com.sun.tools.xjc.model.CReferencePropertyInfo;
import com.sun.tools.xjc.model.Model;
import com.sun.tools.xjc.model.nav.NClass;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.EnumOutline;
import com.sun.tools.xjc.outline.FieldOutline;
import com.sun.tools.xjc.outline.Outline;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElements;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlValue;
import org.eclipse.persistence.oxm.annotations.XmlValueExtension;
import org.glassfish.jaxb.core.api.impl.NameConverter;
import org.glassfish.jaxb.core.v2.model.core.WildcardMode;
import org.w3c.dom.Element;
import org.xml.sax.ErrorHandler;
public class PMMLPlugin extends ComplexPlugin {
@Override
public String getOptionName(){
return "Xpmml";
}
@Override
public String getUsage(){
return null;
}
@Override
public List<QName> getCustomizationElementNames(){
return Arrays.asList(PMMLPlugin.SERIALVERSIONUID_ELEMENT_NAME, PMMLPlugin.SUBPACKAGE_ELEMENT_NAME);
}
@Override
public void postProcessModel(Model model, ErrorHandler errorHandler){
super.postProcessModel(model, errorHandler);
JCodeModel codeModel = model.codeModel;
JClass measureClass = codeModel.ref("org.dmg.pmml.Measure");
JClass nodeClass = codeModel.ref("org.dmg.pmml.tree.Node");
JClass pmmlObjectClass = codeModel.ref("org.dmg.pmml.PMMLObject");
Comparator<CPropertyInfo> comparator = new Comparator<CPropertyInfo>(){
@Override
public int compare(CPropertyInfo left, CPropertyInfo right){
boolean leftAttribute = (left instanceof CAttributePropertyInfo);
boolean rightAttribute = (right instanceof CAttributePropertyInfo);
if(leftAttribute && !rightAttribute){
return -1;
} else
if(!leftAttribute && rightAttribute){
return 1;
}
return 0;
}
};
{
CPluginCustomization serialVersionUIDCustomization = CustomizationUtil.findCustomization(model, PMMLPlugin.SERIALVERSIONUID_ELEMENT_NAME);
if(serialVersionUIDCustomization != null){
Element element = serialVersionUIDCustomization.element;
if(model.serialVersionUID != null){
throw new RuntimeException();
}
int major = parseVersion(element.getAttribute("major"));
int minor = parseVersion(element.getAttribute("minor"));
int patch = parseVersion(element.getAttribute("patch"));
int implementation = parseVersion(element.getAttribute("implementation"));
model.serialVersionUID = (long)((major << 24) | (minor << 16) | (patch << 8) | implementation);
}
}
Map<NClass, CClassInfo> beans = model.beans();
Collection<CClassInfo> classInfos = beans.values();
for(CClassInfo classInfo : classInfos){
CPluginCustomization subpackageCustomization = CustomizationUtil.findCustomization(classInfo, PMMLPlugin.SUBPACKAGE_ELEMENT_NAME);
if(subpackageCustomization != null){
CClassInfoParent.Package packageParent = (CClassInfoParent.Package)classInfo.parent();
Element element = subpackageCustomization.element;
String name = element.getAttribute("name");
if(name == null){
throw new RuntimeException();
}
try {
Field pkgField = CClassInfoParent.Package.class.getDeclaredField("pkg");
if(!pkgField.isAccessible()){
pkgField.setAccessible(true);
}
JPackage subPackage = packageParent.pkg.subPackage(name);
pkgField.set(packageParent, subPackage);
} catch(ReflectiveOperationException roe){
throw new RuntimeException(roe);
}
} // End if
if((classInfo.shortName).equals("ComplexNode")){
try {
Field elementNameField = CClassInfo.class.getDeclaredField("elementName");
if(!elementNameField.isAccessible()){
elementNameField.setAccessible(true);
}
elementNameField.set(classInfo, new QName("http:
} catch(ReflectiveOperationException roe){
throw new RuntimeException(roe);
}
}
List<CPropertyInfo> propertyInfos = classInfo.getProperties();
propertyInfos.sort(comparator);
for(CPropertyInfo propertyInfo : propertyInfos){
String publicName = propertyInfo.getName(true);
String privateName = propertyInfo.getName(false);
if(propertyInfo instanceof CReferencePropertyInfo){
CReferencePropertyInfo referencePropertyInfo = (CReferencePropertyInfo)propertyInfo;
referencePropertyInfo.setWildcard(WildcardMode.LAX);
} // End if
// Collection of values
if(propertyInfo.isCollection()){
if((classInfo.shortName).equals("ComplexNode") && (privateName).equals("node")){
propertyInfo.baseType = nodeClass;
} else
if((classInfo.shortName).equals("VectorFields") && (privateName).equals("fieldRefOrCategoricalPredictor")){
propertyInfo.baseType = pmmlObjectClass;
} // End if
if((privateName).contains("And") || (privateName).contains("Or") || (privateName).equalsIgnoreCase("content")){
propertyInfo.setName(true, "Content");
propertyInfo.setName(false, "content");
} else
{
// Have "arrays" instead of "arraies"
if((privateName).endsWith("array") || (privateName).endsWith("Array")){
publicName += "s";
privateName += "s";
} else
// Have "refs" instead of "reves"
if((privateName).endsWith("ref") || (privateName).endsWith("Ref")){
publicName += "s";
privateName += "s";
} else
{
publicName = JJavaName.getPluralForm(publicName);
privateName = JJavaName.getPluralForm(privateName);
}
propertyInfo.setName(true, publicName);
propertyInfo.setName(false, privateName);
}
} else
// Simple value
{
if((classInfo.shortName).equals("ComparisonMeasure") && (privateName).equals("measure")){
propertyInfo.baseType = measureClass;
} else
if((classInfo.shortName).equals("DecisionTree") && (privateName).equals("missingValueStrategy")){
propertyInfo.baseType = codeModel.directClass("org.dmg.pmml.tree.TreeModel.MissingValueStrategy");
propertyInfo.defaultValue = new CEnumConstantDefaultValue(propertyInfo, propertyInfo.defaultValue);
} else
if((classInfo.shortName).equals("DecisionTree") && (privateName).equals("node")){
propertyInfo.baseType = nodeClass;
} else
if((classInfo.shortName).equals("DecisionTree") && (privateName).equals("noTrueChildStrategy")){
propertyInfo.baseType = codeModel.directClass("org.dmg.pmml.tree.TreeModel.NoTrueChildStrategy");
propertyInfo.defaultValue = new CEnumConstantDefaultValue(propertyInfo, propertyInfo.defaultValue);
} else
if((classInfo.shortName).equals("DecisionTree") && (privateName).equals("splitCharacteristic")){
propertyInfo.baseType = codeModel.directClass("org.dmg.pmml.tree.TreeModel.SplitCharacteristic");
propertyInfo.defaultValue = new CEnumConstantDefaultValue(propertyInfo, propertyInfo.defaultValue);
} else
if((classInfo.shortName).equals("NeuralLayer") && (privateName).equals("activationFunction")){
propertyInfo.baseType = codeModel.directClass("org.dmg.pmml.neural_network.NeuralNetwork.ActivationFunction");
} else
if((classInfo.shortName).equals("NeuralLayer") && (privateName).equals("normalizationMethod")){
propertyInfo.baseType = codeModel.directClass("org.dmg.pmml.neural_network.NeuralNetwork.NormalizationMethod");
} else
if((classInfo.shortName).equals("Regression") && (privateName).equals("normalizationMethod")){
propertyInfo.baseType = codeModel.directClass("org.dmg.pmml.regression.RegressionModel.NormalizationMethod");
propertyInfo.defaultValue = new CEnumConstantDefaultValue(propertyInfo, propertyInfo.defaultValue);
} else
if((classInfo.shortName).equals("TreeModel") && (privateName).equals("node")){
propertyInfo.baseType = nodeClass;
} // End if
if((privateName).equals("functionName")){
propertyInfo.setName(true, "MiningFunction");
propertyInfo.setName(false, "miningFunction");
}
CDefaultValue defaultValue = propertyInfo.defaultValue;
if(defaultValue != null){
propertyInfo.defaultValue = new CShareableDefaultValue(propertyInfo, propertyInfo.defaultValue);
}
}
}
}
}
@Override
public boolean run(Outline outline, Options options, ErrorHandler errorHandler){
Model model = outline.getModel();
JCodeModel codeModel = model.codeModel;
JClass iterableInterface = codeModel.ref("java.lang.Iterable");
JClass iteratorInterface = codeModel.ref("java.util.Iterator");
JClass hasExtensionsInterface = codeModel.ref("org.dmg.pmml.HasExtensions");
JClass stringValueInterface = codeModel.ref("org.dmg.pmml.StringValue");
JClass stringClass = codeModel.ref("java.lang.String");
JClass arraysClass = codeModel.ref("java.util.Arrays");
JClass propertyAnnotation = codeModel.ref("org.jpmml.model.annotations.Property");
List<? extends ClassOutline> classOutlines = new ArrayList<>(outline.getClasses());
classOutlines.sort((left, right) -> (left.implClass.name()).compareToIgnoreCase(right.implClass.name()));
for(ClassOutline classOutline : classOutlines){
JDefinedClass beanClazz = classOutline.implClass;
// Implementations of org.dmg.pmml.HasFieldReference
if(checkType(beanClazz, "org.dmg.pmml.TextIndex")){
createGetterProxy(beanClazz, stringClass, "getField", "getTextField");
createSetterProxy(beanClazz, stringClass, "field", "setField", "setTextField");
} else
if(checkType(beanClazz, "org.dmg.pmml.MiningField")){
createGetterProxy(beanClazz, stringClass, "getField", "getName");
createSetterProxy(beanClazz, stringClass, "field", "setField", "setName");
} // End if
// Implementations of org.dmg.pmml.Indexable
if(checkType(beanClazz, "org.dmg.pmml.DefineFunction") || checkType(beanClazz, "org.dmg.pmml.general_regression.Parameter")){
createGetterProxy(beanClazz, stringClass, "getKey", "getName");
} else
if(checkType(beanClazz, "org.dmg.pmml.MiningField")){
createGetterProxy(beanClazz, stringClass, "getKey", "getName");
} else
if(checkType(beanClazz, "org.dmg.pmml.Target") || checkType(beanClazz, "org.dmg.pmml.VerificationField") || checkType(beanClazz, "org.dmg.pmml.nearest_neighbor.InstanceField")){
createGetterProxy(beanClazz, stringClass, "getKey", "getField");
} else
if(checkType(beanClazz, "org.dmg.pmml.association.Item") || checkType(beanClazz, "org.dmg.pmml.association.Itemset") || checkType(beanClazz, "org.dmg.pmml.sequence.Sequence") || checkType(beanClazz, "org.dmg.pmml.support_vector_machine.VectorInstance") || checkType(beanClazz, "org.dmg.pmml.text.TextDocument")){
createGetterProxy(beanClazz, stringClass, "getKey", "getId");
}
List<JAnnotationUse> beanClazzAnnotations = getAnnotations(beanClazz);
JAnnotationUse xmlAccessorType = findAnnotation(beanClazzAnnotations, XmlAccessorType.class);
if(xmlAccessorType != null){
beanClazzAnnotations.remove(xmlAccessorType);
}
JAnnotationUse xmlRootElement = findAnnotation(beanClazzAnnotations, XmlRootElement.class);
if(xmlRootElement != null){
beanClazzAnnotations.remove(xmlRootElement);
beanClazzAnnotations.add(0, xmlRootElement);
}
Map<String, JFieldVar> fieldVars = beanClazz.fields();
FieldOutline contentFieldOutline = getContentField(classOutline);
if(contentFieldOutline != null){
CPropertyInfo propertyInfo = contentFieldOutline.getPropertyInfo();
String publicName = propertyInfo.getName(true);
String privateName = propertyInfo.getName(false);
JFieldVar fieldVar = fieldVars.get(privateName);
JType elementType = CodeModelUtil.getElementType(fieldVar.type());
beanClazz._implements(iterableInterface.narrow(elementType));
JMethod getElementsMethod = beanClazz.getMethod("get" + publicName, new JType[0]);
JMethod iteratorMethod = beanClazz.method(JMod.PUBLIC, iteratorInterface.narrow(elementType), "iterator");
iteratorMethod.annotate(Override.class);
iteratorMethod.body()._return(JExpr.invoke(getElementsMethod).invoke("iterator"));
moveBefore(beanClazz, iteratorMethod, getElementsMethod);
}
FieldOutline extensionsFieldOutline = getExtensionsField(classOutline);
if(extensionsFieldOutline != null){
beanClazz._implements(hasExtensionsInterface.narrow(beanClazz));
}
FieldOutline[] fieldOutlines = classOutline.getDeclaredFields();
for(FieldOutline fieldOutline : fieldOutlines){
CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();
String publicName = propertyInfo.getName(true);
String privateName = propertyInfo.getName(false);
JFieldVar fieldVar = fieldVars.get(privateName);
String name = fieldVar.name();
JMods modifiers = fieldVar.mods();
if((modifiers.getValue() & JMod.PRIVATE) != JMod.PRIVATE){
modifiers.setPrivate();
}
JType type = fieldVar.type();
CShareableDefaultValue defaultValue = (CShareableDefaultValue)propertyInfo.defaultValue;
if(defaultValue != null){
if(defaultValue.isShared()){
beanClazz.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, type, defaultValue.getField(), defaultValue.computeInit(outline));
}
}
JMethod getterMethod = beanClazz.getMethod("get" + publicName, new JType[0]);
JMethod setterMethod = beanClazz.getMethod("set" + publicName, new JType[]{type});
if(getterMethod != null){
JType returnType = getterMethod.type();
if(returnType.isPrimitive() && !type.isPrimitive()){
JType boxifiedReturnType = returnType.boxify();
if((boxifiedReturnType).equals(type)){
getterMethod.type(boxifiedReturnType);
}
}
} // End if
if(setterMethod != null){
setterMethod.type(beanClazz);
JVar param = (setterMethod.params()).get(0);
param.name(name);
param.annotate(propertyAnnotation).param("value", name);
setterMethod.body()._return(JExpr._this());
} // End if
if(propertyInfo.isCollection()){
JType elementType = CodeModelUtil.getElementType(type);
JFieldRef fieldRef = JExpr.refthis(name);
JMethod getElementsMethod = beanClazz.getMethod("get" + publicName, new JType[0]);
JMethod hasElementsMethod = beanClazz.method(JMod.PUBLIC, boolean.class, "has" + publicName);
hasElementsMethod.body()._return((fieldRef.ne(JExpr._null())).cand((fieldRef.invoke("size")).gt(JExpr.lit(0))));
moveBefore(beanClazz, hasElementsMethod, getElementsMethod);
JMethod addElementsMethod = beanClazz.method(JMod.PUBLIC, beanClazz, "add" + publicName);
JVar param = addElementsMethod.varParam(elementType, name);
addElementsMethod.body().add(JExpr.invoke(getterMethod).invoke("addAll").arg(arraysClass.staticInvoke("asList").arg(param)));
addElementsMethod.body()._return(JExpr._this());
moveAfter(beanClazz, addElementsMethod, getElementsMethod);
} // End if
if(propertyInfo instanceof CAttributePropertyInfo){
declareAttributeField(beanClazz, fieldVar);
} else
if(propertyInfo instanceof CElementPropertyInfo){
declareElementField(beanClazz, fieldVar);
}
List<JAnnotationUse> fieldVarAnnotations = getAnnotations(fieldVar);
// XXX
if(("node").equals(name) || ("nodes").equals(name)){
JAnnotationUse xmlElement = findAnnotation(fieldVarAnnotations, XmlElement.class);
fieldVarAnnotations.remove(xmlElement);
JAnnotationUse xmlElements = fieldVar.annotate(XmlElements.class);
JAnnotationArrayMember valueArray = xmlElements.paramArray("value");
valueArray.param(xmlElement);
fieldVarAnnotations.remove(xmlElements);
fieldVarAnnotations.add(0, xmlElements);
} // End if
if(hasAnnotation(fieldVarAnnotations, XmlValue.class)){
fieldVar.annotate(XmlValueExtension.class);
}
}
if(checkType(beanClazz, "org.dmg.pmml.False") || checkType(beanClazz, "org.dmg.pmml.True")){
createSingleton(codeModel, beanClazz);
} // End if
if(model.serialVersionUID != null){
beanClazz.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, long.class, "serialVersionUID", JExpr.lit(model.serialVersionUID));
}
String[][][] baseClassInfos = {
{{"ComparisonField"}, {"getCompareFunction", "setCompareFunction", "getFieldWeight", "setFieldWeight", "getSimilarityScale", "setSimilarityScale"}},
{{"EmbeddedModel"}, {"getAlgorithmName", "setAlgorithmName", "getLocalTransformations", "setLocalTransformations", "getMiningFunction", "setMiningFunction", "getModelName", "setModelName", "getModelStats", "setModelStats", "getOutput", "setOutput", "getTargets", "setTargets"}},
{{"Kernel"}, {"getDescription", "setDescription"}},
{{"Model"}, {"getAlgorithmName", "setAlgorithmName", "getLocalTransformations", "setLocalTransformations", "getMathContext", "setMathContext", "getMiningFunction", "setMiningFunction", "getMiningSchema", "setMiningSchema", "getModelExplanation", "setModelExplanation", "getModelName", "setModelName", "getModelStats", "setModelStats", "getModelVerification", "setModelVerification", "getOutput", "setOutput", "isScorable", "setScorable", "getTargets", "setTargets"}},
{{"ModelQuality"}, {"getDataName", "setDataName"}},
{{"ParameterCell"}, {"getParameterName", "setParameterName", "getTargetCategory", "setTargetCategory"}},
{{"PredictorList"}, {"hasPredictors", "getPredictors", "addPredictors"}},
{{"SparseArray"}, {"getDefaultValue", "setDefaultValue", "hasEntries", "getEntries", "addEntries", "hasIndices", "getIndices", "addIndices", "getN", "setN"}},
{{"Term"}, {"getCoefficient", "setCoefficient"}}
};
for(String[][] baseClassInfo : baseClassInfos){
addOverrideAnnotations(beanClazz, baseClassInfo);
}
String[][][] markerInterfaceInfos = {
{{"HasActivationFunction"}, {"getActivationFunction", "setActivationFunction", "getAltitude", "setAltitude", "getLeakage", "setLeakage", "getThreshold", "setThreshold", "getWidth", "setWidth"}},
{{"HasBaselineScore"}, {"getBaselineScore", "setBaselineScore"}},
{{"HasContinuousDomain"}, {"hasIntervals", "getIntervals", "addIntervals"}},
{{"HasDataType", "Field"}, {"getDataType", "setDataType"}},
{{"HasDefaultValue"}, {"getDefaultValue", "setDefaultValue"}},
{{"HasDerivedFields"}, {"hasDerivedFields", "getDerivedFields", "addDerivedFields"}},
{{"HasDiscreteDomain"}, {"hasValues", "getValues", "addValues"}},
{{"HasDisplayName"}, {"getDisplayName", "setDisplayName"}},
{{"HasExpression"}, {"getExpression", "setExpression"}},
{{"HasExtensions"}, {"hasExtensions", "getExtensions", "addExtensions"}},
{{"HasFieldReference", "ComparisonField"}, {"getField", "setField"}},
{{"HasId", "Entity", "NeuralEntity", "Node", "Rule"}, {"getId", "setId"}},
{{"HasLocator"}, {"getLocator", "setLocator"}},
{{"HasMapMissingTo"}, {"getMapMissingTo", "setMapMissingTo"}},
{{"HasMixedContent"}, {"hasContent", "getContent", "addContent"}},
{{"HasName", "Field"}, {"getName", "setName"}},
{{"HasNode"}, {"getMissingValueStrategy", "setMissingValueStrategy", "getMissingValuePenalty", "setMissingValuePenalty", "getNoTrueChildStrategy", "setNoTrueChildStrategy", "getSplitCharacteristic", "setSplitCharacteristic", "getNode", "setNode"}},
{{"HasNormalizationMethod"}, {"getNormalizationMethod", "setNormalizationMethod"}},
{{"HasOpType", "Field"}, {"getOpType", "setOpType"}},
{{"HasPredicate", "Node", "Rule"}, {"getPredicate", "setPredicate"}},
{{"HasReasonCode"}, {"getReasonCode", "setReasonCode"}},
{{"HasRecordCount", "Node"}, {"getRecordCount", "setRecordCount"}},
{{"HasRegressionTables"}, {"getNormalizationMethod", "setNormalizationMethod", "hasRegressionTables", "getRegressionTables", "addRegressionTables"}},
{{"HasScore", "Node", "Rule"}, {"getScore", "setScore"}},
{{"HasScoreDistributions", "Node", "Rule"}, {"hasScoreDistributions", "getScoreDistributions", "addScoreDistributions"}},
{{"HasTable"}, {"getTableLocator", "setTableLocator", "getInlineTable", "setInlineTable"}},
{{"HasTargetFieldReference"}, {"getTargetField", "setTargetField"}},
{{"HasValue"}, {"getValue", "setValue"}},
{{"HasValueSet"}, {"getArray", "setArray"}}
};
for(String[][] markerInterfaceInfo : markerInterfaceInfos){
addOverrideAnnotations(beanClazz, markerInterfaceInfo);
}
}
List<? extends EnumOutline> enumOutlines = new ArrayList<>(outline.getEnums());
enumOutlines.sort((left, right) -> (left.clazz.name()).compareToIgnoreCase(right.clazz.name()));
for(EnumOutline enumOutline : enumOutlines){
JDefinedClass clazz = enumOutline.clazz;
clazz._implements(stringValueInterface.narrow(clazz));
JMethod valueMethod = clazz.getMethod("value", new JType[0]);
valueMethod.annotate(Override.class);
JMethod toStringMethod = clazz.method(JMod.PUBLIC, String.class, "toString");
toStringMethod.annotate(Override.class);
toStringMethod.body()._return(JExpr.invoke(valueMethod));
}
if(model.serialVersionUID != null){
model.serialVersionUID = null;
}
return true;
}
static
private FieldOutline getExtensionsField(ClassOutline classOutline){
Predicate<FieldOutline> predicate = new Predicate<FieldOutline>(){
@Override
public boolean test(FieldOutline fieldOutline){
CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();
if(("extensions").equals(propertyInfo.getName(false)) && propertyInfo.isCollection()){
JType elementType = CodeModelUtil.getElementType(fieldOutline.getRawType());
return checkType(elementType, "org.dmg.pmml.Extension");
}
return false;
}
};
return XJCUtil.findSingletonField(classOutline.getDeclaredFields(), predicate);
}
static
private FieldOutline getContentField(ClassOutline classOutline){
Predicate<FieldOutline> predicate = new Predicate<FieldOutline>(){
private String name = classOutline.implClass.name();
@Override
public boolean test(FieldOutline fieldOutline){
CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();
if(propertyInfo.isCollection()){
JType elementType = CodeModelUtil.getElementType(fieldOutline.getRawType());
String name = elementType.name();
return ((this.name).equals(name + "s") || (this.name).equals(JJavaName.getPluralForm(name)));
}
return false;
}
};
return XJCUtil.findSingletonField(classOutline.getDeclaredFields(), predicate);
}
static
private boolean hasAnnotation(Collection<JAnnotationUse> annotations, Class<?> clazz){
JAnnotationUse annotation = findAnnotation(annotations, clazz);
return (annotation != null);
}
static
private JAnnotationUse findAnnotation(Collection<JAnnotationUse> annotations, Class<?> clazz){
String fullName = clazz.getName();
for(JAnnotationUse annotation : annotations){
JClass type = annotation.getAnnotationClass();
if(checkType(type, fullName)){
return annotation;
}
}
return null;
}
static
private List<JAnnotationUse> getAnnotations(JAnnotatable annotatable){
try {
Class<?> clazz = annotatable.getClass();
Field annotationsField;
while(true){
try {
annotationsField = clazz.getDeclaredField("annotations");
break;
} catch(NoSuchFieldException nsfe){
clazz = clazz.getSuperclass();
if(clazz == null){
throw nsfe;
}
}
}
if(!annotationsField.isAccessible()){
annotationsField.setAccessible(true);
}
return (List)annotationsField.get(annotatable);
} catch(ReflectiveOperationException roe){
throw new RuntimeException(roe);
}
}
static
private void createGetterProxy(JDefinedClass beanClazz, JType type, String name, String getterName){
JMethod getterMethod = beanClazz.getMethod(getterName, new JType[0]);
JMethod method = beanClazz.method(JMod.PUBLIC, type, name);
method.annotate(Override.class);
method.body()._return(JExpr.invoke(getterMethod));
moveBefore(beanClazz, method, getterMethod);
}
static
public void createSetterProxy(JDefinedClass beanClazz, JType type, String parameterName, String name, String setterName){
JMethod getterMethod = beanClazz.getMethod(setterName.replace("set", "get"), new JType[0]);
JMethod method = beanClazz.method(JMod.PUBLIC, beanClazz, name);
method.annotate(Override.class);
JVar nameParameter = method.param(type, parameterName);
method.body()._return(JExpr.invoke(setterName).arg(nameParameter));
moveBefore(beanClazz, method, getterMethod);
}
static
public void createSingleton(JCodeModel codeModel, JDefinedClass beanClazz){
JDefinedClass definedBeanClazz = codeModel.anonymousClass(beanClazz);
JMethod hasExtensionsMethod = definedBeanClazz.method(JMod.PUBLIC, boolean.class, "hasExtensions");
hasExtensionsMethod.annotate(Override.class);
(hasExtensionsMethod.body())._return(JExpr.FALSE);
JMethod getExtensionsMethod = definedBeanClazz.method(JMod.PUBLIC, List.class, "getExtensions");
getExtensionsMethod.annotate(Override.class);
(getExtensionsMethod.body())._throw(JExpr._new(codeModel.ref(UnsupportedOperationException.class)));
JFieldVar instanceField = beanClazz.field(JMod.PUBLIC | JMod.FINAL | JMod.STATIC, beanClazz, "INSTANCE", JExpr._new(definedBeanClazz));
}
static
private void declareAttributeField(JDefinedClass beanClazz, JFieldVar fieldVar){
JDefinedClass attributesInterface = ensureInterface(beanClazz._package(), "PMMLAttributes");
declareField(attributesInterface, beanClazz, fieldVar);
}
static
private void declareElementField(JDefinedClass beanClazz, JFieldVar fieldVar){
JDefinedClass elementsInterface = ensureInterface(beanClazz._package(), "PMMLElements");
declareField(elementsInterface, beanClazz, fieldVar);
}
static
private void declareField(JDefinedClass _interface, JDefinedClass beanClazz, JFieldVar fieldVar){
JCodeModel codeModel = _interface.owner();
JExpression init = codeModel.ref("org.jpmml.model.ReflectionUtil").staticInvoke("getField").arg(beanClazz.dotclass()).arg(fieldVar.name());
_interface.field(0, Field.class, (beanClazz.name() + "_" + fieldVar.name()).toUpperCase(), init);
}
static
private void addOverrideAnnotations(JDefinedClass beanClazz, String[][] typeMemberInfo){
Set<String> typeNames = new LinkedHashSet<>(Arrays.asList(typeMemberInfo[0]));
Set<String> methodNames = new LinkedHashSet<>(Arrays.asList(typeMemberInfo[1]));
boolean matches = false;
{
JClass beanSuperClazz = beanClazz._extends();
String name = (beanSuperClazz.erasure()).name();
matches |= typeNames.contains(name);
}
for(Iterator<JClass> it = beanClazz._implements(); it.hasNext(); ){
JClass _interface = it.next();
String name = (_interface.erasure()).name();
matches |= typeNames.contains(name);
}
if(!matches){
return;
}
Collection<JMethod> methods = beanClazz.methods();
for(JMethod method : methods){
String name = method.name();
if(!methodNames.contains(name)){
continue;
}
List<JVar> params = method.params();
if((name.startsWith("has") || name.startsWith("is") || name.startsWith("get")) && params.size() == 0){
if(!hasAnnotation(method.annotations(), Override.class)){
method.annotate(Override.class);
}
} else
if(name.startsWith("add") && params.size() == 0 && method.hasVarArgs()){
method.annotate(Override.class);
} else
if(name.startsWith("set") && params.size() == 1){
if(!hasAnnotation(method.annotations(), Override.class)){
method.annotate(Override.class);
}
} else
{
throw new RuntimeException();
}
}
}
static
private JDefinedClass ensureInterface(JPackage _package, String name){
try {
return _package._interface(name);
} catch(JClassAlreadyExistsException jcaee){
return jcaee.getExistingClass();
}
}
static
private void moveBefore(JDefinedClass beanClazz, JMethod method, JMethod referenceMethod){
List<JMethod> methods = (List<JMethod>)beanClazz.methods();
int index = methods.indexOf(referenceMethod);
if(index < 0){
throw new RuntimeException();
}
methods.remove(method);
methods.add(index, method);
}
static
private void moveAfter(JDefinedClass beanClazz, JMethod method, JMethod referenceMethod){
List<JMethod> methods = (List<JMethod>)beanClazz.methods();
int index = methods.indexOf(referenceMethod);
if(index < 0){
throw new RuntimeException();
}
methods.remove(method);
methods.add(index + 1, method);
}
static
private boolean checkType(JType type, String fullName){
return (type.fullName()).equals(fullName);
}
static
private int parseVersion(String version){
if(version == null){
throw new RuntimeException();
}
int value = Integer.parseInt(version);
if(value < 0 || value > 255){
throw new RuntimeException();
}
return value;
}
static
private class CEnumConstantDefaultValue extends CDefaultValue {
private CPropertyInfo propertyInfo = null;
private CDefaultValue parent = null;
private CEnumConstantDefaultValue(CPropertyInfo propertyInfo, CDefaultValue parent){
setPropertyInfo(propertyInfo);
setParent(parent);
}
@Override
public JExpression compute(Outline outline){
CPropertyInfo propertyInfo = getPropertyInfo();
CDefaultValue parent = getParent();
JStringLiteral stringLiteral = (JStringLiteral)parent.compute(outline);
String name = NameConverter.standard.toConstantName(stringLiteral.str);
return ((JClass)propertyInfo.baseType).staticRef(name);
}
public CPropertyInfo getPropertyInfo(){
return this.propertyInfo;
}
private void setPropertyInfo(CPropertyInfo propertyInfo){
this.propertyInfo = propertyInfo;
}
public CDefaultValue getParent(){
return this.parent;
}
private void setParent(CDefaultValue parent){
this.parent = parent;
}
}
static
private class CShareableDefaultValue extends CDefaultValue {
private CPropertyInfo propertyInfo = null;
private CDefaultValue parent = null;
private String field = null;
private CShareableDefaultValue(CPropertyInfo propertyInfo, CDefaultValue parent){
setPropertyInfo(propertyInfo);
setParent(parent);
setField(formatField(propertyInfo.getName(false)));
}
@Override
public JExpression compute(Outline outline){
JExpression expression = computeInit(outline);
if((expression instanceof JFieldRef) || (expression instanceof JStringLiteral)){
setField(null);
return expression;
}
return JExpr.ref(getField());
}
public JExpression computeInit(Outline outline){
CDefaultValue parent = getParent();
return parent.compute(outline);
}
public boolean isShared(){
String field = getField();
return (field != null);
}
public CPropertyInfo getPropertyInfo(){
return this.propertyInfo;
}
private void setPropertyInfo(CPropertyInfo propertyInfo){
this.propertyInfo = propertyInfo;
}
public CDefaultValue getParent(){
return this.parent;
}
private void setParent(CDefaultValue parent){
this.parent = parent;
}
public String getField(){
return this.field;
}
private void setField(String field){
this.field = field;
}
static
private String formatField(String string){
StringBuilder sb = new StringBuilder();
sb.append("DEFAULT_");
for(int i = 0; i < string.length(); i++){
char c = string.charAt(i);
if(Character.isUpperCase(c)){
sb.append('_');
}
sb.append(Character.toUpperCase(c));
}
return sb.toString();
}
}
public static final String NAMESPACE_URI = "http://jpmml.org/jpmml-model";
public static final QName SERIALVERSIONUID_ELEMENT_NAME = new QName(PMMLPlugin.NAMESPACE_URI, "serialVersionUID");
public static final QName SUBPACKAGE_ELEMENT_NAME = new QName(PMMLPlugin.NAMESPACE_URI, "subpackage");
}
|
package org.jpmml.xjc;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.namespace.QName;
import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JFieldRef;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JJavaName;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JMods;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JStringLiteral;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;
import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.model.CAttributePropertyInfo;
import com.sun.tools.xjc.model.CClassInfo;
import com.sun.tools.xjc.model.CClassInfoParent;
import com.sun.tools.xjc.model.CDefaultValue;
import com.sun.tools.xjc.model.CPluginCustomization;
import com.sun.tools.xjc.model.CPropertyInfo;
import com.sun.tools.xjc.model.Model;
import com.sun.tools.xjc.model.nav.NClass;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.EnumOutline;
import com.sun.tools.xjc.outline.FieldOutline;
import com.sun.tools.xjc.outline.Outline;
import org.eclipse.persistence.oxm.annotations.XmlValueExtension;
import org.jvnet.jaxb2_commons.plugin.AbstractParameterizablePlugin;
import org.jvnet.jaxb2_commons.util.CustomizationUtils;
import org.w3c.dom.Element;
import org.xml.sax.ErrorHandler;
public class PMMLPlugin extends AbstractParameterizablePlugin {
@Override
public String getOptionName(){
return "Xpmml";
}
@Override
public String getUsage(){
return null;
}
@Override
public Collection<QName> getCustomizationElementNames(){
return Arrays.asList(PMMLPlugin.SERIALVERSIONUID_ELEMENT_NAME, PMMLPlugin.SUBPACKAGE_ELEMENT_NAME);
}
@Override
public void postProcessModel(Model model, ErrorHandler errorHandler){
super.postProcessModel(model, errorHandler);
JCodeModel codeModel = model.codeModel;
JClass measureClass = codeModel.ref("org.dmg.pmml.Measure");
JClass nodeClass = codeModel.ref("org.dmg.pmml.tree.Node");
JClass pmmlObjectClass = codeModel.ref("org.dmg.pmml.PMMLObject");
JClass activationFunctionEnum = codeModel.directClass("org.dmg.pmml.neural_network.NeuralNetwork.ActivationFunction");
JClass normalizationMethodEnum = codeModel.directClass("org.dmg.pmml.neural_network.NeuralNetwork.NormalizationMethod");
Comparator<CPropertyInfo> comparator = new Comparator<CPropertyInfo>(){
@Override
public int compare(CPropertyInfo left, CPropertyInfo right){
boolean leftAttribute = (left instanceof CAttributePropertyInfo);
boolean rightAttribute = (right instanceof CAttributePropertyInfo);
if(leftAttribute && !rightAttribute){
return -1;
} else
if(!leftAttribute && rightAttribute){
return 1;
}
return 0;
}
};
{
CPluginCustomization serialVersionUIDCustomization = CustomizationUtils.findCustomization(model, PMMLPlugin.SERIALVERSIONUID_ELEMENT_NAME);
if(serialVersionUIDCustomization != null){
Element element = serialVersionUIDCustomization.element;
if(model.serialVersionUID != null){
throw new RuntimeException();
}
int major = parseVersion(element.getAttribute("major"));
int minor = parseVersion(element.getAttribute("minor"));
int patch = parseVersion(element.getAttribute("patch"));
int implementation = parseVersion(element.getAttribute("implementation"));
model.serialVersionUID = (long)((major << 24) | (minor << 16) | (patch << 8) | implementation);
}
}
Map<NClass, CClassInfo> beans = model.beans();
Collection<CClassInfo> classInfos = beans.values();
for(CClassInfo classInfo : classInfos){
CPluginCustomization subpackageCustomization = CustomizationUtils.findCustomization(classInfo, PMMLPlugin.SUBPACKAGE_ELEMENT_NAME);
if(subpackageCustomization != null){
CClassInfoParent.Package packageParent = (CClassInfoParent.Package)classInfo.parent();
Element element = subpackageCustomization.element;
String name = element.getAttribute("name");
if(name == null){
throw new RuntimeException();
}
try {
Field field = CClassInfoParent.Package.class.getDeclaredField("pkg");
if(!field.isAccessible()){
field.setAccessible(true);
}
JPackage subPackage = packageParent.pkg.subPackage(name);
field.set(packageParent, subPackage);
} catch(ReflectiveOperationException roe){
throw new RuntimeException(roe);
}
} // End if
if((classInfo.shortName).equals("ComplexNode")){
try {
Field field = CClassInfo.class.getDeclaredField("elementName");
if(!field.isAccessible()){
field.setAccessible(true);
}
field.set(classInfo, new QName("http:
} catch(ReflectiveOperationException roe){
throw new RuntimeException(roe);
}
}
List<CPropertyInfo> propertyInfos = classInfo.getProperties();
propertyInfos.sort(comparator);
for(CPropertyInfo propertyInfo : propertyInfos){
String publicName = propertyInfo.getName(true);
String privateName = propertyInfo.getName(false);
// Collection of values
if(propertyInfo.isCollection()){
if((classInfo.shortName).equals("ComplexNode") && (privateName).equals("node")){
propertyInfo.baseType = nodeClass;
} else
if((classInfo.shortName).equals("VectorFields") && (privateName).equals("fieldRefOrCategoricalPredictor")){
propertyInfo.baseType = pmmlObjectClass;
} // End if
if((privateName).contains("And") || (privateName).contains("Or") || (privateName).equalsIgnoreCase("content")){
propertyInfo.setName(true, "Content");
propertyInfo.setName(false, "content");
} else
{
// Have "arrays" instead of "arraies"
if((privateName).endsWith("array") || (privateName).endsWith("Array")){
publicName += "s";
privateName += "s";
} else
// Have "refs" instead of "reves"
if((privateName).endsWith("ref") || (privateName).endsWith("Ref")){
publicName += "s";
privateName += "s";
} else
{
publicName = JJavaName.getPluralForm(publicName);
privateName = JJavaName.getPluralForm(privateName);
}
propertyInfo.setName(true, publicName);
propertyInfo.setName(false, privateName);
}
} else
// Simple value
{
if((classInfo.shortName).equals("ComparisonMeasure") && (privateName).equals("measure")){
propertyInfo.baseType = measureClass;
} else
if((classInfo.shortName).equals("DecisionTree") && (privateName).equals("node")){
propertyInfo.baseType = nodeClass;
} else
if((classInfo.shortName).equals("NeuralLayer") && (privateName).equals("activationFunction")){
propertyInfo.baseType = activationFunctionEnum;
} else
if((classInfo.shortName).equals("NeuralLayer") && (privateName).equals("normalizationMethod")){
propertyInfo.baseType = normalizationMethodEnum;
} else
if((classInfo.shortName).equals("TreeModel") && (privateName).equals("node")){
propertyInfo.baseType = nodeClass;
} // End if
if((privateName).equals("functionName")){
propertyInfo.setName(true, "MiningFunction");
propertyInfo.setName(false, "miningFunction");
}
CDefaultValue defaultValue = propertyInfo.defaultValue;
if(defaultValue != null){
propertyInfo.defaultValue = new CShareableDefaultValue(propertyInfo, propertyInfo.defaultValue);
}
}
}
}
}
@Override
public boolean run(Outline outline, Options options, ErrorHandler errorHandler){
Model model = outline.getModel();
JCodeModel codeModel = model.codeModel;
JClass iterableInterface = codeModel.ref("java.lang.Iterable");
JClass iteratorInterface = codeModel.ref("java.util.Iterator");
JClass hasExtensionsInterface = codeModel.ref("org.dmg.pmml.HasExtensions");
JClass stringValueInterface = codeModel.ref("org.dmg.pmml.StringValue");
JClass stringClass = codeModel.ref("java.lang.String");
JClass arraysClass = codeModel.ref("java.util.Arrays");
JClass fieldNameClass = codeModel.ref("org.dmg.pmml.FieldName");
JClass propertyAnnotation = codeModel.ref("org.jpmml.model.annotations.Property");
Collection<? extends ClassOutline> classOutlines = outline.getClasses();
for(ClassOutline classOutline : classOutlines){
JDefinedClass beanClazz = classOutline.implClass;
// Implementations of org.dmg.pmml.HasFieldReference
if(checkType(beanClazz, "org.dmg.pmml.TextIndex")){
createGetterProxy(beanClazz, fieldNameClass, "getField", "getTextField");
createSetterProxy(beanClazz, fieldNameClass, "field", "setField", "setTextField");
} // End if
// Implementations of org.dmg.pmml.HasName
if(checkType(beanClazz, "org.dmg.pmml.regression.CategoricalPredictor") || checkType(beanClazz, "org.dmg.pmml.regression.NumericPredictor")){
createGetterProxy(beanClazz, fieldNameClass, "getName", "getField");
createSetterProxy(beanClazz, fieldNameClass, "name", "setName", "setField");
} // End if
// Implementations of org.dmg.pmml.Indexable
if(checkType(beanClazz, "org.dmg.pmml.DefineFunction") || checkType(beanClazz, "org.dmg.pmml.general_regression.Parameter")){
createGetterProxy(beanClazz, stringClass, "getKey", "getName");
} else
if(checkType(beanClazz, "org.dmg.pmml.MiningField")){
createGetterProxy(beanClazz, fieldNameClass, "getKey", "getName");
} else
if(checkType(beanClazz, "org.dmg.pmml.Target") || checkType(beanClazz, "org.dmg.pmml.VerificationField") || checkType(beanClazz, "org.dmg.pmml.nearest_neighbor.InstanceField")){
createGetterProxy(beanClazz, fieldNameClass, "getKey", "getField");
} else
if(checkType(beanClazz, "org.dmg.pmml.association.Item") || checkType(beanClazz, "org.dmg.pmml.association.Itemset") || checkType(beanClazz, "org.dmg.pmml.sequence.Sequence") || checkType(beanClazz, "org.dmg.pmml.support_vector_machine.VectorInstance") || checkType(beanClazz, "org.dmg.pmml.text.TextDocument")){
createGetterProxy(beanClazz, stringClass, "getKey", "getId");
}
Map<String, JFieldVar> fieldVars = beanClazz.fields();
FieldOutline contentFieldOutline = getContentField(classOutline);
if(contentFieldOutline != null){
CPropertyInfo propertyInfo = contentFieldOutline.getPropertyInfo();
JFieldVar fieldVar = fieldVars.get(propertyInfo.getName(false));
JType elementType = CodeModelUtil.getElementType(fieldVar.type());
beanClazz._implements(iterableInterface.narrow(elementType));
JMethod getElementsMethod = beanClazz.getMethod("get" + propertyInfo.getName(true), new JType[0]);
JMethod iteratorMethod = beanClazz.method(JMod.PUBLIC, iteratorInterface.narrow(elementType), "iterator");
iteratorMethod.annotate(Override.class);
iteratorMethod.body()._return(JExpr.invoke(getElementsMethod).invoke("iterator"));
moveBefore(beanClazz, iteratorMethod, getElementsMethod);
}
FieldOutline extensionsFieldOutline = getExtensionsField(classOutline);
if(extensionsFieldOutline != null){
beanClazz._implements(hasExtensionsInterface.narrow(beanClazz));
}
FieldOutline[] fieldOutlines = classOutline.getDeclaredFields();
for(FieldOutline fieldOutline : fieldOutlines){
CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();
JFieldVar fieldVar = fieldVars.get(propertyInfo.getName(false));
JMods modifiers = fieldVar.mods();
if((modifiers.getValue() & JMod.PRIVATE) != JMod.PRIVATE){
modifiers.setPrivate();
}
JType type = fieldVar.type();
CShareableDefaultValue defaultValue = (CShareableDefaultValue)propertyInfo.defaultValue;
if(defaultValue != null){
if(defaultValue.isShared()){
beanClazz.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, fieldVar.type(), defaultValue.getField(), defaultValue.computeInit(outline));
}
}
JMethod getterMethod = beanClazz.getMethod("get" + propertyInfo.getName(true), new JType[0]);
JMethod setterMethod = beanClazz.getMethod("set" + propertyInfo.getName(true), new JType[]{type});
if(getterMethod != null){
JType returnType = getterMethod.type();
if(returnType.isPrimitive() && !type.isPrimitive()){
JType boxifiedReturnType = returnType.boxify();
if((boxifiedReturnType).equals(type)){
getterMethod.type(boxifiedReturnType);
}
}
} // End if
if(setterMethod != null){
setterMethod.type(beanClazz);
JVar param = (setterMethod.params()).get(0);
param.name(fieldVar.name());
param.annotate(propertyAnnotation).param("value", fieldVar.name());
setterMethod.body()._return(JExpr._this());
} // End if
if(propertyInfo.isCollection()){
JType elementType = CodeModelUtil.getElementType(type);
JFieldRef fieldRef = JExpr.refthis(fieldVar.name());
JMethod getElementsMethod = beanClazz.getMethod("get" + propertyInfo.getName(true), new JType[0]);
JMethod hasElementsMethod = beanClazz.method(JMod.PUBLIC, boolean.class, "has" + propertyInfo.getName(true));
hasElementsMethod.body()._return((fieldRef.ne(JExpr._null())).cand((fieldRef.invoke("size")).gt(JExpr.lit(0))));
moveBefore(beanClazz, hasElementsMethod, getElementsMethod);
JMethod addElementsMethod = beanClazz.method(JMod.PUBLIC, beanClazz, "add" + propertyInfo.getName(true));
JVar param = addElementsMethod.varParam(elementType, fieldVar.name());
addElementsMethod.body().add(JExpr.invoke(getterMethod).invoke("addAll").arg(arraysClass.staticInvoke("asList").arg(param)));
addElementsMethod.body()._return(JExpr._this());
moveAfter(beanClazz, addElementsMethod, getElementsMethod);
}
Collection<JAnnotationUse> annotations = fieldVar.annotations();
if(hasAnnotation(annotations, XmlValue.class)){
fieldVar.annotate(XmlValueExtension.class);
}
}
if(model.serialVersionUID != null){
beanClazz.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, long.class, "serialVersionUID", JExpr.lit(model.serialVersionUID));
}
String[][][] markerInterfaces = {
{{"HasContinuousDomain"}, {"hasIntervals", "getIntervals", "addIntervals"}},
{{"HasDataType", "Field"}, {"getDataType", "setDataType"}},
{{"HasDefaultValue"}, {"getDefaultValue", "setDefaultValue"}},
{{"HasDiscreteDomain"}, {"hasValues", "getValues", "addValues"}},
{{"HasDisplayName"}, {"getDisplayName", "setDisplayName"}},
{{"HasExpression"}, {"getExpression", "setExpression"}},
{{"HasExtensions"}, {"hasExtensions", "getExtensions", "addExtensions"}},
{{"HasFieldReference", "ComparisonField"}, {"getField", "setField"}},
{{"HasId", "Entity", "Node", "Rule"}, {"getId", "setId"}},
{{"HasLocator"}, {"getLocator", "setLocator"}},
{{"HasMapMissingTo"}, {"getMapMissingTo", "setMapMissingTo"}},
{{"HasMixedContent"}, {"hasContext", "getContent", "addContent"}},
{{"HasName", "Field", "Term"}, {"getName", "setName"}},
{{"HasOpType", "Field"}, {"getOpType", "setOpType"}},
{{"HasPredicate", "Node", "Rule"}, {"getPredicate", "setPredicate"}},
{{"HasScore", "Node", "Rule"}, {"getScore", "setScore"}},
{{"HasTable"}, {"getTableLocator", "setTableLocator", "getInlineTable", "setInlineTable"}},
{{"HasValue"}, {"getValue", "setValue"}},
{{"HasValueSet"}, {"getArray", "setArray"}}
};
for(String[][] markerInterface : markerInterfaces){
String[] types = markerInterface[0];
String[] members = markerInterface[1];
boolean matches = false;
{
JClass superClazz = beanClazz._extends();
superClazz = superClazz.erasure();
for(int i = 1; i < types.length; i++){
matches |= (superClazz.name()).equals(types[i]);
}
}
for(Iterator<JClass> it = beanClazz._implements(); it.hasNext(); ){
JClass _interface = it.next();
_interface = _interface.erasure();
matches |= (_interface.name()).equals(types[0]);
}
if(!matches){
continue;
}
Collection<JMethod> methods = beanClazz.methods();
for(int i = 0; i < members.length; i++){
for(JMethod method : methods){
String name = method.name();
if(!(name).equals(members[i])){
continue;
} // End if
List<JVar> params = method.params();
if((name.startsWith("has") || name.startsWith("get")) && params.size() == 0){
if(!hasAnnotation(method.annotations(), Override.class)){
method.annotate(Override.class);
}
} else
if(name.startsWith("add") && params.size() == 0 && method.hasVarArgs()){
method.annotate(Override.class);
} else
if(name.startsWith("set") && params.size() == 1){
if(!hasAnnotation(method.annotations(), Override.class)){
method.annotate(Override.class);
}
}
}
}
}
}
Collection<? extends EnumOutline> enumOutlines = outline.getEnums();
for(EnumOutline enumOutline : enumOutlines){
JDefinedClass clazz = enumOutline.clazz;
clazz._implements(stringValueInterface.narrow(clazz));
JMethod valueMethod = clazz.getMethod("value", new JType[0]);
valueMethod.annotate(Override.class);
JMethod toStringMethod = clazz.method(JMod.PUBLIC, String.class, "toString");
toStringMethod.annotate(Override.class);
toStringMethod.body()._return(JExpr.invoke(valueMethod));
}
if(model.serialVersionUID != null){
model.serialVersionUID = null;
}
return true;
}
static
private FieldOutline getExtensionsField(ClassOutline classOutline){
Predicate<FieldOutline> predicate = new Predicate<FieldOutline>(){
@Override
public boolean test(FieldOutline fieldOutline){
CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();
if(("extensions").equals(propertyInfo.getName(false)) && propertyInfo.isCollection()){
JType elementType = CodeModelUtil.getElementType(fieldOutline.getRawType());
return checkType(elementType, "org.dmg.pmml.Extension");
}
return false;
}
};
return XJCUtil.findSingletonField(classOutline.getDeclaredFields(), predicate);
}
static
private FieldOutline getContentField(ClassOutline classOutline){
Predicate<FieldOutline> predicate = new Predicate<FieldOutline>(){
private String name = classOutline.implClass.name();
@Override
public boolean test(FieldOutline fieldOutline){
CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();
if(propertyInfo.isCollection()){
JType elementType = CodeModelUtil.getElementType(fieldOutline.getRawType());
String name = elementType.name();
return ((this.name).equals(name + "s") || (this.name).equals(JJavaName.getPluralForm(name)));
}
return false;
}
};
return XJCUtil.findSingletonField(classOutline.getDeclaredFields(), predicate);
}
static
private boolean hasAnnotation(Collection<JAnnotationUse> annotations, Class<?> clazz){
JAnnotationUse annotation = findAnnotation(annotations, clazz);
return (annotation != null);
}
static
private JAnnotationUse findAnnotation(Collection<JAnnotationUse> annotations, Class<?> clazz){
String fullName = clazz.getName();
for(JAnnotationUse annotation : annotations){
JClass type = annotation.getAnnotationClass();
if(checkType(type, fullName)){
return annotation;
}
}
return null;
}
static
private void createGetterProxy(JDefinedClass beanClazz, JType type, String name, String getterName){
JMethod getterMethod = beanClazz.getMethod(getterName, new JType[0]);
JMethod method = beanClazz.method(JMod.PUBLIC, type, name);
method.annotate(Override.class);
method.body()._return(JExpr.invoke(getterMethod));
moveBefore(beanClazz, method, getterMethod);
}
static
public void createSetterProxy(JDefinedClass beanClazz, JType type, String parameterName, String name, String setterName){
JMethod getterMethod = beanClazz.getMethod(setterName.replace("set", "get"), new JType[0]);
JMethod method = beanClazz.method(JMod.PUBLIC, beanClazz, name);
method.annotate(Override.class);
JVar nameParameter = method.param(type, parameterName);
method.body()._return(JExpr.invoke(setterName).arg(nameParameter));
moveBefore(beanClazz, method, getterMethod);
}
static
private void moveBefore(JDefinedClass beanClazz, JMethod method, JMethod referenceMethod){
List<JMethod> methods = (List<JMethod>)beanClazz.methods();
int index = methods.indexOf(referenceMethod);
if(index < 0){
throw new RuntimeException();
}
methods.remove(method);
methods.add(index, method);
}
static
private void moveAfter(JDefinedClass beanClazz, JMethod method, JMethod referenceMethod){
List<JMethod> methods = (List<JMethod>)beanClazz.methods();
int index = methods.indexOf(referenceMethod);
if(index < 0){
throw new RuntimeException();
}
methods.remove(method);
methods.add(index + 1, method);
}
static
private boolean checkType(JType type, String fullName){
return (type.fullName()).equals(fullName);
}
static
private int parseVersion(String version){
if(version == null){
throw new RuntimeException();
}
int value = Integer.parseInt(version);
if(value < 0 || value > 255){
throw new RuntimeException();
}
return value;
}
static
private class CShareableDefaultValue extends CDefaultValue {
private CDefaultValue parent = null;
private String field = null;
private CShareableDefaultValue(CPropertyInfo propertyInfo, CDefaultValue parent){
setParent(parent);
setField(formatField(propertyInfo.getName(false)));
}
@Override
public JExpression compute(Outline outline){
JExpression expression = computeInit(outline);
if((expression instanceof JFieldRef) || (expression instanceof JStringLiteral)){
setField(null);
return expression;
}
return JExpr.ref(getField());
}
public JExpression computeInit(Outline outline){
CDefaultValue parent = getParent();
return parent.compute(outline);
}
public boolean isShared(){
String field = getField();
return (field != null);
}
public CDefaultValue getParent(){
return this.parent;
}
private void setParent(CDefaultValue parent){
this.parent = parent;
}
public String getField(){
return this.field;
}
private void setField(String field){
this.field = field;
}
static
private String formatField(String string){
StringBuilder sb = new StringBuilder();
sb.append("DEFAULT_");
for(int i = 0; i < string.length(); i++){
char c = string.charAt(i);
if(Character.isUpperCase(c)){
sb.append('_');
}
sb.append(Character.toUpperCase(c));
}
return sb.toString();
}
}
public static final QName SERIALVERSIONUID_ELEMENT_NAME = new QName("http://jpmml.org/jpmml-model", "serialVersionUID");
public static final QName SUBPACKAGE_ELEMENT_NAME = new QName("http://jpmml.org/jpmml-model", "subpackage");
}
|
package yuku.alkitab.base;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ShareCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.graphics.ColorUtils;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.URLSpan;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import org.json.JSONException;
import org.json.JSONObject;
import yuku.afw.V;
import yuku.afw.storage.Preferences;
import yuku.alkitab.base.ac.GotoActivity;
import yuku.alkitab.base.ac.MarkerListActivity;
import yuku.alkitab.base.ac.MarkersActivity;
import yuku.alkitab.base.ac.NoteActivity;
import yuku.alkitab.base.ac.SearchActivity;
import yuku.alkitab.base.ac.SettingsActivity;
import yuku.alkitab.base.ac.ShareActivity;
import yuku.alkitab.base.ac.base.BaseLeftDrawerActivity;
import yuku.alkitab.base.config.AppConfig;
import yuku.alkitab.base.dialog.ProgressMarkListDialog;
import yuku.alkitab.base.dialog.ProgressMarkRenameDialog;
import yuku.alkitab.base.dialog.TypeBookmarkDialog;
import yuku.alkitab.base.dialog.TypeHighlightDialog;
import yuku.alkitab.base.dialog.VersesDialog;
import yuku.alkitab.base.dialog.XrefDialog;
import yuku.alkitab.base.model.MVersion;
import yuku.alkitab.base.model.MVersionDb;
import yuku.alkitab.base.model.MVersionInternal;
import yuku.alkitab.base.model.VersionImpl;
import yuku.alkitab.base.storage.Prefkey;
import yuku.alkitab.base.util.Announce;
import yuku.alkitab.base.util.AppLog;
import yuku.alkitab.base.util.Appearances;
import yuku.alkitab.base.util.CurrentReading;
import yuku.alkitab.base.util.ExtensionManager;
import yuku.alkitab.base.util.Highlights;
import yuku.alkitab.base.util.History;
import yuku.alkitab.base.util.Jumper;
import yuku.alkitab.base.util.LidToAri;
import yuku.alkitab.base.util.OtherAppIntegration;
import yuku.alkitab.base.util.ShareUrl;
import yuku.alkitab.base.util.Sqlitil;
import yuku.alkitab.base.widget.CallbackSpan;
import yuku.alkitab.base.widget.Floater;
import yuku.alkitab.base.widget.FormattedTextRenderer;
import yuku.alkitab.base.widget.GotoButton;
import yuku.alkitab.base.widget.LabeledSplitHandleButton;
import yuku.alkitab.base.widget.LeftDrawer;
import yuku.alkitab.base.widget.MaterialDialogAdapterHelper;
import yuku.alkitab.base.widget.ScrollbarSetter;
import yuku.alkitab.base.widget.SingleViewVerseAdapter;
import yuku.alkitab.base.widget.SplitHandleButton;
import yuku.alkitab.base.widget.TextAppearancePanel;
import yuku.alkitab.base.widget.TwofingerLinearLayout;
import yuku.alkitab.base.widget.VerseInlineLinkSpan;
import yuku.alkitab.base.widget.VerseRenderer;
import yuku.alkitab.base.widget.VersesView;
import yuku.alkitab.debug.BuildConfig;
import yuku.alkitab.debug.R;
import yuku.alkitab.model.Book;
import yuku.alkitab.model.FootnoteEntry;
import yuku.alkitab.model.Label;
import yuku.alkitab.model.Marker;
import yuku.alkitab.model.PericopeBlock;
import yuku.alkitab.model.ProgressMark;
import yuku.alkitab.model.SingleChapterVerses;
import yuku.alkitab.model.Version;
import yuku.alkitab.util.Ari;
import yuku.alkitab.util.IntArrayList;
import yuku.devoxx.flowlayout.FlowLayout;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import static yuku.alkitab.base.util.Literals.Array;
public class IsiActivity extends BaseLeftDrawerActivity implements XrefDialog.XrefDialogListener, LeftDrawer.Text.Listener, ProgressMarkListDialog.Listener {
public static final String TAG = IsiActivity.class.getSimpleName();
public static final String ACTION_ATTRIBUTE_MAP_CHANGED = "yuku.alkitab.action.ATTRIBUTE_MAP_CHANGED";
public static final String ACTION_ACTIVE_VERSION_CHANGED = IsiActivity.class.getName() + ".action.ACTIVE_VERSION_CHANGED";
public static final String ACTION_NIGHT_MODE_CHANGED = IsiActivity.class.getName() + ".action.NIGHT_MODE_CHANGED";
public static final String ACTION_NEEDS_RESTART = IsiActivity.class.getName() + ".action.NEEDS_RESTART";
private static final int REQCODE_goto = 1;
private static final int REQCODE_share = 7;
private static final int REQCODE_textAppearanceGetFonts = 9;
private static final int REQCODE_textAppearanceCustomColors = 10;
private static final int REQCODE_edit_note_1 = 11;
private static final int REQCODE_edit_note_2 = 12;
private static final String EXTRA_verseUrl = "verseUrl";
private boolean uncheckVersesWhenActionModeDestroyed = true;
private boolean needsRestart; // whether this activity needs to be restarted
private GotoButton.FloaterDragListener bGoto_floaterDrag = new GotoButton.FloaterDragListener() {
final int[] floaterLocationOnScreen = {0, 0};
@Override
public void onFloaterDragStart(final float screenX, final float screenY) {
floater.show(activeBook.bookId, chapter_1);
floater.onDragStart(S.activeVersion());
}
@Override
public void onFloaterDragMove(final float screenX, final float screenY) {
floater.getLocationOnScreen(floaterLocationOnScreen);
floater.onDragMove(screenX - floaterLocationOnScreen[0], screenY - floaterLocationOnScreen[1]);
}
@Override
public void onFloaterDragComplete(final float screenX, final float screenY) {
floater.hide();
floater.onDragComplete(screenX - floaterLocationOnScreen[0], screenY - floaterLocationOnScreen[1]);
}
};
final Floater.Listener floater_listener = new Floater.Listener() {
@Override
public void onSelectComplete(final int ari) {
jumpToAri(ari);
history.add(ari);
}
};
TwofingerLinearLayout.Listener splitRoot_listener = new TwofingerLinearLayout.Listener() {
float startFontSize;
float startDx = Float.MIN_VALUE;
float chapterSwipeCellWidth; // initted later
boolean moreSwipeYAllowed = true; // to prevent setting and unsetting fullscreen many times within one gesture
@Override
public void onOnefingerLeft() {
App.trackEvent("text_onefinger_left");
bRight_click();
}
@Override
public void onOnefingerRight() {
App.trackEvent("text_onefinger_right");
bLeft_click();
}
@Override
public void onTwofingerStart() {
chapterSwipeCellWidth = 24.f * getResources().getDisplayMetrics().density;
startFontSize = Preferences.getFloat(Prefkey.ukuranHuruf2, (float) App.context.getResources().getInteger(R.integer.pref_ukuranHuruf2_default));
}
@Override
public void onTwofingerScale(final float scale) {
float nowFontSize = startFontSize * scale;
if (nowFontSize < 2.f) nowFontSize = 2.f;
if (nowFontSize > 42.f) nowFontSize = 42.f;
Preferences.setFloat(Prefkey.ukuranHuruf2, nowFontSize);
applyPreferences();
if (textAppearancePanel != null) {
textAppearancePanel.displayValues();
}
}
@Override
public void onTwofingerDragX(final float dx) {
if (startDx == Float.MIN_VALUE) { // just started
startDx = dx;
if (dx < 0) {
bRight_click();
} else {
bLeft_click();
}
} else { // more
// more to the left
while (dx < startDx - chapterSwipeCellWidth) {
startDx -= chapterSwipeCellWidth;
bRight_click();
}
while (dx > startDx + chapterSwipeCellWidth) {
startDx += chapterSwipeCellWidth;
bLeft_click();
}
}
}
@Override
public void onTwofingerDragY(final float dy) {
if (!moreSwipeYAllowed) return;
if (dy < 0) {
App.trackEvent("text_twofinger_up");
setFullScreen(true);
leftDrawer.getHandle().setFullScreen(true);
moreSwipeYAllowed = false;
} else {
App.trackEvent("text_twofinger_down");
setFullScreen(false);
leftDrawer.getHandle().setFullScreen(false);
moreSwipeYAllowed = false;
}
}
@Override
public void onTwofingerEnd(final TwofingerLinearLayout.Mode mode) {
startFontSize = 0;
startDx = Float.MIN_VALUE;
moreSwipeYAllowed = true;
}
};
DrawerLayout drawerLayout;
LeftDrawer.Text leftDrawer;
FrameLayout overlayContainer;
ViewGroup root;
Toolbar toolbar;
VersesView lsSplit0;
VersesView lsSplit1;
TextView tSplitEmpty;
TwofingerLinearLayout splitRoot;
LabeledSplitHandleButton splitHandleButton;
GotoButton bGoto;
ImageButton bLeft;
ImageButton bRight;
TextView bVersion;
Floater floater;
Book activeBook;
int chapter_1 = 0;
boolean fullScreen;
Toast fullScreenToast;
History history;
NfcAdapter nfcAdapter;
ActionMode actionMode;
boolean dictionaryMode;
TextAppearancePanel textAppearancePanel;
// temporary states
Boolean hasEsvsbAsal;
Version activeSplitVersion;
String activeSplitVersionId;
final CallbackSpan.OnClickListener<Object> parallelListener = (widget, data) -> {
if (data instanceof String) {
final int ari = jumpTo((String) data);
if (ari != 0) {
history.add(ari);
}
} else if (data instanceof Integer) {
final int ari = (Integer) data;
jumpToAri(ari);
history.add(ari);
}
};
final CallbackSpan.OnClickListener<SingleViewVerseAdapter.DictionaryLinkInfo> dictionaryListener = (widget, data) -> {
final ContentResolver cr = getContentResolver();
final Uri uri = Uri.parse("content://org.sabda.kamus.provider/define").buildUpon()
.appendQueryParameter("key", data.key)
.appendQueryParameter("mode", "snippet")
.build();
Cursor c;
try {
c = cr.query(uri, null, null, null, null);
} catch (Exception e) {
new MaterialDialog.Builder(this)
.content(R.string.dict_no_results)
.positiveText(R.string.ok)
.show();
return;
}
if (c == null) {
OtherAppIntegration.askToInstallDictionary(this);
return;
}
try {
if (c.getCount() == 0) {
new MaterialDialog.Builder(this)
.content(R.string.dict_no_results)
.positiveText(R.string.ok)
.show();
} else {
c.moveToNext();
final Spanned rendered = Html.fromHtml(c.getString(c.getColumnIndexOrThrow("definition")));
final SpannableStringBuilder sb = rendered instanceof SpannableStringBuilder ? (SpannableStringBuilder) rendered : new SpannableStringBuilder(rendered);
// remove links
for (final URLSpan span : sb.getSpans(0, sb.length(), URLSpan.class)) {
sb.removeSpan(span);
}
new MaterialDialog.Builder(this)
.title(data.orig_text)
.content(sb)
.positiveText(R.string.dict_open_full)
.onPositive((dialog, which) -> {
final Intent intent = new Intent("org.sabda.kamus.action.VIEW");
intent.putExtra("key", data.key);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
OtherAppIntegration.askToInstallDictionary(IsiActivity.this);
}
})
.show();
}
} finally {
c.close();
}
};
final ViewTreeObserver.OnGlobalLayoutListener splitRoot_globalLayout = new ViewTreeObserver.OnGlobalLayoutListener() {
Point lastSize;
@Override
public void onGlobalLayout() {
if (lastSize != null && lastSize.x == splitRoot.getWidth() && lastSize.y == splitRoot.getHeight()) {
return; // no need to layout now
}
if (activeSplitVersion == null) {
return; // we are not splitting
}
configureSplitSizes();
if (lastSize == null) {
lastSize = new Point();
}
lastSize.x = splitRoot.getWidth();
lastSize.y = splitRoot.getHeight();
}
};
static class IntentResult {
public int ari;
public boolean selectVerse;
public int selectVerseCount;
public IntentResult(final int ari) {
this.ari = ari;
}
}
public static Intent createIntent() {
return new Intent(App.context, IsiActivity.class);
}
public static Intent createIntent(int ari) {
Intent res = new Intent(App.context, IsiActivity.class);
res.setAction("yuku.alkitab.action.VIEW");
res.putExtra("ari", ari);
return res;
}
final BroadcastReceiver reloadAttributeMapReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
reloadBothAttributeMaps();
}
};
@Override protected void onCreate(Bundle savedInstanceState) {
AppLog.d(TAG, "@@onCreate start");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_isi);
AppLog.d(TAG, "@@onCreate setCV");
drawerLayout = V.get(this, R.id.drawerLayout);
leftDrawer = V.get(this, R.id.left_drawer);
leftDrawer.configure(this, drawerLayout);
toolbar = V.get(this, R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
ab.setDisplayShowTitleEnabled(false);
ab.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
bGoto = V.get(this, R.id.bGoto);
bLeft = V.get(this, R.id.bLeft);
bRight = V.get(this, R.id.bRight);
bVersion = V.get(this, R.id.bVersion);
overlayContainer = V.get(this, R.id.overlayContainer);
root = V.get(this, R.id.root);
lsSplit0 = V.get(this, R.id.lsSplit0);
lsSplit1 = V.get(this, R.id.lsSplit1);
tSplitEmpty = V.get(this, R.id.tSplitEmpty);
splitRoot = V.get(this, R.id.splitRoot);
splitRoot.getViewTreeObserver().addOnGlobalLayoutListener(splitRoot_globalLayout);
splitHandleButton = V.get(this, R.id.splitHandleButton);
floater = V.get(this, R.id.floater);
// If layout is changed, updateToolbarLocation must be updated as well. This will be called in DEBUG to make sure
// updateToolbarLocation is also updated when layout is updated.
if (BuildConfig.DEBUG) {
if (root.getChildCount() != 2 || root.getChildAt(0).getId() != R.id.toolbar || root.getChildAt(1).getId() != R.id.splitRoot) {
throw new RuntimeException("Layout changed and this is no longer compatible with updateToolbarLocation");
}
}
updateToolbarLocation();
lsSplit0.setName("lsSplit0");
lsSplit1.setName("lsSplit1");
splitRoot.setListener(splitRoot_listener);
bGoto.setOnClickListener(v -> bGoto_click());
bGoto.setOnLongClickListener(v -> {
bGoto_longClick();
return true;
});
bGoto.setFloaterDragListener(bGoto_floaterDrag);
bLeft.setOnClickListener(v -> bLeft_click());
bRight.setOnClickListener(v -> bRight_click());
bVersion.setOnClickListener(v -> bVersion_click());
floater.setListener(floater_listener);
lsSplit0.setOnKeyListener((v, keyCode, event) -> {
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
return press(keyCode);
} else if (action == KeyEvent.ACTION_MULTIPLE) {
return press(keyCode);
}
return false;
});
// listeners
lsSplit0.setParallelListener(parallelListener);
lsSplit0.setAttributeListener(new AttributeListener()); // have to be distinct from lsSplit1
lsSplit0.setInlineLinkSpanFactory(new VerseInlineLinkSpanFactory(lsSplit0));
lsSplit0.setSelectedVersesListener(lsSplit0_selectedVerses);
lsSplit0.setOnVerseScrollListener(lsSplit0_verseScroll);
lsSplit0.setDictionaryListener(dictionaryListener);
// additional setup for split1
lsSplit1.setVerseSelectionMode(VersesView.VerseSelectionMode.multiple);
lsSplit1.setEmptyView(tSplitEmpty);
lsSplit1.setParallelListener(parallelListener);
lsSplit1.setAttributeListener(new AttributeListener()); // have to be distinct from lsSplit0
lsSplit1.setInlineLinkSpanFactory(new VerseInlineLinkSpanFactory(lsSplit1));
lsSplit1.setSelectedVersesListener(lsSplit1_selectedVerses);
lsSplit1.setOnVerseScrollListener(lsSplit1_verseScroll);
lsSplit1.setDictionaryListener(dictionaryListener);
// for splitting
splitHandleButton.setListener(splitHandleButton_listener);
splitHandleButton.setButtonPressListener(splitHandleButton_labelPressed);
// migrate old history?
History.migrateOldHistoryWhenNeeded();
history = History.getInstance();
initNfcIfAvailable();
final IntentResult intentResult = processIntent(getIntent(), "onCreate");
final int openingAri;
final boolean selectVerse;
final int selectVerseCount;
if (intentResult == null) {
// restore the last (version; book; chapter and verse).
final int lastBookId = Preferences.getInt(Prefkey.lastBookId, 0);
final int lastChapter = Preferences.getInt(Prefkey.lastChapter, 0);
final int lastVerse = Preferences.getInt(Prefkey.lastVerse, 0);
openingAri = Ari.encode(lastBookId, lastChapter, lastVerse);
selectVerse = false;
selectVerseCount = 1;
AppLog.d(TAG, "Going to the last: bookId=" + lastBookId + " chapter=" + lastChapter + " verse=" + lastVerse);
} else {
openingAri = intentResult.ari;
selectVerse = intentResult.selectVerse;
selectVerseCount = intentResult.selectVerseCount;
}
{ // load book
final Book book = S.activeVersion().getBook(Ari.toBook(openingAri));
if (book != null) {
this.activeBook = book;
} else { // can't load last book or bookId 0
this.activeBook = S.activeVersion().getFirstBook();
}
if (this.activeBook == null) { // version failed to load, so books are also failed to load. Fallback!
S.setActiveVersion(VersionImpl.getInternalVersion(), MVersionInternal.getVersionInternalId());
this.activeBook = S.activeVersion().getFirstBook();
}
}
// first display of active version
displayActiveVersion();
// load chapter and verse
display(Ari.toChapter(openingAri), Ari.toVerse(openingAri));
if (intentResult != null) { // also add to history if not opening the last seen verse
history.add(openingAri);
}
{ // load last split version. This must be after load book, chapter, and verse.
final String lastSplitVersionId = Preferences.getString(Prefkey.lastSplitVersionId, null);
if (lastSplitVersionId != null) {
final String splitOrientation = Preferences.getString(Prefkey.lastSplitOrientation);
if (LabeledSplitHandleButton.Orientation.horizontal.name().equals(splitOrientation)) {
splitHandleButton.setOrientation(LabeledSplitHandleButton.Orientation.horizontal);
} else {
splitHandleButton.setOrientation(LabeledSplitHandleButton.Orientation.vertical);
}
final MVersion splitMv = S.getVersionFromVersionId(lastSplitVersionId);
final MVersion splitMvActual = splitMv == null ? S.getMVersionInternal() : splitMv;
if (loadSplitVersion(splitMvActual)) {
openSplitDisplay();
displaySplitFollowingMaster(Ari.toVerse(openingAri));
}
}
}
if (selectVerse) {
for (int i = 0; i < selectVerseCount; i++) {
final int verse_1 = Ari.toVerse(openingAri) + i;
callAttentionForVerseToBothSplits(verse_1);
}
}
App.getLbm().registerReceiver(reloadAttributeMapReceiver, new IntentFilter(ACTION_ATTRIBUTE_MAP_CHANGED));
Announce.checkAnnouncements();
App.getLbm().registerReceiver(needsRestartReceiver, new IntentFilter(ACTION_NEEDS_RESTART));
AppLog.d(TAG, "@@onCreate end");
}
void callAttentionForVerseToBothSplits(final int verse_1) {
lsSplit0.callAttentionForVerse(verse_1);
if (activeSplitVersion != null) {
lsSplit1.callAttentionForVerse(verse_1);
}
}
final BroadcastReceiver needsRestartReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
needsRestart = true;
}
};
@Override protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
processIntent(intent, "onNewIntent");
}
@Override
protected void onDestroy() {
super.onDestroy();
App.getLbm().unregisterReceiver(reloadAttributeMapReceiver);
App.getLbm().unregisterReceiver(needsRestartReceiver);
}
/**
* @return non-null if the intent is handled by any of the intent handler (e.g. nfc or VIEW)
*/
private IntentResult processIntent(Intent intent, String via) {
U.dumpIntent(intent, via);
{
final IntentResult result = tryGetIntentResultFromBeam(intent);
if (result != null) return result;
}
{
final IntentResult result = tryGetIntentResultFromView(intent);
if (result != null) return result;
}
return null;
}
/** did we get here from VIEW intent? */
private IntentResult tryGetIntentResultFromView(Intent intent) {
if (!U.equals(intent.getAction(), "yuku.alkitab.action.VIEW")) return null;
final boolean selectVerse = intent.getBooleanExtra("selectVerse", false);
final int selectVerseCount = intent.getIntExtra("selectVerseCount", 1);
if (intent.hasExtra("ari")) {
int ari = intent.getIntExtra("ari", 0);
if (ari != 0) {
final IntentResult res = new IntentResult(ari);
res.selectVerse = selectVerse;
res.selectVerseCount = selectVerseCount;
return res;
} else {
new MaterialDialog.Builder(this)
.content("Invalid ari: " + ari)
.positiveText(R.string.ok)
.show();
return null;
}
} else if (intent.hasExtra("lid")) {
int lid = intent.getIntExtra("lid", 0);
int ari = LidToAri.lidToAri(lid);
if (ari != 0) {
jumpToAri(ari);
history.add(ari);
final IntentResult res = new IntentResult(ari);
res.selectVerse = selectVerse;
res.selectVerseCount = selectVerseCount;
return res;
} else {
new MaterialDialog.Builder(this)
.content("Invalid lid: " + lid)
.positiveText(R.string.ok)
.show();
return null;
}
} else {
return null;
}
}
private void initNfcIfAvailable() {
nfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
if (nfcAdapter != null) {
nfcAdapter.setNdefPushMessageCallback(event -> {
JSONObject obj = new JSONObject();
try {
obj.put("ari", Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, lsSplit0.getVerseBasedOnScroll()));
} catch (JSONException e) { // won't happen
}
byte[] payload = obj.toString().getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "application/vnd.yuku.alkitab.nfc.beam".getBytes(), new byte[0], payload);
return new NdefMessage(new NdefRecord[] {
record,
NdefRecord.createApplicationRecord(getPackageName()),
});
}, this);
}
}
@Override protected void onPause() {
super.onPause();
disableNfcForegroundDispatchIfAvailable();
}
private void disableNfcForegroundDispatchIfAvailable() {
final NfcAdapter _nfcAdapter = this.nfcAdapter;
if (_nfcAdapter != null) {
try {
_nfcAdapter.disableForegroundDispatch(this);
} catch (IllegalStateException e) {
AppLog.e(TAG, "sometimes this happens.", e);
}
}
}
@Override protected void onResume() {
super.onResume();
enableNfcForegroundDispatchIfAvailable();
}
private void enableNfcForegroundDispatchIfAvailable() {
if (nfcAdapter != null) {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, IsiActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("application/vnd.yuku.alkitab.nfc.beam");
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("fail mime type", e);
}
IntentFilter[] intentFiltersArray = new IntentFilter[] {ndef, };
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
}
}
private IntentResult tryGetIntentResultFromBeam(Intent intent) {
String action = intent.getAction();
if (!U.equals(action, NfcAdapter.ACTION_NDEF_DISCOVERED)) return null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
if (rawMsgs == null || rawMsgs.length <= 0) return null;
NdefMessage msg = (NdefMessage) rawMsgs[0];
// record 0 contains the MIME type, record 1 is the AAR, if present
NdefRecord[] records = msg.getRecords();
if (records.length <= 0) return null;
String json = new String(records[0].getPayload());
try {
JSONObject obj = new JSONObject(json);
final int ari = obj.optInt("ari", -1);
if (ari == -1) return null;
return new IntentResult(ari);
} catch (JSONException e) {
AppLog.e(TAG, "Malformed json from nfc", e);
return null;
}
}
boolean loadVersion(final MVersion mv, boolean display) {
try {
final Version version = mv.getVersion();
if (version == null) {
throw new RuntimeException(); // caught below
}
if (this.activeBook != null) { // we already have some other version loaded, so make the new version open the same book
int bookId = this.activeBook.bookId;
Book book = version.getBook(bookId);
if (book != null) { // we load the new book succesfully
this.activeBook = book;
} else { // too bad, this book was not found, get any book
this.activeBook = version.getFirstBook();
}
}
S.setActiveVersion(version, mv.getVersionId());
displayActiveVersion();
if (display) {
display(chapter_1, lsSplit0.getVerseBasedOnScroll(), false);
}
App.getLbm().sendBroadcast(new Intent(ACTION_ACTIVE_VERSION_CHANGED));
return true;
} catch (Throwable e) { // so we don't crash on the beginning of the app
AppLog.e(TAG, "Error opening main version", e);
new MaterialDialog.Builder(IsiActivity.this)
.content(getString(R.string.version_error_opening, mv.longName))
.positiveText(R.string.ok)
.show();
return false;
}
}
private void displayActiveVersion() {
bVersion.setText(S.activeVersion().getInitials());
splitHandleButton.setLabel1("\u25b2 " + S.activeVersion().getInitials());
}
boolean loadSplitVersion(final MVersion mv) {
try {
final Version version = mv.getVersion();
if (version == null) {
throw new RuntimeException(); // caught below
}
activeSplitVersion = version;
activeSplitVersionId = mv.getVersionId();
splitHandleButton.setLabel2(version.getInitials() + " \u25bc");
configureTextAppearancePanelForSplitVersion();
return true;
} catch (Throwable e) { // so we don't crash on the beginning of the app
AppLog.e(TAG, "Error opening split version", e);
new MaterialDialog.Builder(IsiActivity.this)
.content(getString(R.string.version_error_opening, mv.longName))
.positiveText(R.string.ok)
.show();
return false;
}
}
private void configureTextAppearancePanelForSplitVersion() {
if (textAppearancePanel != null) {
if (activeSplitVersion == null) {
textAppearancePanel.clearSplitVersion();
} else {
textAppearancePanel.setSplitVersion(activeSplitVersionId, activeSplitVersion.getLongName());
}
}
}
boolean press(int keyCode) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
bLeft_click();
return true;
} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
bRight_click();
return true;
}
VersesView.PressResult pressResult = lsSplit0.press(keyCode);
switch (pressResult.kind) {
case left:
bLeft_click();
return true;
case right:
bRight_click();
return true;
case consumed:
if (activeSplitVersion != null) {
lsSplit1.scrollToVerse(pressResult.targetVerse_1);
}
return true;
default:
return false;
}
}
/**
* Jump to a given verse reference in string format.
* @return ari of the parsed reference
*/
int jumpTo(String reference) {
if (reference.trim().length() == 0) {
return 0;
}
AppLog.d(TAG, "going to jump to " + reference);
Jumper jumper = new Jumper(reference);
if (! jumper.getParseSucceeded()) {
new MaterialDialog.Builder(this)
.content(R.string.alamat_tidak_sah_alamat, reference)
.positiveText(R.string.ok)
.show();
return 0;
}
int bookId = jumper.getBookId(S.activeVersion().getConsecutiveBooks());
Book selected;
if (bookId != -1) {
Book book = S.activeVersion().getBook(bookId);
if (book != null) {
selected = book;
} else {
// not avail, just fallback
selected = this.activeBook;
}
} else {
selected = this.activeBook;
}
// set book
this.activeBook = selected;
int chapter = jumper.getChapter();
int verse = jumper.getVerse();
int ari_cv;
if (chapter == -1 && verse == -1) {
ari_cv = display(1, 1);
} else {
ari_cv = display(chapter, verse);
}
return Ari.encode(selected.bookId, ari_cv);
}
/**
* Jump to a given ari
*/
void jumpToAri(final int ari) {
if (ari == 0) return;
final int bookId = Ari.toBook(ari);
final Book book = S.activeVersion().getBook(bookId);
if (book == null) {
AppLog.w(TAG, "bookId=" + bookId + " not found for ari=" + ari);
return;
}
this.activeBook = book;
final int ari_cv = display(Ari.toChapter(ari), Ari.toVerse(ari));
// call attention to the verse only if the displayed verse is equal to the requested verse
if (ari == Ari.encode(this.activeBook.bookId, ari_cv)) {
callAttentionForVerseToBothSplits(Ari.toVerse(ari));
}
}
private CharSequence referenceFromSelectedVerses(IntArrayList selectedVerses, Book book) {
if (selectedVerses.size() == 0) {
// should not be possible. So we don't do anything.
return book.reference(this.chapter_1);
} else if (selectedVerses.size() == 1) {
return book.reference(this.chapter_1, selectedVerses.get(0));
} else {
return book.reference(this.chapter_1, selectedVerses);
}
}
/**
* Construct text for copying or sharing (in plain text).
* @param isSplitVersion whether take the verse text from the main or from the split version.
* @return [0] text for copy/share, [1] text to be submitted to the share url service
*/
String[] prepareTextForCopyShare(IntArrayList selectedVerses_1, CharSequence reference, boolean isSplitVersion) {
final StringBuilder res0 = new StringBuilder();
final StringBuilder res1 = new StringBuilder();
res0.append(reference);
if (Preferences.getBoolean(getString(R.string.pref_copyWithVersionName_key), getResources().getBoolean(R.bool.pref_copyWithVersionName_default))) {
final Version version = isSplitVersion ? activeSplitVersion : S.activeVersion();
final String versionShortName = version.getShortName();
if (versionShortName != null) {
res0.append(" (").append(versionShortName).append(")");
}
}
if (Preferences.getBoolean(getString(R.string.pref_copyWithVerseNumbers_key), false) && selectedVerses_1.size() > 1) {
res0.append('\n');
// append each selected verse with verse number prepended
for (int i = 0, len = selectedVerses_1.size(); i < len; i++) {
final int verse_1 = selectedVerses_1.get(i);
final String verseText = isSplitVersion ? lsSplit1.getVerseText(verse_1) : lsSplit0.getVerseText(verse_1);
if (verseText != null) {
final String verseTextPlain = U.removeSpecialCodes(verseText);
res0.append(verse_1);
res1.append(verse_1);
res0.append(' ');
res1.append(' ');
res0.append(verseTextPlain);
res1.append(verseText);
if (i != len - 1) {
res0.append('\n');
res1.append('\n');
}
}
}
} else {
res0.append(" ");
// append each selected verse without verse number prepended
for (int i = 0; i < selectedVerses_1.size(); i++) {
final int verse_1 = selectedVerses_1.get(i);
final String verseText = isSplitVersion ? lsSplit1.getVerseText(verse_1) : lsSplit0.getVerseText(verse_1);
if (verseText != null) {
final String verseTextPlain = U.removeSpecialCodes(verseText);
if (i != 0) {
res0.append('\n');
res1.append('\n');
}
res0.append(verseTextPlain);
res1.append(verseText);
}
}
}
return Array(res0.toString(), res1.toString());
}
private void applyPreferences() {
// make sure S applied variables are set first
S.recalculateAppliedValuesBasedOnPreferences();
{ // apply background color, and clear window background to prevent overdraw
getWindow().setBackgroundDrawableResource(android.R.color.transparent);
final int backgroundColor = S.applied().backgroundColor;
root.setBackgroundColor(backgroundColor);
lsSplit0.setCacheColorHint(backgroundColor);
lsSplit1.setCacheColorHint(backgroundColor);
// ensure scrollbar is visible on Material devices
if (Build.VERSION.SDK_INT >= 21) {
final Drawable thumb;
if (ColorUtils.calculateLuminance(backgroundColor) > 0.5) {
thumb = getResources().getDrawable(R.drawable.scrollbar_handle_material_for_light, null);
} else {
thumb = getResources().getDrawable(R.drawable.scrollbar_handle_material_for_dark, null);
}
ScrollbarSetter.setVerticalThumb(lsSplit0, thumb);
ScrollbarSetter.setVerticalThumb(lsSplit1, thumb);
}
}
// necessary
lsSplit0.invalidateViews();
lsSplit1.invalidateViews();
SettingsActivity.setPaddingBasedOnPreferences(lsSplit0);
SettingsActivity.setPaddingBasedOnPreferences(lsSplit1);
}
@Override protected void onStop() {
super.onStop();
Preferences.hold();
try {
Preferences.setInt(Prefkey.lastBookId, this.activeBook.bookId);
Preferences.setInt(Prefkey.lastChapter, chapter_1);
Preferences.setInt(Prefkey.lastVerse, lsSplit0.getVerseBasedOnScroll());
Preferences.setString(Prefkey.lastVersionId, S.activeVersionId());
if (activeSplitVersion == null) {
Preferences.remove(Prefkey.lastSplitVersionId);
} else {
Preferences.setString(Prefkey.lastSplitVersionId, activeSplitVersionId);
Preferences.setString(Prefkey.lastSplitOrientation, splitHandleButton.getOrientation().name());
}
} finally {
Preferences.unhold();
}
history.save();
}
@Override protected void onStart() {
super.onStart();
applyPreferences();
getWindow().getDecorView().setKeepScreenOn(Preferences.getBoolean(getString(R.string.pref_keepScreenOn_key), getResources().getBoolean(R.bool.pref_keepScreenOn_default)));
if (needsRestart) {
needsRestart = false;
final Intent originalIntent = getIntent();
finish();
startActivity(originalIntent);
}
}
@Override public void onBackPressed() {
final boolean debug = Preferences.getBoolean("secret_debug_back_button", false);
if (debug) Toast.makeText(this, "@@onBackPressed TAP=" + (textAppearancePanel != null) + " fullScreen=" + fullScreen, Toast.LENGTH_SHORT).show();
if (textAppearancePanel != null) {
if (debug) Toast.makeText(this, "inside textAppearancePanel != null", Toast.LENGTH_SHORT).show();
textAppearancePanel.hide();
textAppearancePanel = null;
} else if (fullScreen) {
if (debug) Toast.makeText(this, "inside fullScreen == true", Toast.LENGTH_SHORT).show();
setFullScreen(false);
leftDrawer.getHandle().setFullScreen(false);
} else {
if (debug) Toast.makeText(this, "will call super", Toast.LENGTH_SHORT).show();
super.onBackPressed();
}
}
void bGoto_click() {
App.trackEvent("nav_goto_button_click");
final Runnable r = () -> startActivityForResult(GotoActivity.createIntent(this.activeBook.bookId, this.chapter_1, lsSplit0.getVerseBasedOnScroll()), REQCODE_goto);
if (!Preferences.getBoolean(Prefkey.history_button_understood, false) && history.getSize() > 0) {
new MaterialDialog.Builder(this)
.content(R.string.goto_button_history_tip)
.positiveText(R.string.ok)
.onPositive((dialog, which) -> {
Preferences.setBoolean(Prefkey.history_button_understood, true);
r.run();
})
.show();
} else {
r.run();
}
}
void bGoto_longClick() {
App.trackEvent("nav_goto_button_long_click");
if (history.getSize() > 0) {
MaterialDialogAdapterHelper.show(new MaterialDialog.Builder(this), new HistoryAdapter());
Preferences.setBoolean(Prefkey.history_button_understood, true);
} else {
Snackbar.make(root, R.string.recentverses_not_available, Snackbar.LENGTH_SHORT).show();
}
}
static class HistoryEntryHolder extends RecyclerView.ViewHolder {
final TextView text1;
public HistoryEntryHolder(final View itemView) {
super(itemView);
text1 = V.get(itemView, android.R.id.text1);
}
}
class HistoryAdapter extends MaterialDialogAdapterHelper.Adapter {
private final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(App.context);
private final java.text.DateFormat mediumDateFormat = DateFormat.getMediumDateFormat(App.context);
final String thisCreatorId = U.getInstallationId();
int defaultTextColor;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final View view = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
final TextView textView = (TextView) view;
defaultTextColor = textView.getCurrentTextColor();
return new HistoryEntryHolder(view);
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder _holder_, final int position) {
final HistoryEntryHolder holder = (HistoryEntryHolder) _holder_;
{
int ari = history.getAri(position);
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append(S.activeVersion().reference(ari));
sb.append(" ");
int sb_len = sb.length();
sb.append(formatTimestamp(history.getTimestamp(position)));
sb.setSpan(new ForegroundColorSpan(0xffaaaaaa), sb_len, sb.length(), 0);
sb.setSpan(new RelativeSizeSpan(0.7f), sb_len, sb.length(), 0);
holder.text1.setText(sb);
if (thisCreatorId.equals(history.getCreatorId(position))) {
holder.text1.setTextColor(defaultTextColor);
} else {
holder.text1.setTextColor(ResourcesCompat.getColor(getResources(), R.color.escape, getTheme()));
}
}
holder.itemView.setOnClickListener(v -> {
dismissDialog();
final int which = holder.getAdapterPosition();
final int ari = history.getAri(which);
jumpToAri(ari);
history.add(ari);
});
}
private CharSequence formatTimestamp(final long timestamp) {
{
long now = System.currentTimeMillis();
long delta = now - timestamp;
if (delta <= 200000) {
return getString(R.string.recentverses_just_now);
} else if (delta <= 3600000) {
return getString(R.string.recentverses_min_plural_ago, Math.round(delta / 60000.0));
}
}
{
Calendar now = GregorianCalendar.getInstance();
Calendar that = GregorianCalendar.getInstance();
that.setTimeInMillis(timestamp);
if (now.get(Calendar.YEAR) == that.get(Calendar.YEAR)) {
if (now.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR)) {
return getString(R.string.recentverses_today_time, timeFormat.format(that.getTime()));
} else if (now.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR) + 1) {
return getString(R.string.recentverses_yesterday_time, timeFormat.format(that.getTime()));
}
}
return mediumDateFormat.format(that.getTime());
}
}
@Override
public int getItemCount() {
return history.getSize();
}
}
public void buildMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.activity_isi, menu);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
buildMenu(menu);
return true;
}
@Override public boolean onPrepareOptionsMenu(Menu menu) {
if (menu != null) {
buildMenu(menu);
}
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
leftDrawer.toggleDrawer();
return true;
case R.id.menuSearch:
App.trackEvent("nav_search_click");
menuSearch_click();
return true;
}
return super.onOptionsItemSelected(item);
}
@TargetApi(19)
void setFullScreen(boolean yes) {
if (fullScreen == yes) return; // no change
final View decorView = getWindow().getDecorView();
if (yes) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
if (Build.VERSION.SDK_INT >= 19) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE
);
}
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().show();
if (Build.VERSION.SDK_INT >= 19) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
fullScreen = yes;
updateToolbarLocation();
}
void updateToolbarLocation() {
// 3 kinds of possible layout:
// - fullscreen
// - not fullscreen, toolbar at bottom
// - not fullscreen, toolbar at top
// root contains exactly 2 children: toolbar and splitRoot. This is checked in DEBUG in onCreate.
// Need to move toolbar and splitRoot in order to accomplish this.
if (!fullScreen) {
root.removeView(toolbar);
root.removeView(splitRoot);
if (Preferences.getBoolean(R.string.pref_bottomToolbarOnText_key, R.bool.pref_bottomToolbarOnText_default)) {
root.addView(splitRoot);
root.addView(toolbar);
} else {
root.addView(toolbar);
root.addView(splitRoot);
}
}
}
@Override
public void onWindowFocusChanged(final boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && fullScreen) {
if (Build.VERSION.SDK_INT >= 19) {
final View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE
);
}
}
}
void setShowTextAppearancePanel(boolean yes) {
if (yes) {
if (textAppearancePanel == null) { // not showing yet
textAppearancePanel = new TextAppearancePanel(this, overlayContainer, new TextAppearancePanel.Listener() {
@Override public void onValueChanged() {
applyPreferences();
}
@Override
public void onCloseButtonClick() {
textAppearancePanel.hide();
textAppearancePanel = null;
}
}, REQCODE_textAppearanceGetFonts, REQCODE_textAppearanceCustomColors);
configureTextAppearancePanelForSplitVersion();
textAppearancePanel.show();
}
} else {
if (textAppearancePanel != null) {
textAppearancePanel.hide();
textAppearancePanel = null;
}
}
}
void setNightMode(boolean yes) {
final boolean previousValue = Preferences.getBoolean(Prefkey.is_night_mode, false);
if (previousValue == yes) return;
Preferences.setBoolean(Prefkey.is_night_mode, yes);
applyPreferences();
applyActionBarAndStatusBarColors();
if (textAppearancePanel != null) {
textAppearancePanel.displayValues();
}
App.getLbm().sendBroadcast(new Intent(ACTION_NIGHT_MODE_CHANGED));
}
void openVersionsDialog() {
S.openVersionsDialog(this, false, S.activeVersionId(), mv -> loadVersion(mv, true));
}
void openSplitVersionsDialog() {
S.openVersionsDialog(this, true, activeSplitVersionId, mv -> {
if (mv == null) { // closing split version
disableSplitVersion();
} else {
boolean ok = loadSplitVersion(mv);
if (ok) {
openSplitDisplay();
displaySplitFollowingMaster();
} else {
disableSplitVersion();
}
}
});
}
void disableSplitVersion() {
activeSplitVersion = null;
activeSplitVersionId = null;
closeSplitDisplay();
configureTextAppearancePanelForSplitVersion();
}
void openSplitDisplay() {
if (splitHandleButton.getVisibility() == View.VISIBLE) {
return; // it's already split, no need to do anything
}
configureSplitSizes();
bVersion.setVisibility(View.GONE);
if (actionMode != null) actionMode.invalidate();
leftDrawer.getHandle().setSplitVersion(true);
}
void configureSplitSizes() {
splitHandleButton.setVisibility(View.VISIBLE);
float prop = Preferences.getFloat(Prefkey.lastSplitProp, Float.MIN_VALUE);
if (prop == Float.MIN_VALUE || prop < 0.f || prop > 1.f) {
prop = 0.5f; // guard against invalid values
}
final int splitHandleThickness = getResources().getDimensionPixelSize(R.dimen.split_handle_thickness);
if (splitHandleButton.getOrientation() == LabeledSplitHandleButton.Orientation.vertical) {
splitRoot.setOrientation(LinearLayout.VERTICAL);
final int totalHeight = splitRoot.getHeight();
final int masterHeight = (int) ((totalHeight - splitHandleThickness) * prop);
{ // divide the screen space
final ViewGroup.LayoutParams lp = lsSplit0.getLayoutParams();
lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
lp.height = masterHeight;
lsSplit0.setLayoutParams(lp);
}
// no need to set height, because it has been set to match_parent, so it takes the remaining space.
lsSplit1.setVisibility(View.VISIBLE);
{
final ViewGroup.LayoutParams lp = splitHandleButton.getLayoutParams();
lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
lp.height = splitHandleThickness;
splitHandleButton.setLayoutParams(lp);
}
} else {
splitRoot.setOrientation(LinearLayout.HORIZONTAL);
final int totalWidth = splitRoot.getWidth();
final int masterWidth = (int) ((totalWidth - splitHandleThickness) * prop);
{ // divide the screen space
final ViewGroup.LayoutParams lp = lsSplit0.getLayoutParams();
lp.width = masterWidth;
lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
lsSplit0.setLayoutParams(lp);
}
// no need to set width, because it has been set to match_parent, so it takes the remaining space.
lsSplit1.setVisibility(View.VISIBLE);
{
final ViewGroup.LayoutParams lp = splitHandleButton.getLayoutParams();
lp.width = splitHandleThickness;
lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
splitHandleButton.setLayoutParams(lp);
}
}
}
void closeSplitDisplay() {
if (splitHandleButton.getVisibility() == View.GONE) {
return; // it's already not split, no need to do anything
}
splitHandleButton.setVisibility(View.GONE);
lsSplit1.setVisibility(View.GONE);
{
final ViewGroup.LayoutParams lp = lsSplit0.getLayoutParams();
lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
lsSplit0.setLayoutParams(lp);
}
bVersion.setVisibility(View.VISIBLE);
if (actionMode != null) actionMode.invalidate();
leftDrawer.getHandle().setSplitVersion(false);
}
private void menuSearch_click() {
startActivity(SearchActivity.createIntent(this.activeBook.bookId));
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQCODE_goto && resultCode == RESULT_OK) {
GotoActivity.Result result = GotoActivity.obtainResult(data);
if (result != null) {
final int ari_cv;
if (result.bookId == -1) {
// stay on the same book
ari_cv = display(result.chapter_1, result.verse_1);
// call attention to the verse only if the displayed verse is equal to the requested verse
if (Ari.encode(0, result.chapter_1, result.verse_1) == ari_cv) {
callAttentionForVerseToBothSplits(result.verse_1);
}
} else {
// change book
final Book book = S.activeVersion().getBook(result.bookId);
if (book != null) {
this.activeBook = book;
} else { // no book, just chapter and verse.
result.bookId = this.activeBook.bookId;
}
ari_cv = display(result.chapter_1, result.verse_1);
// select the verse only if the displayed verse is equal to the requested verse
if (Ari.encode(result.bookId, result.chapter_1, result.verse_1) == Ari.encode(this.activeBook.bookId, ari_cv)) {
callAttentionForVerseToBothSplits(result.verse_1);
}
}
if (result.verse_1 == 0 && Ari.toVerse(ari_cv) == 1) {
// verse 0 requested, but display method causes it to show verse_1 1.
// However we want to store verse_1 0 on the history.
history.add(Ari.encode(this.activeBook.bookId, Ari.toChapter(ari_cv), 0));
} else {
history.add(Ari.encode(this.activeBook.bookId, ari_cv));
}
}
} else if (requestCode == REQCODE_share && resultCode == RESULT_OK) {
ShareActivity.Result result = ShareActivity.obtainResult(data);
if (result != null && result.chosenIntent != null) {
Intent chosenIntent = result.chosenIntent;
final String packageName = chosenIntent.getComponent().getPackageName();
if (U.equals(packageName, "com.facebook.katana")) {
String verseUrl = chosenIntent.getStringExtra(EXTRA_verseUrl);
if (verseUrl != null) {
chosenIntent.putExtra(Intent.EXTRA_TEXT, verseUrl); // change text to url
}
} else if (U.equals(packageName, "com.whatsapp")) {
chosenIntent.removeExtra(Intent.EXTRA_SUBJECT);
}
startActivity(chosenIntent);
}
} else if (requestCode == REQCODE_textAppearanceGetFonts) {
if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data);
} else if (requestCode == REQCODE_textAppearanceCustomColors) {
if (textAppearancePanel != null) textAppearancePanel.onActivityResult(requestCode, resultCode, data);
} else if (requestCode == REQCODE_edit_note_1 && resultCode == RESULT_OK) {
reloadBothAttributeMaps();
} else if (requestCode == REQCODE_edit_note_2 && resultCode == RESULT_OK) {
lsSplit0.uncheckAllVerses(true);
reloadBothAttributeMaps();
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Display specified chapter and verse of the active book. By default all checked verses will be unchecked.
* @return Ari that contains only chapter and verse. Book always set to 0.
*/
int display(int chapter_1, int verse_1) {
return display(chapter_1, verse_1, true);
}
/**
* Display specified chapter and verse of the active book.
* @param uncheckAllVerses whether we want to always make all verses unchecked after this operation.
* @return Ari that contains only chapter and verse. Book always set to 0.
*/
int display(int chapter_1, int verse_1, boolean uncheckAllVerses) {
int current_chapter_1 = this.chapter_1;
if (chapter_1 < 1) chapter_1 = 1;
if (chapter_1 > this.activeBook.chapter_count) chapter_1 = this.activeBook.chapter_count;
if (verse_1 < 1) verse_1 = 1;
if (verse_1 > this.activeBook.verse_counts[chapter_1 - 1]) verse_1 = this.activeBook.verse_counts[chapter_1 - 1];
{ // main
this.uncheckVersesWhenActionModeDestroyed = false;
try {
boolean ok = loadChapterToVersesView(lsSplit0, S.activeVersion(), S.activeVersionId(), this.activeBook, chapter_1, current_chapter_1, uncheckAllVerses);
if (!ok) return 0;
} finally {
this.uncheckVersesWhenActionModeDestroyed = true;
}
// tell activity
this.chapter_1 = chapter_1;
lsSplit0.scrollToVerse(verse_1);
}
displaySplitFollowingMaster(verse_1);
// set goto button text
final String reference = this.activeBook.reference(chapter_1);
bGoto.setText(reference.replace(' ', '\u00a0'));
if (fullScreen) {
if (fullScreenToast == null) {
fullScreenToast = Toast.makeText(this, reference, Toast.LENGTH_SHORT);
fullScreenToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0);
} else {
fullScreenToast.setText(reference);
}
fullScreenToast.show();
}
if (dictionaryMode) {
finishDictionaryMode();
}
return Ari.encode(0, chapter_1, verse_1);
}
void displaySplitFollowingMaster() {
displaySplitFollowingMaster(lsSplit0.getVerseBasedOnScroll());
}
private void displaySplitFollowingMaster(int verse_1) {
if (activeSplitVersion != null) { // split1
final Book splitBook = activeSplitVersion.getBook(this.activeBook.bookId);
if (splitBook == null) {
tSplitEmpty.setText(getString(R.string.split_version_cant_display_verse, this.activeBook.reference(this.chapter_1), activeSplitVersion.getLongName()));
tSplitEmpty.setTextColor(S.applied().fontColor);
lsSplit1.setDataEmpty();
} else {
this.uncheckVersesWhenActionModeDestroyed = false;
try {
loadChapterToVersesView(lsSplit1, activeSplitVersion, activeSplitVersionId, splitBook, this.chapter_1, this.chapter_1, true);
} finally {
this.uncheckVersesWhenActionModeDestroyed = true;
}
lsSplit1.scrollToVerse(verse_1);
}
}
}
static boolean loadChapterToVersesView(VersesView versesView, Version version, String versionId, Book book, int chapter_1, int current_chapter_1, boolean uncheckAllVerses) {
final SingleChapterVerses verses = version.loadChapterText(book, chapter_1);
if (verses == null) {
return false;
}
//# max is set to 30 (one chapter has max of 30 blocks. Already almost impossible)
int max = 30;
int[] pericope_aris = new int[max];
PericopeBlock[] pericope_blocks = new PericopeBlock[max];
int nblock = version.loadPericope(book.bookId, chapter_1, pericope_aris, pericope_blocks, max);
boolean retainSelectedVerses = (!uncheckAllVerses && chapter_1 == current_chapter_1);
versesView.setDataWithRetainSelectedVerses(retainSelectedVerses, Ari.encode(book.bookId, chapter_1, 0), pericope_aris, pericope_blocks, nblock, verses, version, versionId);
return true;
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if (press(keyCode)) return true;
return super.onKeyDown(keyCode, event);
}
@Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
if (press(keyCode)) return true;
return super.onKeyMultiple(keyCode, repeatCount, event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
final String volumeButtonsForNavigation = Preferences.getString(R.string.pref_volumeButtonNavigation_key, R.string.pref_volumeButtonNavigation_default);
if (! U.equals(volumeButtonsForNavigation, "default")) { // consume here
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) return true;
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
protected LeftDrawer getLeftDrawer() {
return leftDrawer;
}
void bLeft_click() {
App.trackEvent("nav_left_click");
final Book currentBook = this.activeBook;
if (chapter_1 == 1) {
// we are in the beginning of the book, so go to prev book
int tryBookId = currentBook.bookId - 1;
while (tryBookId >= 0) {
Book newBook = S.activeVersion().getBook(tryBookId);
if (newBook != null) {
this.activeBook = newBook;
int newChapter_1 = newBook.chapter_count; // to the last chapter
display(newChapter_1, 1);
break;
}
tryBookId
}
// whileelse: now is already Genesis 1. No need to do anything
} else {
int newChapter = chapter_1 - 1;
display(newChapter, 1);
}
}
void bRight_click() {
App.trackEvent("nav_right_click");
final Book currentBook = this.activeBook;
if (chapter_1 >= currentBook.chapter_count) {
final int maxBookId = S.activeVersion().getMaxBookIdPlusOne();
int tryBookId = currentBook.bookId + 1;
while (tryBookId < maxBookId) {
final Book newBook = S.activeVersion().getBook(tryBookId);
if (newBook != null) {
this.activeBook = newBook;
display(1, 1);
break;
}
tryBookId++;
}
// whileelse: now is already Revelation (or the last book) at the last chapter. No need to do anything
} else {
int newChapter = chapter_1 + 1;
display(newChapter, 1);
}
}
void bVersion_click() {
App.trackEvent("nav_version_click");
openVersionsDialog();
}
@Override public boolean onSearchRequested() {
menuSearch_click();
return true;
}
@Override public void onVerseSelected(XrefDialog dialog, int arif_source, int ari_target) {
final int ari_source = arif_source >>> 8;
dialog.dismiss();
jumpToAri(ari_target);
// add both xref source and target, so user can go back to source easily
history.add(ari_source);
history.add(ari_target);
}
class AttributeListener implements VersesView.AttributeListener {
void openBookmarkDialog(final long _id) {
final TypeBookmarkDialog dialog = TypeBookmarkDialog.EditExisting(IsiActivity.this, _id);
dialog.setListener(() -> {
lsSplit0.reloadAttributeMap();
if (activeSplitVersion != null) {
lsSplit1.reloadAttributeMap();
}
});
dialog.show();
}
@Override
public void onBookmarkAttributeClick(final Version version, final String versionId, final int ari) {
final List<Marker> markers = S.getDb().listMarkersForAriKind(ari, Marker.Kind.bookmark);
if (markers.size() == 1) {
openBookmarkDialog(markers.get(0)._id);
} else {
MaterialDialogAdapterHelper.show(new MaterialDialog.Builder(IsiActivity.this).title(R.string.edit_bookmark), new MultipleMarkerSelectAdapter(version, versionId, markers, Marker.Kind.bookmark));
}
}
void openNoteDialog(final long _id) {
startActivityForResult(NoteActivity.createEditExistingIntent(_id), REQCODE_edit_note_1);
}
@Override
public void onNoteAttributeClick(final Version version, final String versionId, final int ari) {
final List<Marker> markers = S.getDb().listMarkersForAriKind(ari, Marker.Kind.note);
if (markers.size() == 1) {
openNoteDialog(markers.get(0)._id);
} else {
MaterialDialogAdapterHelper.show(new MaterialDialog.Builder(IsiActivity.this).title(R.string.edit_note), new MultipleMarkerSelectAdapter(version, versionId, markers, Marker.Kind.note));
}
}
class MarkerHolder extends RecyclerView.ViewHolder {
final TextView lDate;
final TextView lCaption;
final TextView lSnippet;
final FlowLayout panelLabels;
public MarkerHolder(final View itemView) {
super(itemView);
lDate = V.get(itemView, R.id.lDate);
lCaption = V.get(itemView, R.id.lCaption);
lSnippet = V.get(itemView, R.id.lSnippet);
panelLabels = V.get(itemView, R.id.panelLabels);
}
}
class MultipleMarkerSelectAdapter extends MaterialDialogAdapterHelper.Adapter {
final Version version;
final float textSizeMult;
final List<Marker> markers;
final Marker.Kind kind;
public MultipleMarkerSelectAdapter(final Version version, final String versionId, final List<Marker> markers, final Marker.Kind kind) {
this.version = version;
this.textSizeMult = S.getDb().getPerVersionSettings(versionId).fontSizeMultiplier;
this.markers = markers;
this.kind = kind;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
return new MarkerHolder(getLayoutInflater().inflate(R.layout.item_marker, parent, false));
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder _holder_, final int position) {
final MarkerHolder holder = (MarkerHolder) _holder_;
{
final Marker marker = markers.get(position);
{
final Date addTime = marker.createTime;
final Date modifyTime = marker.modifyTime;
if (addTime.equals(modifyTime)) {
holder.lDate.setText(Sqlitil.toLocaleDateMedium(addTime));
} else {
holder.lDate.setText(getString(R.string.create_edited_modified_time, Sqlitil.toLocaleDateMedium(addTime), Sqlitil.toLocaleDateMedium(modifyTime)));
}
Appearances.applyMarkerDateTextAppearance(holder.lDate, textSizeMult);
}
final int ari = marker.ari;
final String reference = version.reference(ari);
final String caption = marker.caption;
if (kind == Marker.Kind.bookmark) {
holder.lCaption.setText(caption);
Appearances.applyMarkerTitleTextAppearance(holder.lCaption, textSizeMult);
holder.lSnippet.setVisibility(View.GONE);
final List<Label> labels = S.getDb().listLabelsByMarker(marker);
if (labels.size() != 0) {
holder.panelLabels.setVisibility(View.VISIBLE);
holder.panelLabels.removeAllViews();
for (Label label : labels) {
holder.panelLabels.addView(MarkerListActivity.getLabelView(getLayoutInflater(), holder.panelLabels, label));
}
} else {
holder.panelLabels.setVisibility(View.GONE);
}
} else if (kind == Marker.Kind.note) {
holder.lCaption.setText(reference);
Appearances.applyMarkerTitleTextAppearance(holder.lCaption, textSizeMult);
holder.lSnippet.setText(caption);
Appearances.applyTextAppearance(holder.lSnippet, textSizeMult);
}
holder.itemView.setBackgroundColor(S.applied().backgroundColor);
}
holder.itemView.setOnClickListener(v -> {
dismissDialog();
final int which = holder.getAdapterPosition();
final Marker marker = markers.get(which);
if (kind == Marker.Kind.bookmark) {
openBookmarkDialog(marker._id);
} else if (kind == Marker.Kind.note) {
openNoteDialog(marker._id);
}
});
}
@Override
public int getItemCount() {
return markers.size();
}
}
@Override
public void onProgressMarkAttributeClick(final Version version, final String versionId, final int preset_id) {
final ProgressMark progressMark = S.getDb().getProgressMarkByPresetId(preset_id);
ProgressMarkRenameDialog.show(IsiActivity.this, progressMark, new ProgressMarkRenameDialog.Listener() {
@Override
public void onOked() {
lsSplit0.uncheckAllVerses(true);
}
@Override
public void onDeleted() {
lsSplit0.uncheckAllVerses(true);
}
});
}
@Override
public void onHasMapsAttributeClick(final Version version, final String versionId, final int ari) {
String locale = null;
if (this == lsSplit0.getAttributeListener()) {
locale = S.activeVersion().getLocale();
} else if (this == lsSplit1.getAttributeListener()) {
locale = activeSplitVersion.getLocale();
}
try {
final Intent intent = new Intent("palki.maps.action.SHOW_MAPS_DIALOG");
intent.putExtra("ari", ari);
if (locale != null) {
intent.putExtra("locale", locale);
}
startActivity(intent);
} catch (ActivityNotFoundException e) {
new MaterialDialog.Builder(IsiActivity.this)
.content(R.string.maps_could_not_open)
.positiveText(R.string.ok)
.show();
}
}
}
class VerseInlineLinkSpanFactory implements VerseInlineLinkSpan.Factory {
private final Object source;
VerseInlineLinkSpanFactory(final Object source) {
this.source = source;
}
@Override
public VerseInlineLinkSpan create(final VerseInlineLinkSpan.Type type, final int arif) {
return new VerseInlineLinkSpan(type, arif, source) {
@Override
public void onClick(final Type type, final int arif, final Object source) {
if (type == Type.xref) {
final XrefDialog dialog = XrefDialog.newInstance(arif);
// TODO setSourceVersion here is not restored when dialog is restored
if (source == lsSplit0) { // use activeVersion
dialog.setSourceVersion(S.activeVersion(), S.activeVersionId());
} else if (source == lsSplit1) { // use activeSplitVersion
dialog.setSourceVersion(activeSplitVersion, activeSplitVersionId);
}
FragmentManager fm = getSupportFragmentManager();
dialog.show(fm, XrefDialog.class.getSimpleName());
} else if (type == Type.footnote) {
FootnoteEntry fe = null;
if (source == lsSplit0) { // use activeVersion
fe = S.activeVersion().getFootnoteEntry(arif);
} else if (source == lsSplit1) { // use activeSplitVersion
fe = activeSplitVersion.getFootnoteEntry(arif);
}
if (fe != null) {
final SpannableStringBuilder footnoteText = new SpannableStringBuilder();
VerseRenderer.appendSuperscriptNumber(footnoteText, arif & 0xff);
footnoteText.append(" ");
new MaterialDialog.Builder(IsiActivity.this)
.content(FormattedTextRenderer.render(fe.content, footnoteText))
.positiveText(R.string.ok)
.show();
} else {
new MaterialDialog.Builder(IsiActivity.this)
.content(String.format(Locale.US, "Error: footnote arif 0x%08x couldn't be loaded", arif))
.positiveText(R.string.ok)
.show();
}
} else {
new MaterialDialog.Builder(IsiActivity.this)
.content("Error: Unknown inline link type: " + type)
.positiveText("OK")
.show();
}
}
};
}
}
VersesView.SelectedVersesListener lsSplit0_selectedVerses = new VersesView.DefaultSelectedVersesListener() {
@Override public void onSomeVersesSelected(VersesView v) {
if (activeSplitVersion != null) {
// synchronize the selection with the split view
IntArrayList selectedVerses = v.getSelectedVerses_1();
lsSplit1.checkVerses(selectedVerses, false);
}
if (actionMode == null) {
actionMode = startSupportActionMode(actionMode_callback);
}
if (actionMode != null) {
actionMode.invalidate();
}
}
@Override public void onNoVersesSelected(VersesView v) {
if (activeSplitVersion != null) {
// synchronize the selection with the split view
lsSplit1.uncheckAllVerses(false);
}
if (actionMode != null) {
actionMode.finish();
actionMode = null;
}
}
};
VersesView.SelectedVersesListener lsSplit1_selectedVerses = new VersesView.DefaultSelectedVersesListener() {
@Override public void onSomeVersesSelected(VersesView v) {
// synchronize the selection with the main view
IntArrayList selectedVerses = v.getSelectedVerses_1();
lsSplit0.checkVerses(selectedVerses, true);
}
@Override public void onNoVersesSelected(VersesView v) {
lsSplit0.uncheckAllVerses(true);
}
};
VersesView.OnVerseScrollListener lsSplit0_verseScroll = new VersesView.OnVerseScrollListener() {
@Override public void onVerseScroll(VersesView v, boolean isPericope, int verse_1, float prop) {
if (!isPericope && activeSplitVersion != null) {
lsSplit1.scrollToVerse(verse_1, prop);
}
}
@Override public void onScrollToTop(VersesView v) {
if (activeSplitVersion != null) {
lsSplit1.scrollToTop();
}
}
};
VersesView.OnVerseScrollListener lsSplit1_verseScroll = new VersesView.OnVerseScrollListener() {
@Override public void onVerseScroll(VersesView v, boolean isPericope, int verse_1, float prop) {
if (!isPericope) {
lsSplit0.scrollToVerse(verse_1, prop);
}
}
@Override public void onScrollToTop(VersesView v) {
lsSplit0.scrollToTop();
}
};
ActionMode.Callback actionMode_callback = new ActionMode.Callback() {
private static final int MENU_GROUP_EXTENSIONS = Menu.FIRST + 1;
private static final int MENU_EXTENSIONS_FIRST_ID = 0x1000;
List<ExtensionManager.Info> extensions;
@Override public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.context_isi, menu);
AppLog.d(TAG, "@@onCreateActionMode");
/* The following "esvsbasal" thing is a personal thing by yuku that doesn't matter to anyone else.
* Please ignore it and leave it intact. */
if (hasEsvsbAsal == null) {
try {
getPackageManager().getApplicationInfo("yuku.esvsbasal", 0);
hasEsvsbAsal = true;
} catch (PackageManager.NameNotFoundException e) {
hasEsvsbAsal = false;
}
}
if (hasEsvsbAsal) {
MenuItem esvsb = menu.findItem(R.id.menuEsvsb);
if (esvsb != null) esvsb.setVisible(true);
}
// show book name and chapter
final String reference = activeBook.reference(chapter_1);
mode.setTitle(reference);
return true;
}
@Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
final MenuItem menuAddBookmark = menu.findItem(R.id.menuAddBookmark);
final MenuItem menuAddNote = menu.findItem(R.id.menuAddNote);
final MenuItem menuCompare = menu.findItem(R.id.menuCompare);
final IntArrayList selected = lsSplit0.getSelectedVerses_1();
final boolean single = selected.size() == 1;
boolean contiguous = true;
if (!single) {
int next = selected.get(0) + 1;
for (int i = 1, len = selected.size(); i < len; i++) {
final int cur = selected.get(i);
if (next != cur) {
contiguous = false;
break;
}
next = cur + 1;
}
}
menuAddBookmark.setVisible(contiguous);
menuAddNote.setVisible(contiguous);
menuCompare.setVisible(single);
// just "copy" or ("copy primary" "copy secondary" "copy both")
// same with "share".
final MenuItem menuCopy = menu.findItem(R.id.menuCopy);
final MenuItem menuCopySplit0 = menu.findItem(R.id.menuCopySplit0);
final MenuItem menuCopySplit1 = menu.findItem(R.id.menuCopySplit1);
final MenuItem menuCopyBothSplits = menu.findItem(R.id.menuCopyBothSplits);
final MenuItem menuShare = menu.findItem(R.id.menuShare);
final MenuItem menuShareSplit0 = menu.findItem(R.id.menuShareSplit0);
final MenuItem menuShareSplit1 = menu.findItem(R.id.menuShareSplit1);
final MenuItem menuShareBothSplits = menu.findItem(R.id.menuShareBothSplits);
final boolean split = activeSplitVersion != null;
menuCopy.setVisible(!split);
menuCopySplit0.setVisible(split);
menuCopySplit1.setVisible(split);
menuCopyBothSplits.setVisible(split);
menuShare.setVisible(!split);
menuShareSplit0.setVisible(split);
menuShareSplit1.setVisible(split);
menuShareBothSplits.setVisible(split);
// show selected verses
if (single) {
mode.setSubtitle(R.string.verse_select_one_verse_selected);
} else {
mode.setSubtitle(getString(R.string.verse_select_multiple_verse_selected, selected.size()));
}
final MenuItem menuGuide = menu.findItem(R.id.menuGuide);
final MenuItem menuCommentary = menu.findItem(R.id.menuCommentary);
final MenuItem menuDictionary = menu.findItem(R.id.menuDictionary);
// force-show these items on sw600dp, otherwise never show
final int showAsAction = getResources().getConfiguration().smallestScreenWidthDp >= 600 ? MenuItem.SHOW_AS_ACTION_ALWAYS : MenuItem.SHOW_AS_ACTION_NEVER;
menuGuide.setShowAsActionFlags(showAsAction);
menuCommentary.setShowAsActionFlags(showAsAction);
menuDictionary.setShowAsActionFlags(showAsAction);
// set visibility according to appconfig
final AppConfig c = AppConfig.get();
menuGuide.setVisible(c.menuGuide);
menuCommentary.setVisible(c.menuCommentary);
// do not show dictionary item if not needed because of auto-lookup from
menuDictionary.setVisible(c.menuDictionary
&& !Preferences.getBoolean(getString(R.string.pref_autoDictionaryAnalyze_key), getResources().getBoolean(R.bool.pref_autoDictionaryAnalyze_default))
);
{ // extensions
extensions = ExtensionManager.getExtensions();
menu.removeGroup(MENU_GROUP_EXTENSIONS);
for (int i = 0; i < extensions.size(); i++) {
final ExtensionManager.Info extension = extensions.get(i);
if (single || (/* not single */ extension.supportsMultipleVerses)) {
menu.add(MENU_GROUP_EXTENSIONS, MENU_EXTENSIONS_FIRST_ID + i, 0, extension.label);
}
}
}
return true;
}
@Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
final IntArrayList selected = lsSplit0.getSelectedVerses_1();
if (selected.size() == 0) return true;
final CharSequence reference = referenceFromSelectedVerses(selected, activeBook);
final int itemId = item.getItemId();
switch (itemId) {
case R.id.menuCopy:
case R.id.menuCopySplit0:
case R.id.menuCopySplit1:
case R.id.menuCopyBothSplits: { // copy, can be multiple verses
final String[] t;
if (itemId == R.id.menuCopy || itemId == R.id.menuCopySplit0 || itemId == R.id.menuCopyBothSplits) {
t = prepareTextForCopyShare(selected, reference, false);
} else { // menuCopySplit1
t = prepareTextForCopyShare(selected, reference, true);
}
if (itemId == R.id.menuCopyBothSplits && activeSplitVersion != null) { // put guard on activeSplitVersion
appendSplitTextForCopyShare(t);
}
final String textToCopy = t[0];
final String textToSubmit = t[1];
ShareUrl.make(IsiActivity.this, !Preferences.getBoolean(getString(R.string.pref_copyWithShareUrl_key), getResources().getBoolean(R.bool.pref_copyWithShareUrl_default)), textToSubmit, Ari.encode(activeBook.bookId, chapter_1, 0), selected, reference.toString(), S.activeVersion(), MVersionDb.presetNameFromVersionId(S.activeVersionId()), new ShareUrl.Callback() {
@Override
public void onSuccess(final String shareUrl) {
U.copyToClipboard(textToCopy + "\n\n" + shareUrl);
}
@Override
public void onUserCancel() {
U.copyToClipboard(textToCopy);
}
@Override
public void onError(final Exception e) {
U.copyToClipboard(textToCopy);
}
@Override
public void onFinally() {
lsSplit0.uncheckAllVerses(true);
Snackbar.make(root, getString(R.string.alamat_sudah_disalin, reference), Snackbar.LENGTH_SHORT).show();
mode.finish();
}
});
} return true;
case R.id.menuShare:
case R.id.menuShareSplit0:
case R.id.menuShareSplit1:
case R.id.menuShareBothSplits: { // share, can be multiple verses
final String[] t;
if (itemId == R.id.menuShare || itemId == R.id.menuShareSplit0 || itemId == R.id.menuShareBothSplits) {
t = prepareTextForCopyShare(selected, reference, false);
} else { // menuShareSplit1
t = prepareTextForCopyShare(selected, reference, true);
}
if (itemId == R.id.menuShareBothSplits && activeSplitVersion != null) { // put guard on activeSplitVersion
appendSplitTextForCopyShare(t);
}
final String textToShare = t[0];
final String textToSubmit = t[1];
final Intent intent = ShareCompat.IntentBuilder.from(IsiActivity.this)
.setType("text/plain")
.setSubject(reference.toString())
.getIntent();
ShareUrl.make(IsiActivity.this, !Preferences.getBoolean(getString(R.string.pref_copyWithShareUrl_key), getResources().getBoolean(R.bool.pref_copyWithShareUrl_default)), textToSubmit, Ari.encode(activeBook.bookId, chapter_1, 0), selected, reference.toString(), S.activeVersion(), MVersionDb.presetNameFromVersionId(S.activeVersionId()), new ShareUrl.Callback() {
@Override
public void onSuccess(final String shareUrl) {
intent.putExtra(Intent.EXTRA_TEXT, textToShare + "\n\n" + shareUrl);
intent.putExtra(EXTRA_verseUrl, shareUrl);
}
@Override
public void onUserCancel() {
intent.putExtra(Intent.EXTRA_TEXT, textToShare);
}
@Override
public void onError(final Exception e) {
intent.putExtra(Intent.EXTRA_TEXT, textToShare);
}
@Override
public void onFinally() {
startActivityForResult(ShareActivity.createIntent(intent, getString(R.string.bagikan_alamat, reference)), REQCODE_share);
lsSplit0.uncheckAllVerses(true);
mode.finish();
}
});
} return true;
case R.id.menuCompare: {
final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, selected.get(0));
final VersesDialog dialog = VersesDialog.newCompareInstance(ari);
dialog.show(getSupportFragmentManager(), "compare_dialog");
dialog.setListener(new VersesDialog.VersesDialogListener() {
@Override
public void onComparedVerseSelected(final VersesDialog dialog, final int ari, final MVersion mversion) {
loadVersion(mversion, true);
dialog.dismiss();
}
});
} return true;
case R.id.menuAddBookmark: {
// contract: this menu only appears when contiguous verses are selected
if (selected.get(selected.size() - 1) - selected.get(0) != selected.size() - 1) {
throw new RuntimeException("Non contiguous verses when adding bookmark: " + selected);
}
final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, selected.get(0));
final int verseCount = selected.size();
// always create a new bookmark
TypeBookmarkDialog dialog = TypeBookmarkDialog.NewBookmark(IsiActivity.this, ari, verseCount);
dialog.setListener(() -> {
lsSplit0.uncheckAllVerses(true);
reloadBothAttributeMaps();
});
dialog.show();
mode.finish();
} return true;
case R.id.menuAddNote: {
// contract: this menu only appears when contiguous verses are selected
if (selected.get(selected.size() - 1) - selected.get(0) != selected.size() - 1) {
throw new RuntimeException("Non contiguous verses when adding note: " + selected);
}
final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, selected.get(0));
final int verseCount = selected.size();
// always create a new note
startActivityForResult(NoteActivity.createNewNoteIntent(S.activeVersion().referenceWithVerseCount(ari, verseCount), ari, verseCount), REQCODE_edit_note_2);
mode.finish();
} return true;
case R.id.menuAddHighlight: {
final int ariBc = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, 0);
int colorRgb = S.getDb().getHighlightColorRgb(ariBc, selected);
final TypeHighlightDialog.Listener listener = colorRgb1 -> {
lsSplit0.uncheckAllVerses(true);
reloadBothAttributeMaps();
};
if (selected.size() == 1) {
final VerseRenderer.FormattedTextResult ftr = new VerseRenderer.FormattedTextResult();
final int ari = Ari.encodeWithBc(ariBc, selected.get(0));
final String rawVerseText = S.activeVersion().loadVerseText(ari);
final Highlights.Info info = S.getDb().getHighlightColorRgb(ari);
assert rawVerseText != null;
VerseRenderer.render(null, null, ari, rawVerseText, "" + Ari.toVerse(ari), null, false, null, ftr);
new TypeHighlightDialog(IsiActivity.this, ari, listener, colorRgb, info, reference, ftr.result);
} else {
new TypeHighlightDialog(IsiActivity.this, ariBc, selected, listener, colorRgb, reference);
}
mode.finish();
} return true;
case R.id.menuEsvsb: {
final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, selected.get(0));
try {
Intent intent = new Intent("yuku.esvsbasal.action.GOTO");
intent.putExtra("ari", ari);
startActivity(intent);
} catch (Exception e) {
AppLog.e(TAG, "ESVSB starting", e);
}
} return true;
case R.id.menuGuide: {
final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, 0);
try {
getPackageManager().getPackageInfo("org.sabda.pedia", 0);
final Intent intent = new Intent("org.sabda.pedia.action.VIEW");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("ari", ari);
startActivity(intent);
} catch (PackageManager.NameNotFoundException e) {
OtherAppIntegration.openMarket(IsiActivity.this, "org.sabda.pedia");
}
} return true;
case R.id.menuCommentary: {
final int ari = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, selected.get(0));
try {
getPackageManager().getPackageInfo("org.sabda.tafsiran", 0);
final Intent intent = new Intent("org.sabda.tafsiran.action.VIEW");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("ari", ari);
startActivity(intent);
} catch (PackageManager.NameNotFoundException e) {
OtherAppIntegration.openMarket(IsiActivity.this, "org.sabda.tafsiran");
}
} return true;
case R.id.menuDictionary: {
final int ariBc = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, 0);
final SparseBooleanArray aris = new SparseBooleanArray();
for (int i = 0, len = selected.size(); i < len; i++) {
final int verse_1 = selected.get(i);
final int ari = Ari.encodeWithBc(ariBc, verse_1);
aris.put(ari, true);
}
startDictionaryMode(aris);
} return true;
default: if (itemId >= MENU_EXTENSIONS_FIRST_ID && itemId < MENU_EXTENSIONS_FIRST_ID + extensions.size()) {
final ExtensionManager.Info extension = extensions.get(itemId - MENU_EXTENSIONS_FIRST_ID);
final Intent intent = new Intent(ExtensionManager.ACTION_SHOW_VERSE_INFO);
intent.setComponent(new ComponentName(extension.activityInfo.packageName, extension.activityInfo.name));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// prepare extra "aris"
final int[] aris = new int[selected.size()];
final int ariBc = Ari.encode(IsiActivity.this.activeBook.bookId, IsiActivity.this.chapter_1, 0);
for (int i = 0, len = selected.size(); i < len; i++) {
final int verse_1 = selected.get(i);
final int ari = Ari.encodeWithBc(ariBc, verse_1);
aris[i] = ari;
}
intent.putExtra("aris", aris);
if (extension.includeVerseText) {
// prepare extra "verseTexts"
final String[] verseTexts = new String[selected.size()];
for (int i = 0, len = selected.size(); i < len; i++) {
final int verse_1 = selected.get(i);
final String verseText = lsSplit0.getVerseText(verse_1);
if (extension.includeVerseTextFormatting) {
verseTexts[i] = verseText;
} else {
verseTexts[i] = U.removeSpecialCodes(verseText);
}
}
intent.putExtra("verseTexts", verseTexts);
}
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
new MaterialDialog.Builder(IsiActivity.this)
.content("Error ANFE starting extension\n\n" + extension.activityInfo.packageName + "/" + extension.activityInfo.name)
.positiveText(R.string.ok)
.show();
}
return true;
}
}
return false;
}
/**
* @param t [0] is text to copy, [1] is text to submit
*/
void appendSplitTextForCopyShare(final String[] t) {
final Book splitBook = activeSplitVersion.getBook(activeBook.bookId);
if (splitBook != null) {
IntArrayList selectedSplit = lsSplit1.getSelectedVerses_1();
CharSequence referenceSplit = referenceFromSelectedVerses(selectedSplit, splitBook);
final String[] a = prepareTextForCopyShare(selectedSplit, referenceSplit, true);
t[0] += "\n\n" + a[0];
t[1] += "\n\n" + a[1];
}
}
@Override public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
// FIXME even with this guard, verses are still unchecked when switching version while both Fullscreen and Split is active.
// This guard only fixes unchecking of verses when in fullscreen mode.
if (uncheckVersesWhenActionModeDestroyed) {
lsSplit0.uncheckAllVerses(true);
}
}
};
void reloadBothAttributeMaps() {
lsSplit0.reloadAttributeMap();
if (activeSplitVersion != null) {
lsSplit1.reloadAttributeMap();
}
}
final SplitHandleButton.SplitHandleButtonListener splitHandleButton_listener = new SplitHandleButton.SplitHandleButtonListener() {
int first;
int handle;
int root;
float prop; // proportion from top or left
@Override public void onHandleDragStart() {
splitRoot.setOnefingerEnabled(false);
if (splitHandleButton.getOrientation() == SplitHandleButton.Orientation.vertical) {
first = lsSplit0.getHeight();
handle = splitHandleButton.getHeight();
root = splitRoot.getHeight();
} else {
first = lsSplit0.getWidth();
handle = splitHandleButton.getWidth();
root = splitRoot.getWidth();
}
prop = Float.MIN_VALUE; // guard against glitches
}
@Override
public void onHandleDragMoveX(final float dxSinceLast, final float dxSinceStart) {
final int newW = (int) (first + dxSinceStart);
final int maxW = root - handle;
final ViewGroup.LayoutParams lp = lsSplit0.getLayoutParams();
lp.width = newW < 0? 0: newW > maxW? maxW: newW;
lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
lsSplit0.setLayoutParams(lp);
prop = (float) lp.width / maxW;
}
@Override public void onHandleDragMoveY(float dySinceLast, float dySinceStart) {
final int newH = (int) (first + dySinceStart);
final int maxH = root - handle;
final ViewGroup.LayoutParams lp = lsSplit0.getLayoutParams();
lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
lp.height = newH < 0? 0: newH > maxH? maxH: newH;
lsSplit0.setLayoutParams(lp);
prop = (float) lp.height / maxH;
}
@Override public void onHandleDragStop() {
splitRoot.setOnefingerEnabled(true);
if (prop != Float.MIN_VALUE) {
Preferences.setFloat(Prefkey.lastSplitProp, prop);
}
}
};
LabeledSplitHandleButton.ButtonPressListener splitHandleButton_labelPressed = which -> {
switch (which) {
case rotate:
closeSplitDisplay();
openSplitDisplay();
break;
case start:
openVersionsDialog();
break;
case end:
openSplitVersionsDialog();
break;
}
};
void startDictionaryMode(final SparseBooleanArray aris) {
if (!OtherAppIntegration.hasIntegratedDictionaryApp()) {
OtherAppIntegration.askToInstallDictionary(this);
return;
}
dictionaryMode = true;
lsSplit0.setDictionaryModeAris(aris);
lsSplit1.setDictionaryModeAris(aris);
}
void finishDictionaryMode() {
dictionaryMode = false;
lsSplit0.setDictionaryModeAris(null);
lsSplit1.setDictionaryModeAris(null);
}
@Override
public void bMarkers_click() {
startActivity(MarkersActivity.createIntent());
}
@Override
public void bDisplay_click() {
App.trackEvent("left_drawer_display_click");
setShowTextAppearancePanel(textAppearancePanel == null);
}
@Override
public void cFullScreen_checkedChange(final boolean isChecked) {
App.trackEvent("left_drawer_full_screen_click");
setFullScreen(isChecked);
}
@Override
public void cNightMode_checkedChange(final boolean isChecked) {
App.trackEvent("left_drawer_night_mode_click");
setNightMode(isChecked);
}
@Override
public void cSplitVersion_checkedChange(final SwitchCompat cSplitVersion, final boolean isChecked) {
App.trackEvent("left_drawer_split_click");
if (isChecked) {
cSplitVersion.setChecked(false); // do it later, at the version chooser dialog
openSplitVersionsDialog();
} else {
disableSplitVersion();
}
}
@Override
public void bProgressMarkList_click() {
App.trackEvent("left_drawer_progress_mark_list_click");
if (S.getDb().countAllProgressMarks() > 0) {
final ProgressMarkListDialog dialog = new ProgressMarkListDialog();
dialog.show(getSupportFragmentManager(), "dialog_progress_mark_list");
leftDrawer.closeDrawer();
} else {
new MaterialDialog.Builder(this)
.content(R.string.pm_activate_tutorial)
.positiveText(R.string.ok)
.show();
}
}
@Override
public void bProgress_click(final int preset_id) {
gotoProgressMark(preset_id);
}
@Override
public void bCurrentReadingClose_click() {
App.trackEvent("left_drawer_current_reading_close_click");
CurrentReading.clear();
}
@Override
public void bCurrentReadingReference_click() {
App.trackEvent("left_drawer_current_reading_verse_reference_click");
final int[] aris = CurrentReading.get();
if (aris == null) {
return;
}
final int ari_start = aris[0];
jumpToAri(ari_start);
history.add(ari_start);
leftDrawer.closeDrawer();
}
private void gotoProgressMark(final int preset_id) {
final ProgressMark progressMark = S.getDb().getProgressMarkByPresetId(preset_id);
if (progressMark == null) {
return;
}
final int ari = progressMark.ari;
if (ari != 0) {
App.trackEvent("left_drawer_progress_mark_pin_click_succeed");
jumpToAri(ari);
history.add(ari);
} else {
App.trackEvent("left_drawer_progress_mark_pin_click_failed");
new MaterialDialog.Builder(this)
.content(R.string.pm_activate_tutorial)
.positiveText(R.string.ok)
.show();
}
}
@Override
public void onProgressMarkSelected(final int preset_id) {
gotoProgressMark(preset_id);
}
}
|
package yuku.alkitab.base.ac;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import yuku.alkitab.R;
import yuku.alkitab.base.AddonManager;
import yuku.alkitab.base.AddonManager.DonlotListener;
import yuku.alkitab.base.AddonManager.DonlotThread;
import yuku.alkitab.base.AddonManager.Elemen;
import yuku.alkitab.base.S;
import yuku.alkitab.base.U;
import yuku.alkitab.base.ac.base.BaseActivity;
import yuku.alkitab.base.config.BuildConfig;
import yuku.alkitab.base.model.Edisi;
import yuku.alkitab.base.pdbconvert.ConvertOptionsDialog;
import yuku.alkitab.base.pdbconvert.ConvertOptionsDialog.ConvertOptionsCallback;
import yuku.alkitab.base.pdbconvert.ConvertPdbToYes;
import yuku.alkitab.base.pdbconvert.ConvertPdbToYes.ConvertParams;
import yuku.alkitab.base.pdbconvert.ConvertPdbToYes.ConvertProgressListener;
import yuku.alkitab.base.pdbconvert.ConvertPdbToYes.ConvertResult;
import yuku.alkitab.base.storage.Db;
import yuku.alkitab.base.storage.Preferences;
import yuku.alkitab.base.storage.YesPembaca;
import yuku.androidcrypto.DigestType;
import yuku.androidcrypto.Digester;
import yuku.filechooser.FileChooserActivity;
import yuku.filechooser.FileChooserConfig;
import yuku.filechooser.FileChooserConfig.Mode;
import yuku.filechooser.FileChooserResult;
public class EdisiActivity extends BaseActivity {
public static final String TAG = EdisiActivity.class.getSimpleName();
private static final int REQCODE_openFile = 1;
ListView lsEdisi;
EdisiAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
S.siapinKitab();
S.bacaPengaturan();
setContentView(R.layout.activity_edisi);
setTitle(R.string.kelola_versi);
adapter = new EdisiAdapter();
adapter.init();
lsEdisi = (ListView) findViewById(R.id.lsEdisi);
lsEdisi.setAdapter(adapter);
lsEdisi.setOnItemClickListener(lsEdisi_itemClick);
registerForContextMenu(lsEdisi);
}
private void bikinMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.activity_edisi, menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
bikinMenu(menu);
return true;
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if (menu != null) {
bikinMenu(menu);
}
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuTambah:
klikPadaBukaFile();
return true;
}
return super.onOptionsItemSelected(item);
}
private OnItemClickListener lsEdisi_itemClick = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
MEdisi item = adapter.getItem(position);
if (item instanceof MEdisiInternal) {
// ga ngapa2in, wong internal ko
} else if (item instanceof MEdisiPreset) {
klikPadaEdisiPreset((CheckBox) v.findViewById(R.id.cAktif), (MEdisiPreset) item);
} else if (item instanceof MEdisiYes) {
klikPadaEdisiYes((CheckBox) v.findViewById(R.id.cAktif), (MEdisiYes) item);
} else if (position == adapter.getCount() - 1) {
klikPadaBukaFile();
}
adapter.notifyDataSetChanged();
}
};
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (menu == null) return;
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
if (info.position == adapter.getCount() - 1) {
// ga ada menu untuk Buka file
} else {
getMenuInflater().inflate(R.menu.context_edisi, menu);
MenuItem menuBuang = menu.findItem(R.id.menuBuang);
if (menuBuang != null) {
menuBuang.setEnabled(false);
MEdisi item = adapter.getItem(info.position);
if (item instanceof MEdisiYes) {
menuBuang.setEnabled(true);
}
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuBuang: {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
MEdisi edisi = adapter.getItem(info.position);
if (edisi instanceof MEdisiYes) {
S.getDb().hapusEdisiYes((MEdisiYes) edisi);
adapter.initDaftarEdisiYes();
adapter.notifyDataSetChanged();
}
return true;
}
case R.id.menuDetails: {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
MEdisi edisi = adapter.getItem(info.position);
StringBuilder details = new StringBuilder();
if (edisi instanceof MEdisiInternal) details.append(getString(R.string.ed_type_built_in) + '\n');
if (edisi instanceof MEdisiPreset) details.append(getString(R.string.ed_type_preset) + '\n');
if (edisi instanceof MEdisiYes) details.append(getString(R.string.ed_type_add_on) + '\n');
details.append(getString(R.string.ed_title_title, edisi.judul) + '\n');
if (edisi instanceof MEdisiPreset) {
MEdisiPreset preset = (MEdisiPreset) edisi;
if (AddonManager.cekAdaEdisi(preset.namafile_preset)) {
details.append(getString(R.string.ed_stored_in_file, AddonManager.getEdisiPath(preset.namafile_preset)) + '\n');
} else {
details.append(getString(R.string.ed_default_filename_file, preset.namafile_preset) + '\n');
details.append(getString(R.string.ed_download_url_url, preset.url) + '\n');
}
}
if (edisi instanceof MEdisiYes) {
MEdisiYes yes = (MEdisiYes) edisi;
if (yes.namafile_pdbasal != null) {
details.append(getString(R.string.ed_pdb_file_name_original_file, yes.namafile_pdbasal) + '\n');
}
details.append(getString(R.string.ed_stored_in_file, yes.namafile) + '\n');
if (yes.keterangan != null) {
details.append(getString(R.string.ed_version_info_info, yes.keterangan) + '\n');
}
}
new AlertDialog.Builder(this)
.setTitle(R.string.ed_version_details)
.setMessage(details)
.setPositiveButton(R.string.ok, null)
.show();
return true;
}
}
return false;
}
void klikPadaEdisiPreset(final CheckBox cAktif, final MEdisiPreset edisi) {
if (cAktif.isChecked()) {
edisi.setAktif(false);
} else {
// tergantung uda ada belum, kalo uda ada filenya sih centang aja
if (edisi.adaFileDatanya()) {
edisi.setAktif(true);
} else {
DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
final ProgressDialog pd = new ProgressDialog(EdisiActivity.this);
DonlotListener donlotListener = new DonlotListener() {
@Override
public void onSelesaiDonlot(Elemen e) {
EdisiActivity.this.runOnUiThread(new Runnable() {
@Override public void run() {
Toast.makeText(getApplicationContext(),
getString(R.string.selesai_mengunduh_edisi_judul_disimpan_di_path, edisi.judul, AddonManager.getEdisiPath(edisi.namafile_preset)),
Toast.LENGTH_LONG).show();
}
});
pd.dismiss();
}
@Override
public void onGagalDonlot(Elemen e, final String keterangan, final Throwable t) {
EdisiActivity.this.runOnUiThread(new Runnable() {
@Override public void run() {
Toast.makeText(
getApplicationContext(),
keterangan != null ? keterangan : getString(R.string.gagal_mengunduh_edisi_judul_ex_pastikan_internet, edisi.judul,
t == null ? "null" : t.getClass().getCanonicalName() + ": " + t.getMessage()), Toast.LENGTH_LONG).show(); //$NON-NLS-1$ //$NON-NLS-2$
}
});
pd.dismiss();
}
@Override
public void onProgress(Elemen e, final int sampe, int total) {
EdisiActivity.this.runOnUiThread(new Runnable() {
@Override public void run() {
if (sampe >= 0) {
pd.setMessage(getString(R.string.terunduh_sampe_byte, sampe));
} else {
pd.setMessage(getString(R.string.sedang_mendekompres_harap_tunggu));
}
}
});
Log.d(TAG, "onProgress " + sampe); //$NON-NLS-1$
}
@Override
public void onBatalDonlot(Elemen e) {
EdisiActivity.this.runOnUiThread(new Runnable() {
@Override public void run() {
Toast.makeText(getApplicationContext(), R.string.pengunduhan_dibatalkan, Toast.LENGTH_SHORT).show();
}
});
pd.dismiss();
}
};
@Override
public void onClick(DialogInterface dialog, int which) {
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.setTitle(getString(R.string.mengunduh_nama, edisi.namafile_preset));
pd.setMessage(getString(R.string.mulai_mengunduh));
pd.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (AddonManager.cekAdaEdisi(edisi.namafile_preset)) {
edisi.setAktif(true);
}
adapter.initDaftarEdisiYes();
adapter.notifyDataSetChanged();
}
});
DonlotThread donlotThread = AddonManager.getDonlotThread(getApplicationContext());
final Elemen e = donlotThread.antrikan(edisi.url, AddonManager.getEdisiPath(edisi.namafile_preset), donlotListener);
if (e != null) {
pd.show();
}
pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
e.hentikan = true;
}
});
}
};
new AlertDialog.Builder(EdisiActivity.this)
.setTitle(R.string.mengunduh_tambahan)
.setMessage(getString(R.string.file_edisipath_tidak_ditemukan_apakah_anda_mau_mengunduhnya, AddonManager.getEdisiPath(edisi.namafile_preset)))
.setPositiveButton(R.string.yes, clickListener)
.setNegativeButton(R.string.no, null)
.show();
}
}
}
void klikPadaEdisiYes(final CheckBox cAktif, final MEdisiYes edisi) {
if (cAktif.isChecked()) {
edisi.setAktif(false);
} else {
if (edisi.adaFileDatanya()) {
edisi.setAktif(true);
} else {
new AlertDialog.Builder(this)
.setTitle(R.string.cannot_find_data_file)
.setMessage(getString(R.string.the_file_for_this_version_is_no_longer_available_file, edisi.namafile))
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
S.getDb().hapusEdisiYes(edisi);
adapter.initDaftarEdisiYes();
adapter.notifyDataSetChanged();
}
})
.setNegativeButton(R.string.no, null)
.show();
}
}
}
void klikPadaBukaFile() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
FileChooserConfig config = new FileChooserConfig();
config.mode = Mode.Open;
config.initialDir = Environment.getExternalStorageDirectory().getAbsolutePath();
config.title = getString(R.string.ed_choose_pdb_or_yes_file);
config.pattern = ".*\\.(?i:pdb|yes)"; //$NON-NLS-1$
startActivityForResult(FileChooserActivity.createIntent(getApplicationContext(), config), REQCODE_openFile);
} else {
new AlertDialog.Builder(this)
.setMessage(R.string.ed_no_external_storage)
.setPositiveButton(R.string.ok, null)
.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQCODE_openFile) {
FileChooserResult result = FileChooserActivity.obtainResult(data);
if (result == null) {
return;
}
String filename = result.firstFilename;
if (filename.toLowerCase().endsWith(".yes")) { //$NON-NLS-1$
handleFileOpenYes(filename, null);
} else if (filename.toLowerCase().endsWith(".pdb")) { //$NON-NLS-1$
handleFileOpenPdb(filename);
} else {
Toast.makeText(getApplicationContext(), R.string.ed_invalid_file_selected, Toast.LENGTH_SHORT).show();
}
}
}
void handleFileOpenYes(String filename, String namapdbasal) {
{ // cari dup
boolean dup = false;
BuildConfig c = BuildConfig.get(getApplicationContext());
for (MEdisiPreset preset: c.xpreset) {
if (filename.equals(AddonManager.getEdisiPath(preset.namafile_preset))) {
dup = true;
break;
}
}
if (!dup) dup = S.getDb().adakahEdisiYesDenganNamafile(filename);
if (dup) {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.ed_file_file_sudah_ada_dalam_daftar_versi, filename))
.setPositiveButton(R.string.ok, null)
.show();
return;
}
}
try {
YesPembaca pembaca = new YesPembaca(getApplicationContext(), filename);
int urutanTerbesar = S.getDb().getUrutanTerbesarEdisiYes();
if (urutanTerbesar == 0) urutanTerbesar = 100; // default
MEdisiYes yes = new MEdisiYes();
yes.jenis = Db.Edisi.jenis_yes;
yes.judul = pembaca.getJudul();
yes.keterangan = pembaca.getKeterangan();
yes.namafile = filename;
yes.namafile_pdbasal = namapdbasal;
yes.urutan = urutanTerbesar + 1;
S.getDb().tambahEdisiYesDenganAktif(yes, true);
adapter.initDaftarEdisiYes();
adapter.notifyDataSetChanged();
} catch (Exception e) {
new AlertDialog.Builder(this)
.setTitle(R.string.ed_error_encountered)
.setMessage(e.getClass().getSimpleName() + ": " + e.getMessage()) //$NON-NLS-1$
.setPositiveButton(R.string.ok, null)
.show();
}
}
private void handleFileOpenPdb(final String namafilepdb) {
final String namayes = namaYes(namafilepdb, ConvertPdbToYes.VERSI_CONVERTER);
// cek apakah sudah ada.
if (S.getDb().adakahEdisiYesDenganNamafile(AddonManager.getEdisiPath(namayes))) {
new AlertDialog.Builder(this)
.setMessage(R.string.ed_this_file_is_already_on_the_list)
.setPositiveButton(R.string.ok, null)
.show();
return;
}
boolean mkdirOk = AddonManager.mkYesDir();
if (!mkdirOk) {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.tidak_bisa_membuat_folder, AddonManager.getYesPath()))
.setPositiveButton(R.string.ok, null)
.show();
return;
}
ConvertOptionsCallback callback = new ConvertOptionsCallback() {
@Override public void onPdbReadError(Throwable e) {
showPdbReadErrorDialog(e);
}
@Override public void onOk(final ConvertParams params) {
final String namafileyes = AddonManager.getEdisiPath(namayes);
final ProgressDialog pd = ProgressDialog.show(EdisiActivity.this, null, getString(R.string.ed_reading_pdb_file), true, false);
new AsyncTask<String, Object, ConvertResult>() {
@Override protected ConvertResult doInBackground(String... _unused_) {
ConvertPdbToYes converter = new ConvertPdbToYes();
converter.setConvertProgressListener(new ConvertProgressListener() {
@Override public void onProgress(int at, String message) {
Log.d(TAG, "Progress " + at + ": " + message); //$NON-NLS-1$ //$NON-NLS-2$
publishProgress(at, message);
}
@Override public void onFinish() {
Log.d(TAG, "Finish"); //$NON-NLS-1$
publishProgress(null, null);
}
});
return converter.convert(getApplicationContext(), namafilepdb, namafileyes, params);
}
@Override protected void onProgressUpdate(Object... values) {
if (values[0] == null) {
pd.setMessage(getString(R.string.ed_finished));
} else {
int at = (Integer) values[0];
String message = (String) values[1];
pd.setMessage("(" + at + ") " + message + "..."); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
}
};
@Override protected void onPostExecute(ConvertResult result) {
pd.dismiss();
if (result.exception != null) {
showPdbReadErrorDialog(result.exception);
} else {
// sukses.
handleFileOpenYes(namafileyes, new File(namafilepdb).getName());
if (result.unconvertedBookNames != null && result.unconvertedBookNames.size() > 0) {
StringBuilder msg = new StringBuilder(getString(R.string.ed_the_following_books_from_the_pdb_file_are_not_recognized) + '\n');
for (String s: result.unconvertedBookNames) {
msg.append("- ").append(s).append('\n'); //$NON-NLS-1$
}
new AlertDialog.Builder(EdisiActivity.this)
.setMessage(msg)
.setPositiveButton(R.string.ok, null)
.show();
}
}
}
}.execute();
}
};
ConvertOptionsDialog dialog = new ConvertOptionsDialog(this, namafilepdb, callback);
dialog.show();
}
void showPdbReadErrorDialog(Throwable exception) {
new AlertDialog.Builder(EdisiActivity.this)
.setTitle(R.string.ed_error_reading_pdb_file)
.setMessage(getString(R.string.ed_details) + U.tampilException(exception))
.setPositiveButton(R.string.ok, null)
.show();
};
/**
* @return nama file untuk yes yang dikonvert dari pdbnya, semacam "pdb-1234abcd-1.yes". Ga pake path.
*/
private String namaYes(String namafilepdb, int versi) {
byte[] digest = Digester.digestFile(DigestType.SHA1, new File(namafilepdb));
if (digest == null) return null;
String hash = Digester.toHex(digest).substring(0, 8);
return "pdb-" + hash + "-" + String.valueOf(versi) + ".yes"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
}
// model
public static abstract class MEdisi {
public String judul;
public int jenis;
public int urutan;
/** id unik untuk dibandingkan */
public abstract String getEdisiId();
/** return edisi supaya bisa mulai dibaca. null kalau ga memungkinkan */
public abstract Edisi getEdisi(Context context);
public abstract void setAktif(boolean aktif);
public abstract boolean getAktif();
public abstract boolean adaFileDatanya();
}
public static class MEdisiInternal extends MEdisi {
public static String getEdisiInternalId() {
return "internal"; //$NON-NLS-1$
}
@Override public String getEdisiId() {
return getEdisiInternalId();
}
@Override
public Edisi getEdisi(Context context) {
return S.getEdisiInternal();
}
@Override
public void setAktif(boolean aktif) {
// NOOP
}
@Override
public boolean getAktif() {
return true; // selalu aktif
}
@Override public boolean adaFileDatanya() {
return true; // selalu ada
}
}
public static class MEdisiPreset extends MEdisi {
public String url;
public String namafile_preset;
@Override public boolean getAktif() {
return Preferences.getBoolean("edisi/preset/" + this.namafile_preset + "/aktif", true); //$NON-NLS-1$ //$NON-NLS-2$
}
@Override public void setAktif(boolean aktif) {
Preferences.setBoolean("edisi/preset/" + this.namafile_preset + "/aktif", aktif); //$NON-NLS-1$ //$NON-NLS-2$
}
@Override
public String getEdisiId() {
return "preset/" + namafile_preset; //$NON-NLS-1$
}
@Override
public Edisi getEdisi(Context context) {
if (adaFileDatanya()) {
return new Edisi(new YesPembaca(context, AddonManager.getEdisiPath(namafile_preset)));
} else {
return null;
}
}
@Override public boolean adaFileDatanya() {
return AddonManager.cekAdaEdisi(namafile_preset);
}
}
public static class MEdisiYes extends MEdisi {
public String keterangan;
public String namafile;
public String namafile_pdbasal;
public boolean cache_aktif; // supaya ga usa dibaca tulis terus dari db
@Override
public String getEdisiId() {
return "yes/" + namafile; //$NON-NLS-1$
}
@Override
public Edisi getEdisi(Context context) {
if (adaFileDatanya()) {
return new Edisi(new YesPembaca(context, namafile));
} else {
return null;
}
}
@Override
public void setAktif(boolean aktif) {
this.cache_aktif = aktif;
S.getDb().setEdisiYesAktif(this.namafile, aktif);
}
@Override
public boolean getAktif() {
return this.cache_aktif;
}
@Override public boolean adaFileDatanya() {
File f = new File(namafile);
return f.exists() && f.canRead();
}
}
public class EdisiAdapter extends BaseAdapter {
MEdisiInternal internal;
List<MEdisiPreset> xpreset;
List<MEdisiYes> xyes;
public void init() {
BuildConfig c = BuildConfig.get(getApplicationContext());
internal = new MEdisiInternal();
internal.setAktif(true);
internal.jenis = Db.Edisi.jenis_internal;
internal.judul = c.internalJudul;
internal.urutan = 1;
xpreset = new ArrayList<MEdisiPreset>();
xpreset.addAll(c.xpreset);
// betulin keaktifannya berdasarkan adanya file dan pref
for (MEdisiPreset preset: xpreset) {
if (!AddonManager.cekAdaEdisi(preset.namafile_preset)) {
preset.setAktif(false);
}
}
initDaftarEdisiYes();
}
public void initDaftarEdisiYes() {
xyes = S.getDb().listSemuaEdisi();
}
@Override
public int getCount() {
return 1 /* internal */ + xpreset.size() + xyes.size() + 1 /* open */;
}
@Override
public MEdisi getItem(int position) {
if (position < 1) return internal;
if (position < 1 + xpreset.size()) return xpreset.get(position - 1);
if (position < 1 + xpreset.size() + xyes.size()) return xyes.get(position - 1 - xpreset.size());
if (position < 1 + xpreset.size() + xyes.size() + 1) return null; /* open */
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View res = convertView != null? convertView: getLayoutInflater().inflate(R.layout.item_edisi, null);
CheckBox cAktif = (CheckBox) res.findViewById(R.id.cAktif);
TextView lJudul = (TextView) res.findViewById(R.id.lJudul);
TextView lNamafile = (TextView) res.findViewById(R.id.lNamafile);
if (position == getCount() - 1) {
// pilihan untuk open
cAktif.setVisibility(View.GONE);
lJudul.setText(R.string.ed_buka_file_pdb_yes_lainnya);
lJudul.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_menu_add, 0, 0, 0);
lNamafile.setVisibility(View.GONE);
} else {
// salah satu dari edisi yang ada
MEdisi medisi = getItem(position);
cAktif.setVisibility(View.VISIBLE);
cAktif.setFocusable(false);
cAktif.setClickable(false);
cAktif.setChecked(medisi.getAktif());
lJudul.setText(medisi.judul);
lJudul.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
if (medisi instanceof MEdisiInternal) {
cAktif.setEnabled(false);
lNamafile.setVisibility(View.GONE);
} else if (medisi instanceof MEdisiPreset) {
cAktif.setEnabled(true);
String namafile_preset = ((MEdisiPreset) medisi).namafile_preset;
if (AddonManager.cekAdaEdisi(namafile_preset)) {
lNamafile.setVisibility(View.GONE);
} else {
lNamafile.setVisibility(View.VISIBLE);
lNamafile.setText(R.string.ed_tekan_untuk_mengunduh);
}
} else if (medisi instanceof MEdisiYes) {
cAktif.setEnabled(true);
lNamafile.setVisibility(View.VISIBLE);
MEdisiYes yes = (MEdisiYes) medisi;
String extra = ""; //$NON-NLS-1$
if (yes.keterangan != null) {
extra += yes.keterangan;
}
lNamafile.setText(extra);
}
}
return res;
}
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app;
import cc.arduino.packages.MonitorFactory;
import com.jcraft.jsch.JSchException;
import jssc.SerialPortException;
import processing.app.debug.*;
import processing.app.forms.PasswordAuthorizationDialog;
import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMapException;
import processing.app.legacy.PApplet;
import processing.app.syntax.*;
import processing.app.tools.*;
import static processing.app.I18n._;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.print.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
import cc.arduino.packages.BoardPort;
import cc.arduino.packages.Uploader;
import cc.arduino.packages.uploaders.SerialUploader;
/**
* Main editor panel for the Processing Development Environment.
*/
@SuppressWarnings("serial")
public class Editor extends JFrame implements RunnerListener {
private final static List<String> BOARD_PROTOCOLS_ORDER = Arrays.asList(new String[]{"serial", "network"});
private final static List<String> BOARD_PROTOCOLS_ORDER_TRANSLATIONS = Arrays.asList(new String[]{_("Serial ports"), _("Network ports")});
Base base;
// otherwise, if the window is resized with the message label
// set to blank, it's preferredSize() will be fukered
static protected final String EMPTY =
" " +
" " +
" ";
/** Command on Mac OS X, Ctrl on Windows and Linux */
static final int SHORTCUT_KEY_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** Command-W on Mac OS X, Ctrl-W on Windows and Linux */
static final KeyStroke WINDOW_CLOSE_KEYSTROKE =
KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK);
/** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */
static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK |
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/**
* true if this file has not yet been given a name by the user
*/
boolean untitled;
PageFormat pageFormat;
PrinterJob printerJob;
// file, sketch, and tools menus for re-inserting items
JMenu fileMenu;
JMenu sketchMenu;
JMenu toolsMenu;
int numTools = 0;
EditorToolbar toolbar;
// these menus are shared so that they needn't be rebuilt for all windows
// each time a sketch is created, renamed, or moved.
static JMenu toolbarMenu;
static JMenu sketchbookMenu;
static JMenu examplesMenu;
static JMenu importMenu;
// these menus are shared so that the board and serial port selections
// are the same for all windows (since the board and serial port that are
// actually used are determined by the preferences, which are shared)
static List<JMenu> boardsMenus;
static JMenu serialMenu;
static AbstractMonitor serialMonitor;
EditorHeader header;
EditorStatus status;
EditorConsole console;
JSplitPane splitPane;
JPanel consolePanel;
JLabel lineNumberComponent;
// currently opened program
Sketch sketch;
EditorLineStatus lineStatus;
//JEditorPane editorPane;
JEditTextArea textarea;
EditorListener listener;
// runtime information and window placement
Point sketchWindowLocation;
//Runner runtime;
JMenuItem exportAppItem;
JMenuItem saveMenuItem;
JMenuItem saveAsMenuItem;
boolean running;
//boolean presenting;
boolean uploading;
// undo fellers
JMenuItem undoItem, redoItem;
protected UndoAction undoAction;
protected RedoAction redoAction;
LastUndoableEditAwareUndoManager undo;
// used internally, and only briefly
CompoundEdit compoundEdit;
FindReplace find;
Runnable runHandler;
Runnable presentHandler;
Runnable stopHandler;
Runnable exportHandler;
Runnable exportAppHandler;
public Editor(Base ibase, File file, int[] location) throws Exception {
super("Arduino");
this.base = ibase;
Base.setIcon(this);
// Install default actions for Run, Present, etc.
resetHandlers();
// add listener to handle window close box hit event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
base.handleClose(Editor.this);
}
});
// don't close the window when clicked, the app will take care
// of that via the handleQuitInternal() methods
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// When bringing a window to front, let the Base know
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
// System.err.println("activate"); // not coming through
base.handleActivated(Editor.this);
// re-add the sub-menus that are shared by all windows
fileMenu.insert(sketchbookMenu, 2);
fileMenu.insert(examplesMenu, 3);
sketchMenu.insert(importMenu, 4);
int offset = 0;
for (JMenu menu : boardsMenus) {
toolsMenu.insert(menu, numTools + offset);
offset++;
}
toolsMenu.insert(serialMenu, numTools + offset);
}
// added for 1.0.5
public void windowDeactivated(WindowEvent e) {
// System.err.println("deactivate"); // not coming through
fileMenu.remove(sketchbookMenu);
fileMenu.remove(examplesMenu);
sketchMenu.remove(importMenu);
for (JMenu menu : boardsMenus) {
toolsMenu.remove(menu);
}
toolsMenu.remove(serialMenu);
}
});
//PdeKeywords keywords = new PdeKeywords();
//sketchbook = new Sketchbook(this);
buildMenuBar();
// For rev 0120, placing things inside a JPanel
Container contentPain = getContentPane();
contentPain.setLayout(new BorderLayout());
JPanel pain = new JPanel();
pain.setLayout(new BorderLayout());
contentPain.add(pain, BorderLayout.CENTER);
Box box = Box.createVerticalBox();
Box upper = Box.createVerticalBox();
if (toolbarMenu == null) {
toolbarMenu = new JMenu();
base.rebuildToolbarMenu(toolbarMenu);
}
toolbar = new EditorToolbar(this, toolbarMenu);
upper.add(toolbar);
header = new EditorHeader(this);
upper.add(header);
textarea = new JEditTextArea(new PdeTextAreaDefaults());
textarea.setName("editor");
textarea.setRightClickPopup(new TextAreaPopup());
textarea.setHorizontalOffset(6);
// assemble console panel, consisting of status area and the console itself
consolePanel = new JPanel();
consolePanel.setLayout(new BorderLayout());
status = new EditorStatus(this);
consolePanel.add(status, BorderLayout.NORTH);
console = new EditorConsole(this);
console.setName("console");
// windows puts an ugly border on this guy
console.setBorder(null);
consolePanel.add(console, BorderLayout.CENTER);
lineStatus = new EditorLineStatus(textarea);
consolePanel.add(lineStatus, BorderLayout.SOUTH);
upper.add(textarea);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
upper, consolePanel);
splitPane.setOneTouchExpandable(true);
// repaint child panes while resizing
splitPane.setContinuousLayout(true);
// if window increases in size, give all of increase to
// the textarea in the uppper pane
splitPane.setResizeWeight(1D);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
splitPane.setBorder(null);
// the default size on windows is too small and kinda ugly
int dividerSize = Preferences.getInteger("editor.divider.size");
if (dividerSize != 0) {
splitPane.setDividerSize(dividerSize);
}
// the following changed from 600, 400 for netbooks
splitPane.setMinimumSize(new Dimension(600, 100));
box.add(splitPane);
// hopefully these are no longer needed w/ swing
// (har har har.. that was wishful thinking)
listener = new EditorListener(this, textarea);
pain.add(box);
// get shift down/up events so we can show the alt version of toolbar buttons
textarea.addKeyListener(toolbar);
pain.setTransferHandler(new FileDropHandler());
// System.out.println("t1");
// Finish preparing Editor (formerly found in Base)
pack();
// System.out.println("t2");
// Set the window bounds and the divider location before setting it visible
setPlacement(location);
// Set the minimum size for the editor window
setMinimumSize(new Dimension(Preferences.getInteger("editor.window.width.min"),
Preferences.getInteger("editor.window.height.min")));
// System.out.println("t3");
// Bring back the general options for the editor
applyPreferences();
// System.out.println("t4");
// Open the document that was passed in
boolean loaded = handleOpenInternal(file);
if (!loaded) sketch = null;
// System.out.println("t5");
// All set, now show the window
//setVisible(true);
}
/**
* Handles files dragged & dropped from the desktop and into the editor
* window. Dragging files into the editor window is the same as using
* "Sketch → Add File" for each file.
*/
class FileDropHandler extends TransferHandler {
public boolean canImport(JComponent dest, DataFlavor[] flavors) {
return true;
}
@SuppressWarnings("unchecked")
public boolean importData(JComponent src, Transferable transferable) {
int successful = 0;
try {
DataFlavor uriListFlavor =
new DataFlavor("text/uri-list;class=java.lang.String");
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> list = (List<File>)
transferable.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : list) {
if (sketch.addFile(file)) {
successful++;
}
}
} else if (transferable.isDataFlavorSupported(uriListFlavor)) {
// Some platforms (Mac OS X and Linux, when this began) preferred
// this method of moving files.
String data = (String)transferable.getTransferData(uriListFlavor);
String[] pieces = PApplet.splitTokens(data, "\r\n");
for (int i = 0; i < pieces.length; i++) {
if (pieces[i].startsWith("#")) continue;
String path = null;
if (pieces[i].startsWith("file:
path = pieces[i].substring(7);
} else if (pieces[i].startsWith("file:/")) {
path = pieces[i].substring(5);
}
if (sketch.addFile(new File(path))) {
successful++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
if (successful == 0) {
statusError(_("No files were added to the sketch."));
} else if (successful == 1) {
statusNotice(_("One file added to the sketch."));
} else {
statusNotice(
I18n.format(_("{0} files added to the sketch."), successful));
}
return true;
}
}
protected void setPlacement(int[] location) {
setBounds(location[0], location[1], location[2], location[3]);
if (location[4] != 0) {
splitPane.setDividerLocation(location[4]);
}
}
protected int[] getPlacement() {
int[] location = new int[5];
// Get the dimensions of the Frame
Rectangle bounds = getBounds();
location[0] = bounds.x;
location[1] = bounds.y;
location[2] = bounds.width;
location[3] = bounds.height;
// Get the current placement of the divider
location[4] = splitPane.getDividerLocation();
return location;
}
/**
* Hack for #@#)$(* Mac OS X 10.2.
* <p/>
* This appears to only be required on OS X 10.2, and is not
* even being called on later versions of OS X or Windows.
*/
// public Dimension getMinimumSize() {
// //System.out.println("getting minimum size");
// return new Dimension(500, 550);
/**
* Read and apply new values from the preferences, either because
* the app is just starting up, or the user just finished messing
* with things in the Preferences window.
*/
protected void applyPreferences() {
// apply the setting for 'use external editor'
boolean external = Preferences.getBoolean("editor.external");
textarea.setEditable(!external);
saveMenuItem.setEnabled(!external);
saveAsMenuItem.setEnabled(!external);
textarea.setDisplayLineNumbers(Preferences.getBoolean("editor.linenumbers"));
TextAreaPainter painter = textarea.getPainter();
if (external) {
// disable line highlight and turn off the caret when disabling
Color color = Theme.getColor("editor.external.bgcolor");
painter.setBackground(color);
painter.setLineHighlightEnabled(false);
textarea.setCaretVisible(false);
} else {
Color color = Theme.getColor("editor.bgcolor");
painter.setBackground(color);
boolean highlight = Preferences.getBoolean("editor.linehighlight");
painter.setLineHighlightEnabled(highlight);
textarea.setCaretVisible(true);
}
// apply changes to the font size for the editor
//TextAreaPainter painter = textarea.getPainter();
painter.setFont(Preferences.getFont("editor.font"));
//Font font = painter.getFont();
//textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36));
// in case tab expansion stuff has changed
listener.applyPreferences();
// in case moved to a new location
// For 0125, changing to async version (to be implemented later)
//sketchbook.rebuildMenus();
// For 0126, moved into Base, which will notify all editors.
//base.rebuildMenusAsync();
}
protected void buildMenuBar() throws Exception {
JMenuBar menubar = new JMenuBar();
menubar.add(buildFileMenu());
menubar.add(buildEditMenu());
menubar.add(buildSketchMenu());
menubar.add(buildToolsMenu());
menubar.add(buildHelpMenu());
setJMenuBar(menubar);
}
protected JMenu buildFileMenu() {
JMenuItem item;
fileMenu = new JMenu(_("File"));
item = newJMenuItem(_("New"), 'N');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleNew();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
item = Editor.newJMenuItem(_("Open..."), 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleOpenPrompt();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
if (sketchbookMenu == null) {
sketchbookMenu = new JMenu(_("Sketchbook"));
MenuScroller.setScrollerFor(sketchbookMenu);
base.rebuildSketchbookMenu(sketchbookMenu);
}
fileMenu.add(sketchbookMenu);
if (examplesMenu == null) {
examplesMenu = new JMenu(_("Examples"));
MenuScroller.setScrollerFor(examplesMenu);
base.rebuildExamplesMenu(examplesMenu);
}
fileMenu.add(examplesMenu);
item = Editor.newJMenuItem(_("Close"), 'W');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleClose(Editor.this);
}
});
fileMenu.add(item);
saveMenuItem = newJMenuItem(_("Save"), 'S');
saveMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSave(false);
}
});
fileMenu.add(saveMenuItem);
saveAsMenuItem = newJMenuItemShift(_("Save As..."), 'S');
saveAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSaveAs();
}
});
fileMenu.add(saveAsMenuItem);
item = newJMenuItem(_("Upload"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(false);
}
});
fileMenu.add(item);
item = newJMenuItemShift(_("Upload Using Programmer"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(true);
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItemShift(_("Page Setup"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePageSetup();
}
});
fileMenu.add(item);
item = newJMenuItem(_("Print"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePrint();
}
});
fileMenu.add(item);
// macosx already has its own preferences and quit menu
if (!OSUtils.isMacOS()) {
fileMenu.addSeparator();
item = newJMenuItem(_("Preferences"), ',');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handlePrefs();
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItem(_("Quit"), 'Q');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleQuit();
}
});
fileMenu.add(item);
}
return fileMenu;
}
protected JMenu buildSketchMenu() {
JMenuItem item;
sketchMenu = new JMenu(_("Sketch"));
item = newJMenuItem(_("Verify / Compile"), 'R');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleRun(false);
}
});
sketchMenu.add(item);
// item = newJMenuItemShift("Verify / Compile (verbose)", 'R');
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleRun(true);
// sketchMenu.add(item);
// item = new JMenuItem("Stop");
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleStop();
// sketchMenu.add(item);
sketchMenu.addSeparator();
if (importMenu == null) {
importMenu = new JMenu(_("Import Library..."));
MenuScroller.setScrollerFor(importMenu);
base.rebuildImportMenu(importMenu);
}
sketchMenu.add(importMenu);
item = newJMenuItem(_("Show Sketch Folder"), 'K');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openFolder(sketch.getFolder());
}
});
sketchMenu.add(item);
item.setEnabled(Base.openFolderAvailable());
item = new JMenuItem(_("Add File..."));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sketch.handleAddFile();
}
});
sketchMenu.add(item);
return sketchMenu;
}
protected JMenu buildToolsMenu() throws Exception {
toolsMenu = new JMenu(_("Tools"));
JMenu menu = toolsMenu;
JMenuItem item;
addInternalTools(menu);
item = newJMenuItemShift(_("Serial Monitor"), 'M');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSerial();
}
});
menu.add(item);
addTools(menu, Base.getToolsFolder());
File sketchbookTools = new File(Base.getSketchbookFolder(), "tools");
addTools(menu, sketchbookTools);
menu.addSeparator();
numTools = menu.getItemCount();
// XXX: DAM: these should probably be implemented using the Tools plugin
// API, if possible (i.e. if it supports custom actions, etc.)
if (boardsMenus == null) {
boardsMenus = new LinkedList<JMenu>();
JMenu boardsMenu = new JMenu(_("Board"));
MenuScroller.setScrollerFor(boardsMenu);
Editor.boardsMenus.add(boardsMenu);
toolsMenu.add(boardsMenu);
base.rebuildBoardsMenu(toolsMenu, this);
//Debug: rebuild imports
importMenu.removeAll();
base.rebuildImportMenu(importMenu);
}
if (serialMenu == null)
serialMenu = new JMenu(_("Port"));
populatePortMenu();
menu.add(serialMenu);
menu.addSeparator();
JMenu programmerMenu = new JMenu(_("Programmer"));
base.rebuildProgrammerMenu(programmerMenu);
menu.add(programmerMenu);
item = new JMenuItem(_("Burn Bootloader"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleBurnBootloader();
}
});
menu.add(item);
menu.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {}
public void menuDeselected(MenuEvent e) {}
public void menuSelected(MenuEvent e) {
//System.out.println("Tools menu selected.");
populatePortMenu();
}
});
return menu;
}
protected void addTools(JMenu menu, File sourceFolder) {
if (sourceFolder == null)
return;
Map<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>();
File[] folders = sourceFolder.listFiles(new FileFilter() {
public boolean accept(File folder) {
if (folder.isDirectory()) {
//System.out.println("checking " + folder);
File subfolder = new File(folder, "tool");
return subfolder.exists();
}
return false;
}
});
if (folders == null || folders.length == 0) {
return;
}
for (int i = 0; i < folders.length; i++) {
File toolDirectory = new File(folders[i], "tool");
try {
// add dir to classpath for .classes
//urlList.add(toolDirectory.toURL());
// add .jar files to classpath
File[] archives = toolDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".jar") ||
name.toLowerCase().endsWith(".zip"));
}
});
URL[] urlList = new URL[archives.length];
for (int j = 0; j < urlList.length; j++) {
urlList[j] = archives[j].toURI().toURL();
}
URLClassLoader loader = new URLClassLoader(urlList);
String className = null;
for (int j = 0; j < archives.length; j++) {
className = findClassInZipFile(folders[i].getName(), archives[j]);
if (className != null) break;
}
// If no class name found, just move on.
if (className == null) continue;
Class<?> toolClass = Class.forName(className, true, loader);
final Tool tool = (Tool) toolClass.newInstance();
tool.init(Editor.this);
String title = tool.getMenuTitle();
JMenuItem item = new JMenuItem(title);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
//new Thread(tool).start();
}
});
//menu.add(item);
toolItems.put(title, item);
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<String> toolList = new ArrayList<String>(toolItems.keySet());
if (toolList.size() == 0) return;
menu.addSeparator();
Collections.sort(toolList);
for (String title : toolList) {
menu.add((JMenuItem) toolItems.get(title));
}
}
protected String findClassInZipFile(String base, File file) {
// Class file to search for
String classFileName = "/" + base + ".class";
ZipFile zipFile = null;
try {
zipFile = new ZipFile(file);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (!entry.isDirectory()) {
String name = entry.getName();
//System.out.println("entry: " + name);
if (name.endsWith(classFileName)) {
//int slash = name.lastIndexOf('/');
//String packageName = (slash == -1) ? "" : name.substring(0, slash);
// Remove .class and convert slashes to periods.
return name.substring(0, name.length() - 6).replace('/', '.');
}
}
}
} catch (IOException e) {
//System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
e.printStackTrace();
} finally {
if (zipFile != null)
try {
zipFile.close();
} catch (IOException e) {
}
}
return null;
}
protected JMenuItem createToolMenuItem(String className) {
try {
Class<?> toolClass = Class.forName(className);
final Tool tool = (Tool) toolClass.newInstance();
JMenuItem item = new JMenuItem(tool.getMenuTitle());
tool.init(Editor.this);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
}
});
return item;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected JMenu addInternalTools(JMenu menu) {
JMenuItem item;
item = createToolMenuItem("cc.arduino.packages.formatter.AStyle");
item.setName("menuToolsAutoFormat");
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers));
menu.add(item);
//menu.add(createToolMenuItem("processing.app.tools.CreateFont"));
//menu.add(createToolMenuItem("processing.app.tools.ColorSelector"));
menu.add(createToolMenuItem("processing.app.tools.Archiver"));
menu.add(createToolMenuItem("processing.app.tools.FixEncoding"));
// // These are temporary entries while Android mode is being worked out.
// // The mode will not be in the tools menu, and won't involve a cmd-key
// if (!Base.RELEASE) {
// item = createToolMenuItem("processing.app.tools.android.AndroidTool");
// item.setAccelerator(KeyStroke.getKeyStroke('D', modifiers));
// menu.add(item);
// menu.add(createToolMenuItem("processing.app.tools.android.Reset"));
return menu;
}
class SerialMenuListener implements ActionListener {
private final String serialPort;
public SerialMenuListener(String serialPort) {
this.serialPort = serialPort;
}
public void actionPerformed(ActionEvent e) {
selectSerialPort(serialPort);
base.onBoardOrPortChange();
}
}
protected void selectSerialPort(String name) {
if(serialMenu == null) {
System.out.println(_("serialMenu is null"));
return;
}
if (name == null) {
System.out.println(_("name is null"));
return;
}
JCheckBoxMenuItem selection = null;
for (int i = 0; i < serialMenu.getItemCount(); i++) {
JMenuItem menuItem = serialMenu.getItem(i);
if (!(menuItem instanceof JCheckBoxMenuItem)) {
continue;
}
JCheckBoxMenuItem checkBoxMenuItem = ((JCheckBoxMenuItem) menuItem);
if (checkBoxMenuItem == null) {
System.out.println(_("name is null"));
continue;
}
checkBoxMenuItem.setState(false);
if (name.equals(checkBoxMenuItem.getText())) selection = checkBoxMenuItem;
}
if (selection != null) selection.setState(true);
//System.out.println(item.getLabel());
Base.selectSerialPort(name);
if (serialMonitor != null) {
try {
serialMonitor.close();
serialMonitor.setVisible(false);
} catch (Exception e) {
// ignore
}
}
onBoardOrPortChange();
//System.out.println("set to " + get("serial.port"));
}
protected void populatePortMenu() {
serialMenu.removeAll();
String selectedPort = Preferences.get("serial.port");
List<BoardPort> ports = Base.getDiscoveryManager().discovery();
ports = Base.getPlatform().filterPorts(ports, Preferences.getBoolean("serial.ports.showall"));
Collections.sort(ports, new Comparator<BoardPort>() {
@Override
public int compare(BoardPort o1, BoardPort o2) {
return BOARD_PROTOCOLS_ORDER.indexOf(o1.getProtocol()) - BOARD_PROTOCOLS_ORDER.indexOf(o2.getProtocol());
}
});
String lastProtocol = null;
String lastProtocolTranslated;
for (BoardPort port : ports) {
if (lastProtocol == null || !port.getProtocol().equals(lastProtocol)) {
if (lastProtocol != null) {
serialMenu.addSeparator();
}
lastProtocol = port.getProtocol();
if (BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol()) != -1) {
lastProtocolTranslated = BOARD_PROTOCOLS_ORDER_TRANSLATIONS.get(BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol()));
} else {
lastProtocolTranslated = port.getProtocol();
}
serialMenu.add(new JMenuItem(_(lastProtocolTranslated)));
}
String address = port.getAddress();
String label = port.getLabel();
JCheckBoxMenuItem item = new JCheckBoxMenuItem(label, address.equals(selectedPort));
item.addActionListener(new SerialMenuListener(address));
serialMenu.add(item);
}
serialMenu.setEnabled(serialMenu.getMenuComponentCount() > 0);
}
protected JMenu buildHelpMenu() {
// To deal with a Mac OS X 10.5 bug, add an extra space after the name
// so that the OS doesn't try to insert its slow help menu.
JMenu menu = new JMenu(_("Help"));
JMenuItem item;
item = new JMenuItem(_("Getting Started"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showGettingStarted();
}
});
menu.add(item);
item = new JMenuItem(_("Environment"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showEnvironment();
}
});
menu.add(item);
item = new JMenuItem(_("Troubleshooting"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showTroubleshooting();
}
});
menu.add(item);
item = new JMenuItem(_("Reference"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showReference();
}
});
menu.add(item);
item = newJMenuItemShift(_("Find in Reference"), 'F');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// if (textarea.isSelectionActive()) {
// handleFindReference();
handleFindReference();
}
});
menu.add(item);
item = new JMenuItem(_("Frequently Asked Questions"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showFAQ();
}
});
menu.add(item);
item = new JMenuItem(_("Visit Arduino.cc"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openURL(_("http://arduino.cc/"));
}
});
menu.add(item);
// macosx already has its own about menu
if (!OSUtils.isMacOS()) {
menu.addSeparator();
item = new JMenuItem(_("About Arduino"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleAbout();
}
});
menu.add(item);
}
return menu;
}
protected JMenu buildEditMenu() {
JMenu menu = new JMenu(_("Edit"));
menu.setName("menuEdit");
JMenuItem item;
undoItem = newJMenuItem(_("Undo"), 'Z');
undoItem.setName("menuEditUndo");
undoItem.addActionListener(undoAction = new UndoAction());
menu.add(undoItem);
if (!OSUtils.isMacOS()) {
redoItem = newJMenuItem(_("Redo"), 'Y');
} else {
redoItem = newJMenuItemShift(_("Redo"), 'Z');
}
redoItem.setName("menuEditRedo");
redoItem.addActionListener(redoAction = new RedoAction());
menu.add(redoItem);
menu.addSeparator();
// TODO "cut" and "copy" should really only be enabled
// if some text is currently selected
item = newJMenuItem(_("Cut"), 'X');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCut();
}
});
menu.add(item);
item = newJMenuItem(_("Copy"), 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.copy();
}
});
menu.add(item);
item = newJMenuItemShift(_("Copy for Forum"), 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
new DiscourseFormat(Editor.this, false).show();
}
});
menu.add(item);
item = newJMenuItemAlt(_("Copy as HTML"), 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
new DiscourseFormat(Editor.this, true).show();
}
});
menu.add(item);
item = newJMenuItem(_("Paste"), 'V');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.paste();
sketch.setModified(true);
}
});
menu.add(item);
item = newJMenuItem(_("Select All"), 'A');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.selectAll();
}
});
menu.add(item);
menu.addSeparator();
item = newJMenuItem(_("Comment/Uncomment"), '/');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCommentUncomment();
}
});
menu.add(item);
item = newJMenuItem(_("Increase Indent"), ']');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(true);
}
});
menu.add(item);
item = newJMenuItem(_("Decrease Indent"), '[');
item.setName("menuDecreaseIndent");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(false);
}
});
menu.add(item);
menu.addSeparator();
item = newJMenuItem(_("Find..."), 'F');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find == null) {
find = new FindReplace(Editor.this);
}
if (getSelectedText()!= null) find.setFindText( getSelectedText() );
//new FindReplace(Editor.this).show();
find.setVisible(true);
//find.setVisible(true);
}
});
menu.add(item);
// TODO find next should only be enabled after a
// search has actually taken place
item = newJMenuItem(_("Find Next"), 'G');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find != null) {
find.findNext();
}
}
});
menu.add(item);
item = newJMenuItemShift(_("Find Previous"), 'G');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find != null) {
find.findPrevious();
}
}
});
menu.add(item);
item = newJMenuItem(_("Use Selection For Find"), 'E');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find == null) {
find = new FindReplace(Editor.this);
}
find.setFindText( getSelectedText() );
}
});
menu.add(item);
return menu;
}
/**
* A software engineer, somewhere, needs to have his abstraction
* taken away. In some countries they jail or beat people for writing
* the sort of API that would require a five line helper function
* just to set the command key for a menu item.
*/
static public JMenuItem newJMenuItem(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK));
return menuItem;
}
/**
* Like newJMenuItem() but adds shift as a modifier for the key command.
*/
static public JMenuItem newJMenuItemShift(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK | ActionEvent.SHIFT_MASK));
return menuItem;
}
/**
* Same as newJMenuItem(), but adds the ALT (on Linux and Windows)
* or OPTION (on Mac OS X) key as a modifier.
*/
static public JMenuItem newJMenuItemAlt(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK));
return menuItem;
}
class UndoAction extends AbstractAction {
public UndoAction() {
super("Undo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.undo();
} catch (CannotUndoException ex) {
//System.out.println("Unable to undo: " + ex);
//ex.printStackTrace();
}
if (undo.getLastUndoableEdit() != null && undo.getLastUndoableEdit() instanceof CaretAwareUndoableEdit) {
CaretAwareUndoableEdit undoableEdit = (CaretAwareUndoableEdit) undo.getLastUndoableEdit();
int nextCaretPosition = undoableEdit.getCaretPosition() - 1;
if (nextCaretPosition >= 0 && textarea.getDocumentLength() > nextCaretPosition) {
textarea.setCaretPosition(nextCaretPosition);
}
}
updateUndoState();
redoAction.updateRedoState();
}
protected void updateUndoState() {
if (undo.canUndo()) {
this.setEnabled(true);
undoItem.setEnabled(true);
undoItem.setText(undo.getUndoPresentationName());
putValue(Action.NAME, undo.getUndoPresentationName());
if (sketch != null) {
sketch.setModified(true); // 0107
}
} else {
this.setEnabled(false);
undoItem.setEnabled(false);
undoItem.setText(_("Undo"));
putValue(Action.NAME, "Undo");
if (sketch != null) {
sketch.setModified(false); // 0107
}
}
}
}
class RedoAction extends AbstractAction {
public RedoAction() {
super("Redo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.redo();
} catch (CannotRedoException ex) {
//System.out.println("Unable to redo: " + ex);
//ex.printStackTrace();
}
if (undo.getLastUndoableEdit() != null && undo.getLastUndoableEdit() instanceof CaretAwareUndoableEdit) {
CaretAwareUndoableEdit undoableEdit = (CaretAwareUndoableEdit) undo.getLastUndoableEdit();
textarea.setCaretPosition(undoableEdit.getCaretPosition());
}
updateRedoState();
undoAction.updateUndoState();
}
protected void updateRedoState() {
if (undo.canRedo()) {
redoItem.setEnabled(true);
redoItem.setText(undo.getRedoPresentationName());
putValue(Action.NAME, undo.getRedoPresentationName());
} else {
this.setEnabled(false);
redoItem.setEnabled(false);
redoItem.setText(_("Redo"));
putValue(Action.NAME, "Redo");
}
}
}
// these will be done in a more generic way soon, more like:
// setHandler("action name", Runnable);
// but for the time being, working out the kinks of how many things to
// abstract from the editor in this fashion.
public void setHandlers(Runnable runHandler, Runnable presentHandler,
Runnable stopHandler,
Runnable exportHandler, Runnable exportAppHandler) {
this.runHandler = runHandler;
this.presentHandler = presentHandler;
this.stopHandler = stopHandler;
this.exportHandler = exportHandler;
this.exportAppHandler = exportAppHandler;
}
public void resetHandlers() {
runHandler = new BuildHandler();
presentHandler = new BuildHandler(true);
stopHandler = new DefaultStopHandler();
exportHandler = new DefaultExportHandler();
exportAppHandler = new DefaultExportAppHandler();
}
/**
* Gets the current sketch object.
*/
public Sketch getSketch() {
return sketch;
}
/**
* Get the JEditTextArea object for use (not recommended). This should only
* be used in obscure cases that really need to hack the internals of the
* JEditTextArea. Most tools should only interface via the get/set functions
* found in this class. This will maintain compatibility with future releases,
* which will not use JEditTextArea.
*/
public JEditTextArea getTextArea() {
return textarea;
}
/**
* Get the contents of the current buffer. Used by the Sketch class.
*/
public String getText() {
return textarea.getText();
}
/**
* Get a range of text from the current buffer.
*/
public String getText(int start, int stop) {
return textarea.getText(start, stop - start);
}
/**
* Replace the entire contents of the front-most tab.
*/
public void setText(String what) {
startCompoundEdit();
textarea.setText(what);
stopCompoundEdit();
}
public void insertText(String what) {
startCompoundEdit();
int caret = getCaretOffset();
setSelection(caret, caret);
textarea.setSelectedText(what);
stopCompoundEdit();
}
/**
* Called to update the text but not switch to a different set of code
* (which would affect the undo manager).
*/
// public void setText2(String what, int start, int stop) {
// beginCompoundEdit();
// textarea.setText(what);
// endCompoundEdit();
// // make sure that a tool isn't asking for a bad location
// start = Math.max(0, Math.min(start, textarea.getDocumentLength()));
// stop = Math.max(0, Math.min(start, textarea.getDocumentLength()));
// textarea.select(start, stop);
// textarea.requestFocus(); // get the caret blinking
public String getSelectedText() {
return textarea.getSelectedText();
}
public void setSelectedText(String what) {
textarea.setSelectedText(what);
}
public void setSelection(int start, int stop) {
// make sure that a tool isn't asking for a bad location
start = PApplet.constrain(start, 0, textarea.getDocumentLength());
stop = PApplet.constrain(stop, 0, textarea.getDocumentLength());
textarea.select(start, stop);
}
/**
* Get the position (character offset) of the caret. With text selected,
* this will be the last character actually selected, no matter the direction
* of the selection. That is, if the user clicks and drags to select lines
* 7 up to 4, then the caret position will be somewhere on line four.
*/
public int getCaretOffset() {
return textarea.getCaretPosition();
}
/**
* True if some text is currently selected.
*/
public boolean isSelectionActive() {
return textarea.isSelectionActive();
}
/**
* Get the beginning point of the current selection.
*/
public int getSelectionStart() {
return textarea.getSelectionStart();
}
/**
* Get the end point of the current selection.
*/
public int getSelectionStop() {
return textarea.getSelectionStop();
}
/**
* Get text for a specified line.
*/
public String getLineText(int line) {
return textarea.getLineText(line);
}
/**
* Replace the text on a specified line.
*/
public void setLineText(int line, String what) {
startCompoundEdit();
textarea.select(getLineStartOffset(line), getLineStopOffset(line));
textarea.setSelectedText(what);
stopCompoundEdit();
}
/**
* Get character offset for the start of a given line of text.
*/
public int getLineStartOffset(int line) {
return textarea.getLineStartOffset(line);
}
/**
* Get character offset for end of a given line of text.
*/
public int getLineStopOffset(int line) {
return textarea.getLineStopOffset(line);
}
/**
* Get the number of lines in the currently displayed buffer.
*/
public int getLineCount() {
return textarea.getLineCount();
}
/**
* Use before a manipulating text to group editing operations together as a
* single undo. Use stopCompoundEdit() once finished.
*/
public void startCompoundEdit() {
compoundEdit = new CompoundEdit();
}
/**
* Use with startCompoundEdit() to group edit operations in a single undo.
*/
public void stopCompoundEdit() {
compoundEdit.end();
undo.addEdit(compoundEdit);
undoAction.updateUndoState();
redoAction.updateRedoState();
compoundEdit = null;
}
public int getScrollPosition() {
return textarea.getScrollPosition();
}
/**
* Switch between tabs, this swaps out the Document object
* that's currently being manipulated.
*/
protected void setCode(SketchCodeDocument codeDoc) {
SyntaxDocument document = (SyntaxDocument) codeDoc.getDocument();
if (document == null) { // this document not yet inited
document = new SyntaxDocument();
codeDoc.setDocument(document);
// turn on syntax highlighting
document.setTokenMarker(new PdeKeywords());
// insert the program text into the document object
try {
document.insertString(0, codeDoc.getCode().getProgram(), null);
} catch (BadLocationException bl) {
bl.printStackTrace();
}
// set up this guy's own undo manager
// code.undo = new UndoManager();
// connect the undo listener to the editor
document.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent e) {
if (compoundEdit != null) {
compoundEdit.addEdit(e.getEdit());
} else if (undo != null) {
undo.addEdit(new CaretAwareUndoableEdit(e.getEdit(), textarea));
undoAction.updateUndoState();
redoAction.updateRedoState();
}
}
});
}
// update the document object that's in use
textarea.setDocument(document,
codeDoc.getSelectionStart(), codeDoc.getSelectionStop(),
codeDoc.getScrollPosition());
textarea.requestFocus(); // get the caret blinking
this.undo = codeDoc.getUndo();
undoAction.updateUndoState();
redoAction.updateRedoState();
}
/**
* Implements Edit → Cut.
*/
public void handleCut() {
textarea.cut();
sketch.setModified(true);
}
/**
* Implements Edit → Copy.
*/
public void handleCopy() {
textarea.copy();
}
protected void handleDiscourseCopy() {
new DiscourseFormat(Editor.this, false).show();
}
protected void handleHTMLCopy() {
new DiscourseFormat(Editor.this, true).show();
}
/**
* Implements Edit → Paste.
*/
public void handlePaste() {
textarea.paste();
sketch.setModified(true);
}
/**
* Implements Edit → Select All.
*/
public void handleSelectAll() {
textarea.selectAll();
}
protected void handleCommentUncomment() {
startCompoundEdit();
int startLine = textarea.getSelectionStartLine();
int stopLine = textarea.getSelectionStopLine();
int lastLineStart = textarea.getLineStartOffset(stopLine);
int selectionStop = textarea.getSelectionStop();
// If the selection ends at the beginning of the last line,
// then don't (un)comment that line.
if (selectionStop == lastLineStart) {
// Though if there's no selection, don't do that
if (textarea.isSelectionActive()) {
stopLine
}
}
// If the text is empty, ignore the user.
// Also ensure that all lines are commented (not just the first)
// when determining whether to comment or uncomment.
int length = textarea.getDocumentLength();
boolean commented = true;
for (int i = startLine; commented && (i <= stopLine); i++) {
int pos = textarea.getLineStartOffset(i);
if (pos + 2 > length) {
commented = false;
} else {
// Check the first two characters to see if it's already a comment.
String begin = textarea.getText(pos, 2);
//System.out.println("begin is '" + begin + "'");
commented = begin.equals("
}
}
for (int line = startLine; line <= stopLine; line++) {
int location = textarea.getLineStartOffset(line);
if (commented) {
// remove a comment
textarea.select(location, location+2);
if (textarea.getSelectedText().equals("
textarea.setSelectedText("");
}
} else {
// add a comment
textarea.select(location, location);
textarea.setSelectedText("
}
}
// Subtract one from the end, otherwise selects past the current line.
// (Which causes subsequent calls to keep expanding the selection)
textarea.select(textarea.getLineStartOffset(startLine),
textarea.getLineStopOffset(stopLine) - 1);
stopCompoundEdit();
}
protected void handleIndentOutdent(boolean indent) {
int tabSize = Preferences.getInteger("editor.tabs.size");
String tabString = Editor.EMPTY.substring(0, tabSize);
startCompoundEdit();
int startLine = textarea.getSelectionStartLine();
int stopLine = textarea.getSelectionStopLine();
// If the selection ends at the beginning of the last line,
// then don't (un)comment that line.
int lastLineStart = textarea.getLineStartOffset(stopLine);
int selectionStop = textarea.getSelectionStop();
if (selectionStop == lastLineStart) {
// Though if there's no selection, don't do that
if (textarea.isSelectionActive()) {
stopLine
}
}
for (int line = startLine; line <= stopLine; line++) {
int location = textarea.getLineStartOffset(line);
if (indent) {
textarea.select(location, location);
textarea.setSelectedText(tabString);
} else { // outdent
textarea.select(location, location + tabSize);
// Don't eat code if it's not indented
if (textarea.getSelectedText().equals(tabString)) {
textarea.setSelectedText("");
}
}
}
// Subtract one from the end, otherwise selects past the current line.
// (Which causes subsequent calls to keep expanding the selection)
textarea.select(textarea.getLineStartOffset(startLine),
textarea.getLineStopOffset(stopLine) - 1);
stopCompoundEdit();
}
protected String getCurrentKeyword() {
String text = "";
if (textarea.getSelectedText() != null)
text = textarea.getSelectedText().trim();
try {
int current = textarea.getCaretPosition();
int startOffset = 0;
int endIndex = current;
String tmp = textarea.getDocument().getText(current, 1);
// TODO probably a regexp that matches Arduino lang special chars
// already exists.
String regexp = "[\\s\\n();\\\\.!='\\[\\]{}]";
while (!tmp.matches(regexp)) {
endIndex++;
tmp = textarea.getDocument().getText(endIndex, 1);
}
// For some reason document index start at 2.
// if( current - start < 2 ) return;
tmp = "";
while (!tmp.matches(regexp)) {
startOffset++;
if (current - startOffset < 0) {
tmp = textarea.getDocument().getText(0, 1);
break;
} else
tmp = textarea.getDocument().getText(current - startOffset, 1);
}
startOffset
int length = endIndex - current + startOffset;
text = textarea.getDocument().getText(current - startOffset, length);
} catch (BadLocationException bl) {
bl.printStackTrace();
}
return text;
}
protected void handleFindReference() {
String text = getCurrentKeyword();
String referenceFile = PdeKeywords.getReference(text);
if (referenceFile == null) {
statusNotice(I18n.format(_("No reference available for \"{0}\""), text));
} else {
Base.showReference("Reference/" + referenceFile);
}
}
/**
* Implements Sketch → Run.
* @param verbose Set true to run with verbose output.
*/
public void handleRun(final boolean verbose) {
internalCloseRunner();
if (Preferences.getBoolean("editor.save_on_verify")) {
if (sketch.isModified() && !sketch.isReadOnly()) {
handleSave(true);
}
}
running = true;
toolbar.activate(EditorToolbar.RUN);
status.progress(_("Compiling sketch..."));
// do this to advance/clear the terminal window / dos prompt / etc
for (int i = 0; i < 10; i++) System.out.println();
// clear the console on each run, unless the user doesn't want to
if (Preferences.getBoolean("console.auto_clear")) {
console.clear();
}
// Cannot use invokeLater() here, otherwise it gets
// placed on the event thread and causes a hang--bad idea all around.
new Thread(verbose ? presentHandler : runHandler).start();
}
class BuildHandler implements Runnable {
private final boolean verbose;
public BuildHandler() {
this(false);
}
public BuildHandler(boolean verbose) {
this.verbose = verbose;
}
@Override
public void run() {
try {
sketch.prepare();
sketch.build(verbose);
statusNotice(_("Done compiling."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while compiling: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (Exception e) {
status.unprogress();
statusError(e);
}
status.unprogress();
toolbar.deactivate(EditorToolbar.RUN);
}
}
class DefaultStopHandler implements Runnable {
public void run() {
// TODO
// DAM: we should try to kill the compilation or upload process here.
}
}
/**
* Set the location of the sketch run window. Used by Runner to update the
* Editor about window drag events while the sketch is running.
*/
public void setSketchLocation(Point p) {
sketchWindowLocation = p;
}
/**
* Get the last location of the sketch's run window. Used by Runner to make
* the window show up in the same location as when it was last closed.
*/
public Point getSketchLocation() {
return sketchWindowLocation;
}
/**
* Implements Sketch → Stop, or pressing Stop on the toolbar.
*/
public void handleStop() { // called by menu or buttons
// toolbar.activate(EditorToolbar.STOP);
internalCloseRunner();
toolbar.deactivate(EditorToolbar.RUN);
// toolbar.deactivate(EditorToolbar.STOP);
// focus the PDE again after quitting presentation mode [toxi 030903]
toFront();
}
/**
* Deactivate the Run button. This is called by Runner to notify that the
* sketch has stopped running, usually in response to an error (or maybe
* the sketch completing and exiting?) Tools should not call this function.
* To initiate a "stop" action, call handleStop() instead.
*/
public void internalRunnerClosed() {
running = false;
toolbar.deactivate(EditorToolbar.RUN);
}
/**
* Handle internal shutdown of the runner.
*/
public void internalCloseRunner() {
running = false;
if (stopHandler != null)
try {
stopHandler.run();
} catch (Exception e) { }
}
/**
* Check if the sketch is modified and ask user to save changes.
* @return false if canceling the close/quit operation
*/
protected boolean checkModified() {
if (!sketch.isModified()) return true;
// As of Processing 1.0.10, this always happens immediately.
toFront();
String prompt = I18n.format(_("Save changes to \"{0}\"? "), sketch.getName());
if (!OSUtils.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(this, prompt, _("Close"),
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
switch (result) {
case JOptionPane.YES_OPTION:
return handleSave(true);
case JOptionPane.NO_OPTION:
return true; // ok to continue
case JOptionPane.CANCEL_OPTION:
case JOptionPane.CLOSED_OPTION: // Escape key pressed
return false;
default:
throw new IllegalStateException();
}
} else {
// This code is disabled unless Java 1.5 is being used on Mac OS X
// because of a Java bug that prevents the initial value of the
// dialog from being set properly (at least on my MacBook Pro).
// The bug causes the "Don't Save" option to be the highlighted,
// blinking, default. This sucks. But I'll tell you what doesn't
// suck--workarounds for the Mac and Apple's snobby attitude about it!
// I think it's nifty that they treat their developers like dirt.
// Pane formatting adapted from the quaqua guide
JOptionPane pane =
new JOptionPane(_("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Do you want to save changes to this sketch<BR>" +
" before closing?</b>" +
"<p>If you don't save, your changes will be lost."),
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
_("Save"), _("Cancel"), _("Don't Save")
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
// on macosx, setting the destructive property places this option
// away from the others at the lefthand side
pane.putClientProperty("Quaqua.OptionPane.destructiveOption",
new Integer(2));
JDialog dialog = pane.createDialog(this, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) { // save (and close/quit)
return handleSave(true);
} else if (result == options[2]) { // don't save (still close/quit)
return true;
} else { // cancel?
return false;
}
}
}
/**
* Open a sketch from a particular path, but don't check to save changes.
* Used by Sketch.saveAs() to re-open a sketch after the "Save As"
*/
protected void handleOpenUnchecked(File file, int codeIndex,
int selStart, int selStop, int scrollPos) {
internalCloseRunner();
handleOpenInternal(file);
// Replacing a document that may be untitled. If this is an actual
// untitled document, then editor.untitled will be set by Base.
untitled = false;
sketch.setCurrentCode(codeIndex);
textarea.select(selStart, selStop);
textarea.setScrollPosition(scrollPos);
}
/**
* Second stage of open, occurs after having checked to see if the
* modifications (if any) to the previous sketch need to be saved.
*/
protected boolean handleOpenInternal(File sketchFile) {
// check to make sure that this .pde file is
// in a folder of the same name
String fileName = sketchFile.getName();
File file = SketchData.checkSketchFile(sketchFile);
if (file == null)
{
if (!fileName.endsWith(".ino") && !fileName.endsWith(".pde")) {
Base.showWarning(_("Bad file selected"),
_("Arduino can only open its own sketches\n" +
"and other files ending in .ino or .pde"), null);
return false;
} else {
String properParent =
fileName.substring(0, fileName.length() - 4);
Object[] options = { _("OK"), _("Cancel") };
String prompt = I18n.format(_("The file \"{0}\" needs to be inside\n" +
"a sketch folder named \"{1}\".\n" +
"Create this folder, move the file, and continue?"),
fileName,
properParent);
int result = JOptionPane.showOptionDialog(this,
prompt,
_("Moving"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.YES_OPTION) {
// create properly named folder
File properFolder = new File(sketchFile.getParent(), properParent);
if (properFolder.exists()) {
Base.showWarning(_("Error"),
I18n.format(
_("A folder named \"{0}\" already exists. " +
"Can't open sketch."),
properParent
),
null);
return false;
}
if (!properFolder.mkdirs()) {
//throw new IOException("Couldn't create sketch folder");
Base.showWarning(_("Error"),
_("Could not create the sketch folder."), null);
return false;
}
// copy the sketch inside
File properPdeFile = new File(properFolder, sketchFile.getName());
try {
Base.copyFile(sketchFile, properPdeFile);
} catch (IOException e) {
Base.showWarning(_("Error"), _("Could not copy to a proper location."), e);
return false;
}
// remove the original file, so user doesn't get confused
sketchFile.delete();
// update with the new path
file = properPdeFile;
} else if (result == JOptionPane.NO_OPTION) {
return false;
}
}
}
try {
sketch = new Sketch(this, file);
} catch (IOException e) {
Base.showWarning(_("Error"), _("Could not create the sketch."), e);
return false;
}
header.rebuild();
// Set the title of the window to "sketch_070752a - Processing 0126"
setTitle(I18n.format(_("{0} | Arduino {1}"), sketch.getName(),
BaseNoGui.VERSION_NAME));
// Disable untitled setting from previous document, if any
untitled = false;
// Store information on who's open and running
// (in case there's a crash or something that can't be recovered)
base.storeSketches();
Preferences.save();
// opening was successful
return true;
// } catch (Exception e) {
// e.printStackTrace();
// statusError(e);
// return false;
}
public boolean handleSave(boolean immediately) {
//stopRunner();
handleStop(); // 0136
if (untitled) {
return handleSaveAs();
// need to get the name, user might also cancel here
} else if (immediately) {
return handleSave2();
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
handleSave2();
}
});
}
return true;
}
protected boolean handleSave2() {
toolbar.activate(EditorToolbar.SAVE);
statusNotice(_("Saving..."));
boolean saved = false;
try {
saved = sketch.save();
if (saved)
statusNotice(_("Done Saving."));
else
statusEmpty();
// rebuild sketch menu in case a save-as was forced
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenus();
//sketchbook.rebuildMenusAsync();
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
// zero out the current action,
// so that checkModified2 will just do nothing
//checkModifiedMode = 0;
// this is used when another operation calls a save
}
//toolbar.clear();
toolbar.deactivate(EditorToolbar.SAVE);
return saved;
}
public boolean handleSaveAs() {
//stopRunner(); // formerly from 0135
handleStop();
toolbar.activate(EditorToolbar.SAVE);
//SwingUtilities.invokeLater(new Runnable() {
//public void run() {
statusNotice(_("Saving..."));
try {
if (sketch.saveAs()) {
statusNotice(_("Done Saving."));
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenusAsync();
} else {
statusNotice(_("Save Canceled."));
return false;
}
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
} finally {
// make sure the toolbar button deactivates
toolbar.deactivate(EditorToolbar.SAVE);
}
return true;
}
public boolean serialPrompt() {
int count = serialMenu.getItemCount();
Object[] names = new Object[count];
for (int i = 0; i < count; i++) {
names[i] = ((JCheckBoxMenuItem)serialMenu.getItem(i)).getText();
}
String result = (String)
JOptionPane.showInputDialog(this,
I18n.format(
_("Serial port {0} not found.\n" +
"Retry the upload with another serial port?"),
Preferences.get("serial.port")
),
"Serial port not found",
JOptionPane.PLAIN_MESSAGE,
null,
names,
0);
if (result == null) return false;
selectSerialPort(result);
base.onBoardOrPortChange();
return true;
}
/**
* Called by Sketch → Export.
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
* <p/>
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
/**
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
*
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
synchronized public void handleExport(final boolean usingProgrammer) {
if (Preferences.getBoolean("editor.save_on_verify")) {
if (sketch.isModified() && !sketch.isReadOnly()) {
handleSave(true);
}
}
toolbar.activate(EditorToolbar.EXPORT);
console.clear();
status.progress(_("Uploading to I/O Board..."));
new Thread(usingProgrammer ? exportAppHandler : exportHandler).start();
}
// DAM: in Arduino, this is upload
class DefaultExportHandler implements Runnable {
public void run() {
try {
if (serialMonitor != null) {
serialMonitor.close();
serialMonitor.setVisible(false);
}
uploading = true;
boolean success = sketch.exportApplet(false);
if (success) {
statusNotice(_("Done uploading."));
} else {
// error message will already be visible
}
} catch (SerialNotFoundException e) {
populatePortMenu();
if (serialMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice(_("Upload canceled."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while uploading: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivate(EditorToolbar.EXPORT);
}
}
// DAM: in Arduino, this is upload (with verbose output)
class DefaultExportAppHandler implements Runnable {
public void run() {
try {
if (serialMonitor != null) {
serialMonitor.close();
serialMonitor.setVisible(false);
}
uploading = true;
boolean success = sketch.exportApplet(true);
if (success) {
statusNotice(_("Done uploading."));
} else {
// error message will already be visible
}
} catch (SerialNotFoundException e) {
populatePortMenu();
if (serialMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice(_("Upload canceled."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while uploading: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivate(EditorToolbar.EXPORT);
}
}
protected boolean handleExportCheckModified() {
if (!sketch.isModified()) return true;
Object[] options = { _("OK"), _("Cancel") };
int result = JOptionPane.showOptionDialog(this,
_("Save changes before export?"),
_("Save"),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.OK_OPTION) {
handleSave(true);
} else {
// why it's not CANCEL_OPTION is beyond me (at least on the mac)
// but f-- it.. let's get this shite done..
//} else if (result == JOptionPane.CANCEL_OPTION) {
statusNotice(_("Export canceled, changes must first be saved."));
//toolbar.clear();
return false;
}
return true;
}
public void handleSerial() {
if (uploading) return;
if (serialMonitor != null) {
try {
serialMonitor.close();
serialMonitor.setVisible(false);
} catch (Exception e) {
// noop
}
}
BoardPort port = Base.getDiscoveryManager().find(Preferences.get("serial.port"));
if (port == null) {
statusError(I18n.format("Board at {0} is not available", Preferences.get("serial.port")));
return;
}
serialMonitor = new MonitorFactory().newMonitor(port);
serialMonitor.setIconImage(getIconImage());
boolean success = false;
do {
if (serialMonitor.requiresAuthorization() && !Preferences.has(serialMonitor.getAuthorizationKey())) {
PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, _("Type board password to access its console"));
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if (dialog.isCancelled()) {
statusNotice(_("Unable to open serial monitor"));
return;
}
Preferences.set(serialMonitor.getAuthorizationKey(), dialog.getPassword());
}
try {
serialMonitor.open();
serialMonitor.setVisible(true);
success = true;
} catch (ConnectException e) {
statusError(_("Unable to connect: is the sketch using the bridge?"));
} catch (JSchException e) {
statusError(_("Unable to connect: wrong password?"));
} catch (SerialException e) {
String errorMessage = e.getMessage();
if (e.getCause() != null && e.getCause() instanceof SerialPortException) {
errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")";
}
statusError(errorMessage);
} catch (Exception e) {
statusError(e);
} finally {
if (serialMonitor.requiresAuthorization() && !success) {
Preferences.remove(serialMonitor.getAuthorizationKey());
}
}
} while (serialMonitor.requiresAuthorization() && !success);
}
protected void handleBurnBootloader() {
console.clear();
statusNotice(_("Burning bootloader to I/O Board (this may take a minute)..."));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Uploader uploader = new SerialUploader();
if (uploader.burnBootloader()) {
statusNotice(_("Done burning bootloader."));
} else {
statusError(_("Error while burning bootloader."));
// error message will already be visible
}
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while burning bootloader: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
statusError(e.getMessage());
} catch (Exception e) {
statusError(_("Error while burning bootloader."));
e.printStackTrace();
}
}
});
}
/**
* Handler for File → Page Setup.
*/
public void handlePageSetup() {
//printerJob = null;
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}
if (pageFormat == null) {
pageFormat = printerJob.defaultPage();
}
pageFormat = printerJob.pageDialog(pageFormat);
//System.out.println("page format is " + pageFormat);
}
/**
* Handler for File → Print.
*/
public void handlePrint() {
statusNotice(_("Printing..."));
//printerJob = null;
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}
if (pageFormat != null) {
//System.out.println("setting page format " + pageFormat);
printerJob.setPrintable(textarea.getPainter(), pageFormat);
} else {
printerJob.setPrintable(textarea.getPainter());
}
// set the name of the job to the code name
printerJob.setJobName(sketch.getCurrentCode().getPrettyName());
if (printerJob.printDialog()) {
try {
printerJob.print();
statusNotice(_("Done printing."));
} catch (PrinterException pe) {
statusError(_("Error while printing."));
pe.printStackTrace();
}
} else {
statusNotice(_("Printing canceled."));
}
//printerJob = null; // clear this out?
}
/**
* Show an error int the status bar.
*/
public void statusError(String what) {
System.err.println(what);
status.error(what);
//new Exception("deactivating RUN").printStackTrace();
toolbar.deactivate(EditorToolbar.RUN);
}
/**
* Show an exception in the editor status bar.
*/
public void statusError(Exception e) {
e.printStackTrace();
// if (e == null) {
// System.err.println("Editor.statusError() was passed a null exception.");
// return;
if (e instanceof RunnerException) {
RunnerException re = (RunnerException) e;
if (re.hasCodeIndex()) {
sketch.setCurrentCode(re.getCodeIndex());
}
if (re.hasCodeLine()) {
int line = re.getCodeLine();
// subtract one from the end so that the \n ain't included
if (line >= textarea.getLineCount()) {
// The error is at the end of this current chunk of code,
// so the last line needs to be selected.
line = textarea.getLineCount() - 1;
if (textarea.getLineText(line).length() == 0) {
// The last line may be zero length, meaning nothing to select.
// If so, back up one more line.
line
}
}
if (line < 0 || line >= textarea.getLineCount()) {
System.err.println(I18n.format(_("Bad error line: {0}"), line));
} else {
textarea.select(textarea.getLineStartOffset(line),
textarea.getLineStopOffset(line) - 1);
}
}
}
// Since this will catch all Exception types, spend some time figuring
// out which kind and try to give a better error message to the user.
String mess = e.getMessage();
if (mess != null) {
String javaLang = "java.lang.";
if (mess.indexOf(javaLang) == 0) {
mess = mess.substring(javaLang.length());
}
String rxString = "RuntimeException: ";
if (mess.indexOf(rxString) == 0) {
mess = mess.substring(rxString.length());
}
statusError(mess);
}
// e.printStackTrace();
}
/**
* Show a notice message in the editor status bar.
*/
public void statusNotice(String msg) {
status.notice(msg);
}
/**
* Clear the status area.
*/
public void statusEmpty() {
statusNotice(EMPTY);
}
protected void onBoardOrPortChange() {
Map<String, String> boardPreferences = Base.getBoardPreferences();
lineStatus.setBoardName(boardPreferences.get("name"));
lineStatus.setSerialPort(Preferences.get("serial.port"));
lineStatus.repaint();
}
/**
* Returns the edit popup menu.
*/
class TextAreaPopup extends JPopupMenu {
//private String currentDir = System.getProperty("user.dir");
private String referenceFile = null;
private JMenuItem cutItem;
private JMenuItem copyItem;
private JMenuItem discourseItem;
private JMenuItem referenceItem;
private JMenuItem openURLItem;
private JSeparator openURLItemSeparator;
private String clickedURL;
public TextAreaPopup() {
openURLItem = new JMenuItem(_("Open URL"));
openURLItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openURL(clickedURL);
}
});
add(openURLItem);
openURLItemSeparator = new JSeparator();
add(openURLItemSeparator);
cutItem = new JMenuItem(_("Cut"));
cutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCut();
}
});
add(cutItem);
copyItem = new JMenuItem(_("Copy"));
copyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCopy();
}
});
add(copyItem);
discourseItem = new JMenuItem(_("Copy for Forum"));
discourseItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleDiscourseCopy();
}
});
add(discourseItem);
discourseItem = new JMenuItem(_("Copy as HTML"));
discourseItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleHTMLCopy();
}
});
add(discourseItem);
JMenuItem item = new JMenuItem(_("Paste"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePaste();
}
});
add(item);
item = new JMenuItem(_("Select All"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSelectAll();
}
});
add(item);
addSeparator();
item = new JMenuItem(_("Comment/Uncomment"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCommentUncomment();
}
});
add(item);
item = new JMenuItem(_("Increase Indent"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(true);
}
});
add(item);
item = new JMenuItem(_("Decrease Indent"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(false);
}
});
add(item);
addSeparator();
referenceItem = new JMenuItem(_("Find in Reference"));
referenceItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleFindReference();
}
});
add(referenceItem);
}
// if no text is selected, disable copy and cut menu items
public void show(Component component, int x, int y) {
int lineNo = textarea.getLineOfOffset(textarea.xyToOffset(x, y));
int offset = textarea.xToOffset(lineNo, x);
String line = textarea.getLineText(lineNo);
clickedURL = textarea.checkClickedURL(line, offset);
if (clickedURL != null) {
openURLItem.setVisible(true);
openURLItemSeparator.setVisible(true);
} else {
openURLItem.setVisible(false);
openURLItemSeparator.setVisible(false);
}
if (textarea.isSelectionActive()) {
cutItem.setEnabled(true);
copyItem.setEnabled(true);
discourseItem.setEnabled(true);
} else {
cutItem.setEnabled(false);
copyItem.setEnabled(false);
discourseItem.setEnabled(false);
}
referenceFile = PdeKeywords.getReference(getCurrentKeyword());
referenceItem.setEnabled(referenceFile != null);
super.show(component, x, y);
}
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app;
import cc.arduino.packages.MonitorFactory;
import com.jcraft.jsch.JSchException;
import processing.app.debug.*;
import processing.app.forms.PasswordAuthorizationDialog;
import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMapException;
import processing.app.legacy.PApplet;
import processing.app.syntax.*;
import processing.app.tools.*;
import static processing.app.I18n._;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.print.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
import cc.arduino.packages.BoardPort;
import cc.arduino.packages.Uploader;
import cc.arduino.packages.uploaders.SerialUploader;
/**
* Main editor panel for the Processing Development Environment.
*/
@SuppressWarnings("serial")
public class Editor extends JFrame implements RunnerListener {
Base base;
// otherwise, if the window is resized with the message label
// set to blank, it's preferredSize() will be fukered
static protected final String EMPTY =
" " +
" " +
" ";
/** Command on Mac OS X, Ctrl on Windows and Linux */
static final int SHORTCUT_KEY_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** Command-W on Mac OS X, Ctrl-W on Windows and Linux */
static final KeyStroke WINDOW_CLOSE_KEYSTROKE =
KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK);
/** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */
static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK |
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/**
* true if this file has not yet been given a name by the user
*/
boolean untitled;
PageFormat pageFormat;
PrinterJob printerJob;
// file, sketch, and tools menus for re-inserting items
JMenu fileMenu;
JMenu sketchMenu;
JMenu toolsMenu;
int numTools = 0;
EditorToolbar toolbar;
// these menus are shared so that they needn't be rebuilt for all windows
// each time a sketch is created, renamed, or moved.
static JMenu toolbarMenu;
static JMenu sketchbookMenu;
static JMenu examplesMenu;
static JMenu importMenu;
// these menus are shared so that the board and serial port selections
// are the same for all windows (since the board and serial port that are
// actually used are determined by the preferences, which are shared)
static List<JMenu> boardsMenus;
static JMenu serialMenu;
static AbstractMonitor serialMonitor;
EditorHeader header;
EditorStatus status;
EditorConsole console;
JSplitPane splitPane;
JPanel consolePanel;
JLabel lineNumberComponent;
// currently opened program
Sketch sketch;
EditorLineStatus lineStatus;
//JEditorPane editorPane;
JEditTextArea textarea;
EditorListener listener;
// runtime information and window placement
Point sketchWindowLocation;
//Runner runtime;
JMenuItem exportAppItem;
JMenuItem saveMenuItem;
JMenuItem saveAsMenuItem;
boolean running;
//boolean presenting;
boolean uploading;
// undo fellers
JMenuItem undoItem, redoItem;
protected UndoAction undoAction;
protected RedoAction redoAction;
LastUndoableEditAwareUndoManager undo;
// used internally, and only briefly
CompoundEdit compoundEdit;
FindReplace find;
Runnable runHandler;
Runnable presentHandler;
Runnable stopHandler;
Runnable exportHandler;
Runnable exportAppHandler;
public Editor(Base ibase, File file, int[] location) throws Exception {
super("Arduino");
this.base = ibase;
Base.setIcon(this);
// Install default actions for Run, Present, etc.
resetHandlers();
// add listener to handle window close box hit event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
base.handleClose(Editor.this);
}
});
// don't close the window when clicked, the app will take care
// of that via the handleQuitInternal() methods
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// When bringing a window to front, let the Base know
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
// System.err.println("activate"); // not coming through
base.handleActivated(Editor.this);
// re-add the sub-menus that are shared by all windows
fileMenu.insert(sketchbookMenu, 2);
fileMenu.insert(examplesMenu, 3);
sketchMenu.insert(importMenu, 4);
int offset = 0;
for (JMenu menu : boardsMenus) {
toolsMenu.insert(menu, numTools + offset);
offset++;
}
toolsMenu.insert(serialMenu, numTools + offset);
}
// added for 1.0.5
public void windowDeactivated(WindowEvent e) {
// System.err.println("deactivate"); // not coming through
fileMenu.remove(sketchbookMenu);
fileMenu.remove(examplesMenu);
sketchMenu.remove(importMenu);
for (JMenu menu : boardsMenus) {
toolsMenu.remove(menu);
}
toolsMenu.remove(serialMenu);
}
});
//PdeKeywords keywords = new PdeKeywords();
//sketchbook = new Sketchbook(this);
buildMenuBar();
// For rev 0120, placing things inside a JPanel
Container contentPain = getContentPane();
contentPain.setLayout(new BorderLayout());
JPanel pain = new JPanel();
pain.setLayout(new BorderLayout());
contentPain.add(pain, BorderLayout.CENTER);
Box box = Box.createVerticalBox();
Box upper = Box.createVerticalBox();
if (toolbarMenu == null) {
toolbarMenu = new JMenu();
base.rebuildToolbarMenu(toolbarMenu);
}
toolbar = new EditorToolbar(this, toolbarMenu);
upper.add(toolbar);
header = new EditorHeader(this);
upper.add(header);
textarea = new JEditTextArea(new PdeTextAreaDefaults());
textarea.setName("editor");
textarea.setRightClickPopup(new TextAreaPopup());
textarea.setHorizontalOffset(6);
// assemble console panel, consisting of status area and the console itself
consolePanel = new JPanel();
consolePanel.setLayout(new BorderLayout());
status = new EditorStatus(this);
consolePanel.add(status, BorderLayout.NORTH);
console = new EditorConsole(this);
console.setName("console");
// windows puts an ugly border on this guy
console.setBorder(null);
consolePanel.add(console, BorderLayout.CENTER);
lineStatus = new EditorLineStatus(textarea);
consolePanel.add(lineStatus, BorderLayout.SOUTH);
upper.add(textarea);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
upper, consolePanel);
splitPane.setOneTouchExpandable(true);
// repaint child panes while resizing
splitPane.setContinuousLayout(true);
// if window increases in size, give all of increase to
// the textarea in the uppper pane
splitPane.setResizeWeight(1D);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
splitPane.setBorder(null);
// the default size on windows is too small and kinda ugly
int dividerSize = Preferences.getInteger("editor.divider.size");
if (dividerSize != 0) {
splitPane.setDividerSize(dividerSize);
}
// the following changed from 600, 400 for netbooks
splitPane.setMinimumSize(new Dimension(600, 100));
box.add(splitPane);
// hopefully these are no longer needed w/ swing
// (har har har.. that was wishful thinking)
listener = new EditorListener(this, textarea);
pain.add(box);
// get shift down/up events so we can show the alt version of toolbar buttons
textarea.addKeyListener(toolbar);
pain.setTransferHandler(new FileDropHandler());
// System.out.println("t1");
// Finish preparing Editor (formerly found in Base)
pack();
// System.out.println("t2");
// Set the window bounds and the divider location before setting it visible
setPlacement(location);
// Set the minimum size for the editor window
setMinimumSize(new Dimension(Preferences.getInteger("editor.window.width.min"),
Preferences.getInteger("editor.window.height.min")));
// System.out.println("t3");
// Bring back the general options for the editor
applyPreferences();
// System.out.println("t4");
// Open the document that was passed in
boolean loaded = handleOpenInternal(file);
if (!loaded) sketch = null;
// System.out.println("t5");
// All set, now show the window
//setVisible(true);
}
/**
* Handles files dragged & dropped from the desktop and into the editor
* window. Dragging files into the editor window is the same as using
* "Sketch → Add File" for each file.
*/
class FileDropHandler extends TransferHandler {
public boolean canImport(JComponent dest, DataFlavor[] flavors) {
return true;
}
@SuppressWarnings("unchecked")
public boolean importData(JComponent src, Transferable transferable) {
int successful = 0;
try {
DataFlavor uriListFlavor =
new DataFlavor("text/uri-list;class=java.lang.String");
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> list = (List<File>)
transferable.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : list) {
if (sketch.addFile(file)) {
successful++;
}
}
} else if (transferable.isDataFlavorSupported(uriListFlavor)) {
// Some platforms (Mac OS X and Linux, when this began) preferred
// this method of moving files.
String data = (String)transferable.getTransferData(uriListFlavor);
String[] pieces = PApplet.splitTokens(data, "\r\n");
for (int i = 0; i < pieces.length; i++) {
if (pieces[i].startsWith("#")) continue;
String path = null;
if (pieces[i].startsWith("file:
path = pieces[i].substring(7);
} else if (pieces[i].startsWith("file:/")) {
path = pieces[i].substring(5);
}
if (sketch.addFile(new File(path))) {
successful++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
if (successful == 0) {
statusError(_("No files were added to the sketch."));
} else if (successful == 1) {
statusNotice(_("One file added to the sketch."));
} else {
statusNotice(
I18n.format(_("{0} files added to the sketch."), successful));
}
return true;
}
}
protected void setPlacement(int[] location) {
setBounds(location[0], location[1], location[2], location[3]);
if (location[4] != 0) {
splitPane.setDividerLocation(location[4]);
}
}
protected int[] getPlacement() {
int[] location = new int[5];
// Get the dimensions of the Frame
Rectangle bounds = getBounds();
location[0] = bounds.x;
location[1] = bounds.y;
location[2] = bounds.width;
location[3] = bounds.height;
// Get the current placement of the divider
location[4] = splitPane.getDividerLocation();
return location;
}
/**
* Hack for #@#)$(* Mac OS X 10.2.
* <p/>
* This appears to only be required on OS X 10.2, and is not
* even being called on later versions of OS X or Windows.
*/
// public Dimension getMinimumSize() {
// //System.out.println("getting minimum size");
// return new Dimension(500, 550);
/**
* Read and apply new values from the preferences, either because
* the app is just starting up, or the user just finished messing
* with things in the Preferences window.
*/
protected void applyPreferences() {
// apply the setting for 'use external editor'
boolean external = Preferences.getBoolean("editor.external");
textarea.setEditable(!external);
saveMenuItem.setEnabled(!external);
saveAsMenuItem.setEnabled(!external);
textarea.setDisplayLineNumbers(Preferences.getBoolean("editor.linenumbers"));
TextAreaPainter painter = textarea.getPainter();
if (external) {
// disable line highlight and turn off the caret when disabling
Color color = Theme.getColor("editor.external.bgcolor");
painter.setBackground(color);
painter.setLineHighlightEnabled(false);
textarea.setCaretVisible(false);
} else {
Color color = Theme.getColor("editor.bgcolor");
painter.setBackground(color);
boolean highlight = Preferences.getBoolean("editor.linehighlight");
painter.setLineHighlightEnabled(highlight);
textarea.setCaretVisible(true);
}
// apply changes to the font size for the editor
//TextAreaPainter painter = textarea.getPainter();
painter.setFont(Preferences.getFont("editor.font"));
//Font font = painter.getFont();
//textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36));
// in case tab expansion stuff has changed
listener.applyPreferences();
// in case moved to a new location
// For 0125, changing to async version (to be implemented later)
//sketchbook.rebuildMenus();
// For 0126, moved into Base, which will notify all editors.
//base.rebuildMenusAsync();
}
protected void buildMenuBar() throws Exception {
JMenuBar menubar = new JMenuBar();
menubar.add(buildFileMenu());
menubar.add(buildEditMenu());
menubar.add(buildSketchMenu());
menubar.add(buildToolsMenu());
menubar.add(buildHelpMenu());
setJMenuBar(menubar);
}
protected JMenu buildFileMenu() {
JMenuItem item;
fileMenu = new JMenu(_("File"));
item = newJMenuItem(_("New"), 'N');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleNew();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
item = Editor.newJMenuItem(_("Open..."), 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleOpenPrompt();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
if (sketchbookMenu == null) {
sketchbookMenu = new JMenu(_("Sketchbook"));
MenuScroller.setScrollerFor(sketchbookMenu);
base.rebuildSketchbookMenu(sketchbookMenu);
}
fileMenu.add(sketchbookMenu);
if (examplesMenu == null) {
examplesMenu = new JMenu(_("Examples"));
MenuScroller.setScrollerFor(examplesMenu);
base.rebuildExamplesMenu(examplesMenu);
}
fileMenu.add(examplesMenu);
item = Editor.newJMenuItem(_("Close"), 'W');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleClose(Editor.this);
}
});
fileMenu.add(item);
saveMenuItem = newJMenuItem(_("Save"), 'S');
saveMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSave(false);
}
});
fileMenu.add(saveMenuItem);
saveAsMenuItem = newJMenuItemShift(_("Save As..."), 'S');
saveAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSaveAs();
}
});
fileMenu.add(saveAsMenuItem);
item = newJMenuItem(_("Upload"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(false);
}
});
fileMenu.add(item);
item = newJMenuItemShift(_("Upload Using Programmer"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(true);
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItemShift(_("Page Setup"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePageSetup();
}
});
fileMenu.add(item);
item = newJMenuItem(_("Print"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePrint();
}
});
fileMenu.add(item);
// macosx already has its own preferences and quit menu
if (!OSUtils.isMacOS()) {
fileMenu.addSeparator();
item = newJMenuItem(_("Preferences"), ',');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handlePrefs();
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItem(_("Quit"), 'Q');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleQuit();
}
});
fileMenu.add(item);
}
return fileMenu;
}
protected JMenu buildSketchMenu() {
JMenuItem item;
sketchMenu = new JMenu(_("Sketch"));
item = newJMenuItem(_("Verify / Compile"), 'R');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleRun(false);
}
});
sketchMenu.add(item);
// item = newJMenuItemShift("Verify / Compile (verbose)", 'R');
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleRun(true);
// sketchMenu.add(item);
// item = new JMenuItem("Stop");
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleStop();
// sketchMenu.add(item);
sketchMenu.addSeparator();
if (importMenu == null) {
importMenu = new JMenu(_("Import Library..."));
MenuScroller.setScrollerFor(importMenu);
base.rebuildImportMenu(importMenu);
}
sketchMenu.add(importMenu);
item = newJMenuItem(_("Show Sketch Folder"), 'K');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openFolder(sketch.getFolder());
}
});
sketchMenu.add(item);
item.setEnabled(Base.openFolderAvailable());
item = new JMenuItem(_("Add File..."));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sketch.handleAddFile();
}
});
sketchMenu.add(item);
return sketchMenu;
}
protected JMenu buildToolsMenu() throws Exception {
toolsMenu = new JMenu(_("Tools"));
JMenu menu = toolsMenu;
JMenuItem item;
addInternalTools(menu);
item = newJMenuItemShift(_("Serial Monitor"), 'M');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSerial();
}
});
menu.add(item);
addTools(menu, Base.getToolsFolder());
File sketchbookTools = new File(Base.getSketchbookFolder(), "tools");
addTools(menu, sketchbookTools);
menu.addSeparator();
numTools = menu.getItemCount();
// XXX: DAM: these should probably be implemented using the Tools plugin
// API, if possible (i.e. if it supports custom actions, etc.)
if (boardsMenus == null) {
boardsMenus = new LinkedList<JMenu>();
JMenu boardsMenu = new JMenu(_("Board"));
MenuScroller.setScrollerFor(boardsMenu);
Editor.boardsMenus.add(boardsMenu);
toolsMenu.add(boardsMenu);
base.rebuildBoardsMenu(toolsMenu, this);
//Debug: rebuild imports
importMenu.removeAll();
base.rebuildImportMenu(importMenu);
}
if (serialMenu == null)
serialMenu = new JMenu(_("Port"));
populatePortMenu();
menu.add(serialMenu);
menu.addSeparator();
JMenu programmerMenu = new JMenu(_("Programmer"));
base.rebuildProgrammerMenu(programmerMenu);
menu.add(programmerMenu);
item = new JMenuItem(_("Burn Bootloader"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleBurnBootloader();
}
});
menu.add(item);
menu.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {}
public void menuDeselected(MenuEvent e) {}
public void menuSelected(MenuEvent e) {
//System.out.println("Tools menu selected.");
populatePortMenu();
}
});
return menu;
}
protected void addTools(JMenu menu, File sourceFolder) {
if (sourceFolder == null)
return;
Map<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>();
File[] folders = sourceFolder.listFiles(new FileFilter() {
public boolean accept(File folder) {
if (folder.isDirectory()) {
//System.out.println("checking " + folder);
File subfolder = new File(folder, "tool");
return subfolder.exists();
}
return false;
}
});
if (folders == null || folders.length == 0) {
return;
}
for (int i = 0; i < folders.length; i++) {
File toolDirectory = new File(folders[i], "tool");
try {
// add dir to classpath for .classes
//urlList.add(toolDirectory.toURL());
// add .jar files to classpath
File[] archives = toolDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".jar") ||
name.toLowerCase().endsWith(".zip"));
}
});
URL[] urlList = new URL[archives.length];
for (int j = 0; j < urlList.length; j++) {
urlList[j] = archives[j].toURI().toURL();
}
URLClassLoader loader = new URLClassLoader(urlList);
String className = null;
for (int j = 0; j < archives.length; j++) {
className = findClassInZipFile(folders[i].getName(), archives[j]);
if (className != null) break;
}
// If no class name found, just move on.
if (className == null) continue;
Class<?> toolClass = Class.forName(className, true, loader);
final Tool tool = (Tool) toolClass.newInstance();
tool.init(Editor.this);
String title = tool.getMenuTitle();
JMenuItem item = new JMenuItem(title);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
//new Thread(tool).start();
}
});
//menu.add(item);
toolItems.put(title, item);
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<String> toolList = new ArrayList<String>(toolItems.keySet());
if (toolList.size() == 0) return;
menu.addSeparator();
Collections.sort(toolList);
for (String title : toolList) {
menu.add((JMenuItem) toolItems.get(title));
}
}
protected String findClassInZipFile(String base, File file) {
// Class file to search for
String classFileName = "/" + base + ".class";
ZipFile zipFile = null;
try {
zipFile = new ZipFile(file);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (!entry.isDirectory()) {
String name = entry.getName();
//System.out.println("entry: " + name);
if (name.endsWith(classFileName)) {
//int slash = name.lastIndexOf('/');
//String packageName = (slash == -1) ? "" : name.substring(0, slash);
// Remove .class and convert slashes to periods.
return name.substring(0, name.length() - 6).replace('/', '.');
}
}
}
} catch (IOException e) {
//System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
e.printStackTrace();
} finally {
if (zipFile != null)
try {
zipFile.close();
} catch (IOException e) {
}
}
return null;
}
protected JMenuItem createToolMenuItem(String className) {
try {
Class<?> toolClass = Class.forName(className);
final Tool tool = (Tool) toolClass.newInstance();
JMenuItem item = new JMenuItem(tool.getMenuTitle());
tool.init(Editor.this);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
}
});
return item;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected JMenu addInternalTools(JMenu menu) {
JMenuItem item;
item = createToolMenuItem("cc.arduino.packages.formatter.AStyle");
item.setName("menuToolsAutoFormat");
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers));
menu.add(item);
//menu.add(createToolMenuItem("processing.app.tools.CreateFont"));
//menu.add(createToolMenuItem("processing.app.tools.ColorSelector"));
menu.add(createToolMenuItem("processing.app.tools.Archiver"));
menu.add(createToolMenuItem("processing.app.tools.FixEncoding"));
// // These are temporary entries while Android mode is being worked out.
// // The mode will not be in the tools menu, and won't involve a cmd-key
// if (!Base.RELEASE) {
// item = createToolMenuItem("processing.app.tools.android.AndroidTool");
// item.setAccelerator(KeyStroke.getKeyStroke('D', modifiers));
// menu.add(item);
// menu.add(createToolMenuItem("processing.app.tools.android.Reset"));
return menu;
}
class SerialMenuListener implements ActionListener {
private final String serialPort;
public SerialMenuListener(String serialPort) {
this.serialPort = serialPort;
}
public void actionPerformed(ActionEvent e) {
selectSerialPort(serialPort);
base.onBoardOrPortChange();
}
}
protected void selectSerialPort(String name) {
if(serialMenu == null) {
System.out.println(_("serialMenu is null"));
return;
}
if (name == null) {
System.out.println(_("name is null"));
return;
}
JCheckBoxMenuItem selection = null;
for (int i = 0; i < serialMenu.getItemCount(); i++) {
JCheckBoxMenuItem item = ((JCheckBoxMenuItem)serialMenu.getItem(i));
if (item == null) {
System.out.println(_("name is null"));
continue;
}
item.setState(false);
if (name.equals(item.getText())) selection = item;
}
if (selection != null) selection.setState(true);
//System.out.println(item.getLabel());
Base.selectSerialPort(name);
if (serialMonitor != null) {
try {
serialMonitor.close();
serialMonitor.setVisible(false);
} catch (Exception e) {
// ignore
}
}
onBoardOrPortChange();
//System.out.println("set to " + get("serial.port"));
}
protected void populatePortMenu() {
serialMenu.removeAll();
String selectedPort = Preferences.get("serial.port");
List<BoardPort> ports = Base.getDiscoveryManager().discovery();
for (BoardPort port : ports) {
String address = port.getAddress();
String label = port.getLabel();
JCheckBoxMenuItem item = new JCheckBoxMenuItem(label, address.equals(selectedPort));
item.addActionListener(new SerialMenuListener(address));
serialMenu.add(item);
}
serialMenu.setEnabled(serialMenu.getMenuComponentCount() > 0);
}
protected JMenu buildHelpMenu() {
// To deal with a Mac OS X 10.5 bug, add an extra space after the name
// so that the OS doesn't try to insert its slow help menu.
JMenu menu = new JMenu(_("Help"));
JMenuItem item;
item = new JMenuItem(_("Getting Started"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showGettingStarted();
}
});
menu.add(item);
item = new JMenuItem(_("Environment"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showEnvironment();
}
});
menu.add(item);
item = new JMenuItem(_("Troubleshooting"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showTroubleshooting();
}
});
menu.add(item);
item = new JMenuItem(_("Reference"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showReference();
}
});
menu.add(item);
item = newJMenuItemShift(_("Find in Reference"), 'F');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// if (textarea.isSelectionActive()) {
// handleFindReference();
handleFindReference();
}
});
menu.add(item);
item = new JMenuItem(_("Frequently Asked Questions"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showFAQ();
}
});
menu.add(item);
item = new JMenuItem(_("Visit Arduino.cc"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openURL(_("http://arduino.cc/"));
}
});
menu.add(item);
// macosx already has its own about menu
if (!OSUtils.isMacOS()) {
menu.addSeparator();
item = new JMenuItem(_("About Arduino"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleAbout();
}
});
menu.add(item);
}
return menu;
}
protected JMenu buildEditMenu() {
JMenu menu = new JMenu(_("Edit"));
menu.setName("menuEdit");
JMenuItem item;
undoItem = newJMenuItem(_("Undo"), 'Z');
undoItem.setName("menuEditUndo");
undoItem.addActionListener(undoAction = new UndoAction());
menu.add(undoItem);
if (!OSUtils.isMacOS()) {
redoItem = newJMenuItem(_("Redo"), 'Y');
} else {
redoItem = newJMenuItemShift(_("Redo"), 'Z');
}
redoItem.setName("menuEditRedo");
redoItem.addActionListener(redoAction = new RedoAction());
menu.add(redoItem);
menu.addSeparator();
// TODO "cut" and "copy" should really only be enabled
// if some text is currently selected
item = newJMenuItem(_("Cut"), 'X');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCut();
}
});
menu.add(item);
item = newJMenuItem(_("Copy"), 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.copy();
}
});
menu.add(item);
item = newJMenuItemShift(_("Copy for Forum"), 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
new DiscourseFormat(Editor.this, false).show();
}
});
menu.add(item);
item = newJMenuItemAlt(_("Copy as HTML"), 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
new DiscourseFormat(Editor.this, true).show();
}
});
menu.add(item);
item = newJMenuItem(_("Paste"), 'V');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.paste();
sketch.setModified(true);
}
});
menu.add(item);
item = newJMenuItem(_("Select All"), 'A');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.selectAll();
}
});
menu.add(item);
menu.addSeparator();
item = newJMenuItem(_("Comment/Uncomment"), '/');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCommentUncomment();
}
});
menu.add(item);
item = newJMenuItem(_("Increase Indent"), ']');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(true);
}
});
menu.add(item);
item = newJMenuItem(_("Decrease Indent"), '[');
item.setName("menuDecreaseIndent");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(false);
}
});
menu.add(item);
menu.addSeparator();
item = newJMenuItem(_("Find..."), 'F');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find == null) {
find = new FindReplace(Editor.this);
}
if (getSelectedText()!= null) find.setFindText( getSelectedText() );
//new FindReplace(Editor.this).show();
find.setVisible(true);
//find.setVisible(true);
}
});
menu.add(item);
// TODO find next should only be enabled after a
// search has actually taken place
item = newJMenuItem(_("Find Next"), 'G');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find != null) {
find.findNext();
}
}
});
menu.add(item);
item = newJMenuItemShift(_("Find Previous"), 'G');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find != null) {
find.findPrevious();
}
}
});
menu.add(item);
item = newJMenuItem(_("Use Selection For Find"), 'E');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find == null) {
find = new FindReplace(Editor.this);
}
find.setFindText( getSelectedText() );
}
});
menu.add(item);
return menu;
}
/**
* A software engineer, somewhere, needs to have his abstraction
* taken away. In some countries they jail or beat people for writing
* the sort of API that would require a five line helper function
* just to set the command key for a menu item.
*/
static public JMenuItem newJMenuItem(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK));
return menuItem;
}
/**
* Like newJMenuItem() but adds shift as a modifier for the key command.
*/
static public JMenuItem newJMenuItemShift(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK | ActionEvent.SHIFT_MASK));
return menuItem;
}
/**
* Same as newJMenuItem(), but adds the ALT (on Linux and Windows)
* or OPTION (on Mac OS X) key as a modifier.
*/
static public JMenuItem newJMenuItemAlt(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK));
return menuItem;
}
class UndoAction extends AbstractAction {
public UndoAction() {
super("Undo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.undo();
} catch (CannotUndoException ex) {
//System.out.println("Unable to undo: " + ex);
//ex.printStackTrace();
}
if (undo.getLastUndoableEdit() != null && undo.getLastUndoableEdit() instanceof CaretAwareUndoableEdit) {
CaretAwareUndoableEdit undoableEdit = (CaretAwareUndoableEdit) undo.getLastUndoableEdit();
int nextCaretPosition = undoableEdit.getCaretPosition() - 1;
if (nextCaretPosition >= 0 && textarea.getDocumentLength() > nextCaretPosition) {
textarea.setCaretPosition(nextCaretPosition);
}
}
updateUndoState();
redoAction.updateRedoState();
}
protected void updateUndoState() {
if (undo.canUndo()) {
this.setEnabled(true);
undoItem.setEnabled(true);
undoItem.setText(undo.getUndoPresentationName());
putValue(Action.NAME, undo.getUndoPresentationName());
if (sketch != null) {
sketch.setModified(true); // 0107
}
} else {
this.setEnabled(false);
undoItem.setEnabled(false);
undoItem.setText(_("Undo"));
putValue(Action.NAME, "Undo");
if (sketch != null) {
sketch.setModified(false); // 0107
}
}
}
}
class RedoAction extends AbstractAction {
public RedoAction() {
super("Redo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.redo();
} catch (CannotRedoException ex) {
//System.out.println("Unable to redo: " + ex);
//ex.printStackTrace();
}
if (undo.getLastUndoableEdit() != null && undo.getLastUndoableEdit() instanceof CaretAwareUndoableEdit) {
CaretAwareUndoableEdit undoableEdit = (CaretAwareUndoableEdit) undo.getLastUndoableEdit();
textarea.setCaretPosition(undoableEdit.getCaretPosition());
}
updateRedoState();
undoAction.updateUndoState();
}
protected void updateRedoState() {
if (undo.canRedo()) {
redoItem.setEnabled(true);
redoItem.setText(undo.getRedoPresentationName());
putValue(Action.NAME, undo.getRedoPresentationName());
} else {
this.setEnabled(false);
redoItem.setEnabled(false);
redoItem.setText(_("Redo"));
putValue(Action.NAME, "Redo");
}
}
}
// these will be done in a more generic way soon, more like:
// setHandler("action name", Runnable);
// but for the time being, working out the kinks of how many things to
// abstract from the editor in this fashion.
public void setHandlers(Runnable runHandler, Runnable presentHandler,
Runnable stopHandler,
Runnable exportHandler, Runnable exportAppHandler) {
this.runHandler = runHandler;
this.presentHandler = presentHandler;
this.stopHandler = stopHandler;
this.exportHandler = exportHandler;
this.exportAppHandler = exportAppHandler;
}
public void resetHandlers() {
runHandler = new BuildHandler();
presentHandler = new BuildHandler(true);
stopHandler = new DefaultStopHandler();
exportHandler = new DefaultExportHandler();
exportAppHandler = new DefaultExportAppHandler();
}
/**
* Gets the current sketch object.
*/
public Sketch getSketch() {
return sketch;
}
/**
* Get the JEditTextArea object for use (not recommended). This should only
* be used in obscure cases that really need to hack the internals of the
* JEditTextArea. Most tools should only interface via the get/set functions
* found in this class. This will maintain compatibility with future releases,
* which will not use JEditTextArea.
*/
public JEditTextArea getTextArea() {
return textarea;
}
/**
* Get the contents of the current buffer. Used by the Sketch class.
*/
public String getText() {
return textarea.getText();
}
/**
* Get a range of text from the current buffer.
*/
public String getText(int start, int stop) {
return textarea.getText(start, stop - start);
}
/**
* Replace the entire contents of the front-most tab.
*/
public void setText(String what) {
startCompoundEdit();
textarea.setText(what);
stopCompoundEdit();
}
public void insertText(String what) {
startCompoundEdit();
int caret = getCaretOffset();
setSelection(caret, caret);
textarea.setSelectedText(what);
stopCompoundEdit();
}
/**
* Called to update the text but not switch to a different set of code
* (which would affect the undo manager).
*/
// public void setText2(String what, int start, int stop) {
// beginCompoundEdit();
// textarea.setText(what);
// endCompoundEdit();
// // make sure that a tool isn't asking for a bad location
// start = Math.max(0, Math.min(start, textarea.getDocumentLength()));
// stop = Math.max(0, Math.min(start, textarea.getDocumentLength()));
// textarea.select(start, stop);
// textarea.requestFocus(); // get the caret blinking
public String getSelectedText() {
return textarea.getSelectedText();
}
public void setSelectedText(String what) {
textarea.setSelectedText(what);
}
public void setSelection(int start, int stop) {
// make sure that a tool isn't asking for a bad location
start = PApplet.constrain(start, 0, textarea.getDocumentLength());
stop = PApplet.constrain(stop, 0, textarea.getDocumentLength());
textarea.select(start, stop);
}
/**
* Get the position (character offset) of the caret. With text selected,
* this will be the last character actually selected, no matter the direction
* of the selection. That is, if the user clicks and drags to select lines
* 7 up to 4, then the caret position will be somewhere on line four.
*/
public int getCaretOffset() {
return textarea.getCaretPosition();
}
/**
* True if some text is currently selected.
*/
public boolean isSelectionActive() {
return textarea.isSelectionActive();
}
/**
* Get the beginning point of the current selection.
*/
public int getSelectionStart() {
return textarea.getSelectionStart();
}
/**
* Get the end point of the current selection.
*/
public int getSelectionStop() {
return textarea.getSelectionStop();
}
/**
* Get text for a specified line.
*/
public String getLineText(int line) {
return textarea.getLineText(line);
}
/**
* Replace the text on a specified line.
*/
public void setLineText(int line, String what) {
startCompoundEdit();
textarea.select(getLineStartOffset(line), getLineStopOffset(line));
textarea.setSelectedText(what);
stopCompoundEdit();
}
/**
* Get character offset for the start of a given line of text.
*/
public int getLineStartOffset(int line) {
return textarea.getLineStartOffset(line);
}
/**
* Get character offset for end of a given line of text.
*/
public int getLineStopOffset(int line) {
return textarea.getLineStopOffset(line);
}
/**
* Get the number of lines in the currently displayed buffer.
*/
public int getLineCount() {
return textarea.getLineCount();
}
/**
* Use before a manipulating text to group editing operations together as a
* single undo. Use stopCompoundEdit() once finished.
*/
public void startCompoundEdit() {
compoundEdit = new CompoundEdit();
}
/**
* Use with startCompoundEdit() to group edit operations in a single undo.
*/
public void stopCompoundEdit() {
compoundEdit.end();
undo.addEdit(compoundEdit);
undoAction.updateUndoState();
redoAction.updateRedoState();
compoundEdit = null;
}
public int getScrollPosition() {
return textarea.getScrollPosition();
}
/**
* Switch between tabs, this swaps out the Document object
* that's currently being manipulated.
*/
protected void setCode(SketchCodeDocument codeDoc) {
SyntaxDocument document = (SyntaxDocument) codeDoc.getDocument();
if (document == null) { // this document not yet inited
document = new SyntaxDocument();
codeDoc.setDocument(document);
// turn on syntax highlighting
document.setTokenMarker(new PdeKeywords());
// insert the program text into the document object
try {
document.insertString(0, codeDoc.getCode().getProgram(), null);
} catch (BadLocationException bl) {
bl.printStackTrace();
}
// set up this guy's own undo manager
// code.undo = new UndoManager();
// connect the undo listener to the editor
document.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent e) {
if (compoundEdit != null) {
compoundEdit.addEdit(e.getEdit());
} else if (undo != null) {
undo.addEdit(new CaretAwareUndoableEdit(e.getEdit(), textarea));
undoAction.updateUndoState();
redoAction.updateRedoState();
}
}
});
}
// update the document object that's in use
textarea.setDocument(document,
codeDoc.getSelectionStart(), codeDoc.getSelectionStop(),
codeDoc.getScrollPosition());
textarea.requestFocus(); // get the caret blinking
this.undo = codeDoc.getUndo();
undoAction.updateUndoState();
redoAction.updateRedoState();
}
/**
* Implements Edit → Cut.
*/
public void handleCut() {
textarea.cut();
sketch.setModified(true);
}
/**
* Implements Edit → Copy.
*/
public void handleCopy() {
textarea.copy();
}
protected void handleDiscourseCopy() {
new DiscourseFormat(Editor.this, false).show();
}
protected void handleHTMLCopy() {
new DiscourseFormat(Editor.this, true).show();
}
/**
* Implements Edit → Paste.
*/
public void handlePaste() {
textarea.paste();
sketch.setModified(true);
}
/**
* Implements Edit → Select All.
*/
public void handleSelectAll() {
textarea.selectAll();
}
protected void handleCommentUncomment() {
startCompoundEdit();
int startLine = textarea.getSelectionStartLine();
int stopLine = textarea.getSelectionStopLine();
int lastLineStart = textarea.getLineStartOffset(stopLine);
int selectionStop = textarea.getSelectionStop();
// If the selection ends at the beginning of the last line,
// then don't (un)comment that line.
if (selectionStop == lastLineStart) {
// Though if there's no selection, don't do that
if (textarea.isSelectionActive()) {
stopLine
}
}
// If the text is empty, ignore the user.
// Also ensure that all lines are commented (not just the first)
// when determining whether to comment or uncomment.
int length = textarea.getDocumentLength();
boolean commented = true;
for (int i = startLine; commented && (i <= stopLine); i++) {
int pos = textarea.getLineStartOffset(i);
if (pos + 2 > length) {
commented = false;
} else {
// Check the first two characters to see if it's already a comment.
String begin = textarea.getText(pos, 2);
//System.out.println("begin is '" + begin + "'");
commented = begin.equals("
}
}
for (int line = startLine; line <= stopLine; line++) {
int location = textarea.getLineStartOffset(line);
if (commented) {
// remove a comment
textarea.select(location, location+2);
if (textarea.getSelectedText().equals("
textarea.setSelectedText("");
}
} else {
// add a comment
textarea.select(location, location);
textarea.setSelectedText("
}
}
// Subtract one from the end, otherwise selects past the current line.
// (Which causes subsequent calls to keep expanding the selection)
textarea.select(textarea.getLineStartOffset(startLine),
textarea.getLineStopOffset(stopLine) - 1);
stopCompoundEdit();
}
protected void handleIndentOutdent(boolean indent) {
int tabSize = Preferences.getInteger("editor.tabs.size");
String tabString = Editor.EMPTY.substring(0, tabSize);
startCompoundEdit();
int startLine = textarea.getSelectionStartLine();
int stopLine = textarea.getSelectionStopLine();
// If the selection ends at the beginning of the last line,
// then don't (un)comment that line.
int lastLineStart = textarea.getLineStartOffset(stopLine);
int selectionStop = textarea.getSelectionStop();
if (selectionStop == lastLineStart) {
// Though if there's no selection, don't do that
if (textarea.isSelectionActive()) {
stopLine
}
}
for (int line = startLine; line <= stopLine; line++) {
int location = textarea.getLineStartOffset(line);
if (indent) {
textarea.select(location, location);
textarea.setSelectedText(tabString);
} else { // outdent
textarea.select(location, location + tabSize);
// Don't eat code if it's not indented
if (textarea.getSelectedText().equals(tabString)) {
textarea.setSelectedText("");
}
}
}
// Subtract one from the end, otherwise selects past the current line.
// (Which causes subsequent calls to keep expanding the selection)
textarea.select(textarea.getLineStartOffset(startLine),
textarea.getLineStopOffset(stopLine) - 1);
stopCompoundEdit();
}
protected String getCurrentKeyword() {
String text = "";
if (textarea.getSelectedText() != null)
text = textarea.getSelectedText().trim();
try {
int current = textarea.getCaretPosition();
int startOffset = 0;
int endIndex = current;
String tmp = textarea.getDocument().getText(current, 1);
// TODO probably a regexp that matches Arduino lang special chars
// already exists.
String regexp = "[\\s\\n();\\\\.!='\\[\\]{}]";
while (!tmp.matches(regexp)) {
endIndex++;
tmp = textarea.getDocument().getText(endIndex, 1);
}
// For some reason document index start at 2.
// if( current - start < 2 ) return;
tmp = "";
while (!tmp.matches(regexp)) {
startOffset++;
if (current - startOffset < 0) {
tmp = textarea.getDocument().getText(0, 1);
break;
} else
tmp = textarea.getDocument().getText(current - startOffset, 1);
}
startOffset
int length = endIndex - current + startOffset;
text = textarea.getDocument().getText(current - startOffset, length);
} catch (BadLocationException bl) {
bl.printStackTrace();
}
return text;
}
protected void handleFindReference() {
String text = getCurrentKeyword();
String referenceFile = PdeKeywords.getReference(text);
if (referenceFile == null) {
statusNotice(I18n.format(_("No reference available for \"{0}\""), text));
} else {
Base.showReference(I18n.format(_("{0}.html"), referenceFile));
}
}
/**
* Implements Sketch → Run.
* @param verbose Set true to run with verbose output.
*/
public void handleRun(final boolean verbose) {
internalCloseRunner();
if (Preferences.getBoolean("editor.save_on_verify")) {
if (sketch.isModified() && !sketch.isReadOnly()) {
handleSave(true);
}
}
running = true;
toolbar.activate(EditorToolbar.RUN);
status.progress(_("Compiling sketch..."));
// do this to advance/clear the terminal window / dos prompt / etc
for (int i = 0; i < 10; i++) System.out.println();
// clear the console on each run, unless the user doesn't want to
if (Preferences.getBoolean("console.auto_clear")) {
console.clear();
}
// Cannot use invokeLater() here, otherwise it gets
// placed on the event thread and causes a hang--bad idea all around.
new Thread(verbose ? presentHandler : runHandler).start();
}
class BuildHandler implements Runnable {
private final boolean verbose;
public BuildHandler() {
this(false);
}
public BuildHandler(boolean verbose) {
this.verbose = verbose;
}
@Override
public void run() {
try {
sketch.prepare();
sketch.build(verbose);
statusNotice(_("Done compiling."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while compiling: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (Exception e) {
status.unprogress();
statusError(e);
}
status.unprogress();
toolbar.deactivate(EditorToolbar.RUN);
}
}
class DefaultStopHandler implements Runnable {
public void run() {
// TODO
// DAM: we should try to kill the compilation or upload process here.
}
}
/**
* Set the location of the sketch run window. Used by Runner to update the
* Editor about window drag events while the sketch is running.
*/
public void setSketchLocation(Point p) {
sketchWindowLocation = p;
}
/**
* Get the last location of the sketch's run window. Used by Runner to make
* the window show up in the same location as when it was last closed.
*/
public Point getSketchLocation() {
return sketchWindowLocation;
}
/**
* Implements Sketch → Stop, or pressing Stop on the toolbar.
*/
public void handleStop() { // called by menu or buttons
// toolbar.activate(EditorToolbar.STOP);
internalCloseRunner();
toolbar.deactivate(EditorToolbar.RUN);
// toolbar.deactivate(EditorToolbar.STOP);
// focus the PDE again after quitting presentation mode [toxi 030903]
toFront();
}
/**
* Deactivate the Run button. This is called by Runner to notify that the
* sketch has stopped running, usually in response to an error (or maybe
* the sketch completing and exiting?) Tools should not call this function.
* To initiate a "stop" action, call handleStop() instead.
*/
public void internalRunnerClosed() {
running = false;
toolbar.deactivate(EditorToolbar.RUN);
}
/**
* Handle internal shutdown of the runner.
*/
public void internalCloseRunner() {
running = false;
if (stopHandler != null)
try {
stopHandler.run();
} catch (Exception e) { }
}
/**
* Check if the sketch is modified and ask user to save changes.
* @return false if canceling the close/quit operation
*/
protected boolean checkModified() {
if (!sketch.isModified()) return true;
// As of Processing 1.0.10, this always happens immediately.
String prompt = I18n.format(_("Save changes to \"{0}\"? "), sketch.getName());
if (!OSUtils.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(this, prompt, _("Close"),
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
switch (result) {
case JOptionPane.YES_OPTION:
return handleSave(true);
case JOptionPane.NO_OPTION:
return true; // ok to continue
case JOptionPane.CANCEL_OPTION:
case JOptionPane.CLOSED_OPTION: // Escape key pressed
return false;
default:
throw new IllegalStateException();
}
} else {
// This code is disabled unless Java 1.5 is being used on Mac OS X
// because of a Java bug that prevents the initial value of the
// dialog from being set properly (at least on my MacBook Pro).
// The bug causes the "Don't Save" option to be the highlighted,
// blinking, default. This sucks. But I'll tell you what doesn't
// suck--workarounds for the Mac and Apple's snobby attitude about it!
// I think it's nifty that they treat their developers like dirt.
// Pane formatting adapted from the quaqua guide
JOptionPane pane =
new JOptionPane(_("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Do you want to save changes to this sketch<BR>" +
" before closing?</b>" +
"<p>If you don't save, your changes will be lost."),
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
_("Save"), _("Cancel"), _("Don't Save")
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
// on macosx, setting the destructive property places this option
// away from the others at the lefthand side
pane.putClientProperty("Quaqua.OptionPane.destructiveOption",
new Integer(2));
JDialog dialog = pane.createDialog(this, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) { // save (and close/quit)
return handleSave(true);
} else if (result == options[2]) { // don't save (still close/quit)
return true;
} else { // cancel?
return false;
}
}
}
/**
* Open a sketch from a particular path, but don't check to save changes.
* Used by Sketch.saveAs() to re-open a sketch after the "Save As"
*/
protected void handleOpenUnchecked(File file, int codeIndex,
int selStart, int selStop, int scrollPos) {
internalCloseRunner();
handleOpenInternal(file);
// Replacing a document that may be untitled. If this is an actual
// untitled document, then editor.untitled will be set by Base.
untitled = false;
sketch.setCurrentCode(codeIndex);
textarea.select(selStart, selStop);
textarea.setScrollPosition(scrollPos);
}
/**
* Second stage of open, occurs after having checked to see if the
* modifications (if any) to the previous sketch need to be saved.
*/
protected boolean handleOpenInternal(File sketchFile) {
// check to make sure that this .pde file is
// in a folder of the same name
String fileName = sketchFile.getName();
File file = SketchData.checkSketchFile(sketchFile);
if (file == null)
{
if (!fileName.endsWith(".ino") && !fileName.endsWith(".pde")) {
Base.showWarning(_("Bad file selected"),
_("Arduino can only open its own sketches\n" +
"and other files ending in .ino or .pde"), null);
return false;
} else {
String properParent =
fileName.substring(0, fileName.length() - 4);
Object[] options = { _("OK"), _("Cancel") };
String prompt = I18n.format(_("The file \"{0}\" needs to be inside\n" +
"a sketch folder named \"{1}\".\n" +
"Create this folder, move the file, and continue?"),
fileName,
properParent);
int result = JOptionPane.showOptionDialog(this,
prompt,
_("Moving"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.YES_OPTION) {
// create properly named folder
File properFolder = new File(sketchFile.getParent(), properParent);
if (properFolder.exists()) {
Base.showWarning(_("Error"),
I18n.format(
_("A folder named \"{0}\" already exists. " +
"Can't open sketch."),
properParent
),
null);
return false;
}
if (!properFolder.mkdirs()) {
//throw new IOException("Couldn't create sketch folder");
Base.showWarning(_("Error"),
_("Could not create the sketch folder."), null);
return false;
}
// copy the sketch inside
File properPdeFile = new File(properFolder, sketchFile.getName());
try {
Base.copyFile(file, properPdeFile);
} catch (IOException e) {
Base.showWarning(_("Error"), _("Could not copy to a proper location."), e);
return false;
}
// remove the original file, so user doesn't get confused
sketchFile.delete();
// update with the new path
file = properPdeFile;
} else if (result == JOptionPane.NO_OPTION) {
return false;
}
}
}
try {
sketch = new Sketch(this, file);
} catch (IOException e) {
Base.showWarning(_("Error"), _("Could not create the sketch."), e);
return false;
}
header.rebuild();
// Set the title of the window to "sketch_070752a - Processing 0126"
setTitle(I18n.format(_("{0} | Arduino {1}"), sketch.getName(),
BaseNoGui.VERSION_NAME));
// Disable untitled setting from previous document, if any
untitled = false;
// Store information on who's open and running
// (in case there's a crash or something that can't be recovered)
base.storeSketches();
Preferences.save();
// opening was successful
return true;
// } catch (Exception e) {
// e.printStackTrace();
// statusError(e);
// return false;
}
public boolean handleSave(boolean immediately) {
//stopRunner();
handleStop(); // 0136
if (untitled) {
return handleSaveAs();
// need to get the name, user might also cancel here
} else if (immediately) {
return handleSave2();
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
handleSave2();
}
});
}
return true;
}
protected boolean handleSave2() {
toolbar.activate(EditorToolbar.SAVE);
statusNotice(_("Saving..."));
boolean saved = false;
try {
saved = sketch.save();
if (saved)
statusNotice(_("Done Saving."));
else
statusEmpty();
// rebuild sketch menu in case a save-as was forced
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenus();
//sketchbook.rebuildMenusAsync();
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
// zero out the current action,
// so that checkModified2 will just do nothing
//checkModifiedMode = 0;
// this is used when another operation calls a save
}
//toolbar.clear();
toolbar.deactivate(EditorToolbar.SAVE);
return saved;
}
public boolean handleSaveAs() {
//stopRunner(); // formerly from 0135
handleStop();
toolbar.activate(EditorToolbar.SAVE);
//SwingUtilities.invokeLater(new Runnable() {
//public void run() {
statusNotice(_("Saving..."));
try {
if (sketch.saveAs()) {
statusNotice(_("Done Saving."));
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenusAsync();
} else {
statusNotice(_("Save Canceled."));
return false;
}
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
} finally {
// make sure the toolbar button deactivates
toolbar.deactivate(EditorToolbar.SAVE);
}
return true;
}
public boolean serialPrompt() {
int count = serialMenu.getItemCount();
Object[] names = new Object[count];
for (int i = 0; i < count; i++) {
names[i] = ((JCheckBoxMenuItem)serialMenu.getItem(i)).getText();
}
String result = (String)
JOptionPane.showInputDialog(this,
I18n.format(
_("Serial port {0} not found.\n" +
"Retry the upload with another serial port?"),
Preferences.get("serial.port")
),
"Serial port not found",
JOptionPane.PLAIN_MESSAGE,
null,
names,
0);
if (result == null) return false;
selectSerialPort(result);
base.onBoardOrPortChange();
return true;
}
/**
* Called by Sketch → Export.
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
* <p/>
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
/**
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
*
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
synchronized public void handleExport(final boolean usingProgrammer) {
if (Preferences.getBoolean("editor.save_on_verify")) {
if (sketch.isModified() && !sketch.isReadOnly()) {
handleSave(true);
}
}
toolbar.activate(EditorToolbar.EXPORT);
console.clear();
status.progress(_("Uploading to I/O Board..."));
new Thread(usingProgrammer ? exportAppHandler : exportHandler).start();
}
// DAM: in Arduino, this is upload
class DefaultExportHandler implements Runnable {
public void run() {
try {
if (serialMonitor != null) {
serialMonitor.close();
serialMonitor.setVisible(false);
}
uploading = true;
boolean success = sketch.exportApplet(false);
if (success) {
statusNotice(_("Done uploading."));
} else {
// error message will already be visible
}
} catch (SerialNotFoundException e) {
populatePortMenu();
if (serialMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice(_("Upload canceled."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while uploading: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivate(EditorToolbar.EXPORT);
}
}
// DAM: in Arduino, this is upload (with verbose output)
class DefaultExportAppHandler implements Runnable {
public void run() {
try {
if (serialMonitor != null) {
serialMonitor.close();
serialMonitor.setVisible(false);
}
uploading = true;
boolean success = sketch.exportApplet(true);
if (success) {
statusNotice(_("Done uploading."));
} else {
// error message will already be visible
}
} catch (SerialNotFoundException e) {
populatePortMenu();
if (serialMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice(_("Upload canceled."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while uploading: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivate(EditorToolbar.EXPORT);
}
}
protected boolean handleExportCheckModified() {
if (!sketch.isModified()) return true;
Object[] options = { _("OK"), _("Cancel") };
int result = JOptionPane.showOptionDialog(this,
_("Save changes before export?"),
_("Save"),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.OK_OPTION) {
handleSave(true);
} else {
// why it's not CANCEL_OPTION is beyond me (at least on the mac)
// but f-- it.. let's get this shite done..
//} else if (result == JOptionPane.CANCEL_OPTION) {
statusNotice(_("Export canceled, changes must first be saved."));
//toolbar.clear();
return false;
}
return true;
}
public void handleSerial() {
if (uploading) return;
if (serialMonitor != null) {
try {
serialMonitor.close();
serialMonitor.setVisible(false);
} catch (Exception e) {
// noop
}
}
BoardPort port = Base.getDiscoveryManager().find(Preferences.get("serial.port"));
if (port == null) {
statusError(I18n.format("Board at {0} is not available", Preferences.get("serial.port")));
return;
}
serialMonitor = new MonitorFactory().newMonitor(port);
serialMonitor.setIconImage(getIconImage());
boolean success = false;
do {
if (serialMonitor.requiresAuthorization() && !Preferences.has(serialMonitor.getAuthorizationKey())) {
PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, _("Type board password to access its console"));
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if (dialog.isCancelled()) {
statusNotice(_("Unable to open serial monitor"));
return;
}
Preferences.set(serialMonitor.getAuthorizationKey(), dialog.getPassword());
}
try {
serialMonitor.open();
serialMonitor.setVisible(true);
success = true;
} catch (ConnectException e) {
statusError(_("Unable to connect: is the sketch using the bridge?"));
} catch (JSchException e) {
statusError(_("Unable to connect: wrong password?"));
} catch (Exception e) {
statusError(e);
} finally {
if (serialMonitor.requiresAuthorization() && !success) {
Preferences.remove(serialMonitor.getAuthorizationKey());
}
}
} while (serialMonitor.requiresAuthorization() && !success);
}
protected void handleBurnBootloader() {
console.clear();
statusNotice(_("Burning bootloader to I/O Board (this may take a minute)..."));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Uploader uploader = new SerialUploader();
if (uploader.burnBootloader()) {
statusNotice(_("Done burning bootloader."));
} else {
statusError(_("Error while burning bootloader."));
// error message will already be visible
}
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while burning bootloader: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
statusError(e.getMessage());
} catch (Exception e) {
statusError(_("Error while burning bootloader."));
e.printStackTrace();
}
}
});
}
/**
* Handler for File → Page Setup.
*/
public void handlePageSetup() {
//printerJob = null;
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}
if (pageFormat == null) {
pageFormat = printerJob.defaultPage();
}
pageFormat = printerJob.pageDialog(pageFormat);
//System.out.println("page format is " + pageFormat);
}
/**
* Handler for File → Print.
*/
public void handlePrint() {
statusNotice(_("Printing..."));
//printerJob = null;
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}
if (pageFormat != null) {
//System.out.println("setting page format " + pageFormat);
printerJob.setPrintable(textarea.getPainter(), pageFormat);
} else {
printerJob.setPrintable(textarea.getPainter());
}
// set the name of the job to the code name
printerJob.setJobName(sketch.getCurrentCode().getPrettyName());
if (printerJob.printDialog()) {
try {
printerJob.print();
statusNotice(_("Done printing."));
} catch (PrinterException pe) {
statusError(_("Error while printing."));
pe.printStackTrace();
}
} else {
statusNotice(_("Printing canceled."));
}
//printerJob = null; // clear this out?
}
/**
* Show an error int the status bar.
*/
public void statusError(String what) {
System.err.println(what);
status.error(what);
//new Exception("deactivating RUN").printStackTrace();
toolbar.deactivate(EditorToolbar.RUN);
}
/**
* Show an exception in the editor status bar.
*/
public void statusError(Exception e) {
e.printStackTrace();
// if (e == null) {
// System.err.println("Editor.statusError() was passed a null exception.");
// return;
if (e instanceof RunnerException) {
RunnerException re = (RunnerException) e;
if (re.hasCodeIndex()) {
sketch.setCurrentCode(re.getCodeIndex());
}
if (re.hasCodeLine()) {
int line = re.getCodeLine();
// subtract one from the end so that the \n ain't included
if (line >= textarea.getLineCount()) {
// The error is at the end of this current chunk of code,
// so the last line needs to be selected.
line = textarea.getLineCount() - 1;
if (textarea.getLineText(line).length() == 0) {
// The last line may be zero length, meaning nothing to select.
// If so, back up one more line.
line
}
}
if (line < 0 || line >= textarea.getLineCount()) {
System.err.println(I18n.format(_("Bad error line: {0}"), line));
} else {
textarea.select(textarea.getLineStartOffset(line),
textarea.getLineStopOffset(line) - 1);
}
}
}
// Since this will catch all Exception types, spend some time figuring
// out which kind and try to give a better error message to the user.
String mess = e.getMessage();
if (mess != null) {
String javaLang = "java.lang.";
if (mess.indexOf(javaLang) == 0) {
mess = mess.substring(javaLang.length());
}
String rxString = "RuntimeException: ";
if (mess.indexOf(rxString) == 0) {
mess = mess.substring(rxString.length());
}
statusError(mess);
}
// e.printStackTrace();
}
/**
* Show a notice message in the editor status bar.
*/
public void statusNotice(String msg) {
status.notice(msg);
}
/**
* Clear the status area.
*/
public void statusEmpty() {
statusNotice(EMPTY);
}
protected void onBoardOrPortChange() {
Map<String, String> boardPreferences = Base.getBoardPreferences();
lineStatus.setBoardName(boardPreferences.get("name"));
lineStatus.setSerialPort(Preferences.get("serial.port"));
lineStatus.repaint();
}
/**
* Returns the edit popup menu.
*/
class TextAreaPopup extends JPopupMenu {
//private String currentDir = System.getProperty("user.dir");
private String referenceFile = null;
private JMenuItem cutItem;
private JMenuItem copyItem;
private JMenuItem discourseItem;
private JMenuItem referenceItem;
private JMenuItem openURLItem;
private JSeparator openURLItemSeparator;
private String clickedURL;
public TextAreaPopup() {
openURLItem = new JMenuItem(_("Open URL"));
openURLItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openURL(clickedURL);
}
});
add(openURLItem);
openURLItemSeparator = new JSeparator();
add(openURLItemSeparator);
cutItem = new JMenuItem(_("Cut"));
cutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCut();
}
});
add(cutItem);
copyItem = new JMenuItem(_("Copy"));
copyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCopy();
}
});
add(copyItem);
discourseItem = new JMenuItem(_("Copy for Forum"));
discourseItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleDiscourseCopy();
}
});
add(discourseItem);
discourseItem = new JMenuItem(_("Copy as HTML"));
discourseItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleHTMLCopy();
}
});
add(discourseItem);
JMenuItem item = new JMenuItem(_("Paste"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePaste();
}
});
add(item);
item = new JMenuItem(_("Select All"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSelectAll();
}
});
add(item);
addSeparator();
item = new JMenuItem(_("Comment/Uncomment"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCommentUncomment();
}
});
add(item);
item = new JMenuItem(_("Increase Indent"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(true);
}
});
add(item);
item = new JMenuItem(_("Decrease Indent"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(false);
}
});
add(item);
addSeparator();
referenceItem = new JMenuItem(_("Find in Reference"));
referenceItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleFindReference();
}
});
add(referenceItem);
}
// if no text is selected, disable copy and cut menu items
public void show(Component component, int x, int y) {
int lineNo = textarea.getLineOfOffset(textarea.xyToOffset(x, y));
int offset = textarea.xToOffset(lineNo, x);
String line = textarea.getLineText(lineNo);
clickedURL = textarea.checkClickedURL(line, offset);
if (clickedURL != null) {
openURLItem.setVisible(true);
openURLItemSeparator.setVisible(true);
} else {
openURLItem.setVisible(false);
openURLItemSeparator.setVisible(false);
}
if (textarea.isSelectionActive()) {
cutItem.setEnabled(true);
copyItem.setEnabled(true);
discourseItem.setEnabled(true);
} else {
cutItem.setEnabled(false);
copyItem.setEnabled(false);
discourseItem.setEnabled(false);
}
referenceFile = PdeKeywords.getReference(getCurrentKeyword());
referenceItem.setEnabled(referenceFile != null);
super.show(component, x, y);
}
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app;
import cc.arduino.packages.MonitorFactory;
import cc.arduino.view.*;
import cc.arduino.view.Event;
import cc.arduino.view.EventListener;
import com.jcraft.jsch.JSchException;
import jssc.SerialPortException;
import processing.app.debug.*;
import processing.app.forms.PasswordAuthorizationDialog;
import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesMapException;
import processing.app.legacy.PApplet;
import processing.app.syntax.*;
import processing.app.tools.*;
import static processing.app.I18n._;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.print.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
import cc.arduino.packages.BoardPort;
import cc.arduino.packages.Uploader;
import cc.arduino.packages.uploaders.SerialUploader;
/**
* Main editor panel for the Processing Development Environment.
*/
@SuppressWarnings("serial")
public class Editor extends JFrame implements RunnerListener {
private final static List<String> BOARD_PROTOCOLS_ORDER = Arrays.asList(new String[]{"serial", "network"});
private final static List<String> BOARD_PROTOCOLS_ORDER_TRANSLATIONS = Arrays.asList(new String[]{_("Serial ports"), _("Network ports")});
Base base;
// otherwise, if the window is resized with the message label
// set to blank, it's preferredSize() will be fukered
static protected final String EMPTY =
" " +
" " +
" ";
/** Command on Mac OS X, Ctrl on Windows and Linux */
static final int SHORTCUT_KEY_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** Command-W on Mac OS X, Ctrl-W on Windows and Linux */
static final KeyStroke WINDOW_CLOSE_KEYSTROKE =
KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK);
/** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */
static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK |
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/**
* true if this file has not yet been given a name by the user
*/
boolean untitled;
PageFormat pageFormat;
PrinterJob printerJob;
// file, sketch, and tools menus for re-inserting items
JMenu fileMenu;
JMenu sketchMenu;
JMenu toolsMenu;
int numTools = 0;
EditorToolbar toolbar;
// these menus are shared so that they needn't be rebuilt for all windows
// each time a sketch is created, renamed, or moved.
static JMenu toolbarMenu;
static JMenu sketchbookMenu;
static JMenu examplesMenu;
static JMenu importMenu;
static JMenu serialMenu;
static AbstractMonitor serialMonitor;
EditorHeader header;
EditorStatus status;
EditorConsole console;
JSplitPane splitPane;
JPanel consolePanel;
JLabel lineNumberComponent;
// currently opened program
Sketch sketch;
EditorLineStatus lineStatus;
//JEditorPane editorPane;
JEditTextArea textarea;
EditorListener listener;
// runtime information and window placement
Point sketchWindowLocation;
//Runner runtime;
JMenuItem exportAppItem;
JMenuItem saveMenuItem;
JMenuItem saveAsMenuItem;
boolean running;
//boolean presenting;
boolean uploading;
// undo fellers
JMenuItem undoItem, redoItem;
protected UndoAction undoAction;
protected RedoAction redoAction;
LastUndoableEditAwareUndoManager undo;
// used internally, and only briefly
CompoundEdit compoundEdit;
FindReplace find;
Runnable runHandler;
Runnable presentHandler;
Runnable stopHandler;
Runnable exportHandler;
Runnable exportAppHandler;
public Editor(Base ibase, File file, int[] location) throws Exception {
super("Arduino");
this.base = ibase;
Base.setIcon(this);
// Install default actions for Run, Present, etc.
resetHandlers();
// add listener to handle window close box hit event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
base.handleClose(Editor.this);
}
});
// don't close the window when clicked, the app will take care
// of that via the handleQuitInternal() methods
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
// When bringing a window to front, let the Base know
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
base.handleActivated(Editor.this);
// re-add the sub-menus that are shared by all windows
fileMenu.insert(sketchbookMenu, 2);
fileMenu.insert(examplesMenu, 3);
buildSketchMenu();
int offset = 0;
for (JMenu menu : base.getBoardsCustomMenus()) {
toolsMenu.insert(menu, numTools + offset);
offset++;
}
toolsMenu.insert(serialMenu, numTools + offset);
}
// added for 1.0.5
public void windowDeactivated(WindowEvent e) {
fileMenu.remove(sketchbookMenu);
fileMenu.remove(examplesMenu);
buildSketchMenu();
List<Component> toolsMenuItemsToRemove = new LinkedList<Component>();
for (Component menuItem : toolsMenu.getMenuComponents()) {
if (menuItem instanceof JComponent) {
Object removeOnWindowDeactivation = ((JComponent) menuItem).getClientProperty("removeOnWindowDeactivation");
if (removeOnWindowDeactivation != null && Boolean.valueOf(removeOnWindowDeactivation.toString())) {
toolsMenuItemsToRemove.add(menuItem);
}
}
}
for (Component menuItem : toolsMenuItemsToRemove) {
toolsMenu.remove(menuItem);
}
toolsMenu.remove(serialMenu);
}
});
//PdeKeywords keywords = new PdeKeywords();
//sketchbook = new Sketchbook(this);
buildMenuBar();
// For rev 0120, placing things inside a JPanel
Container contentPain = getContentPane();
contentPain.setLayout(new BorderLayout());
JPanel pain = new JPanel();
pain.setLayout(new BorderLayout());
contentPain.add(pain, BorderLayout.CENTER);
Box box = Box.createVerticalBox();
Box upper = Box.createVerticalBox();
if (toolbarMenu == null) {
toolbarMenu = new JMenu();
base.rebuildToolbarMenu(toolbarMenu);
}
toolbar = new EditorToolbar(this, toolbarMenu);
upper.add(toolbar);
header = new EditorHeader(this);
upper.add(header);
textarea = new JEditTextArea(new PdeTextAreaDefaults());
textarea.setName("editor");
textarea.setRightClickPopup(new TextAreaPopup());
textarea.setHorizontalOffset(6);
// assemble console panel, consisting of status area and the console itself
consolePanel = new JPanel();
consolePanel.setLayout(new BorderLayout());
status = new EditorStatus(this);
consolePanel.add(status, BorderLayout.NORTH);
console = new EditorConsole(this);
console.setName("console");
// windows puts an ugly border on this guy
console.setBorder(null);
consolePanel.add(console, BorderLayout.CENTER);
lineStatus = new EditorLineStatus(textarea);
consolePanel.add(lineStatus, BorderLayout.SOUTH);
upper.add(textarea);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
upper, consolePanel);
splitPane.setOneTouchExpandable(true);
// repaint child panes while resizing
splitPane.setContinuousLayout(true);
// if window increases in size, give all of increase to
// the textarea in the uppper pane
splitPane.setResizeWeight(1D);
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
splitPane.setBorder(null);
// the default size on windows is too small and kinda ugly
int dividerSize = Preferences.getInteger("editor.divider.size");
if (dividerSize != 0) {
splitPane.setDividerSize(dividerSize);
}
// the following changed from 600, 400 for netbooks
splitPane.setMinimumSize(new Dimension(600, 100));
box.add(splitPane);
// hopefully these are no longer needed w/ swing
// (har har har.. that was wishful thinking)
listener = new EditorListener(this, textarea);
pain.add(box);
// get shift down/up events so we can show the alt version of toolbar buttons
textarea.addKeyListener(toolbar);
pain.setTransferHandler(new FileDropHandler());
// System.out.println("t1");
// Finish preparing Editor (formerly found in Base)
pack();
// System.out.println("t2");
// Set the window bounds and the divider location before setting it visible
setPlacement(location);
// Set the minimum size for the editor window
setMinimumSize(new Dimension(Preferences.getInteger("editor.window.width.min"),
Preferences.getInteger("editor.window.height.min")));
// System.out.println("t3");
// Bring back the general options for the editor
applyPreferences();
// System.out.println("t4");
// Open the document that was passed in
boolean loaded = handleOpenInternal(file);
if (!loaded) sketch = null;
// System.out.println("t5");
// All set, now show the window
//setVisible(true);
}
/**
* Handles files dragged & dropped from the desktop and into the editor
* window. Dragging files into the editor window is the same as using
* "Sketch → Add File" for each file.
*/
class FileDropHandler extends TransferHandler {
public boolean canImport(JComponent dest, DataFlavor[] flavors) {
return true;
}
@SuppressWarnings("unchecked")
public boolean importData(JComponent src, Transferable transferable) {
int successful = 0;
try {
DataFlavor uriListFlavor =
new DataFlavor("text/uri-list;class=java.lang.String");
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
List<File> list = (List<File>)
transferable.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : list) {
if (sketch.addFile(file)) {
successful++;
}
}
} else if (transferable.isDataFlavorSupported(uriListFlavor)) {
// Some platforms (Mac OS X and Linux, when this began) preferred
// this method of moving files.
String data = (String)transferable.getTransferData(uriListFlavor);
String[] pieces = PApplet.splitTokens(data, "\r\n");
for (int i = 0; i < pieces.length; i++) {
if (pieces[i].startsWith("#")) continue;
String path = null;
if (pieces[i].startsWith("file:
path = pieces[i].substring(7);
} else if (pieces[i].startsWith("file:/")) {
path = pieces[i].substring(5);
}
if (sketch.addFile(new File(path))) {
successful++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
if (successful == 0) {
statusError(_("No files were added to the sketch."));
} else if (successful == 1) {
statusNotice(_("One file added to the sketch."));
} else {
statusNotice(
I18n.format(_("{0} files added to the sketch."), successful));
}
return true;
}
}
protected void setPlacement(int[] location) {
setBounds(location[0], location[1], location[2], location[3]);
if (location[4] != 0) {
splitPane.setDividerLocation(location[4]);
}
}
protected int[] getPlacement() {
int[] location = new int[5];
// Get the dimensions of the Frame
Rectangle bounds = getBounds();
location[0] = bounds.x;
location[1] = bounds.y;
location[2] = bounds.width;
location[3] = bounds.height;
// Get the current placement of the divider
location[4] = splitPane.getDividerLocation();
return location;
}
/**
* Hack for #@#)$(* Mac OS X 10.2.
* <p/>
* This appears to only be required on OS X 10.2, and is not
* even being called on later versions of OS X or Windows.
*/
// public Dimension getMinimumSize() {
// //System.out.println("getting minimum size");
// return new Dimension(500, 550);
/**
* Read and apply new values from the preferences, either because
* the app is just starting up, or the user just finished messing
* with things in the Preferences window.
*/
protected void applyPreferences() {
// apply the setting for 'use external editor'
boolean external = Preferences.getBoolean("editor.external");
textarea.setEditable(!external);
saveMenuItem.setEnabled(!external);
saveAsMenuItem.setEnabled(!external);
textarea.setDisplayLineNumbers(Preferences.getBoolean("editor.linenumbers"));
TextAreaPainter painter = textarea.getPainter();
if (external) {
// disable line highlight and turn off the caret when disabling
Color color = Theme.getColor("editor.external.bgcolor");
painter.setBackground(color);
painter.setLineHighlightEnabled(false);
textarea.setCaretVisible(false);
} else {
Color color = Theme.getColor("editor.bgcolor");
painter.setBackground(color);
boolean highlight = Preferences.getBoolean("editor.linehighlight");
painter.setLineHighlightEnabled(highlight);
textarea.setCaretVisible(true);
}
// apply changes to the font size for the editor
//TextAreaPainter painter = textarea.getPainter();
painter.setFont(Preferences.getFont("editor.font"));
//Font font = painter.getFont();
//textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36));
// in case tab expansion stuff has changed
listener.applyPreferences();
// in case moved to a new location
// For 0125, changing to async version (to be implemented later)
//sketchbook.rebuildMenus();
// For 0126, moved into Base, which will notify all editors.
//base.rebuildMenusAsync();
}
protected void buildMenuBar() throws Exception {
JMenuBar menubar = new JMenuBar();
menubar.add(buildFileMenu());
menubar.add(buildEditMenu());
menubar.add(buildSketchMenu());
menubar.add(buildToolsMenu());
menubar.add(buildHelpMenu());
setJMenuBar(menubar);
}
protected JMenu buildFileMenu() {
JMenuItem item;
fileMenu = new JMenu(_("File"));
item = newJMenuItem(_("New"), 'N');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleNew();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
item = Editor.newJMenuItem(_("Open..."), 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
base.handleOpenPrompt();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
fileMenu.add(item);
if (sketchbookMenu == null) {
sketchbookMenu = new JMenu(_("Sketchbook"));
MenuScroller.setScrollerFor(sketchbookMenu);
base.rebuildSketchbookMenu(sketchbookMenu);
}
fileMenu.add(sketchbookMenu);
if (examplesMenu == null) {
examplesMenu = new JMenu(_("Examples"));
MenuScroller.setScrollerFor(examplesMenu);
base.rebuildExamplesMenu(examplesMenu);
}
fileMenu.add(examplesMenu);
item = Editor.newJMenuItem(_("Close"), 'W');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleClose(Editor.this);
}
});
fileMenu.add(item);
saveMenuItem = newJMenuItem(_("Save"), 'S');
saveMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSave(false);
}
});
fileMenu.add(saveMenuItem);
saveAsMenuItem = newJMenuItemShift(_("Save As..."), 'S');
saveAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSaveAs();
}
});
fileMenu.add(saveAsMenuItem);
item = newJMenuItem(_("Upload"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(false);
}
});
fileMenu.add(item);
item = newJMenuItemShift(_("Upload Using Programmer"), 'U');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleExport(true);
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItemShift(_("Page Setup"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePageSetup();
}
});
fileMenu.add(item);
item = newJMenuItem(_("Print"), 'P');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePrint();
}
});
fileMenu.add(item);
// macosx already has its own preferences and quit menu
if (!OSUtils.isMacOS()) {
fileMenu.addSeparator();
item = newJMenuItem(_("Preferences"), ',');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handlePrefs();
}
});
fileMenu.add(item);
fileMenu.addSeparator();
item = newJMenuItem(_("Quit"), 'Q');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleQuit();
}
});
fileMenu.add(item);
}
return fileMenu;
}
protected JMenu buildSketchMenu() {
if (sketchMenu == null) {
sketchMenu = new JMenu(_("Sketch"));
} else {
sketchMenu.removeAll();
}
JMenuItem item = newJMenuItem(_("Verify / Compile"), 'R');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleRun(false);
}
});
sketchMenu.add(item);
// item = newJMenuItemShift("Verify / Compile (verbose)", 'R');
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleRun(true);
// sketchMenu.add(item);
// item = new JMenuItem("Stop");
// item.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// handleStop();
// sketchMenu.add(item);
sketchMenu.addSeparator();
item = newJMenuItem(_("Show Sketch Folder"), 'K');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openFolder(sketch.getFolder());
}
});
sketchMenu.add(item);
item.setEnabled(Base.openFolderAvailable());
if (importMenu == null) {
importMenu = new JMenu(_("Include Library"));
MenuScroller.setScrollerFor(importMenu);
base.rebuildImportMenu(importMenu);
}
sketchMenu.add(importMenu);
item = new JMenuItem(_("Add File..."));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sketch.handleAddFile();
}
});
sketchMenu.add(item);
return sketchMenu;
}
protected JMenu buildToolsMenu() throws Exception {
toolsMenu = new JMenu(_("Tools"));
addInternalTools(toolsMenu);
JMenuItem item = newJMenuItemShift(_("Serial Monitor"), 'M');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSerial();
}
});
toolsMenu.add(item);
addTools(toolsMenu, Base.getToolsFolder());
File sketchbookTools = new File(Base.getSketchbookFolder(), "tools");
addTools(toolsMenu, sketchbookTools);
toolsMenu.addSeparator();
numTools = toolsMenu.getItemCount();
// XXX: DAM: these should probably be implemented using the Tools plugin
// API, if possible (i.e. if it supports custom actions, etc.)
for (JMenu menu : base.getBoardsCustomMenus()) {
toolsMenu.add(menu);
}
if (serialMenu == null)
serialMenu = new JMenu(_("Port"));
populatePortMenu();
toolsMenu.add(serialMenu);
toolsMenu.addSeparator();
JMenu programmerMenu = new JMenu(_("Programmer"));
base.rebuildProgrammerMenu(programmerMenu);
toolsMenu.add(programmerMenu);
item = new JMenuItem(_("Burn Bootloader"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleBurnBootloader();
}
});
toolsMenu.add(item);
toolsMenu.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {}
public void menuDeselected(MenuEvent e) {}
public void menuSelected(MenuEvent e) {
//System.out.println("Tools menu selected.");
populatePortMenu();
}
});
return toolsMenu;
}
protected void addTools(JMenu menu, File sourceFolder) {
if (sourceFolder == null)
return;
Map<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>();
File[] folders = sourceFolder.listFiles(new FileFilter() {
public boolean accept(File folder) {
if (folder.isDirectory()) {
//System.out.println("checking " + folder);
File subfolder = new File(folder, "tool");
return subfolder.exists();
}
return false;
}
});
if (folders == null || folders.length == 0) {
return;
}
for (int i = 0; i < folders.length; i++) {
File toolDirectory = new File(folders[i], "tool");
try {
// add dir to classpath for .classes
//urlList.add(toolDirectory.toURL());
// add .jar files to classpath
File[] archives = toolDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".jar") ||
name.toLowerCase().endsWith(".zip"));
}
});
URL[] urlList = new URL[archives.length];
for (int j = 0; j < urlList.length; j++) {
urlList[j] = archives[j].toURI().toURL();
}
URLClassLoader loader = new URLClassLoader(urlList);
String className = null;
for (int j = 0; j < archives.length; j++) {
className = findClassInZipFile(folders[i].getName(), archives[j]);
if (className != null) break;
}
// If no class name found, just move on.
if (className == null) continue;
Class<?> toolClass = Class.forName(className, true, loader);
final Tool tool = (Tool) toolClass.newInstance();
tool.init(Editor.this);
String title = tool.getMenuTitle();
JMenuItem item = new JMenuItem(title);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
//new Thread(tool).start();
}
});
//menu.add(item);
toolItems.put(title, item);
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<String> toolList = new ArrayList<String>(toolItems.keySet());
if (toolList.size() == 0) return;
menu.addSeparator();
Collections.sort(toolList);
for (String title : toolList) {
menu.add((JMenuItem) toolItems.get(title));
}
}
protected String findClassInZipFile(String base, File file) {
// Class file to search for
String classFileName = "/" + base + ".class";
ZipFile zipFile = null;
try {
zipFile = new ZipFile(file);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (!entry.isDirectory()) {
String name = entry.getName();
//System.out.println("entry: " + name);
if (name.endsWith(classFileName)) {
//int slash = name.lastIndexOf('/');
//String packageName = (slash == -1) ? "" : name.substring(0, slash);
// Remove .class and convert slashes to periods.
return name.substring(0, name.length() - 6).replace('/', '.');
}
}
}
} catch (IOException e) {
//System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")");
e.printStackTrace();
} finally {
if (zipFile != null)
try {
zipFile.close();
} catch (IOException e) {
}
}
return null;
}
protected JMenuItem createToolMenuItem(String className) {
try {
Class<?> toolClass = Class.forName(className);
final Tool tool = (Tool) toolClass.newInstance();
JMenuItem item = new JMenuItem(tool.getMenuTitle());
tool.init(Editor.this);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(tool);
}
});
return item;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected JMenu addInternalTools(JMenu menu) {
JMenuItem item;
item = createToolMenuItem("cc.arduino.packages.formatter.AStyle");
item.setName("menuToolsAutoFormat");
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers));
menu.add(item);
//menu.add(createToolMenuItem("processing.app.tools.CreateFont"));
//menu.add(createToolMenuItem("processing.app.tools.ColorSelector"));
menu.add(createToolMenuItem("processing.app.tools.Archiver"));
menu.add(createToolMenuItem("processing.app.tools.FixEncoding"));
// // These are temporary entries while Android mode is being worked out.
// // The mode will not be in the tools menu, and won't involve a cmd-key
// if (!Base.RELEASE) {
// item = createToolMenuItem("processing.app.tools.android.AndroidTool");
// item.setAccelerator(KeyStroke.getKeyStroke('D', modifiers));
// menu.add(item);
// menu.add(createToolMenuItem("processing.app.tools.android.Reset"));
return menu;
}
class SerialMenuListener implements ActionListener {
private final Frame parent;
private final String serialPort;
private final String warning;
public SerialMenuListener(Frame parent, String serialPort, String warning) {
this.parent = parent;
this.serialPort = serialPort;
this.warning = warning;
}
public void actionPerformed(ActionEvent e) {
selectSerialPort(serialPort);
base.onBoardOrPortChange();
if (warning != null && !Preferences.getBoolean("uncertifiedBoardWarning_dontShowMeAgain")) {
SwingUtilities.invokeLater(new ShowUncertifiedBoardWarning(parent));
}
}
}
protected void selectSerialPort(String name) {
if(serialMenu == null) {
System.out.println(_("serialMenu is null"));
return;
}
if (name == null) {
System.out.println(_("name is null"));
return;
}
JCheckBoxMenuItem selection = null;
for (int i = 0; i < serialMenu.getItemCount(); i++) {
JMenuItem menuItem = serialMenu.getItem(i);
if (!(menuItem instanceof JCheckBoxMenuItem)) {
continue;
}
JCheckBoxMenuItem checkBoxMenuItem = ((JCheckBoxMenuItem) menuItem);
if (checkBoxMenuItem == null) {
System.out.println(_("name is null"));
continue;
}
checkBoxMenuItem.setState(false);
if (name.equals(checkBoxMenuItem.getText())) selection = checkBoxMenuItem;
}
if (selection != null) selection.setState(true);
//System.out.println(item.getLabel());
Base.selectSerialPort(name);
if (serialMonitor != null) {
try {
serialMonitor.close();
serialMonitor.setVisible(false);
} catch (Exception e) {
// ignore
}
}
onBoardOrPortChange();
//System.out.println("set to " + get("serial.port"));
}
protected void populatePortMenu() {
serialMenu.removeAll();
String selectedPort = Preferences.get("serial.port");
List<BoardPort> ports = Base.getDiscoveryManager().discovery();
ports = Base.getPlatform().filterPorts(ports, Preferences.getBoolean("serial.ports.showall"));
Collections.sort(ports, new Comparator<BoardPort>() {
@Override
public int compare(BoardPort o1, BoardPort o2) {
return BOARD_PROTOCOLS_ORDER.indexOf(o1.getProtocol()) - BOARD_PROTOCOLS_ORDER.indexOf(o2.getProtocol());
}
});
String lastProtocol = null;
String lastProtocolTranslated;
for (BoardPort port : ports) {
if (lastProtocol == null || !port.getProtocol().equals(lastProtocol)) {
if (lastProtocol != null) {
serialMenu.addSeparator();
}
lastProtocol = port.getProtocol();
if (BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol()) != -1) {
lastProtocolTranslated = BOARD_PROTOCOLS_ORDER_TRANSLATIONS.get(BOARD_PROTOCOLS_ORDER.indexOf(port.getProtocol()));
} else {
lastProtocolTranslated = port.getProtocol();
}
serialMenu.add(new JMenuItem(_(lastProtocolTranslated)));
}
String address = port.getAddress();
String label = port.getLabel();
JCheckBoxMenuItem item = new JCheckBoxMenuItem(label, address.equals(selectedPort));
item.addActionListener(new SerialMenuListener(this, address, port.getPrefs().get("warning")));
serialMenu.add(item);
}
serialMenu.setEnabled(serialMenu.getMenuComponentCount() > 0);
}
protected JMenu buildHelpMenu() {
// To deal with a Mac OS X 10.5 bug, add an extra space after the name
// so that the OS doesn't try to insert its slow help menu.
JMenu menu = new JMenu(_("Help"));
JMenuItem item;
item = new JMenuItem(_("Getting Started"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showGettingStarted();
}
});
menu.add(item);
item = new JMenuItem(_("Environment"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showEnvironment();
}
});
menu.add(item);
item = new JMenuItem(_("Troubleshooting"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showTroubleshooting();
}
});
menu.add(item);
item = new JMenuItem(_("Reference"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showReference();
}
});
menu.add(item);
item = newJMenuItemShift(_("Find in Reference"), 'F');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// if (textarea.isSelectionActive()) {
// handleFindReference();
handleFindReference();
}
});
menu.add(item);
item = new JMenuItem(_("Frequently Asked Questions"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.showFAQ();
}
});
menu.add(item);
item = new JMenuItem(_("Visit Arduino.cc"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openURL(_("http://arduino.cc/"));
}
});
menu.add(item);
// macosx already has its own about menu
if (!OSUtils.isMacOS()) {
menu.addSeparator();
item = new JMenuItem(_("About Arduino"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
base.handleAbout();
}
});
menu.add(item);
}
return menu;
}
protected JMenu buildEditMenu() {
JMenu menu = new JMenu(_("Edit"));
menu.setName("menuEdit");
JMenuItem item;
undoItem = newJMenuItem(_("Undo"), 'Z');
undoItem.setName("menuEditUndo");
undoItem.addActionListener(undoAction = new UndoAction());
menu.add(undoItem);
if (!OSUtils.isMacOS()) {
redoItem = newJMenuItem(_("Redo"), 'Y');
} else {
redoItem = newJMenuItemShift(_("Redo"), 'Z');
}
redoItem.setName("menuEditRedo");
redoItem.addActionListener(redoAction = new RedoAction());
menu.add(redoItem);
menu.addSeparator();
// TODO "cut" and "copy" should really only be enabled
// if some text is currently selected
item = newJMenuItem(_("Cut"), 'X');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCut();
}
});
menu.add(item);
item = newJMenuItem(_("Copy"), 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.copy();
}
});
menu.add(item);
item = newJMenuItemShift(_("Copy for Forum"), 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
new DiscourseFormat(Editor.this, false).show();
}
});
menu.add(item);
item = newJMenuItemAlt(_("Copy as HTML"), 'C');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
new DiscourseFormat(Editor.this, true).show();
}
});
menu.add(item);
item = newJMenuItem(_("Paste"), 'V');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.paste();
sketch.setModified(true);
}
});
menu.add(item);
item = newJMenuItem(_("Select All"), 'A');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.selectAll();
}
});
menu.add(item);
menu.addSeparator();
item = newJMenuItem(_("Comment/Uncomment"), '/');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCommentUncomment();
}
});
menu.add(item);
item = newJMenuItem(_("Increase Indent"), ']');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(true);
}
});
menu.add(item);
item = newJMenuItem(_("Decrease Indent"), '[');
item.setName("menuDecreaseIndent");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(false);
}
});
menu.add(item);
menu.addSeparator();
item = newJMenuItem(_("Find..."), 'F');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find == null) {
find = new FindReplace(Editor.this);
}
if (getSelectedText()!= null) find.setFindText( getSelectedText() );
//new FindReplace(Editor.this).show();
find.setLocationRelativeTo(Editor.this);
find.setVisible(true);
//find.setVisible(true);
}
});
menu.add(item);
// TODO find next should only be enabled after a
// search has actually taken place
item = newJMenuItem(_("Find Next"), 'G');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find != null) {
find.findNext();
}
}
});
menu.add(item);
item = newJMenuItemShift(_("Find Previous"), 'G');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find != null) {
find.findPrevious();
}
}
});
menu.add(item);
item = newJMenuItem(_("Use Selection For Find"), 'E');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (find == null) {
find = new FindReplace(Editor.this);
}
find.setLocationRelativeTo(Editor.this);
find.setFindText( getSelectedText() );
}
});
menu.add(item);
return menu;
}
/**
* A software engineer, somewhere, needs to have his abstraction
* taken away. In some countries they jail or beat people for writing
* the sort of API that would require a five line helper function
* just to set the command key for a menu item.
*/
static public JMenuItem newJMenuItem(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK));
return menuItem;
}
/**
* Like newJMenuItem() but adds shift as a modifier for the key command.
*/
static public JMenuItem newJMenuItemShift(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK | ActionEvent.SHIFT_MASK));
return menuItem;
}
/**
* Same as newJMenuItem(), but adds the ALT (on Linux and Windows)
* or OPTION (on Mac OS X) key as a modifier.
*/
static public JMenuItem newJMenuItemAlt(String title, int what) {
JMenuItem menuItem = new JMenuItem(title);
menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK));
return menuItem;
}
class UndoAction extends AbstractAction {
public UndoAction() {
super("Undo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.undo();
sketch.setModified(true);
} catch (CannotUndoException ex) {
//System.out.println("Unable to undo: " + ex);
//ex.printStackTrace();
}
if (undo.getLastUndoableEdit() != null && undo.getLastUndoableEdit() instanceof CaretAwareUndoableEdit) {
CaretAwareUndoableEdit undoableEdit = (CaretAwareUndoableEdit) undo.getLastUndoableEdit();
int nextCaretPosition = undoableEdit.getCaretPosition() - 1;
if (nextCaretPosition >= 0 && textarea.getDocumentLength() > nextCaretPosition) {
textarea.setCaretPosition(nextCaretPosition);
}
}
updateUndoState();
redoAction.updateRedoState();
}
protected void updateUndoState() {
if (undo.canUndo()) {
this.setEnabled(true);
undoItem.setEnabled(true);
undoItem.setText(undo.getUndoPresentationName());
putValue(Action.NAME, undo.getUndoPresentationName());
} else {
this.setEnabled(false);
undoItem.setEnabled(false);
undoItem.setText(_("Undo"));
putValue(Action.NAME, "Undo");
}
}
}
class RedoAction extends AbstractAction {
public RedoAction() {
super("Redo");
this.setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.redo();
sketch.setModified(true);
} catch (CannotRedoException ex) {
//System.out.println("Unable to redo: " + ex);
//ex.printStackTrace();
}
if (undo.getLastUndoableEdit() != null && undo.getLastUndoableEdit() instanceof CaretAwareUndoableEdit) {
CaretAwareUndoableEdit undoableEdit = (CaretAwareUndoableEdit) undo.getLastUndoableEdit();
textarea.setCaretPosition(undoableEdit.getCaretPosition());
}
updateRedoState();
undoAction.updateUndoState();
}
protected void updateRedoState() {
if (undo.canRedo()) {
redoItem.setEnabled(true);
redoItem.setText(undo.getRedoPresentationName());
putValue(Action.NAME, undo.getRedoPresentationName());
} else {
this.setEnabled(false);
redoItem.setEnabled(false);
redoItem.setText(_("Redo"));
putValue(Action.NAME, "Redo");
}
}
}
// these will be done in a more generic way soon, more like:
// setHandler("action name", Runnable);
// but for the time being, working out the kinks of how many things to
// abstract from the editor in this fashion.
public void setHandlers(Runnable runHandler, Runnable presentHandler,
Runnable stopHandler,
Runnable exportHandler, Runnable exportAppHandler) {
this.runHandler = runHandler;
this.presentHandler = presentHandler;
this.stopHandler = stopHandler;
this.exportHandler = exportHandler;
this.exportAppHandler = exportAppHandler;
}
public void resetHandlers() {
runHandler = new BuildHandler();
presentHandler = new BuildHandler(true);
stopHandler = new DefaultStopHandler();
exportHandler = new DefaultExportHandler();
exportAppHandler = new DefaultExportAppHandler();
}
/**
* Gets the current sketch object.
*/
public Sketch getSketch() {
return sketch;
}
/**
* Get the JEditTextArea object for use (not recommended). This should only
* be used in obscure cases that really need to hack the internals of the
* JEditTextArea. Most tools should only interface via the get/set functions
* found in this class. This will maintain compatibility with future releases,
* which will not use JEditTextArea.
*/
public JEditTextArea getTextArea() {
return textarea;
}
/**
* Get the contents of the current buffer. Used by the Sketch class.
*/
public String getText() {
return textarea.getText();
}
/**
* Get a range of text from the current buffer.
*/
public String getText(int start, int stop) {
return textarea.getText(start, stop - start);
}
/**
* Replace the entire contents of the front-most tab.
*/
public void setText(String what) {
startCompoundEdit();
textarea.setText(what);
stopCompoundEdit();
}
public void insertText(String what) {
startCompoundEdit();
int caret = getCaretOffset();
setSelection(caret, caret);
textarea.setSelectedText(what);
stopCompoundEdit();
}
/**
* Called to update the text but not switch to a different set of code
* (which would affect the undo manager).
*/
// public void setText2(String what, int start, int stop) {
// beginCompoundEdit();
// textarea.setText(what);
// endCompoundEdit();
// // make sure that a tool isn't asking for a bad location
// start = Math.max(0, Math.min(start, textarea.getDocumentLength()));
// stop = Math.max(0, Math.min(start, textarea.getDocumentLength()));
// textarea.select(start, stop);
// textarea.requestFocus(); // get the caret blinking
public String getSelectedText() {
return textarea.getSelectedText();
}
public void setSelectedText(String what) {
textarea.setSelectedText(what);
}
public void setSelection(int start, int stop) {
// make sure that a tool isn't asking for a bad location
start = PApplet.constrain(start, 0, textarea.getDocumentLength());
stop = PApplet.constrain(stop, 0, textarea.getDocumentLength());
textarea.select(start, stop);
}
/**
* Get the position (character offset) of the caret. With text selected,
* this will be the last character actually selected, no matter the direction
* of the selection. That is, if the user clicks and drags to select lines
* 7 up to 4, then the caret position will be somewhere on line four.
*/
public int getCaretOffset() {
return textarea.getCaretPosition();
}
/**
* True if some text is currently selected.
*/
public boolean isSelectionActive() {
return textarea.isSelectionActive();
}
/**
* Get the beginning point of the current selection.
*/
public int getSelectionStart() {
return textarea.getSelectionStart();
}
/**
* Get the end point of the current selection.
*/
public int getSelectionStop() {
return textarea.getSelectionStop();
}
/**
* Get text for a specified line.
*/
public String getLineText(int line) {
return textarea.getLineText(line);
}
/**
* Replace the text on a specified line.
*/
public void setLineText(int line, String what) {
startCompoundEdit();
textarea.select(getLineStartOffset(line), getLineStopOffset(line));
textarea.setSelectedText(what);
stopCompoundEdit();
}
/**
* Get character offset for the start of a given line of text.
*/
public int getLineStartOffset(int line) {
return textarea.getLineStartOffset(line);
}
/**
* Get character offset for end of a given line of text.
*/
public int getLineStopOffset(int line) {
return textarea.getLineStopOffset(line);
}
/**
* Get the number of lines in the currently displayed buffer.
*/
public int getLineCount() {
return textarea.getLineCount();
}
/**
* Use before a manipulating text to group editing operations together as a
* single undo. Use stopCompoundEdit() once finished.
*/
public void startCompoundEdit() {
compoundEdit = new CompoundEdit();
}
/**
* Use with startCompoundEdit() to group edit operations in a single undo.
*/
public void stopCompoundEdit() {
compoundEdit.end();
undo.addEdit(compoundEdit);
undoAction.updateUndoState();
redoAction.updateRedoState();
compoundEdit = null;
}
public int getScrollPosition() {
return textarea.getScrollPosition();
}
/**
* Switch between tabs, this swaps out the Document object
* that's currently being manipulated.
*/
protected void setCode(SketchCodeDocument codeDoc) {
SyntaxDocument document = (SyntaxDocument) codeDoc.getDocument();
if (document == null) { // this document not yet inited
document = new SyntaxDocument();
codeDoc.setDocument(document);
// turn on syntax highlighting
document.setTokenMarker(new PdeKeywords());
// insert the program text into the document object
try {
document.insertString(0, codeDoc.getCode().getProgram(), null);
} catch (BadLocationException bl) {
bl.printStackTrace();
}
// set up this guy's own undo manager
// code.undo = new UndoManager();
// connect the undo listener to the editor
document.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent e) {
if (compoundEdit != null) {
compoundEdit.addEdit(new CaretAwareUndoableEdit(e.getEdit(), textarea));
} else if (undo != null) {
undo.addEdit(new CaretAwareUndoableEdit(e.getEdit(), textarea));
}
if (compoundEdit != null || undo != null) {
sketch.setModified(true);
undoAction.updateUndoState();
redoAction.updateRedoState();
}
}
});
}
// update the document object that's in use
textarea.setDocument(document,
codeDoc.getSelectionStart(), codeDoc.getSelectionStop(),
codeDoc.getScrollPosition());
textarea.requestFocus(); // get the caret blinking
this.undo = codeDoc.getUndo();
undoAction.updateUndoState();
redoAction.updateRedoState();
}
/**
* Implements Edit → Cut.
*/
public void handleCut() {
textarea.cut();
sketch.setModified(true);
}
/**
* Implements Edit → Copy.
*/
public void handleCopy() {
textarea.copy();
}
protected void handleDiscourseCopy() {
new DiscourseFormat(Editor.this, false).show();
}
protected void handleHTMLCopy() {
new DiscourseFormat(Editor.this, true).show();
}
/**
* Implements Edit → Paste.
*/
public void handlePaste() {
textarea.paste();
sketch.setModified(true);
}
/**
* Implements Edit → Select All.
*/
public void handleSelectAll() {
textarea.selectAll();
}
protected void handleCommentUncomment() {
startCompoundEdit();
int startLine = textarea.getSelectionStartLine();
int stopLine = textarea.getSelectionStopLine();
int lastLineStart = textarea.getLineStartOffset(stopLine);
int selectionStop = textarea.getSelectionStop();
// If the selection ends at the beginning of the last line,
// then don't (un)comment that line.
if (selectionStop == lastLineStart) {
// Though if there's no selection, don't do that
if (textarea.isSelectionActive()) {
stopLine
}
}
// If the text is empty, ignore the user.
// Also ensure that all lines are commented (not just the first)
// when determining whether to comment or uncomment.
int length = textarea.getDocumentLength();
boolean commented = true;
for (int i = startLine; commented && (i <= stopLine); i++) {
int pos = textarea.getLineStartOffset(i);
if (pos + 2 > length) {
commented = false;
} else {
// Check the first two characters to see if it's already a comment.
String begin = textarea.getText(pos, 2);
//System.out.println("begin is '" + begin + "'");
commented = begin.equals("
}
}
for (int line = startLine; line <= stopLine; line++) {
int location = textarea.getLineStartOffset(line);
if (commented) {
// remove a comment
textarea.select(location, location+2);
if (textarea.getSelectedText().equals("
textarea.setSelectedText("");
}
} else {
// add a comment
textarea.select(location, location);
textarea.setSelectedText("
}
}
// Subtract one from the end, otherwise selects past the current line.
// (Which causes subsequent calls to keep expanding the selection)
textarea.select(textarea.getLineStartOffset(startLine),
textarea.getLineStopOffset(stopLine) - 1);
stopCompoundEdit();
}
protected void handleIndentOutdent(boolean indent) {
int tabSize = Preferences.getInteger("editor.tabs.size");
String tabString = Editor.EMPTY.substring(0, tabSize);
startCompoundEdit();
int startLine = textarea.getSelectionStartLine();
int stopLine = textarea.getSelectionStopLine();
// If the selection ends at the beginning of the last line,
// then don't (un)comment that line.
int lastLineStart = textarea.getLineStartOffset(stopLine);
int selectionStop = textarea.getSelectionStop();
if (selectionStop == lastLineStart) {
// Though if there's no selection, don't do that
if (textarea.isSelectionActive()) {
stopLine
}
}
for (int line = startLine; line <= stopLine; line++) {
int location = textarea.getLineStartOffset(line);
if (indent) {
textarea.select(location, location);
textarea.setSelectedText(tabString);
} else { // outdent
textarea.select(location, location + tabSize);
// Don't eat code if it's not indented
if (textarea.getSelectedText().equals(tabString)) {
textarea.setSelectedText("");
}
}
}
// Subtract one from the end, otherwise selects past the current line.
// (Which causes subsequent calls to keep expanding the selection)
textarea.select(textarea.getLineStartOffset(startLine),
textarea.getLineStopOffset(stopLine) - 1);
stopCompoundEdit();
}
protected String getCurrentKeyword() {
String text = "";
if (textarea.getSelectedText() != null)
text = textarea.getSelectedText().trim();
try {
int current = textarea.getCaretPosition();
int startOffset = 0;
int endIndex = current;
String tmp = textarea.getDocument().getText(current, 1);
// TODO probably a regexp that matches Arduino lang special chars
// already exists.
String regexp = "[\\s\\n();\\\\.!='\\[\\]{}]";
while (!tmp.matches(regexp)) {
endIndex++;
tmp = textarea.getDocument().getText(endIndex, 1);
}
// For some reason document index start at 2.
// if( current - start < 2 ) return;
tmp = "";
while (!tmp.matches(regexp)) {
startOffset++;
if (current - startOffset < 0) {
tmp = textarea.getDocument().getText(0, 1);
break;
} else
tmp = textarea.getDocument().getText(current - startOffset, 1);
}
startOffset
int length = endIndex - current + startOffset;
text = textarea.getDocument().getText(current - startOffset, length);
} catch (BadLocationException bl) {
bl.printStackTrace();
}
return text;
}
protected void handleFindReference() {
String text = getCurrentKeyword();
String referenceFile = PdeKeywords.getReference(text);
if (referenceFile == null) {
statusNotice(I18n.format(_("No reference available for \"{0}\""), text));
} else {
Base.showReference("Reference/" + referenceFile);
}
}
/**
* Implements Sketch → Run.
* @param verbose Set true to run with verbose output.
*/
public void handleRun(final boolean verbose) {
internalCloseRunner();
if (Preferences.getBoolean("editor.save_on_verify")) {
if (sketch.isModified() && !sketch.isReadOnly()) {
handleSave(true);
}
}
running = true;
toolbar.activate(EditorToolbar.RUN);
status.progress(_("Compiling sketch..."));
// do this to advance/clear the terminal window / dos prompt / etc
for (int i = 0; i < 10; i++) System.out.println();
// clear the console on each run, unless the user doesn't want to
if (Preferences.getBoolean("console.auto_clear")) {
console.clear();
}
// Cannot use invokeLater() here, otherwise it gets
// placed on the event thread and causes a hang--bad idea all around.
new Thread(verbose ? presentHandler : runHandler).start();
}
class BuildHandler implements Runnable {
private final boolean verbose;
public BuildHandler() {
this(false);
}
public BuildHandler(boolean verbose) {
this.verbose = verbose;
}
@Override
public void run() {
try {
sketch.prepare();
sketch.build(verbose);
statusNotice(_("Done compiling."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while compiling: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (Exception e) {
status.unprogress();
statusError(e);
}
status.unprogress();
toolbar.deactivate(EditorToolbar.RUN);
}
}
class DefaultStopHandler implements Runnable {
public void run() {
// TODO
// DAM: we should try to kill the compilation or upload process here.
}
}
/**
* Set the location of the sketch run window. Used by Runner to update the
* Editor about window drag events while the sketch is running.
*/
public void setSketchLocation(Point p) {
sketchWindowLocation = p;
}
/**
* Get the last location of the sketch's run window. Used by Runner to make
* the window show up in the same location as when it was last closed.
*/
public Point getSketchLocation() {
return sketchWindowLocation;
}
/**
* Implements Sketch → Stop, or pressing Stop on the toolbar.
*/
public void handleStop() { // called by menu or buttons
// toolbar.activate(EditorToolbar.STOP);
internalCloseRunner();
toolbar.deactivate(EditorToolbar.RUN);
// toolbar.deactivate(EditorToolbar.STOP);
// focus the PDE again after quitting presentation mode [toxi 030903]
toFront();
}
/**
* Deactivate the Run button. This is called by Runner to notify that the
* sketch has stopped running, usually in response to an error (or maybe
* the sketch completing and exiting?) Tools should not call this function.
* To initiate a "stop" action, call handleStop() instead.
*/
public void internalRunnerClosed() {
running = false;
toolbar.deactivate(EditorToolbar.RUN);
}
/**
* Handle internal shutdown of the runner.
*/
public void internalCloseRunner() {
running = false;
if (stopHandler != null)
try {
stopHandler.run();
} catch (Exception e) { }
}
/**
* Check if the sketch is modified and ask user to save changes.
* @return false if canceling the close/quit operation
*/
protected boolean checkModified() {
if (!sketch.isModified()) return true;
// As of Processing 1.0.10, this always happens immediately.
toFront();
String prompt = I18n.format(_("Save changes to \"{0}\"? "), sketch.getName());
if (!OSUtils.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(this, prompt, _("Close"),
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
switch (result) {
case JOptionPane.YES_OPTION:
return handleSave(true);
case JOptionPane.NO_OPTION:
return true; // ok to continue
case JOptionPane.CANCEL_OPTION:
case JOptionPane.CLOSED_OPTION: // Escape key pressed
return false;
default:
throw new IllegalStateException();
}
} else {
// This code is disabled unless Java 1.5 is being used on Mac OS X
// because of a Java bug that prevents the initial value of the
// dialog from being set properly (at least on my MacBook Pro).
// The bug causes the "Don't Save" option to be the highlighted,
// blinking, default. This sucks. But I'll tell you what doesn't
// suck--workarounds for the Mac and Apple's snobby attitude about it!
// I think it's nifty that they treat their developers like dirt.
// Pane formatting adapted from the quaqua guide
JOptionPane pane =
new JOptionPane(_("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Do you want to save changes to this sketch<BR>" +
" before closing?</b>" +
"<p>If you don't save, your changes will be lost."),
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
_("Save"), _("Cancel"), _("Don't Save")
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
// on macosx, setting the destructive property places this option
// away from the others at the lefthand side
pane.putClientProperty("Quaqua.OptionPane.destructiveOption",
new Integer(2));
JDialog dialog = pane.createDialog(this, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) { // save (and close/quit)
return handleSave(true);
} else if (result == options[2]) { // don't save (still close/quit)
return true;
} else { // cancel?
return false;
}
}
}
/**
* Open a sketch from a particular path, but don't check to save changes.
* Used by Sketch.saveAs() to re-open a sketch after the "Save As"
*/
protected void handleOpenUnchecked(File file, int codeIndex,
int selStart, int selStop, int scrollPos) {
internalCloseRunner();
handleOpenInternal(file);
// Replacing a document that may be untitled. If this is an actual
// untitled document, then editor.untitled will be set by Base.
untitled = false;
sketch.setCurrentCode(codeIndex);
textarea.select(selStart, selStop);
textarea.setScrollPosition(scrollPos);
}
/**
* Second stage of open, occurs after having checked to see if the
* modifications (if any) to the previous sketch need to be saved.
*/
protected boolean handleOpenInternal(File sketchFile) {
// check to make sure that this .pde file is
// in a folder of the same name
String fileName = sketchFile.getName();
File file = SketchData.checkSketchFile(sketchFile);
if (file == null)
{
if (!fileName.endsWith(".ino") && !fileName.endsWith(".pde")) {
Base.showWarning(_("Bad file selected"),
_("Arduino can only open its own sketches\n" +
"and other files ending in .ino or .pde"), null);
return false;
} else {
String properParent =
fileName.substring(0, fileName.length() - 4);
Object[] options = { _("OK"), _("Cancel") };
String prompt = I18n.format(_("The file \"{0}\" needs to be inside\n" +
"a sketch folder named \"{1}\".\n" +
"Create this folder, move the file, and continue?"),
fileName,
properParent);
int result = JOptionPane.showOptionDialog(this,
prompt,
_("Moving"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.YES_OPTION) {
// create properly named folder
File properFolder = new File(sketchFile.getParent(), properParent);
if (properFolder.exists()) {
Base.showWarning(_("Error"),
I18n.format(
_("A folder named \"{0}\" already exists. " +
"Can't open sketch."),
properParent
),
null);
return false;
}
if (!properFolder.mkdirs()) {
//throw new IOException("Couldn't create sketch folder");
Base.showWarning(_("Error"),
_("Could not create the sketch folder."), null);
return false;
}
// copy the sketch inside
File properPdeFile = new File(properFolder, sketchFile.getName());
try {
Base.copyFile(sketchFile, properPdeFile);
} catch (IOException e) {
Base.showWarning(_("Error"), _("Could not copy to a proper location."), e);
return false;
}
// remove the original file, so user doesn't get confused
sketchFile.delete();
// update with the new path
file = properPdeFile;
} else if (result == JOptionPane.NO_OPTION) {
return false;
}
}
}
try {
sketch = new Sketch(this, file);
} catch (IOException e) {
Base.showWarning(_("Error"), _("Could not create the sketch."), e);
return false;
}
header.rebuild();
// Set the title of the window to "sketch_070752a - Processing 0126"
setTitle(I18n.format(_("{0} | Arduino {1}"), sketch.getName(),
BaseNoGui.VERSION_NAME));
// Disable untitled setting from previous document, if any
untitled = false;
// Store information on who's open and running
// (in case there's a crash or something that can't be recovered)
base.storeSketches();
Preferences.save();
// opening was successful
return true;
// } catch (Exception e) {
// e.printStackTrace();
// statusError(e);
// return false;
}
public boolean handleSave(boolean immediately) {
//stopRunner();
handleStop(); // 0136
if (untitled) {
return handleSaveAs();
// need to get the name, user might also cancel here
} else if (immediately) {
return handleSave2();
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
handleSave2();
}
});
}
return true;
}
protected boolean handleSave2() {
toolbar.activate(EditorToolbar.SAVE);
statusNotice(_("Saving..."));
boolean saved = false;
try {
saved = sketch.save();
if (saved)
statusNotice(_("Done Saving."));
else
statusEmpty();
// rebuild sketch menu in case a save-as was forced
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenus();
//sketchbook.rebuildMenusAsync();
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
// zero out the current action,
// so that checkModified2 will just do nothing
//checkModifiedMode = 0;
// this is used when another operation calls a save
}
//toolbar.clear();
toolbar.deactivate(EditorToolbar.SAVE);
return saved;
}
public boolean handleSaveAs() {
//stopRunner(); // formerly from 0135
handleStop();
toolbar.activate(EditorToolbar.SAVE);
//SwingUtilities.invokeLater(new Runnable() {
//public void run() {
statusNotice(_("Saving..."));
try {
if (sketch.saveAs()) {
statusNotice(_("Done Saving."));
// Disabling this for 0125, instead rebuild the menu inside
// the Save As method of the Sketch object, since that's the
// only one who knows whether something was renamed.
//sketchbook.rebuildMenusAsync();
} else {
statusNotice(_("Save Canceled."));
return false;
}
} catch (Exception e) {
// show the error as a message in the window
statusError(e);
} finally {
// make sure the toolbar button deactivates
toolbar.deactivate(EditorToolbar.SAVE);
}
return true;
}
public boolean serialPrompt() {
int count = serialMenu.getItemCount();
Object[] names = new Object[count];
for (int i = 0; i < count; i++) {
names[i] = ((JCheckBoxMenuItem)serialMenu.getItem(i)).getText();
}
String result = (String)
JOptionPane.showInputDialog(this,
I18n.format(
_("Serial port {0} not found.\n" +
"Retry the upload with another serial port?"),
Preferences.get("serial.port")
),
"Serial port not found",
JOptionPane.PLAIN_MESSAGE,
null,
names,
0);
if (result == null) return false;
selectSerialPort(result);
base.onBoardOrPortChange();
return true;
}
/**
* Called by Sketch → Export.
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
* <p/>
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
/**
* Handles calling the export() function on sketch, and
* queues all the gui status stuff that comes along with it.
*
* Made synchronized to (hopefully) avoid problems of people
* hitting export twice, quickly, and horking things up.
*/
synchronized public void handleExport(final boolean usingProgrammer) {
if (Preferences.getBoolean("editor.save_on_verify")) {
if (sketch.isModified() && !sketch.isReadOnly()) {
handleSave(true);
}
}
toolbar.activate(EditorToolbar.EXPORT);
console.clear();
status.progress(_("Uploading to I/O Board..."));
new Thread(usingProgrammer ? exportAppHandler : exportHandler).start();
}
// DAM: in Arduino, this is upload
class DefaultExportHandler implements Runnable {
public void run() {
try {
if (serialMonitor != null) {
serialMonitor.close();
serialMonitor.setVisible(false);
}
uploading = true;
boolean success = sketch.exportApplet(false);
if (success) {
statusNotice(_("Done uploading."));
} else {
// error message will already be visible
}
} catch (SerialNotFoundException e) {
populatePortMenu();
if (serialMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice(_("Upload canceled."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while uploading: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivate(EditorToolbar.EXPORT);
}
}
// DAM: in Arduino, this is upload (with verbose output)
class DefaultExportAppHandler implements Runnable {
public void run() {
try {
if (serialMonitor != null) {
serialMonitor.close();
serialMonitor.setVisible(false);
}
uploading = true;
boolean success = sketch.exportApplet(true);
if (success) {
statusNotice(_("Done uploading."));
} else {
// error message will already be visible
}
} catch (SerialNotFoundException e) {
populatePortMenu();
if (serialMenu.getItemCount() == 0) statusError(e);
else if (serialPrompt()) run();
else statusNotice(_("Upload canceled."));
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while uploading: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
//statusError("Error during upload.");
//e.printStackTrace();
status.unprogress();
statusError(e);
} catch (Exception e) {
e.printStackTrace();
}
status.unprogress();
uploading = false;
//toolbar.clear();
toolbar.deactivate(EditorToolbar.EXPORT);
}
}
protected boolean handleExportCheckModified() {
if (!sketch.isModified()) return true;
Object[] options = { _("OK"), _("Cancel") };
int result = JOptionPane.showOptionDialog(this,
_("Save changes before export?"),
_("Save"),
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.OK_OPTION) {
handleSave(true);
} else {
// why it's not CANCEL_OPTION is beyond me (at least on the mac)
// but f-- it.. let's get this shite done..
//} else if (result == JOptionPane.CANCEL_OPTION) {
statusNotice(_("Export canceled, changes must first be saved."));
//toolbar.clear();
return false;
}
return true;
}
public void handleSerial() {
if (uploading) return;
if (serialMonitor != null) {
try {
serialMonitor.close();
serialMonitor.setVisible(false);
} catch (Exception e) {
// noop
}
}
BoardPort port = Base.getDiscoveryManager().find(Preferences.get("serial.port"));
if (port == null) {
statusError(I18n.format("Board at {0} is not available", Preferences.get("serial.port")));
return;
}
serialMonitor = new MonitorFactory().newMonitor(port);
serialMonitor.setIconImage(getIconImage());
boolean success = false;
do {
if (serialMonitor.requiresAuthorization() && !Preferences.has(serialMonitor.getAuthorizationKey())) {
PasswordAuthorizationDialog dialog = new PasswordAuthorizationDialog(this, _("Type board password to access its console"));
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
if (dialog.isCancelled()) {
statusNotice(_("Unable to open serial monitor"));
return;
}
Preferences.set(serialMonitor.getAuthorizationKey(), dialog.getPassword());
}
try {
serialMonitor.open();
serialMonitor.setVisible(true);
success = true;
} catch (ConnectException e) {
statusError(_("Unable to connect: is the sketch using the bridge?"));
} catch (JSchException e) {
statusError(_("Unable to connect: wrong password?"));
} catch (SerialException e) {
String errorMessage = e.getMessage();
if (e.getCause() != null && e.getCause() instanceof SerialPortException) {
errorMessage += " (" + ((SerialPortException) e.getCause()).getExceptionType() + ")";
}
statusError(errorMessage);
} catch (Exception e) {
statusError(e);
} finally {
if (serialMonitor.requiresAuthorization() && !success) {
Preferences.remove(serialMonitor.getAuthorizationKey());
}
}
} while (serialMonitor.requiresAuthorization() && !success);
}
protected void handleBurnBootloader() {
console.clear();
statusNotice(_("Burning bootloader to I/O Board (this may take a minute)..."));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Uploader uploader = new SerialUploader();
if (uploader.burnBootloader()) {
statusNotice(_("Done burning bootloader."));
} else {
statusError(_("Error while burning bootloader."));
// error message will already be visible
}
} catch (PreferencesMapException e) {
statusError(I18n.format(
_("Error while burning bootloader: missing '{0}' configuration parameter"),
e.getMessage()));
} catch (RunnerException e) {
statusError(e.getMessage());
} catch (Exception e) {
statusError(_("Error while burning bootloader."));
e.printStackTrace();
}
}
});
}
/**
* Handler for File → Page Setup.
*/
public void handlePageSetup() {
//printerJob = null;
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}
if (pageFormat == null) {
pageFormat = printerJob.defaultPage();
}
pageFormat = printerJob.pageDialog(pageFormat);
//System.out.println("page format is " + pageFormat);
}
/**
* Handler for File → Print.
*/
public void handlePrint() {
statusNotice(_("Printing..."));
//printerJob = null;
if (printerJob == null) {
printerJob = PrinterJob.getPrinterJob();
}
if (pageFormat != null) {
//System.out.println("setting page format " + pageFormat);
printerJob.setPrintable(textarea.getPainter(), pageFormat);
} else {
printerJob.setPrintable(textarea.getPainter());
}
// set the name of the job to the code name
printerJob.setJobName(sketch.getCurrentCode().getPrettyName());
if (printerJob.printDialog()) {
try {
printerJob.print();
statusNotice(_("Done printing."));
} catch (PrinterException pe) {
statusError(_("Error while printing."));
pe.printStackTrace();
}
} else {
statusNotice(_("Printing canceled."));
}
//printerJob = null; // clear this out?
}
/**
* Show an error int the status bar.
*/
public void statusError(String what) {
System.err.println(what);
status.error(what);
//new Exception("deactivating RUN").printStackTrace();
toolbar.deactivate(EditorToolbar.RUN);
}
/**
* Show an exception in the editor status bar.
*/
public void statusError(Exception e) {
e.printStackTrace();
// if (e == null) {
// System.err.println("Editor.statusError() was passed a null exception.");
// return;
if (e instanceof RunnerException) {
RunnerException re = (RunnerException) e;
if (re.hasCodeIndex()) {
sketch.setCurrentCode(re.getCodeIndex());
}
if (re.hasCodeLine()) {
int line = re.getCodeLine();
// subtract one from the end so that the \n ain't included
if (line >= textarea.getLineCount()) {
// The error is at the end of this current chunk of code,
// so the last line needs to be selected.
line = textarea.getLineCount() - 1;
if (textarea.getLineText(line).length() == 0) {
// The last line may be zero length, meaning nothing to select.
// If so, back up one more line.
line
}
}
if (line < 0 || line >= textarea.getLineCount()) {
System.err.println(I18n.format(_("Bad error line: {0}"), line));
} else {
textarea.select(textarea.getLineStartOffset(line),
textarea.getLineStopOffset(line) - 1);
}
}
}
// Since this will catch all Exception types, spend some time figuring
// out which kind and try to give a better error message to the user.
String mess = e.getMessage();
if (mess != null) {
String javaLang = "java.lang.";
if (mess.indexOf(javaLang) == 0) {
mess = mess.substring(javaLang.length());
}
String rxString = "RuntimeException: ";
if (mess.indexOf(rxString) == 0) {
mess = mess.substring(rxString.length());
}
statusError(mess);
}
// e.printStackTrace();
}
/**
* Show a notice message in the editor status bar.
*/
public void statusNotice(String msg) {
status.notice(msg);
}
/**
* Clear the status area.
*/
public void statusEmpty() {
statusNotice(EMPTY);
}
protected void onBoardOrPortChange() {
Map<String, String> boardPreferences = Base.getBoardPreferences();
if (boardPreferences != null)
lineStatus.setBoardName(boardPreferences.get("name"));
else
lineStatus.setBoardName("-");
lineStatus.setSerialPort(Preferences.get("serial.port"));
lineStatus.repaint();
}
/**
* Returns the edit popup menu.
*/
class TextAreaPopup extends JPopupMenu {
//private String currentDir = System.getProperty("user.dir");
private String referenceFile = null;
private JMenuItem cutItem;
private JMenuItem copyItem;
private JMenuItem discourseItem;
private JMenuItem referenceItem;
private JMenuItem openURLItem;
private JSeparator openURLItemSeparator;
private String clickedURL;
public TextAreaPopup() {
openURLItem = new JMenuItem(_("Open URL"));
openURLItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Base.openURL(clickedURL);
}
});
add(openURLItem);
openURLItemSeparator = new JSeparator();
add(openURLItemSeparator);
cutItem = new JMenuItem(_("Cut"));
cutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCut();
}
});
add(cutItem);
copyItem = new JMenuItem(_("Copy"));
copyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCopy();
}
});
add(copyItem);
discourseItem = new JMenuItem(_("Copy for Forum"));
discourseItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleDiscourseCopy();
}
});
add(discourseItem);
discourseItem = new JMenuItem(_("Copy as HTML"));
discourseItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleHTMLCopy();
}
});
add(discourseItem);
JMenuItem item = new JMenuItem(_("Paste"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handlePaste();
}
});
add(item);
item = new JMenuItem(_("Select All"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleSelectAll();
}
});
add(item);
addSeparator();
item = new JMenuItem(_("Comment/Uncomment"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleCommentUncomment();
}
});
add(item);
item = new JMenuItem(_("Increase Indent"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(true);
}
});
add(item);
item = new JMenuItem(_("Decrease Indent"));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleIndentOutdent(false);
}
});
add(item);
addSeparator();
referenceItem = new JMenuItem(_("Find in Reference"));
referenceItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleFindReference();
}
});
add(referenceItem);
}
// if no text is selected, disable copy and cut menu items
public void show(Component component, int x, int y) {
int lineNo = textarea.getLineOfOffset(textarea.xyToOffset(x, y));
int offset = textarea.xToOffset(lineNo, x);
String line = textarea.getLineText(lineNo);
clickedURL = textarea.checkClickedURL(line, offset);
if (clickedURL != null) {
openURLItem.setVisible(true);
openURLItemSeparator.setVisible(true);
} else {
openURLItem.setVisible(false);
openURLItemSeparator.setVisible(false);
}
if (textarea.isSelectionActive()) {
cutItem.setEnabled(true);
copyItem.setEnabled(true);
discourseItem.setEnabled(true);
} else {
cutItem.setEnabled(false);
copyItem.setEnabled(false);
discourseItem.setEnabled(false);
}
referenceFile = PdeKeywords.getReference(getCurrentKeyword());
referenceItem.setEnabled(referenceFile != null);
super.show(component, x, y);
}
}
}
|
package model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.thoughtworks.xstream.annotations.XStreamAlias;
public class SortedArrayList extends ArrayList<Task> {
@XStreamAlias("Comparator")
Comparator<Task> comparator;
public SortedArrayList(Comparator<Task> c) {
this.comparator = c;
}
public boolean addOrder(Task task) {
if (this.size() == 0) {
super.add(0, task);
} else {
int index = Collections.binarySearch(this, task, this.comparator);
if (index < 0) {
index = -(index + 1);
}
super.add(index, task);
}
return true;
}
}
|
package models.campaign;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
/**
* A level represents a combination of karel code, a world, and a set of objectives
*
* A level must always have a description
*
*/
public class Level implements Serializable {
/**
* Serial ID
*/
private static final long serialVersionUID = 11L;
/**
* Name of the level
*/
private String name;
/**
* The world for the level
*/
private World world;
/**
* The set of Karel Code in the level
*/
private ArrayList<String> karelCode;
/**
* The set of Objects in the level
*/
private ArrayList<String> objectives;
/**
* Designates how many bamboo must be picked up
* Only has a value if the bamboo objective is enabled
*
* 1 designates the bamboo objective is not enabled *
*/
private int bambooObjective;
/**
* Description about the level
*/
private String description;
/**
* Constructor
*
* @param world the world for the level to exist in
* @param description the description for the level
*/
public Level(World world, String description){
bambooObjective = -1;
this.world = world;
this.description = description;
}
/**
* Constructor - create a level by giving all the parts
*
* @param world
* @param description
* @param objectives
* @param karelCode
*/
public Level(World world, String description, ArrayList<String> objectives, ArrayList<String> karelCode, int bambooObjective){
this.world = world;
this.description = description;
this.objectives = objectives;
this.karelCode = karelCode;
this.bambooObjective = bambooObjective;
}
/**
* Gets the name of the level
*
* @return the name of the level
*/
public String getName(){
return this.name;
}
/**
* Replace the name of the level
*
* @param name the new name of the level
*/
public void replaceName(String name){
this.name = name;
}
/**
* Gets the world for the level
*
* @return The current world for the level
*/
public World getWorld(){
return this.world;
}
/**
* Gets the objectives in the level
*
* @return the objectives in the world
*/
public ArrayList<String> getObjectives(){
return this.objectives;
}
/**
* Gets the Karel Code in the level
*
* @return the karel code in the world
*/
public ArrayList<String> getKarelCode(){
return this.karelCode;
}
/**
* Change the world in the level
*
* @param world the new world for the level
*/
public void changeWorld(World world){
this.world = world;
}
/**
* Adds the Karel Code to the end of the list
*
* @param karelCode the new code string to add
*/
public void addKarelCode(String karelCode){
this.karelCode.add(karelCode);
}
/**
* Inserts Karel Code into a specific location in the list
*
* @param karelCode the Karel code to add the list
* @param position the position in the list to add it too
* @return boolean true iff able to add the karel code to that position
*/
public boolean insertKarelCode(String karelCode, int position){
if(this.karelCode.size() > position){
this.karelCode.add(position, karelCode);
return true;
}
return false;
}
/**
* Change the position of a Karel code segment
*
* @param oldposition the old position of the code segment
* @param newposition the new position of the code segment
* @return true iff the position change was a success
*/
public boolean changeKarelCodePosition(int oldposition, int newposition){
if(oldposition > this.karelCode.size() || oldposition < this.karelCode.size() || newposition < this.karelCode.size() || newposition > this.karelCode.size()){
return false;
}
this.karelCode.add(newposition, this.karelCode.remove(oldposition));
return true;
}
/**
* Remove Karel code from the list
*
* @param position the position of the code in the list
*/
public void removeKarelCode(int position){
if(this.karelCode.size() > position && position >= 0){
this.karelCode.remove(position);
}
}
/**
* Adds the objective to the ArrayList
*
* @param objective the new objective to add
*/
public void addObjective(String objective){
this.objectives.add(objective);
}
/**
* Removes an objective from the objective list
*
* @param position the position of the objective in the list
*/
public void removeObjective(int position){
if(this.objectives.size() > position && position >= 0){
this.objectives.remove(position);
}
}
/**
* Overwrites the description.
*
* @param description the new description for the level
* @return true iff the old description was overwritten by the new description
*/
public void overwriteDescription(String description){
this.description = description;
}
/**
* @return Iterator of the karelCode.
*/
public Iterator<String> listKarelCode(){
return this.karelCode.iterator();
}
/**
* @return Iterator of the objectives.
*/
public Iterator<String> listObjectives() {
return this.objectives.iterator();
}
}
|
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.ArrayList;
/**
* This class defines a simple embedded SQL utility class that is designed to
* work with PostgreSQL JDBC drivers.
*
*/
public class Messenger {
// reference to physical database connection.
private Connection _connection = null;
// handling the keyboard inputs through a BufferedReader
// This variable can be global for convenience.
static BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
/**
* Creates a new instance of Messenger
*
* @param hostname the MySQL or PostgreSQL server hostname
* @param database the name of the database
* @param username the user name used to login to the database
* @param password the user login password
* @throws java.sql.SQLException when failed to make a connection.
*/
public Messenger (String dbname, String dbport, String user, String passwd) throws SQLException {
System.out.print("Connecting to database...");
try{
// constructs the connection URL
String url = "jdbc:postgresql://localhost:" + dbport + "/" + dbname;
System.out.println ("Connection URL: " + url + "\n");
// obtain a physical connection
this._connection = DriverManager.getConnection(url, user, passwd);
System.out.println("Done");
}catch (Exception e){
System.err.println("Error - Unable to Connect to Database: " + e.getMessage() );
System.out.println("Make sure you started postgres on this machine");
System.exit(-1);
}//end catch
}//end Messenger
/**
* Method to execute an update SQL statement. Update SQL instructions
* includes CREATE, INSERT, UPDATE, DELETE, and DROP.
*
* @param sql the input SQL string
* @throws java.sql.SQLException when update failed
*/
public void executeUpdate (String sql) throws SQLException {
// creates a statement object
Statement stmt = this._connection.createStatement ();
// issues the update instruction
stmt.executeUpdate (sql);
// close the instruction
stmt.close ();
}//end executeUpdate
/**
* Method to execute an input query SQL instruction (i.e. SELECT). This
* method issues the query to the DBMS and outputs the results to
* standard out.
*
* @param query the input query string
* @return the number of rows returned
* @throws java.sql.SQLException when failed to execute the query
*/
public int executeQueryAndPrintResult (String query) throws SQLException {
// creates a statement object
Statement stmt = this._connection.createStatement ();
// issues the query instruction
ResultSet rs = stmt.executeQuery (query);
/*
** obtains the metadata object for the returned result set. The metadata
** contains row and column info.
*/
ResultSetMetaData rsmd = rs.getMetaData ();
int numCol = rsmd.getColumnCount ();
int rowCount = 0;
// iterates through the result set and output them to standard out.
boolean outputHeader = true;
while (rs.next()){
if(outputHeader){
for(int i = 1; i <= numCol; i++){
System.out.print(rsmd.getColumnName(i) + "\t");
}
System.out.println();
outputHeader = false;
}
for (int i=1; i<=numCol; ++i)
System.out.print (rs.getString (i) + "\t");
System.out.println ();
++rowCount;
}//end while
stmt.close ();
return rowCount;
}//end executeQuery
/**
* Method to execute an input query SQL instruction (i.e. SELECT). This
* method issues the query to the DBMS and returns the results as
* a list of records. Each record in turn is a list of attribute values
*
* @param query the input query string
* @return the query result as a list of records
* @throws java.sql.SQLException when failed to execute the query
*/
public List<List<String>> executeQueryAndReturnResult (String query) throws SQLException {
// creates a statement object
Statement stmt = this._connection.createStatement ();
// issues the query instruction
ResultSet rs = stmt.executeQuery (query);
/*
** obtains the metadata object for the returned result set. The metadata
** contains row and column info.
*/
ResultSetMetaData rsmd = rs.getMetaData ();
int numCol = rsmd.getColumnCount ();
int rowCount = 0;
// iterates through the result set and saves the data returned by the query.
boolean outputHeader = false;
List<List<String>> result = new ArrayList<List<String>>();
while (rs.next()){
List<String> record = new ArrayList<String>();
for (int i=1; i<=numCol; ++i)
record.add(rs.getString (i));
result.add(record);
}//end while
stmt.close ();
return result;
}//end executeQueryAndReturnResult
/**
* Method to execute an input query SQL instruction (i.e. SELECT). This
* method issues the query to the DBMS and returns the number of results
*
* @param query the input query string
* @return the number of rows returned
* @throws java.sql.SQLException when failed to execute the query
*/
public int executeQuery (String query) throws SQLException {
// creates a statement object
Statement stmt = this._connection.createStatement ();
// issues the query instruction
ResultSet rs = stmt.executeQuery (query);
int rowCount = 0;
// iterates through the result set and count nuber of results.
if(rs.next()){
rowCount++;
}//end while
stmt.close ();
return rowCount;
}
/**
* Method to fetch the last value from sequence. This
* method issues the query to the DBMS and returns the current
* value of sequence used for autogenerated keys
*
* @param sequence name of the DB sequence
* @return current value of a sequence
* @throws java.sql.SQLException when failed to execute the query
*/
public int getCurrSeqVal(String sequence) throws SQLException {
Statement stmt = this._connection.createStatement ();
ResultSet rs = stmt.executeQuery (String.format("Select currval('%s')", sequence));
if (rs.next())
return rs.getInt(1);
return -1;
}
/**
* Method to close the physical connection if it is open.
*/
public void cleanup(){
try{
if (this._connection != null){
this._connection.close ();
}//end if
}catch (SQLException e){
// ignored.
}//end try
}//end cleanup
/**
* The main execution method
*
* @param args the command line arguments this inclues the <mysql|pgsql> <login file>
*/
public static void main (String[] args) {
if (args.length != 3) {
System.err.println (
"Usage: " +
"java [-classpath <classpath>] " +
Messenger.class.getName () +
" <dbname> <port> <user>");
return;
}//end if
Greeting();
Messenger esql = null;
try{
// use postgres JDBC driver.
Class.forName ("org.postgresql.Driver").newInstance ();
// instantiate the Messenger object and creates a physical
// connection.
String dbname = args[0];
String dbport = args[1];
String user = args[2];
esql = new Messenger (dbname, dbport, user, "");
boolean keepon = true;
while(keepon) {
// These are sample SQL statements
System.out.println("MAIN MENU");
System.out.println("
System.out.println("1. Create user");
System.out.println("2. Log in");
System.out.println("9. < EXIT");
String authorisedUser = null;
switch (readChoice()){
case 1: CreateUser(esql); break;
case 2: authorisedUser = LogIn(esql); break;
case 9: keepon = false; break;
default : System.out.println("Unrecognized choice!"); break;
}//end switch
if (authorisedUser != null) {
boolean usermenu = true;
while(usermenu) {
System.out.println("MAIN MENU");
System.out.println("
System.out.println("1. Add to contact list");
System.out.println("2. Browse contact list");
System.out.println("3. Browse blocked list");
System.out.println("4. View chats");
System.out.println("5. Write a new message");
System.out.println(".........................");
System.out.println("9. Log out");
switch (readChoice()){
case 1: AddToContact(esql, authorisedUser); break;
case 2: ListContacts(esql, authorisedUser); break;
case 3: ListBlocked(esql, authorisedUser); break;
case 4: ListChats(esql, authorisedUser); break;
case 5: NewMessage(esql); break;
case 9: usermenu = false; break;
default : System.out.println("Unrecognized choice!"); break;
}
}
}
}//end while
}catch(Exception e) {
System.err.println (e.getMessage ());
}finally{
// make sure to cleanup the created table and close the connection.
try{
if(esql != null) {
System.out.print("Disconnecting from database...");
esql.cleanup ();
System.out.println("Done\n\nBye !");
}//end if
}catch (Exception e) {
// ignored.
}//end try
}//end try
}//end main
public static void Greeting(){
System.out.println(
"\n\n*******************************************************\n" +
" User Interface \n" +
"*******************************************************\n");
}//end Greeting
/*
* Reads the users choice given from the keyboard
* @int
**/
public static int readChoice() {
int input;
// returns only if a correct value is given.
do {
System.out.print("Please make your choice: ");
try { // read the integer, parse it and break.
input = Integer.parseInt(in.readLine());
break;
}catch (Exception e) {
System.out.println("Your input is invalid!");
continue;
}//end try
}while (true);
return input;
}//end readChoice
/*
* Creates a new user with privided login, passowrd and phoneNum
* An empty block and contact list would be generated and associated with a user
**/
public static void CreateUser(Messenger esql){
try{
System.out.print("\tEnter user login: ");
String login = in.readLine();
System.out.print("\tEnter user password: ");
String password = in.readLine();
System.out.print("\tEnter user phone: ");
String phone = in.readLine();
//Creating empty contact\block lists for a user
esql.executeUpdate("INSERT INTO USER_LIST(list_type) VALUES ('block')");
int block_id = esql.getCurrSeqVal("user_list_list_id_seq");
esql.executeUpdate("INSERT INTO USER_LIST(list_type) VALUES ('contact')");
int contact_id = esql.getCurrSeqVal("user_list_list_id_seq");
String query = String.format("INSERT INTO USR (phoneNum, login, password, block_list, contact_list) VALUES ('%s','%s','%s',%s,%s)", phone, login, password, block_id, contact_id);
esql.executeUpdate(query);
System.out.println ("User successfully created!");
}catch(Exception e){
System.err.println (e.getMessage ());
}
}//end
/*
* Check log in credentials for an existing user
* @return User login or null is the user does not exist
**/
public static String LogIn(Messenger esql){
try{
System.out.print("\tEnter user login: ");
String login = in.readLine();
System.out.print("\tEnter user password: ");
String password = in.readLine();
String query = String.format("SELECT * FROM Usr WHERE login = '%s' AND password = '%s'"
, login, password);
int userNum = esql.executeQuery(query);
if (userNum > 0)
return login;
return null;
}catch(Exception e){
System.err.println (e.getMessage ());
return null;
}
}//end
public static void AddToContact(Messenger esql, String authorisedUser){
try{
//First, ask user for other user's login and check if they exist
String login;
System.out.print("Enter the login name: ");
login = in.readLine();
String query1 = String.format("SELECT COUNT(*) FROM Usr WHERE login = '%s'", login);
int rowCount = esql.executeQuery(query1);
if (rowCount == 1) //requested user exists
{
//Second, get contat list ID
String query2 = String.format("SELECT contact_list FROM Usr WHERE login = '%s'", authorisedUser);
List<List<String>> result;
result = esql.executeQueryAndReturnResult(query2);
int list_id = Integer.parseInt(result.get(0).get(0));
//Third, insert contact to contact list
String query3 = String.format("INSERT INTO USER_LIST_CONTAINS (list_id, list_member) " +
"VALUES('%s', '%s');", list_id, login);
esql.executeUpdate(query3);
System.out.println ("Successfully added to contacts!");
}
else //requested user does not exist
System.out.println ("This user does not exist.");
}catch(Exception e){
System.err.println (e.getMessage ());
}
}//end
public static void ListContacts(Messenger esql, String authorisedUser){
try{
// Browsing current user's contact list
String query = String.format("SELECT ULC.list_member " +
"FROM USR U, USER_LIST UL, USER_LIST_CONTAINS ULC " +
"WHERE U.login = '%s' AND UL.list_id = U.contact_list AND ULC.list_id = UL.list_id ", authorisedUser);
int rowCount = esql.executeQueryAndPrintResult(query);
System.out.println ("total contacts: " + rowCount);
}catch(Exception e){
System.err.println (e.getMessage());
}
}//end
public static void ListBlocked(Messenger esql, String authorisedUser){
try{
// Browsing current user's block list
String query = String.format("SELECT ULC.list_member " +
"FROM USR U, USER_LIST UL, USER_LIST_CONTAINS ULC " +
"WHERE U.login = '%s' AND UL.list_id = U.block_list AND ULC.list_id = UL.list_id ", authorisedUser);
int rowCount = esql.executeQueryAndPrintResult(query);
System.out.println ("total contacts: " + rowCount);
}catch(Exception e){
System.err.println (e.getMessage());
}
}//end
public static void ListChats(Messenger esql, String authorisedUser){
try{
// Browsing current user's block list
String query = String.format("SELECT CL.chat_id, CL.member " +
"FROM CHAT_LIST CL " +
"WHERE UL.list_id = (SELECT chat_id " +
"FROM CHAT_LIST " +
"WHERE member = '%s' ", authorisedUser);
int rowCount = esql.executeQueryAndPrintResult(query);
System.out.println ("total chats: " + rowCount);
}catch(Exception e){
System.err.println (e.getMessage());
}
}//end
public static void NewMessage(Messenger esql){
// Your code goes here.
}//end
public static void Query6(Messenger esql){
// Your code goes here.
}//end Query6
}//end Messenger
|
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("all")
public class BAS_Sample
{
private final Map<String, String> m = new HashMap<String, String>();
public void testIfScope(String s)
{
Object o = new Object();
if (s.equals("Foo"))
{
s = o.toString();
}
}
public String testFPForScope(String s)
{
Object o = new Object();
while (s.length() > 0)
{
o = s.substring(0, 1);
s = s.substring(1);
}
return s;
}
public String testFP2Scopes(String s)
{
Object o = new Object();
if (s.equals("Boo"))
{
s = o.toString();
}
else if (s.equals("Hoo"))
{
s = o.toString();
}
return s;
}
public String test2InnerScopes(String s)
{
Object o = new Object();
if (s != null)
{
if (s.equals("Boo"))
{
s = o.toString();
}
else if (s.equals("Hoo"))
{
s = o.toString();
}
}
return s;
}
public String testFPLoopCond(List<String> in)
{
StringBuilder sb = new StringBuilder();
for (String s : in)
{
sb.append(s);
}
return sb.toString();
}
public List<String> getList()
{
return null;
}
public String testSwitch(int a)
{
String v = "Test";
switch (a)
{
case 1:
v = "Testa";
break;
case 2:
v = "Tesseract";
break;
case 3:
v = "Testy";
break;
default:
v = "Rossa";
break;
}
return null;
}
public void testFPSync(Set<String> a, Set<String> b)
{
String c, d;
synchronized(this)
{
c = a.iterator().next();
d = b.iterator().next();
}
if (d.length() > 0)
{
d = c;
}
}
public int testFPObjChange(Calendar c, boolean b)
{
int hour = c.get(Calendar.HOUR_OF_DAY);
c.set(2000, Calendar.JANUARY, 1);
if (b)
{
return hour;
}
return 0;
}
public void testFPSrcOverwrite(int src, boolean b)
{
int d = src;
src = 0;
if (b)
{
System.out.println(d);
}
}
public void testFPRiskies1(boolean b) {
long start = System.currentTimeMillis();
if (b) {
long delta = System.currentTimeMillis() - start;
System.out.println(delta);
}
}
public String testFPIteratorNext(Collection<String> c, boolean b) {
Iterator<String> it = c.iterator();
String s = it.next();
if (b) {
if (s == null) {
return "yay";
}
}
return it.next();
}
public List<String> testFPSynchronized(String s, String p) {
List<String> l = new ArrayList<String>();
String x = s;
synchronized(s) {
if (p != null) {
l.add(p);
return l;
}
}
return null;
}
}
|
package es.deusto.ingenieria.ssdd.chat;
import java.util.ArrayList;
import es.deusto.ingenieria.ssdd.chat.data.Chat;
import es.deusto.ingenieria.ssdd.chat.data.Mensaje;
import es.deusto.ingenieria.ssdd.chat.data.User;
import es.deusto.ingenieria.ssdd.chat.out.KeepAlive;
import es.deusto.ingenieria.ssdd.exceptions.IPAlreadyInUseException;
import es.deusto.ingenieria.ssdd.exceptions.NickNameAlreadyInUseException;
import es.deusto.ingenieria.ssdd.exceptions.NickNameNotAllowedException;
import es.deusto.ingenieria.ssdd.exceptions.NotLoggedInException;
//TODO puertos
public class Brain {
Handler handler;
ArrayList<User> users;
ArrayList<Chat> chats;
Brain2 brain2;
public Brain(Handler h){
handler = h;
users = new ArrayList<User>();
KeepAlive ka = new KeepAlive(300000, users, h.udpSocket);
ka.start();
brain2 = new Brain2(h.udpSocket, h);
brain2.start();
for (int i = 0; i < 1; i++) {
users.add(new User("nick"+i, "1.1.1."+i, 8000+i));
}
}
public void receivedMessage(String string, String ip, int port){
User u = null;
int numeroUsuarios = users.size();
for (int i = 0; i < numeroUsuarios; i++) {
u = users.get(i);
if(u.getIP().equals(ip)){
break;
}
}
Mensaje m = new Mensaje(string);
switch (m.getCode()) {
case 0:
//received 000 INIT nickname
try {
addUser(m.getText(), ip, port);
sendMessage("001 INIT OK "+port, ip, port);
} catch (IPAlreadyInUseException e) {
sendMessage("004 INIT ERROR IP ALREADY IN USE", ip, port);
} catch (NickNameAlreadyInUseException e) {
sendMessage("002 INIT ERROR NICKNAME USED", ip, port);
} catch (NickNameNotAllowedException e) {
sendMessage("003 INIT ERROR NICKNAME NOT ALLOWED", ip, port);
}
break;
case 100:
//received 100 LIST
sendList(ip, u.getPort());
break;
case 104:
//received 104 LISTERROR last_XXX_without_blanks
sendList(ip, port, m.getText());
break;
case 200:
//received 200 INITCHAT user
try {
userLoggedIn(ip);
} catch (NotLoggedInException e) {
sendMessage("666 ERROR NOT LOGGED IN", ip, port);
}
try{
initChat(m.getText(), ip, port);
}catch (NullPointerException e) {
sendMessage("204 CHAT ERROR USER DOES NOT EXIST", ip, port);
}
break;
case 210:
//received 210 SENDMSG text
try {
userLoggedIn(ip);
} catch (NotLoggedInException e) {
sendMessage("666 ERROR NOT LOGGED IN", ip, port);
}
//TODO
break;
case 300:
//300 LEAVECHAT
try {
userLoggedIn(ip);
} catch (NotLoggedInException e) {
sendMessage("666 ERROR NOT LOGGED IN", ip, port);
}
sendMessage("301 LEAVECHAT OK", ip, port);
leaveChat(ip, port);
break;
case 301:
//301 LEAVECHAT OK
brain2.receivedMessage(string, ip);
try {
userLoggedIn(ip);
} catch (NotLoggedInException e) {
sendMessage("666 ERROR NOT LOGGED IN", ip, port);
}
break;
case 400:
//400 LEAVEAPP
try {
userLoggedIn(ip);
} catch (NotLoggedInException e) {
sendMessage("666 ERROR NOT LOGGED IN", ip, port);
}
leaveApp(m.getText(), ip, port);
break;
default:
break;
}
}
private void leaveChat(String ip, int port) {
User u = null;
Chat c;
int numeroChats = chats.size();
for (int i = 0; i < numeroChats; i++) {
c = chats.get(i);
if(c.getUser1().getIP().equals(ip)){
u = c.getUser2();
break;
}else if(c.getUser2().getIP().equals(ip)){
u = c.getUser1();
break;
}
}
sendMessage("300 LEAVECHAT", u.getIP(), u.getPort());
brain2.registerMessage("300 LEAVECHAT", u.getIP(), u.getPort(), "301 LEAVECHAT OK", ip, port);
}
private void initChat(String text, String ip, int port){
User destinationUser = null;
int numeroUsuarios = users.size();
for (int i = 0; i < numeroUsuarios; i++) {
if(users.get(i).getNick().trim().equals(text.trim())){
destinationUser = users.get(i);
}
}
sendMessage("200 INITCHAT "+text.trim(), destinationUser.getIP(), destinationUser.getPort());
sendMessage("201 CHAT OK", ip, port);
brain2.registerMessage("200 INITCHAT "+text.trim(), destinationUser.getIP(), destinationUser.getPort(), "202 CHAT ACCEPTED", "202 CHAT ACCEPTED", ip, port);
}
private void userLoggedIn(String ip) throws NotLoggedInException {
int numeroUsuarios = users.size();
User u;
String leftUserNickName = "";
for (int i = 0; i < numeroUsuarios; i++) {
u = users.get(i);
if(u.getIP().equals(ip)){
leftUserNickName = users.get(i).getNick();
}
}
if(leftUserNickName.equals("")){
throw new NotLoggedInException();
}
}
private void leaveApp(String text, String ip, int port) {
int numeroUsuarios = users.size();
User u;
String leftUserNickName = "";
for (int i = 0; i < numeroUsuarios; i++) {
u = users.get(i);
if(u.getIP().equals(ip)){
leftUserNickName = users.get(i).getNick();
}
}
if(!leftUserNickName.equals("")){
for (int i = 0; i < numeroUsuarios; i++) {
u = users.get(i);
sendMessage("103 LEFTUSER " + leftUserNickName, u.getIP(), u.getPort());
}
}
}
private void sendList(String ip, int port, String text) {
int code = 100;
String messageType = "LIST";
String numeroMensaje;
Mensaje m;
int numeroUsuarios = users.size();
int numeroMensajes = 0;
int numeroMensajesYaEnviados = Integer.parseInt(text);
for (int i = 0; i < numeroUsuarios; i++) {
m = new Mensaje();
m.setCode(code);
numeroMensaje = Integer.toString(numeroMensajes);
while(numeroMensaje.length()<3){
numeroMensaje = "0"+numeroMensaje;
}
m.setMessageType(messageType);
m.setText(numeroMensaje+" ");
while(i < numeroUsuarios && m.addText(":<:"+(users.get(i).getNick().trim())+":>:")){
i++;
if(i >= numeroUsuarios){
m.fillWithBlanks();
}
}
numeroMensajes++;
if(numeroMensajes>numeroMensajesYaEnviados){
sendMessage(m, ip, port);
}
}
}
private void sendList(String ip, int port) {
int code = 100;
String messageType = "LIST";
String numeroMensaje;
Mensaje m;
int numeroUsuarios = users.size();
int numeroMensajes = 0;
for (int i = 0; i < numeroUsuarios; i++) {
m = new Mensaje();
m.setCode(code);
numeroMensaje = Integer.toString(numeroMensajes);
while(numeroMensaje.length()<3){
numeroMensaje = "0"+numeroMensaje;
}
m.setMessageType(messageType);
m.setText(numeroMensaje+" ");
while(i < numeroUsuarios && m.addText(":<:"+(users.get(i).getNick().trim())+":>:")){
i++;
if(i >= numeroUsuarios){
m.fillWithBlanks();
}
}
numeroMensajes++;
sendMessage(m, ip, port);
}
}
private void sendMessage(Mensaje m, String ip, int port) {
handler.sendMessage(m.getCode()+" "+m.getMessageType()+" "+m.getText(), ip, port);
}
public void sendMessage(String message, String ip, int port){
handler.sendMessage(message, ip, port);
}
public void addUser(String nick, String ip, int port) throws IPAlreadyInUseException, NickNameAlreadyInUseException, NickNameNotAllowedException{
User auxUser;
int numeroUsuarios = users.size();
for (int i = 0; i < numeroUsuarios; i++) {
auxUser = users.get(i);
if(auxUser.getIP().equals(ip)){
throw new IPAlreadyInUseException();
}else if(auxUser.getNick().equals(nick)){
throw new NickNameAlreadyInUseException();
}else if(nick.contains(":<:") && nick.contains(":>:")){
throw new NickNameNotAllowedException();
}
}
for (int i = 0; i < numeroUsuarios; i++) {
auxUser = users.get(i);
sendMessage("102 NEWUSER "+nick, auxUser.getIP(), auxUser.getPort());
}
users.add(new User(nick, ip, port));
}
}
|
package com.rgi.geopackage;
import static org.junit.Assert.fail;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystems;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.rgi.common.BoundingBox;
import com.rgi.common.LatLongConversions;
import com.rgi.common.coordinate.Coordinate;
import com.rgi.common.coordinate.CoordinateReferenceSystem;
import com.rgi.common.coordinate.CrsCoordinate;
import com.rgi.common.util.ImageUtility;
import com.rgi.geopackage.GeoPackage.OpenMode;
import com.rgi.geopackage.core.SpatialReferenceSystem;
import com.rgi.geopackage.tiles.RelativeTileCoordinate;
import com.rgi.geopackage.tiles.Tile;
import com.rgi.geopackage.tiles.TileMatrix;
import com.rgi.geopackage.tiles.TileMatrixSet;
import com.rgi.geopackage.tiles.TileSet;
import com.rgi.geopackage.verification.ConformanceException;
/**
* @author Jenifer Cochran
*/
@SuppressWarnings("static-method")
public class GeoPackageTilesAPITest
{
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
private final Random randomGenerator = new Random();
/**
* This tests if a GeoPackage can add a tile set successfully without throwing errors.
*
* @throws SQLException
* @throws Exception
*/
@Test
public void addTileSet() throws SQLException, Exception
{
final File testFile = this.getRandomFile(5);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("pyramid",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 60.0, 50.0),
gpkg.core().getSpatialReferenceSystem(4326));
int matrixHeight = 2;
int matrixWidth = 4;
int tileHeight = 512;
int tileWidth = 256;
gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
}
final String query = "SELECT table_name FROM gpkg_tile_matrix_set WHERE table_name = 'pyramid';";
try(Connection con = this.getConnection(testFile.getAbsolutePath());
Statement stmt = con.createStatement();
ResultSet tileName = stmt.executeQuery(query);)
{
Assert.assertTrue("The GeoPackage did not set the table_name into the gpkg_tile_matrix_set when adding a new set of tiles.", tileName.next());
final String tableName = tileName.getString("table_name");
Assert.assertTrue("The GeoPackage did not insert the correct table name into the gpkg_tile_matrix_set when adding a new set of tiles.", tableName.equals("pyramid"));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileSetWithNullTileSetEntry() throws SQLException, Exception
{
final File testFile = this.getRandomFile(3);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName", "identifier", "description", new BoundingBox(0.0,0.0,0.0,0.0), gpkg.core().getSpatialReferenceSystem(4326));
gpkg.tiles().addTile(null, gpkg.tiles().getTileMatrix(tileSet, 0), new RelativeTileCoordinate(0, 0, 0), GeoPackageTilesAPITest.createImageBytes());
Assert.fail("Expected GeoPackage to throw an IllegalArgumentException when giving a null value for tileSetEntry.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileSetWithNullBoundingBox() throws Exception
{
final File testFile = this.getRandomFile(3);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles()
.addTileSet("tableName",
"ident",
"desc",
null,
gpkg.core().getSpatialReferenceSystem(4236));
Assert.fail("Expected GeoPackage to throw an IllegalArgumentException when giving a null value for BoundingBox.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileSetWithNullSRS() throws Exception
{
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles()
.addTileSet("name",
"ident",
"desc",
new BoundingBox(0.0,0.0,0.0,0.0),
null);
Assert.fail("GeoPackage should have thrown an IllegalArgumentException when TileEntrySet is null.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test
public void addTileSetWithNewSpatialReferenceSystem() throws SQLException, Exception
{
final File testFile = this.getRandomFile(5);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.core().addSpatialReferenceSystem("scaled world mercator",
9804,
"org",
9804,
"definition",
"description");
}
final String query = "SELECT srs_name FROM gpkg_spatial_ref_sys "+
"WHERE srs_name = 'scaled world mercator' AND "+
"srs_id = 9804 AND "+
"organization = 'org' AND "+
"definition = 'definition' AND "+
"description = 'description';";
try(Connection con = this.getConnection(testFile.getAbsolutePath());
Statement stmt = con.createStatement();
ResultSet srsInfo = stmt.executeQuery(query);)
{
Assert.assertTrue("The Spatial Reference System added to the GeoPackage by the user did not contain the same information given.", srsInfo.next());
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if given a GeoPackage with tiles already inside it can add another Tile Set without throwing an error and verify that it entered the correct information.
*
* @throws SQLException
* @throws Exception
*/
@Test
public void addTileSetToExistingGpkgWithTilesInside() throws SQLException, Exception
{
final File testFile = this.getRandomFile(5);
//create a geopackage with tiles inside
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetONE",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 60.0, 60.0),
gpkg.core().getSpatialReferenceSystem(4326));
int matrixHeight = 2;
int matrixWidth = 2;
int tileHeight = 256;
int tileWidth = 256;
gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
//open a file with tiles inside and add more tiles
try(GeoPackage gpkgWithTiles = new GeoPackage(testFile, OpenMode.Open))
{
final TileSet tileSetEntry2 = gpkgWithTiles.tiles()
.addTileSet("newTileSetTWO",
"title2",
"tiles",
new BoundingBox(0.0, 0.0, 50.0, 70.0),
gpkgWithTiles.core().getSpatialReferenceSystem(4326));
double pixelXSize = (tileSetEntry2.getBoundingBox().getWidth()/matrixWidth)/tileWidth;
double pixelYSize = (tileSetEntry2.getBoundingBox().getHeight()/matrixHeight)/tileHeight;
gpkgWithTiles.tiles().addTileMatrix(tileSetEntry2,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
pixelXSize,
pixelYSize);
}
}
//make sure the information was added to contents table and tile matrix set table
final String query = "SELECT cnts.table_name FROM gpkg_contents AS cnts WHERE cnts.table_name"+
" IN(SELECT tms.table_name FROM gpkg_tile_matrix_set AS tms WHERE cnts.table_name = tms.table_name);";
try(Connection con = this.getConnection(testFile.getAbsolutePath());
Statement stmt = con.createStatement();
ResultSet tileTableNames = stmt.executeQuery(query);)
{
if(!tileTableNames.next())
{
Assert.fail("The two tiles tables where not successfully added to both the gpkg_contents table and the gpkg_tile_matrix_set.");
}
while (tileTableNames.next())
{
final String tilesTableName = tileTableNames.getString("table_name");
Assert.assertTrue("The tiles table names did not match what was being added to the GeoPackage",
tilesTableName.equals("newTileSetTWO") || tilesTableName.equals("tileSetONE"));
}
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if a GeoPackage will throw an error when adding a tileset with the same name as another tileset in the GeoPackage.
*
* @throws SQLException
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
public void addTileSetWithRepeatedTileSetName() throws SQLException, Exception
{
final File testFile = this.getRandomFile(5);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("repeated_name",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 0.0, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
gpkg.tiles().addTileMatrix(tileSet, 0, 2, 2, 2, 2, 2, 2);
final TileSet tileSetEntry2 = gpkg.tiles()
.addTileSet("repeated_name",
"title2",
"tiles",
new BoundingBox(0.0, 0.0, 0.0, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
gpkg.tiles().addTileMatrix(tileSetEntry2, 0, 2, 2, 2, 2, 2, 2);
Assert.fail("The GeoPackage should throw an IllegalArgumentException when a user gives a Tile Set Name that already exists.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if a GeoPackage can add 2 Tile Matrix entries with
* the two different tile pyramids can be entered into one gpkg
*/
@Test
public void addTileSetToExistingTilesTable() throws Exception
{
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"tiles",
"desc",
new BoundingBox(0.0, 0.0, 70.0, 70.0),
gpkg.core().getSpatialReferenceSystem(4326));
final ArrayList<TileSet> tileSetContnentEntries = new ArrayList<>();
tileSetContnentEntries.add(tileSet);
tileSetContnentEntries.add(tileSet);
int matrixHeight = 2;
int matrixWidth = 2;
int tileHeight = 256;
int tileWidth = 256;
gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
int matrixHeight2 = 4;
int matrixWidth2 = 4;
int tileHeight2 = 256;
int tileWidth2 = 256;
gpkg.tiles().addTileMatrix(tileSet,
1,
matrixWidth2,
matrixHeight2,
tileWidth2,
tileHeight2,
(tileSet.getBoundingBox().getWidth()/matrixWidth2)/tileWidth2,
(tileSet.getBoundingBox().getHeight()/matrixHeight2)/tileHeight2);
for(final TileSet gpkgEntry : gpkg.tiles().getTileSets())
{
Assert.assertTrue("The tile entry's information in the GeoPackage does not match what was originally given to a GeoPackage",
tileSetContnentEntries.stream()
.anyMatch(tileEntry -> tileEntry.getBoundingBox().equals(gpkgEntry.getBoundingBox()) &&
tileEntry.getDataType() .equals(gpkgEntry.getDataType()) &&
tileEntry.getDescription().equals(gpkgEntry.getDescription()) &&
tileEntry.getIdentifier() .equals(gpkgEntry.getIdentifier()) &&
tileEntry.getTableName() .equals(gpkgEntry.getTableName()) &&
tileEntry.getSpatialReferenceSystemIdentifier().equals(gpkgEntry.getSpatialReferenceSystemIdentifier())));
}
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delte testFile. testFile: %s", testFile));
}
}
}
}
/**
* This ensures that when a user tries to add
* the same tileSet two times that the TileSet object
* that is returned is the one that already exists in
* the GeoPackage and verifies its contents
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void addSameTileSetTwice() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final File testFile = this.getRandomFile(13);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final String tableName = "tableName";
final String identifier = "identifier";
final String description = "description";
final BoundingBox boundingBox = new BoundingBox(1.0,2.0,3.0,4.0);
final SpatialReferenceSystem srs = gpkg.core().getSpatialReferenceSystem(0);
final TileSet tileSet = gpkg.tiles().addTileSet(tableName,
identifier,
description,
boundingBox,
srs);
final TileSet sameTileSet = gpkg.tiles().addTileSet(tableName,
identifier,
description,
boundingBox,
srs);
Assert.assertTrue("The GeoPackage did not return the same tile set when trying to add the same tile set twice.",
sameTileSet.equals(tileSet.getTableName(),
tileSet.getDataType(),
tileSet.getIdentifier(),
tileSet.getDescription(),
tileSet.getBoundingBox(),
tileSet.getSpatialReferenceSystemIdentifier()));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileSetBadTableName() throws SQLException, FileAlreadyExistsException, ClassNotFoundException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles()
.addTileSet("TableName",
"identifier",
"definition",
null,
gpkg.core().getSpatialReferenceSystem(-1));
Assert.fail("Expected an IllegalArgumentException when giving a null value for bounding box for addTileSet");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileSetBadSRS() throws SQLException, FileAlreadyExistsException, ClassNotFoundException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles()
.addTileSet("TableName",
"identifier",
"definition",
new BoundingBox(0.0,0.0,0.0,0.0),
null);
Assert.fail("Expected an IllegalArgumentException when giving a null value for bounding box for addTileSet");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileSetBadBoundingBox() throws SQLException, FileAlreadyExistsException, ClassNotFoundException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles()
.addTileSet("TableName",
"identifier",
"definition",
new BoundingBox(0.0,0.0,0.0,0.0),
null);
Assert.fail("Expected an IllegalArgumentException when giving a null value for bounding box for addTileSet");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileSetContentEntryInvalidTableName() throws SQLException, Exception
{
final File testFile = this.getRandomFile(5);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles()
.addTileSet("",
"ident",
"desc",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(4326));
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when given a TileSet with an empty string for the table name.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileIllegalArgumentException() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
File testFile = this.getRandomFile(18);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
gpkg.tiles().addTileSet("badTableName^", "identifier", "description", new BoundingBox(0.0,0.0,2.0,2.0), gpkg.core().getSpatialReferenceSystem(0));
fail("Expected to get an IllegalArgumentException for giving an illegal tablename (with symbols not allowed by GeoPackage)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileIllegalArgumentException2() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
File testFile = this.getRandomFile(18);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
gpkg.tiles().addTileSet("gpkg_bad_tablename", "identifier", "description", new BoundingBox(0.0,0.0,2.0,2.0), gpkg.core().getSpatialReferenceSystem(0));
fail("Expected to get an IllegalArgumentException for giving an illegal tablename (starting with gpkg_ which is not allowed by GeoPackage)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileIllegalArgumentException3() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
File testFile = this.getRandomFile(18);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
gpkg.tiles().addTileSet(null, "identifier", "description", new BoundingBox(0.0,0.0,2.0,2.0), gpkg.core().getSpatialReferenceSystem(0));
fail("Expected to get an IllegalArgumentException for giving an illegal tablename (a null value)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if a GeoPackage will return the same tileSets that was given to the GeoPackage when adding tileSets.
* @throws SQLException
* @throws Exception
*/
@Test
public void getTileSetsFromGpkg() throws SQLException, Exception
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"tiles",
"desc",
new BoundingBox(0.0, 0.0, 50.0, 90.0),
gpkg.core().getSpatialReferenceSystem(4326));
final TileSet tileSet2 = gpkg.tiles()
.addTileSet("SecondTileSet",
"ident",
"descrip",
new BoundingBox(1.0,1.0,111.0,122.0),
gpkg.core().getSpatialReferenceSystem(4326));
final ArrayList<TileSet> tileSetContnentEntries = new ArrayList<>();
tileSetContnentEntries.add(tileSet);
tileSetContnentEntries.add(tileSet2);
int matrixHeight = 2;
int matrixWidth = 2;
int tileHeight = 256;
int tileWidth = 256;
gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
int matrixHeight2 = 4;
int matrixWidth2 = 4;
gpkg.tiles().addTileMatrix(tileSet2,
1,
matrixWidth2,
matrixHeight2,
tileWidth,
tileHeight,
(tileSet2.getBoundingBox().getWidth()/matrixWidth2)/tileWidth,
(tileSet2.getBoundingBox().getHeight()/matrixHeight2)/tileHeight);
final Collection<TileSet> tileSetsFromGpkg = gpkg.tiles().getTileSets();
Assert.assertTrue("The number of tileSets added to a GeoPackage do not match with how many is retrieved from a GeoPacakage.",tileSetContnentEntries.size() == tileSetsFromGpkg.size());
for(final TileSet gpkgEntry : tileSetsFromGpkg)
{
Assert.assertTrue("The tile entry's information in the GeoPackage does not match what was originally given to a GeoPackage",
tileSetContnentEntries.stream()
.anyMatch(tileEntry -> tileEntry.getBoundingBox().equals(gpkgEntry.getBoundingBox()) &&
tileEntry.getDataType() .equals(gpkgEntry.getDataType()) &&
tileEntry.getDescription().equals(gpkgEntry.getDescription()) &&
tileEntry.getIdentifier() .equals(gpkgEntry.getIdentifier()) &&
tileEntry.getTableName() .equals(gpkgEntry.getTableName()) &&
tileEntry.getSpatialReferenceSystemIdentifier().equals(gpkgEntry.getSpatialReferenceSystemIdentifier())));
}
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if a GeoPackage will find no tile Sets when searching with an SRS that is not in the GeoPackage.
* @throws SQLException
* @throws Exception
*/
@Test
public void getTileSetWithNewSRS() throws SQLException, Exception
{
final File testFile = this.getRandomFile(7);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final Collection<TileSet> gpkgTileSets = gpkg.tiles().getTileSets(gpkg.core().addSpatialReferenceSystem("name", 123,"org", 123,"def","desc"));
Assert.assertTrue("Should not have found any tile sets because there weren't any in "
+ "GeoPackage that matched the SpatialReferenceSystem given.", gpkgTileSets.size() == 0);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the getTileSet returns null when the tile table
* does not exist
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws SQLException
* @throws ConformanceException
* @throws FileNotFoundException
*/
@Test
public void getTileSetVerifyReturnNull() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(4);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().getTileSet("table_not_here");
Assert.assertTrue("GeoPackage expected to return null when the tile set does not exist in GeoPackage",tileSet == null);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the getTileSet returns the expected
* values.
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws SQLException
* @throws ConformanceException
* @throws FileNotFoundException
*/
@Test
public void getTileSetVerifyReturnCorrectTileSet() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("ttable","identifier", "Desc", new BoundingBox(0.0,0.0,0.0,0.0), gpkg.core().getSpatialReferenceSystem(4326));
final TileSet returnedTileSet = gpkg.tiles().getTileSet("ttable");
Assert.assertTrue("GeoPackage did not return the same values given to tile set",
tileSet.getBoundingBox().equals(returnedTileSet.getBoundingBox()) &&
tileSet.getDescription().equals(returnedTileSet.getDescription()) &&
tileSet.getDataType() .equals(returnedTileSet.getDataType()) &&
tileSet.getIdentifier() .equals(returnedTileSet.getIdentifier()) &&
tileSet.getLastChange() .equals(returnedTileSet.getLastChange()) &&
tileSet.getTableName() .equals(returnedTileSet.getTableName()) &&
tileSet.getSpatialReferenceSystemIdentifier().equals(returnedTileSet.getSpatialReferenceSystemIdentifier()));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTilesIllegalArgumentException() throws SQLException, Exception
{
final File testFile = this.getRandomFile(4);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"ident",
"desc",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(4326));
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, 18, 20, 20, 2,2, 1, 1);
gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(0, 0, 0), new byte[] {1, 2, 3, 4});
Assert.fail("Geopackage should throw a IllegalArgumentExceptionException when Tile Matrix Table "
+ "does not contain a record for the zoom level of a tile in the Pyramid User Data Table.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can detect the tile_row
* is larger than the matrix_height -1. Which is a violation
* of the GeoPackage Specifications. Requirement 55.
* @throws SQLException
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
public void addTilesIllegalArgumentException2() throws SQLException, Exception
{
final File testFile = this.getRandomFile(4);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"ident",
"desc",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(4326));
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, 0, 2, 2, 2, 2, 1, 1);
gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(10, 0, 0), new byte[] {1, 2, 3, 4});
Assert.fail("Geopackage should throw a IllegalArgumentException when tile_row "
+ "is larger than matrix_height - 1 when zoom levels are equal.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can detect the tile_row
* is less than 0. Which is a violation
* of the GeoPackage Specifications. Requirement 55.
* @throws SQLException
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
public void addTilesIllegalArgumentException3() throws SQLException, Exception
{
final File testFile = this.getRandomFile(4);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"ident",
"desc",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(4326));
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, 0, 2, 2, 2, 2, 1, 1);
gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(-1, 0, 0), new byte[] {1, 2, 3, 4});
Assert.fail("Geopackage should throw a IllegalArgumentException when tile_row "
+ "is less than 0.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can detect the tile_column
* is larger than matrix_width -1. Which is a violation
* of the GeoPackage Specifications. Requirement 54.
* @throws SQLException
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
public void addTilesIllegalArgumentException4() throws SQLException, Exception
{
final File testFile = this.getRandomFile(4);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"ident",
"desc",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(4326));
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, 0, 2, 2, 2, 2, 1, 1);
gpkg.tiles().addTile(tileSet,tileMatrix, new RelativeTileCoordinate(0, 10, 0), new byte[] {1, 2, 3, 4});
Assert.fail("Geopackage should throw a IllegalArgumentException when tile_column "
+ "is larger than matrix_width -1.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can detect the tile_column
* is less than 0. Which is a violation
* of the GeoPackage Specifications. Requirement 54.
* @throws SQLException
* @throws Exception
*/
@Test(expected = IllegalArgumentException.class)
public void addTilesIllegalArgumentException5() throws SQLException, Exception
{
final File testFile = this.getRandomFile(4);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"ident",
"desc",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(4326));
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, 0, 2, 2, 2, 2, 1, 1);
gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(0, -1, 0), new byte[] {1, 2, 3, 4});
Assert.fail("Geopackage should throw a IllegalArgumentException when tile_column "
+ "is less than 0.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Geopackage throws an SQLException when opening a Geopackage since it does not contain the default tables
* inside after bypassing the verifier.
*
* @throws SQLException
* @throws Exception
*/
@Test(expected = SQLException.class)
public void addTilesToGpkgAndAddTilesAndSetVerifyToFalse() throws SQLException, Exception
{
final File testFile = this.getRandomFile(37);
testFile.createNewFile();
try(GeoPackage gpkg = new GeoPackage(testFile, false, OpenMode.Open))
{
gpkg.tiles()
.addTileSet("diff_tile_set",
"tile",
"desc",
new BoundingBox(1.0, 1.0, 1.0, 1.0),
gpkg.core().getSpatialReferenceSystem(4326));
Assert.fail("The GeoPackage was expected to throw an SQLException due to no default tables inside the file.");
}
catch(final SQLException ex)
{
final String query = "SELECT table_name FROM gpkg_contents WHERE table_name = 'diff_tile_set';";
try(Connection con = this.getConnection(testFile.getAbsolutePath());
Statement stmt = con.createStatement();
ResultSet tileTableName = stmt.executeQuery(query);)
{
Assert.assertTrue("The data should not be in the contents table since it throws an SQLException", tileTableName.getString("table_name") == null);
}
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This adds a tile to a GeoPackage and verifies
* that the Tile object added into the GeoPackage
* is the same Tile object returned.
* @throws SQLException
* @throws ClassNotFoundException
* @throws ConformanceException
* @throws IOException
*/
@Test
public void addTileMethodByCrsTileCoordinate() throws SQLException, ClassNotFoundException, ConformanceException, IOException
{
final File testFile = this.getRandomFile(18);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(-80.0, -180.0, 80.0, 180.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int zoomLevel = 2;
final int matrixWidth = 2;
final int matrixHeight = 2;
final int tileWidth = 256;
final int tileHeight = 256;
final double pixelXSize = (tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth;
final double pixelYSize = (tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight;
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
pixelXSize,
pixelYSize);
final CoordinateReferenceSystem coordinateReferenceSystem = new CoordinateReferenceSystem("EPSG", 4326);
final CrsCoordinate crsCoordinate = new CrsCoordinate(-60.0, 0.0, coordinateReferenceSystem);
final Tile tileAdded = gpkg.tiles().addTile(tileSet, tileMatrix, crsCoordinate, zoomLevel, GeoPackageTilesAPITest.createImageBytes());
final Tile tileFound = gpkg.tiles().getTile(tileSet, crsCoordinate, zoomLevel);
Assert.assertTrue("The GeoPackage did not return the tile Expected.",
tileAdded.getColumn() == tileFound.getColumn() &&
tileAdded.getIdentifier() == tileFound.getIdentifier() &&
tileAdded.getRow() == tileFound.getRow() &&
tileAdded.getZoomLevel() == tileFound.getZoomLevel() &&
Arrays.equals(tileAdded.getImageData(), tileFound.getImageData()));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This adds a tile to a GeoPackage and verifies
* that the Tile object added into the GeoPackage
* is the same Tile object returned.
* @throws SQLException
* @throws ClassNotFoundException
* @throws ConformanceException
* @throws IOException
*/
@Test
public void addTileMethodByCrsTileCoordinateNullValue() throws SQLException, ClassNotFoundException, ConformanceException, IOException
{
final File testFile = this.getRandomFile(18);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(-80.0, -180.0, 80.0, 180.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int zoomLevel = 2;
final int matrixWidth = 2;
final int matrixHeight = 2;
final int tileWidth = 256;
final int tileHeight = 256;
final double pixelXSize = (tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth;
final double pixelYSize = (tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight;
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
pixelXSize,
pixelYSize);
final CoordinateReferenceSystem coordinateReferenceSystem = new CoordinateReferenceSystem("EPSG", 4326);
final int differentZoomLevel = 12;
final CrsCoordinate crsCoordinate = new CrsCoordinate(-60.0, 0.0, coordinateReferenceSystem);
final Tile tileAdded = gpkg.tiles().addTile(tileSet, tileMatrix, crsCoordinate, differentZoomLevel, GeoPackageTilesAPITest.createImageBytes());
Assert.assertTrue("The Geopackage returned a Tile object that is null when there did not exist a "
+ "tile matrix set with a tile at the zoom level indicated in CRS coodinate",
tileAdded == null);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Test if the GeoPackage can successfully add non empty tiles to a GeoPackage without throwing an error.
*
* @throws SQLException
* @throws Exception
*/
@Test
public void addNonEmptyTile() throws SQLException, Exception
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 50.0, 20.0),
gpkg.core().getSpatialReferenceSystem(4326));
int matrixHeight = 2;
int matrixWidth = 2;
int tileHeight = 256;
int tileWidth = 256;
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet,
2,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(0, 0, 2), new byte[] {1, 2, 3, 4});
}
//use a query to test if the tile was inserted into database and to correct if the image is the same
final String query = "SELECT tile_data FROM tileSetName WHERE zoom_level = 2 AND tile_column = 0 AND tile_row =0;";
try(Connection con = this.getConnection(testFile.getAbsolutePath());
Statement stmt = con.createStatement();
ResultSet tileData = stmt.executeQuery(query);)
{
// assert the image was inputed into the file
Assert.assertTrue("The GeoPackage did not successfully write the tile_data into the GeoPackage", tileData.next());
final byte[] bytes = tileData.getBytes("tile_data");
// compare images
Assert.assertTrue("The GeoPackage tile_data does not match the tile_data of the one given", Arrays.equals(bytes, new byte[] {1, 2, 3, 4}));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = SQLException.class)
public void addDuplicateTiles() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, IllegalArgumentException, FileNotFoundException
{
final File testFile = this.getRandomFile(13);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName", "ident", "description", new BoundingBox(1.1,1.1,100.1,100.1), gpkg.core().getSpatialReferenceSystem(4326));
int matrixHeight = 2;
int matrixWidth = 2;
int tileHeight = 256;
int tileWidth = 256;
final TileMatrix matrixSet = gpkg.tiles().addTileMatrix(tileSet,
1,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
//tile data
final RelativeTileCoordinate coordinate = new RelativeTileCoordinate(0, 1, 1);
final byte[] imageData = new byte[]{1, 2, 3, 4};
//add tile twice
gpkg.tiles().addTile(tileSet, matrixSet, coordinate, imageData);
gpkg.tiles().addTile(tileSet, matrixSet, coordinate, imageData);//see if it will add the same tile twice
Assert.fail("Expected GeoPackage to throw an SQLException due to a unique constraint violation (zoom level, tile column, and tile row)."
+ " Was able to add a duplicate tile.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addBadTile() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 0.0, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
//Tile coords
final RelativeTileCoordinate coord1 = new RelativeTileCoordinate(0, 4, 4);
//add tile to gpkg
final TileMatrix tileMatrix1 = gpkg.tiles().addTileMatrix(tileSet, 4, 10, 10, 1, 1, 1.0, 1.0);
gpkg.tiles().addTile(tileSet, tileMatrix1, coord1, null);
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when adding a null parameter to a Tile object (image data)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addBadTile2() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 0.0, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
//Tile coords
final RelativeTileCoordinate coord1 = new RelativeTileCoordinate(0, 4, 4);
//add tile to gpkg
final TileMatrix tileMatrix1 = gpkg.tiles().addTileMatrix(tileSet, 4, 10, 10, 1, 1, 1.0, 1.0);
gpkg.tiles().addTile(tileSet,tileMatrix1, coord1, new byte[]{});
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when adding an empty parameter to Tile (image data)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addBadTile3() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
//create tiles and file
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 0.0, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
//add tile to gpkg
final TileMatrix tileMatrix1 = gpkg.tiles().addTileMatrix(tileSet, 4, 10, 10, 1, 1, 1.0, 1.0);
gpkg.tiles().addTile(tileSet, tileMatrix1, (RelativeTileCoordinate)null, new byte[]{1,2,3,4});
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when adding a null parameter to a Tile object (coordinate)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addBadTile4() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 0.0, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
//Tile coords
final RelativeTileCoordinate coord1 = new RelativeTileCoordinate(0, 4, 4);
//add tile to gpkg
gpkg.tiles().addTile(tileSet, null, coord1, new byte[]{1,2,3,4});
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when adding a null parameter to a addTile method (tileMatrix)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage get tile will retrieve the correct tile with get tile method.
* @throws Exception
*/
@Test
public void getTile() throws Exception
{
//create tiles and file
final File testFile = this.getRandomFile(6);
final byte[] originalTile1 = new byte[] {1, 2, 3, 4};
final byte[] originalTile2 = new byte[] {1, 2, 3, 4};
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 80.0, 90.0),
gpkg.core().getSpatialReferenceSystem(4326));
//Tile coords
final RelativeTileCoordinate coord1 = new RelativeTileCoordinate(0, 4, 4);
final RelativeTileCoordinate coord2 = new RelativeTileCoordinate(0, 8, 8);
//add tile to gpkg
int matrixHeight = 2;
int matrixWidth = 4;
int tileHeight = 512;
int tileWidth = 256;
final TileMatrix tileMatrix1 = gpkg.tiles().addTileMatrix(tileSet,
4,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
int matrixHeight2 = 4;
int matrixWidth2 = 8;
int tileHeight2 = 512;
int tileWidth2 = 256;
final TileMatrix tileMatrix2 = gpkg.tiles().addTileMatrix(tileSet,
8,
matrixWidth2,
matrixHeight2,
tileWidth2,
tileHeight2,
(tileSet.getBoundingBox().getWidth()/matrixWidth2)/tileWidth2,
(tileSet.getBoundingBox().getHeight()/matrixHeight2)/tileHeight2);
gpkg.tiles().addTile(tileSet, tileMatrix1, coord1, originalTile1);
gpkg.tiles().addTile(tileSet, tileMatrix2, coord2, originalTile2);
//Retrieve tile from gpkg
final Tile gpkgTile1 = gpkg.tiles().getTile(tileSet, coord1);
final Tile gpkgTile2 = gpkg.tiles().getTile(tileSet, coord2);
Assert.assertTrue("GeoPackage did not return the image expected when using getTile method.",
Arrays.equals(gpkgTile1.getImageData(), originalTile1));
Assert.assertTrue("GeoPackage did not return the image expected when using getTile method.",
Arrays.equals(gpkgTile2.getImageData(), originalTile2));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage get tile will retrieve the correct tile with get tile method.
* @throws Exception
*/
@Test
public void getTile2() throws Exception
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 0.0, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
//Tile coords
final RelativeTileCoordinate coord1 = new RelativeTileCoordinate(0, 4, 4);
//Retrieve tile from gpkg
final Tile gpkgTile1 = gpkg.tiles().getTile(tileSet, coord1);
Assert.assertTrue("GeoPackage did not null when the tile doesn't exist in the getTile method.",
gpkgTile1 == null);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage get tile will retrieve the correct tile with get tile method.
* @throws Exception
*/
@Test
public void getTile3() throws Exception
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 50.0, 80.0),
gpkg.core().getSpatialReferenceSystem(4326));
int matrixHeight = 2;
int matrixWidth = 3;
int tileHeight = 512;
int tileWidth = 256;
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
//Tile coords
final RelativeTileCoordinate coord1 = new RelativeTileCoordinate(2, 1, 0);
final byte[] imageData = new byte[]{1,2,3,4};
//Retrieve tile from gpkg
final Tile gpkgTileAdded = gpkg.tiles().addTile(tileSet, tileMatrix, coord1, imageData);
final Tile gpkgTileRecieved = gpkg.tiles().getTile(tileSet, coord1);
Assert.assertTrue("GeoPackage did not return the same tile added to the gpkg.",
gpkgTileAdded.getColumn() == gpkgTileRecieved.getColumn() &&
gpkgTileAdded.getRow() == gpkgTileRecieved.getRow() &&
gpkgTileAdded.getIdentifier() ==(gpkgTileRecieved.getIdentifier()) &&
gpkgTileAdded.getColumn() == gpkgTileRecieved.getColumn() &&
gpkgTileAdded.getRow() == gpkgTileRecieved.getRow() &&
gpkgTileAdded.getZoomLevel() == gpkgTileRecieved.getZoomLevel() &&
Arrays.equals(gpkgTileAdded.getImageData(), gpkgTileRecieved.getImageData()));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if a GeoPackage will return null when the tile being searched for does not exist.
*
* @throws SQLException
* @throws Exception
*/
@Test
public void getTileThatIsNotInGpkg() throws SQLException, Exception
{
final File testFile = this.getRandomFile(4);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
null,
null,
new BoundingBox(0.0, 0.0, 80.0, 80.0),
gpkg.core().getSpatialReferenceSystem(4326));
int matrixWidth = 3;
int matrixHeight = 6;
int tileWidth = 256;
int tileHeight = 256;
// add tile to gpkg
gpkg.tiles().addTileMatrix(tileSet,
2,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
Assert.assertTrue("GeoPackage should have returned null for a missing tile.",
gpkg.tiles().getTile(tileSet, new RelativeTileCoordinate(0, 0, 0)) == null);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void getTileWithNullTileEntrySet() throws SQLException, Exception
{
final File testFile = this.getRandomFile(5);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles().getTile(null, new RelativeTileCoordinate(2, 2, 0));
Assert.fail("GeoPackage did not throw an IllegalArgumentException when giving a null value to table name (using getTile method)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected= IllegalArgumentException.class)
public void getTileWithRequestedTileNull() throws SQLException, Exception
{
final File testFile = this.getRandomFile(5);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles()
.getTile(gpkg.tiles()
.addTileSet("name",
"ident",
"des",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(4326)),
(RelativeTileCoordinate)null);
Assert.fail("GeoPackage did not throw an IllegalArgumentException when giving a null value to requested tile (using getTile method)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test (expected = IllegalArgumentException.class)
public void getTileZoomLevelRangeIncorrect() throws SQLException, Exception
{
final File testFile = this.getRandomFile(5);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles()
.getTile(gpkg.tiles()
.addTileSet("name",
"ind",
"des",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(4326)),
new RelativeTileCoordinate(2, 2, -3));
Assert.fail("GeoPackage did not throw an IllegalArgumentException when giving a zoom level that is out of range (using getTile method)");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This adds a tile to a GeoPackage and verifies
* that the Tile object added into the GeoPackage
* is the same Tile object returned.
* @throws SQLException
* @throws ClassNotFoundException
* @throws ConformanceException
* @throws IOException
*/
@Test
public void getTileRelativeTileCoordinateNonExistant() throws SQLException, ClassNotFoundException, ConformanceException, IOException
{
final File testFile = this.getRandomFile(18);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(-80.0, -180.0, 80.0, 180.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int zoomLevel = 2;
final CoordinateReferenceSystem coordinateReferenceSystem = new CoordinateReferenceSystem("EPSG", 4326);
final CrsCoordinate crsCoordinate = new CrsCoordinate(-60.0, 0.0, coordinateReferenceSystem);
final Tile tileFound = gpkg.tiles().getTile(tileSet, crsCoordinate, zoomLevel);
Assert.assertTrue("The Geopackage returned a Tile object that is null when there did not exist a "
+ "tile with that particular crsTileCoodinate",
tileFound == null);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage will return the all and the correct zoom levels in a GeoPackage
*
* @throws SQLException
* @throws Exception
*/
@Test
public void getZoomLevels() throws SQLException, Exception
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"ident",
"desc",
new BoundingBox(5.0,5.0,50.0,50.0),
gpkg.core().getSpatialReferenceSystem(4326));
// Add tile matrices that represent zoom levels 0 and 12
int matrixHeight = 2;
int matrixWidth = 2;
int tileHeight = 256;
int tileWidth = 256;
gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
gpkg.tiles().addTileMatrix(tileSet,
12,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
final Set<Integer> zooms = gpkg.tiles().getTileZoomLevels(tileSet);
final ArrayList<Integer> expectedZooms = new ArrayList<>();
expectedZooms.add(new Integer(12));
expectedZooms.add(new Integer(0));
for(final Integer zoom : zooms)
{
Assert.assertTrue("The GeoPackage's get zoom levels method did not return expected values.",
expectedZooms.stream()
.anyMatch(currentZoom -> currentZoom.equals(zoom)));
}
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void getZoomLevelsNullTileSetContentEntry() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(7);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles().getTileZoomLevels(null);
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when givinga null parameter to getTileZoomLevels");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void getRowCountNullContentEntry() throws SQLException, Exception
{
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.core().getRowCount(null);
Assert.fail("GeoPackage should have thrown an IllegalArgumentException.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Verifies that the GeoPackage counts the correct number of rows
* with the method getRowCount
* @throws SQLException
* @throws Exception
*/
@Test
public void getRowCountVerify() throws SQLException, Exception
{
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"ident",
"desc",
new BoundingBox(0.0,0.0,50.0,80.0),
gpkg.core().getSpatialReferenceSystem(4326));
//create two TileMatrices to represent the tiles
int matrixHeight = 2;
int matrixWidth = 2;
int tileHeight = 256;
int tileWidth = 256;
final TileMatrix tileMatrix1 = gpkg.tiles().addTileMatrix(tileSet,
1,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
int matrixHeight2 = 4;
int matrixWidth2 = 4;
final TileMatrix tileMatrix2 = gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth2,
matrixHeight2,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth2)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight2)/tileHeight);
//add two tiles
gpkg.tiles().addTile(tileSet, tileMatrix2, new RelativeTileCoordinate(0, 0, 0), new byte[] {1, 2, 3, 4});
gpkg.tiles().addTile(tileSet, tileMatrix1, new RelativeTileCoordinate(0, 0, 1), new byte[] {1, 2, 3, 4});
final long count = gpkg.core().getRowCount(tileSet);
Assert.assertTrue(String.format("Expected a different value from GeoPackage on getRowCount. expected: 2 actual: %d", count),count == 2);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void getTileMatrixSetEntryNullTileSetContentEntry() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(7);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles().getTileMatrixSet(null);
Assert.fail("Expected GeoPackage to throw an IllegalArgumentException when giving a null parameter for TileSet");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test
public void getTileMatricesVerify() throws ClassNotFoundException, SQLException, ConformanceException, IllegalArgumentException, IOException
{
final File testFile = this.getRandomFile(5);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tables", "identifier", "description", new BoundingBox(0.0,0.0,80.0,80.0), gpkg.core().getSpatialReferenceSystem(-1));
int matrixHeight = 2;
int matrixWidth = 4;
int tileHeight = 512;
int tileWidth = 256;
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
int matrixHeight2 = 4;
int matrixWidth2 = 8;
int tileHeight2 = 512;
int tileWidth2 = 256;
final TileMatrix tileMatrix2 = gpkg.tiles().addTileMatrix(tileSet,
3,
matrixWidth2,
matrixHeight2,
tileWidth2,
tileHeight2,
(tileSet.getBoundingBox().getWidth()/matrixWidth2)/tileWidth2,
(tileSet.getBoundingBox().getHeight()/matrixHeight2)/tileHeight2);
gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(0, 0, 0), GeoPackageTilesAPITest.createImageBytes());
gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(0, 1, 0), GeoPackageTilesAPITest.createImageBytes());
final ArrayList<TileMatrix> expectedTileMatrix = new ArrayList<>();
expectedTileMatrix.add(tileMatrix);
expectedTileMatrix.add(tileMatrix2);
final List<TileMatrix> gpkgTileMatrices = gpkg.tiles().getTileMatrices(tileSet);
Assert.assertTrue("Expected the GeoPackage to return two Tile Matrices.",gpkgTileMatrices.size() == 2);
for(final TileMatrix gpkgTileMatrix : gpkg.tiles().getTileMatrices(tileSet))
{
Assert.assertTrue("The tile entry's information in the GeoPackage does not match what was originally given to a GeoPackage",
expectedTileMatrix.stream()
.anyMatch(expectedTM -> expectedTM.getTableName() .equals(gpkgTileMatrix.getTableName()) &&
expectedTM.getMatrixHeight() == gpkgTileMatrix.getMatrixHeight() &&
expectedTM.getMatrixWidth() == gpkgTileMatrix.getMatrixWidth() &&
expectedTM.getPixelXSize() == gpkgTileMatrix.getPixelXSize() &&
expectedTM.getPixelYSize() == gpkgTileMatrix.getPixelYSize() &&
expectedTM.getZoomLevel() == gpkgTileMatrix.getZoomLevel()));
}
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage will return null if no TileMatrix
* Entries are found in the GeoPackage that matches the TileSet given.
* @throws SQLException
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws ConformanceException
* @throws FileNotFoundException
*/
@Test
public void getTileMatricesNonExistant() throws SQLException, FileAlreadyExistsException, ClassNotFoundException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tables",
"identifier",
"description",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(4326));
Assert.assertTrue("Expected the GeoPackage to return null when no tile Matrices are found", gpkg.tiles().getTileMatrices(tileSet).size() == 0);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatricesIllegalArgumentException() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(12);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("name", "identifier", "description", new BoundingBox(0.0,0.0,0.0,0.0), gpkg.core().getSpatialReferenceSystem(-1));
gpkg.tiles().addTileMatrix(tileSet, 0, 0, 5, 6, 7, 8, 9);
Assert.fail("Expected GeoPackage to throw an IllegalArgumentException when giving a Tile Matrix a matrix width that is <= 0");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatricesIllegalArgumentException2() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(12);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("name",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 0.0, 0.0),
gpkg.core().getSpatialReferenceSystem(-1));
gpkg.tiles().addTileMatrix(tileSet, 0, 4, 0, 6, 7, 8, 9);
Assert.fail("Expected GeoPackage to throw an IllegalArgumentException when giving a Tile Matrix a matrix height that is <= 0");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatricesIllegalArgumentException3() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(12);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("name", "identifier", "description", new BoundingBox(0.0, 0.0, 0.0, 0.0), gpkg.core().getSpatialReferenceSystem(-1));
gpkg.tiles().addTileMatrix(tileSet, 0, 4, 5, 0, 7, 8, 9);
Assert.fail("Expected GeoPackage to throw an IllegalArgumentException when giving a Tile Matrix a tile width that is <= 0");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatricesIllegalArgumentException4() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(12);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("name", "identifier", "description", new BoundingBox(0.0,0.0,0.0,0.0), gpkg.core().getSpatialReferenceSystem(-1));
gpkg.tiles().addTileMatrix(tileSet, 0, 4, 5, 6, 0, 8, 9);
Assert.fail("Expected GeoPackage to throw an IllegalArgumentException when giving a Tile Matrix a tile height that is <= 0");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatricesIllegalArgumentException5() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(12);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("name", "identifier", "description", new BoundingBox(0.0,0.0,0.0,0.0), gpkg.core().getSpatialReferenceSystem(-1));
gpkg.tiles().addTileMatrix(tileSet, 0, 4, 5, 6, 7, 0, 9);
Assert.fail("Expected GeoPackage to throw an IllegalArgumentException when giving a Tile Matrix a pixelXsize that is <= 0");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatricesIllegalArgumentException6() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(12);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("name", "identifier", "description", new BoundingBox(0.0,0.0,0.0,0.0), gpkg.core().getSpatialReferenceSystem(-1));
gpkg.tiles().addTileMatrix(tileSet, 0, 4, 5, 6, 7, 8, 0);
Assert.fail("Expected GeoPackage to throw an IllegalArgumentException when giving a Tile Matrix a pixelYSize that is <= 0");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatrixSameZoomDifferentOtherFields() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(13);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("name", "identifier", "description", new BoundingBox(0.0,0.0,0.0,0.0), gpkg.core().getSpatialReferenceSystem(-1));
gpkg.tiles().addTileMatrix(tileSet, 0, 2, 3, 4, 5, 6, 7);
gpkg.tiles().addTileMatrix(tileSet, 0, 3, 2, 5, 4, 7, 6);
Assert.fail("Expected GeoPackage Tiles to throw an IllegalArgumentException when addint a Tile Matrix with the same tile set and zoom level information but differing other fields");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage returns the same TileMatrix when trying
* to add the same TileMatrix twice (verifies the values are the same)
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws SQLException
* @throws ConformanceException
* @throws FileNotFoundException
*/
@Test
public void addTileMatrixTwiceVerify() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(13);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("name", "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), gpkg.core().getSpatialReferenceSystem(-1));
int matrixHeight = 2;
int matrixWidth = 2;
int tileHeight = 256;
int tileWidth = 256;
final TileMatrix tileMatrix1 = gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
final TileMatrix tileMatrix2 = gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
Assert.assertTrue("Expected the GeoPackage to return the existing Tile Matrix.",tileMatrix1.equals(tileMatrix2.getTableName(),
tileMatrix2.getZoomLevel(),
tileMatrix2.getMatrixWidth(),
tileMatrix2.getMatrixHeight(),
tileMatrix2.getTileWidth(),
tileMatrix2.getTileHeight(),
tileMatrix2.getPixelXSize(),
tileMatrix2.getPixelYSize()));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage returns the same TileMatrix when trying
* to add the same TileMatrix twice (verifies the values are the same)
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws SQLException
* @throws ConformanceException
* @throws FileNotFoundException
*/
@Test(expected = IllegalArgumentException.class)
public void addTileMatrixNullTileSet() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(13);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles().addTileMatrix(null, 0, 2, 3, 4, 5, 6, 7);
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when giving a null parameter TileSet to addTileMatrix");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatrixWithNegativeZoomLevel() throws SQLException, FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, ConformanceException
{
final File testFile = this.getRandomFile(12);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(1.0,2.0,3.0,4.0),
gpkg.core().getSpatialReferenceSystem(0));
gpkg.tiles().addTileMatrix(tileSet, -1, 2, 4, 6, 8, 10, 12);
}
finally
{
if (testFile.exists())
{
if (!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if given a non empty tile Matrix Metadata information can be added without throwing an error.
*
* @throws SQLException
* @throws Exception
*/
@Test
public void addNonEmptyTileMatrix() throws SQLException, Exception
{
final File testFile = this.getRandomFile(5);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
//add information to gpkg
final TileSet tileSet = gpkg.tiles()
.addTileSet("tileSetName",
"title",
"tiles",
new BoundingBox(0.0, 0.0, 80.0, 80.0),
gpkg.core().getSpatialReferenceSystem(4326));
int matrixWidth = 4;
int matrixHeight = 8;
int tileWidth = 256;
int tileHeight = 512;
gpkg.tiles().addTileMatrix(tileSet,
1,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
}
//test if information added is accurate
int matrixWidth = 4;
int matrixHeight = 8;
int tileWidth = 256;
int tileHeight = 512;
final String query = String.format("SELECT table_name FROM gpkg_tile_matrix "
+ "WHERE zoom_level = %d AND "
+ " matrix_height = %d AND "
+ " matrix_width = %d AND "
+ " tile_height = %d AND "
+ " tile_width = %d;",
1,
matrixHeight,
matrixWidth,
tileHeight,
tileWidth);
try(Connection con = this.getConnection(testFile.getAbsolutePath());
Statement stmt = con.createStatement();
ResultSet tableName = stmt.executeQuery(query);)
{
Assert.assertTrue("The GeoPackage did not enter the correct record into the gpkg_tile_matrix table", tableName.getString("table_name").equals("tileSetName"));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatrixIllegalBounds() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
File testFile = this.getRandomFile(7);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0,0.0,90.0,180.0),
gpkg.core().getSpatialReferenceSystem(4326));
int zoomLevel = 5;
int matrixWidth = 10;
int matrixHeight = 11;
int tileWidth = 256;
int tileHeight = 512;
double pixelXSize = 500.23123;//invalid pixelx size
double pixelYSize = tileSet.getBoundingBox().getHeight()/matrixHeight/tileHeight;
gpkg.tiles().addTileMatrix(tileSet, zoomLevel, matrixWidth, matrixHeight, tileWidth, tileHeight, pixelXSize, pixelYSize);
fail("Expected GeopackageTiles to throw an IllegalArgtumentException when pixelXSize != boundingBoxHeight/matrixHeight/tileHeight.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void addTileMatrixIllegalBounds2() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
File testFile = this.getRandomFile(7);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0,0.0,90.0,180.0),
gpkg.core().getSpatialReferenceSystem(4326));
int zoomLevel = 5;
int matrixWidth = 10;
int matrixHeight = 11;
int tileWidth = 256;
int tileHeight = 512;
double pixelXSize = tileSet.getBoundingBox().getWidth()/matrixWidth/tileWidth;
double pixelYSize = 500.23123;//invalid pixel y size
gpkg.tiles().addTileMatrix(tileSet, zoomLevel, matrixWidth, matrixHeight, tileWidth, tileHeight, pixelXSize, pixelYSize);
fail("Expected GeopackageTiles to throw an IllegalArgtumentException when pixelXSize != boundingBoxWidth/matrixWidth/tileWidth.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void getTileMatricesNullParameter() throws FileAlreadyExistsException, ClassNotFoundException
, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(12);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles().getTileMatrices(null);
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when giving getTileMatrices a TileSet that is null.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage getTIleMatrix can
* retrieve the correct TileMatrix from the GeoPackage.
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws SQLException
* @throws ConformanceException
* @throws FileNotFoundException
*/
@Test
public void getTileMatrixVerify() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(6);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0,0.0,100.0,100.0),
gpkg.core().getSpatialReferenceSystem(-1));
int matrixHeight = 2;
int matrixWidth = 6;
int tileHeight = 512;
int tileWidth = 256;
gpkg.tiles().addTileMatrix(tileSet,
1,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/tileWidth,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/tileHeight);
int matrixHeight2 = 1;
int matrixWidth2 = 3;
int tileHeight2 = 512;
int tileWidth2 = 256;
final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet,
0,
matrixWidth2,
matrixHeight2,
tileWidth2,
tileHeight2,
(tileSet.getBoundingBox().getWidth()/matrixWidth2)/tileWidth2,
(tileSet.getBoundingBox().getHeight()/matrixHeight2)/tileHeight2);
final TileMatrix returnedTileMatrix = gpkg.tiles().getTileMatrix(tileSet, 0);
Assert.assertTrue("GeoPackage did not return the TileMatrix expected", tileMatrix.getMatrixHeight() == returnedTileMatrix.getMatrixHeight() &&
tileMatrix.getMatrixWidth() == returnedTileMatrix.getMatrixWidth() &&
tileMatrix.getPixelXSize() == returnedTileMatrix.getPixelXSize() &&
tileMatrix.getPixelYSize() == returnedTileMatrix.getPixelYSize() &&
tileMatrix.getTableName() .equals(returnedTileMatrix.getTableName()) &&
tileMatrix.getTileHeight() == returnedTileMatrix.getTileHeight() &&
tileMatrix.getTileWidth() == returnedTileMatrix.getTileWidth() &&
tileMatrix.getZoomLevel() == returnedTileMatrix.getZoomLevel());
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage returns null if the TileMatrix entry does not
* exist in the GeoPackage file.
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws SQLException
* @throws ConformanceException
* @throws FileNotFoundException
*/
@Test
public void getTileMatrixNonExistant() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
final TileSet tileSet = gpkg.tiles()
.addTileSet("TableName",
"identifier",
"description",
new BoundingBox(0.0,0.0,0.0,0.0),
gpkg.core().getSpatialReferenceSystem(-1));
Assert.assertTrue("GeoPackage was supposed to return null when there is a nonexistant TileMatrix entry at that zoom level and TileSet",
null == gpkg.tiles().getTileMatrix(tileSet, 0));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
@Test(expected = IllegalArgumentException.class)
public void getTileMatrixNullParameter() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(10);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
gpkg.tiles().getTileMatrix(null, 8);
Assert.fail("GeoPackage should have thrown an IllegalArgumentException when giving a null parameter for TileSet in the method getTileMatrix");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if getTileMatrixSet retrieves the values that is expected
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws SQLException
* @throws ConformanceException
* @throws FileNotFoundException
*/
@Test
public void getTileMatrixSetVerify() throws FileAlreadyExistsException, ClassNotFoundException, SQLException, ConformanceException, FileNotFoundException
{
final File testFile = this.getRandomFile(12);
try(GeoPackage gpkg = new GeoPackage(testFile))
{
//values for tileMatrixSet
final String tableName = "tableName";
final String identifier = "identifier";
final String description = "description";
final BoundingBox bBox = new BoundingBox(1.0, 2.0, 3.0, 4.0);
final SpatialReferenceSystem srs = gpkg.core().getSpatialReferenceSystem(4326);
//add tileSet and tileMatrixSet to gpkg
final TileSet tileSet = gpkg.tiles().addTileSet(tableName, identifier, description, bBox, srs);
final TileMatrixSet tileMatrixSet = gpkg.tiles().getTileMatrixSet(tileSet);
Assert.assertTrue("Expected different values from getTileMatrixSet for SpatialReferenceSystem or BoundingBox or TableName.",
tileMatrixSet.getBoundingBox() .equals(bBox) &&
tileMatrixSet.getSpatialReferenceSystem().equals(srs) &&
tileMatrixSet.getTableName() .equals(tableName));
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage will throw a GeoPackage Conformance Exception
* when given a GeoPackage that violates a requirement with a severity equal
* to Error
* @throws SQLException
* @throws Exception
*/
@Test(expected = ConformanceException.class)
public void geoPackageConformanceException() throws SQLException, Exception
{
final File testFile = this.getRandomFile(19);
testFile.createNewFile();
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Open))
{
Assert.fail("GeoPackage did not throw a geoPackageConformanceException as expected.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can convert an
* Geodetic crsCoordinate to a relative tile coordinate
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordinateUpperRightGeodetic() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 1;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(45.213192, -45.234567, geodeticRefSys);//upper right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, -180.0, 85.0511287798066, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 0, Expected Column: 1. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 0 && relativeCoord.getColumn() == 1);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can convert an
* Geodetic crsCoordinate to a relative tile coordinate
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordinateUpperLeftGeodetic() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 1;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(85, -180, geodeticRefSys);//upper left tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, -180.0, 85.0511287798066, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 0, Expected Column: 0. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 0 && relativeCoord.getColumn() == 0);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can convert an
* Geodetic crsCoordinate to a relative tile coordinate
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordinateLowerLeftGeodetic() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 1;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(41, -90, geodeticRefSys);//lower left tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, -180.0, 85.0511287798066, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth() /matrixWidth )/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 1, Expected Column: 0. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 1 && relativeCoord.getColumn() == 1);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can convert an
* Geodetic crsCoordinate to a relative tile coordinate
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordinateLowerRightGeodetic() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 1;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(12, 0, geodeticRefSys);//lower right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, -180.0, 85.0511287798066, 0.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 1, Expected Column: 1. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 1 && relativeCoord.getColumn() == 2);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can convert an
* Global Mercator crsCoordinate to a relative tile coordinate
*
* @throws ConformanceException
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
* @throws FileAlreadyExistsException
* @throws IOException
*/
@Test
public void crsToRelativeTileCoordinateUpperLeftGlobalMercator() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 6;
final CoordinateReferenceSystem globalMercator = new CoordinateReferenceSystem("EPSG", 3395);
final Coordinate<Double> coordInMeters = LatLongConversions.latLongToMeters(5, -45);
final CrsCoordinate crsMercatorCoord = new CrsCoordinate(coordInMeters.getY(), coordInMeters.getX(), globalMercator);
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final Coordinate<Double> minBoundingBoxCoord = LatLongConversions.latLongToMeters(-60.0, -90.0);
final Coordinate<Double> maxBoundingBoxCoord = LatLongConversions.latLongToMeters( 10.0, 5.0);
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(minBoundingBoxCoord.getY(), minBoundingBoxCoord.getX(), maxBoundingBoxCoord.getY(), maxBoundingBoxCoord.getX()),
gpkg.core().addSpatialReferenceSystem("EPSG/World Mercator",
3395,
"EPSG",
3395,
"definition",
"description"));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth() /matrixWidth )/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsMercatorCoord, zoomLevel);
Assert.assertTrue(String.format("The GeoPackage did not return the expected row and column from the conversion crs to relative tile coordiante. "
+ " \nExpected Row: 0, Expected Column: 0.\nActual Row: %d, Actual Column: %d.",
relativeCoord.getRow(),
relativeCoord.getColumn()),
relativeCoord.getRow() == 0 && relativeCoord.getColumn() == 0);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can convert an
* Global Mercator crsCoordinate to a relative tile coordinate
*
* @throws ConformanceException
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
* @throws FileAlreadyExistsException
* @throws IOException
*/
@Test
public void crsToRelativeTileCoordinateUpperRightGlobalMercator() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 6;
final CoordinateReferenceSystem globalMercator = new CoordinateReferenceSystem("EPSG", 3395);
final Coordinate<Double> coordInMeters = LatLongConversions.latLongToMeters(5, -42);
final CrsCoordinate crsMercatorCoord = new CrsCoordinate(coordInMeters.getY(), coordInMeters.getX(), globalMercator);
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final Coordinate<Double> minBoundingBoxCoord = LatLongConversions.latLongToMeters(-60.0, -90.0);
final Coordinate<Double> maxBoundingBoxCoord = LatLongConversions.latLongToMeters( 10.0, 5.0);
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(minBoundingBoxCoord.getY(), minBoundingBoxCoord.getX(), maxBoundingBoxCoord.getY(), maxBoundingBoxCoord.getX()),
gpkg.core().addSpatialReferenceSystem("EPSG/World Mercator",
3395,
"EPSG",
3395,
"definition",
"description"));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsMercatorCoord, zoomLevel);
Assert.assertTrue(String.format("The GeoPackage did not return the expected row and column from the conversion crs to relative tile coordiante. "
+ " \nExpected Row: 0, Expected Column: 1.\nActual Row: %d, Actual Column: %d.",
relativeCoord.getRow(),
relativeCoord.getColumn()),
relativeCoord.getRow() == 0 && relativeCoord.getColumn() == 1);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can convert an
* Global Mercator crsCoordinate to a relative tile coordinate
*
* @throws ConformanceException
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
* @throws FileAlreadyExistsException
* @throws IOException
*/
@Test
public void crsToRelativeTileCoordinateLowerLeftGlobalMercator() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 6;
final CoordinateReferenceSystem globalMercator = new CoordinateReferenceSystem("EPSG", 3395);
final Coordinate<Double> coordInMeters = LatLongConversions.latLongToMeters(-45, -47);
final CrsCoordinate crsMercatorCoord = new CrsCoordinate(coordInMeters.getY(), coordInMeters.getX(), globalMercator);
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final Coordinate<Double> minBoundingBoxCoord = LatLongConversions.latLongToMeters(-60.0, -90.0);
final Coordinate<Double> maxBoundingBoxCoord = LatLongConversions.latLongToMeters( 10.0, 5.0);
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(minBoundingBoxCoord.getY(), minBoundingBoxCoord.getX(), maxBoundingBoxCoord.getY(), maxBoundingBoxCoord.getX()),
gpkg.core().addSpatialReferenceSystem("EPSG/World Mercator",
3395,
"EPSG",
3395,
"definition",
"description"));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsMercatorCoord, zoomLevel);
Assert.assertTrue(String.format("The GeoPackage did not return the expected row and column from the conversion crs to relative tile coordiante. "
+ " \nExpected Row: 1, Expected Column: 0.\nActual Row: %d, Actual Column: %d.",
relativeCoord.getRow(),
relativeCoord.getColumn()),
relativeCoord.getRow() == 1 && relativeCoord.getColumn() == 0);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if the GeoPackage can convert an
* Global Mercator crsCoordinate to a relative tile coordinate
*
* @throws ConformanceException
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
* @throws FileAlreadyExistsException
* @throws IOException
*/
@Test
public void crsToRelativeTileCoordinateLowerRightGlobalMercator() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 6;
final CoordinateReferenceSystem globalMercator = new CoordinateReferenceSystem("EPSG", 3395);
final Coordinate<Double> coordInMeters = LatLongConversions.latLongToMeters(-55,5);
final CrsCoordinate crsMercatorCoord = new CrsCoordinate(coordInMeters.getY(), coordInMeters.getX(), globalMercator);
final File testFile = this.getRandomFile(9);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final Coordinate<Double> minBoundingBoxCoord = LatLongConversions.latLongToMeters(-60.0, -90.0);
final Coordinate<Double> maxBoundingBoxCoord = LatLongConversions.latLongToMeters( 10.0, 5.0);
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(minBoundingBoxCoord.getY(), minBoundingBoxCoord.getX(), maxBoundingBoxCoord.getY(), maxBoundingBoxCoord.getX()),
gpkg.core().addSpatialReferenceSystem("EPSG/World Mercator",
3395,
"EPSG",
3395,
"definition",
"description"));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsMercatorCoord, zoomLevel);
Assert.assertTrue(String.format("The GeoPackage did not return the expected row and column from the conversion crs to relative tile coordiante. "
+ " \nExpected Row: 1, Expected Column: 1.\nActual Row: %d, Actual Column: %d.",
relativeCoord.getRow(),
relativeCoord.getColumn()),
relativeCoord.getRow() == 1 && relativeCoord.getColumn() == 2);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if a GeoPackage can translate a
* crs to a relative tile coordinate when there
* are multiple zoom levels and when there are
* more tiles at the higher zoom
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordinateMultipleZoomLevels() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 5;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(-1.25, -27.5, geodeticRefSys);
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(-60.0, -100.0, 60.0, 100.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth1 = 16;
final int matrixHeight1 = 24;
final int pixelXSize = 256;
final int pixelYSize = 512;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth1,
matrixHeight1,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth() /matrixWidth1 )/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight1)/pixelYSize);
final int matrixWidth2 = 4;
final int matrixHeight2 = 6;
final int zoomLevel2 = 3;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel2,
matrixWidth2,
matrixHeight2,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth() /matrixWidth2 )/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight2)/pixelYSize);
final int matrixWidth3 = 8;
final int matrixHeight3 = 12;
final int zoomLevel3 = 4;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel3,
matrixWidth3,
matrixHeight3,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth() /matrixWidth3 )/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight3)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 12, Expected Column: 5. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 12 && relativeCoord.getColumn() == 5);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests the validity of the transformation of
* crs to relative tile coordinate when the crs
* coordinate lies in the middle of four tiles.
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordEdgeCase() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(36.45, 76.4875, geodeticRefSys);//lower right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, -180.0, 85.05, 90.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 20;
final int matrixHeight = 7;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 2, Expected Column: 18. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 3 && relativeCoord.getColumn() == 18);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests the validity of the transformation of
* crs to relative tile coordinate when the crs
* coordinate lies between two tiles on top of each other
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordEdgeCase2() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(25, 10, geodeticRefSys);//lower right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 0, Expected Column: 0. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 1 && relativeCoord.getColumn() == 0);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests the validity of the transformation of
* crs to relative tile coordinate when the crs
* coordinate lies on the left border
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordEdgeCase3() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(40, 0, geodeticRefSys);//upper Left tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 0, Expected Column: 0. \nActual Row: %d, Actual Column: %d",
relativeCoord.getRow(),
relativeCoord.getColumn()),
relativeCoord.getRow() == 0 && relativeCoord.getColumn() == 0);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests the validity of the transformation of
* crs to relative tile coordinate when the crs
* coordinate lies on the right border
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordEdgeCase4() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(30, 30, geodeticRefSys);//upper right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 0, Expected Column: 1. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 0 && relativeCoord.getColumn() == 2);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests the validity of the transformation of
* crs to relative tile coordinate when the crs
* coordinate lies on the top border
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordEdgeCase5() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(50, 20, geodeticRefSys);//upper right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 0, Expected Column: 1. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 0 && relativeCoord.getColumn() == 1);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests the validity of the transformation of
* crs to relative tile coordinate when the crs
* coordinate lies on the bottom border
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordEdgeCase6() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(0, 20, geodeticRefSys);//lower right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue(String.format("The crsToRelativeTileCoordinate did not return the expected values. "
+ "\nExpected Row: 1, Expected Column: 1. \nActual Row: %d, Actual Column: %d", relativeCoord.getRow(), relativeCoord.getColumn()),
relativeCoord.getRow() == 2 && relativeCoord.getColumn() == 1);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if a GeoPackage will throw the appropriate
* exception when giving the method a null value for
* crsCoordinate.
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test(expected = IllegalArgumentException.class)
public void crsToRelativeTileCoordException() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(4326));
gpkg.tiles().crsToRelativeTileCoordinate(tileSet, null, 0);
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when trying to input a crs tile coordinate that was null to the method crsToRelativeTileCoordinate.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* Tests if a GeoPackage will throw the appropriate
* exception when giving the method a null value for
* crsCoordinate.
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test(expected = IllegalArgumentException.class)
public void crsToRelativeTileCoordException2() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final int zoomLevel = 1;
final CoordinateReferenceSystem coordinateReferenceSystem = new CoordinateReferenceSystem("Police", 99);
final CrsCoordinate crsCoord = new CrsCoordinate(20, 15, coordinateReferenceSystem);
gpkg.tiles().crsToRelativeTileCoordinate(null, crsCoord, zoomLevel);
Assert.fail("Expected the GeoPackage to throw an IllegalArgumentException when trying to input a tileSet that was null to the method crsToRelativeTileCoordinate.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests that the appropriate exception
* is thrown when trying to find a crs coordinate
* from a different SRS from the tiles.
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test(expected = IllegalArgumentException.class)
public void crsToRelativeTileCoordException3() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(50, 20, geodeticRefSys);//lower right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(-1));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.fail("Expected the GoePackage to throw an exception when the crs coordinate and the tiles are from two different projections.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests that the appropriate exception
* is thrown when trying to find a crs coordinate
* from with a zoom level that is not in the matrix table
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordException4() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(50, 20, geodeticRefSys);//lower right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
final int differentZoomLevel = 12;
gpkg.tiles().addTileMatrix(tileSet,
differentZoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeTileCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue("Expected the GeoPackage to return a null value when the crs tile coordinate zoom level is not in the tile matrix table.",
relativeTileCoord == null);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests that the appropriate exception
* is thrown when trying to find a crs coordinate
* is not within bounds
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test
public void crsToRelativeTileCoordException5() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG",4326);
final CrsCoordinate crsCoord = new CrsCoordinate(-50, 20, geodeticRefSys);//lower right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
final RelativeTileCoordinate relativeTileCoord = gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.assertTrue("Expected the GeoPackage to return a null value when the crs tile coordinate is outside of the bounding box.",
relativeTileCoord == null);
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
/**
* This tests that the appropriate exception
* is thrown when trying to find a crs coordinate
* from a different SRS from the tiles.
*
* @throws FileAlreadyExistsException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws SQLException
* @throws ConformanceException
*/
@Test(expected = IllegalArgumentException.class)
public void crsToRelativeTileCoordException6() throws FileAlreadyExistsException, ClassNotFoundException, FileNotFoundException, SQLException, ConformanceException
{
final int zoomLevel = 15;
final CoordinateReferenceSystem geodeticRefSys = new CoordinateReferenceSystem("EPSG", 3857);
final CrsCoordinate crsCoord = new CrsCoordinate(50, 20, geodeticRefSys);//lower right tile
final File testFile = this.getRandomFile(8);
try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create))
{
final TileSet tileSet = gpkg.tiles().addTileSet("tableName",
"identifier",
"description",
new BoundingBox(0.0, 0.0, 50.0, 30.0),
gpkg.core().getSpatialReferenceSystem(4326));
final int matrixWidth = 2;
final int matrixHeight = 2;
final int pixelXSize = 256;
final int pixelYSize = 256;
gpkg.tiles().addTileMatrix(tileSet,
zoomLevel,
matrixWidth,
matrixHeight,
pixelXSize,
pixelYSize,
(tileSet.getBoundingBox().getWidth()/matrixWidth)/pixelXSize,
(tileSet.getBoundingBox().getHeight()/matrixHeight)/pixelYSize);
gpkg.tiles().crsToRelativeTileCoordinate(tileSet, crsCoord, zoomLevel);
Assert.fail("Expected the GoePackage to throw an exception when the crs coordinate and the tiles are from two different projections.");
}
finally
{
if(testFile.exists())
{
if(!testFile.delete())
{
throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile));
}
}
}
}
private static byte[] createImageBytes() throws IOException
{
return ImageUtility.bufferedImageToBytes(new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB), "PNG");
}
private String getRanString(final int length)
{
final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
final char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(this.randomGenerator.nextInt(characters.length()));
}
return new String(text);
}
private File getRandomFile(final int length)
{
File testFile;
do
{
testFile = new File(String.format(FileSystems.getDefault().getPath(this.getRanString(length)).toString() + ".gpkg"));
}
while (testFile.exists());
return testFile;
}
private Connection getConnection(final String filePath) throws Exception
{
Class.forName("org.sqlite.JDBC"); // Register the driver
return DriverManager.getConnection("jdbc:sqlite:" + filePath);
}
}
|
package DebugAndJDK8;
import java.util.ArrayList;
public class UnsafeArrayLIst {
static ArrayList al=new ArrayList();
static class AddTask implements Runnable{
public void run() {
try{
Thread.sleep(100);
}catch (InterruptedException e){
}
for(int i=0;i<1000000;i++){
al.add(new Object());
}
}
}
public static void main(String[] args) throws InterruptedException{
Thread t1=new Thread(new AddTask(),"t1");
Thread t2=new Thread(new AddTask(),"t2");
t1.start();
t2.start();
Thread t3=new Thread(new Runnable() {
public void run() {
while (true){
try{
Thread.sleep(1000);
}catch (InterruptedException e){
}
}
}
},"t3");
t3.start();
}
}
|
package org.minimalj.model.test;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.minimalj.application.DevMode;
import org.minimalj.model.EnumUtils;
import org.minimalj.model.PropertyInterface;
import org.minimalj.model.ViewUtil;
import org.minimalj.model.annotation.AnnotationUtil;
import org.minimalj.model.properties.FlatProperties;
import org.minimalj.model.properties.Properties;
import org.minimalj.util.FieldUtils;
import org.minimalj.util.GenericUtils;
import org.minimalj.util.StringUtils;
import org.minimalj.util.resources.Resources;
/**
* Test some restricitions on model classes.<p>
*
* These tests are called by JUnit tests but also by Persistence.
* They are fast and its better to see problems at startup of an application.
*/
public class ModelTest {
private final Collection<Class<?>> mainModelClasses;
private Set<Class<?>> testedClasses = new HashSet<Class<?>>();
private final List<String> problems = new ArrayList<String>();
public ModelTest(Class<?>... mainModelClasses) {
this(Arrays.asList(mainModelClasses));
}
public ModelTest(Collection<Class<?>> mainModelClasses) {
this.mainModelClasses = mainModelClasses;
test();
}
private void test() {
testedClasses.clear();
for (Class<?> clazz : mainModelClasses) {
testClass(clazz, true);
}
}
public List<String> getProblems() {
return problems;
}
public boolean isValid() {
return problems.isEmpty();
}
private void testClass(Class<?> clazz, boolean listsAllowed) {
if (!testedClasses.contains(clazz)) {
testedClasses.add(clazz);
testId(clazz);
testVersion(clazz);
testConstructor(clazz);
testFields(clazz, listsAllowed);
problems.addAll(FlatProperties.testProperties(clazz));
if (DevMode.isActive()) {
testResources(clazz);
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void testConstructor(Class<?> clazz) {
if (Enum.class.isAssignableFrom(clazz)) {
try {
EnumUtils.createEnum((Class<Enum>) clazz, "Test");
} catch (Exception e) {
problems.add("Not possible to create runtime instance of enum " + clazz.getName() + ". Possibly there is no empty constructor");
}
} else {
try {
if (!Modifier.isPublic(clazz.getConstructor().getModifiers())) {
problems.add("Constructor of " + clazz.getName() + " not public");
}
} catch (NoSuchMethodException e) {
problems.add(clazz.getName() + " has no public empty constructor");
}
}
}
private void testId(Class<?> clazz) {
try {
Field fieldId = clazz.getField("id");
if (mainModelClasses.contains(clazz)) {
if (fieldId.getType() == Long.class || fieldId.getType() == Integer.class || fieldId.getType() == Short.class || fieldId.getType() == Byte.class) {
problems.add(clazz.getName() + ": Domain classes ids must be of primitiv type (byte, short, int or long)");
}
if (!FieldUtils.isPublic(fieldId)) {
problems.add(clazz.getName() + ": field id must be public");
}
} else {
problems.add(clazz.getName() + ": Only domain classes are allowed to have an id field");
}
} catch (NoSuchFieldException e) {
if (mainModelClasses.contains(clazz)) {
problems.add(clazz.getName() + ": Domain classes must have an id field of type int oder long");
}
} catch (SecurityException e) {
problems.add(clazz.getName() + " makes SecurityException with the id field");
}
}
private void testVersion(Class<?> clazz) {
try {
Field fieldVersion = clazz.getField("version");
if (mainModelClasses.contains(clazz)) {
if (fieldVersion.getType() == Integer.class) {
problems.add(clazz.getName() + ": Domain classes version must be of primitiv type int");
}
if (!FieldUtils.isPublic(fieldVersion)) {
problems.add(clazz.getName() + ": field version must be public");
}
} else {
problems.add(clazz.getName() + ": Only domain classes are allowed to have an version field");
}
} catch (NoSuchFieldException e) {
// thats ok, version is not mandatory
} catch (SecurityException e) {
problems.add(clazz.getName() + " makes SecurityException with the id field");
}
}
private void testFields(Class<?> clazz, boolean listsAllowed) {
Field[] fields = clazz.getFields();
for (Field field : fields) {
testField(field, listsAllowed);
}
}
private void testField(Field field, boolean listsAllowed) {
if (FieldUtils.isPublic(field) && !FieldUtils.isStatic(field) && !FieldUtils.isTransient(field) && !field.getName().equals("id") && !field.getName().equals("version")) {
testFieldType(field);
testNoMethodsForPublicField(field);
Class<?> fieldType = field.getType();
if (fieldType == String.class || fieldType == Integer.class || fieldType == Long.class) {
testSize(field);
} else if (List.class.equals(fieldType) && !listsAllowed) {
String messagePrefix = field.getName() + " of " + field.getDeclaringClass().getName();
problems.add(messagePrefix + ": not allowed. Only main model class or inline fields in these classes may contain lists");
}
}
}
private void testFieldType(Field field) {
Class<?> fieldType = field.getType();
String messagePrefix = field.getName() + " of " + field.getDeclaringClass().getName();
if (fieldType == List.class || fieldType == Set.class) {
if (!FieldUtils.isFinal(field)) {
problems.add(messagePrefix + " must be final (" + fieldType.getSimpleName() + " Fields must be final)");
}
if (fieldType == List.class) {
testListFieldType(field, messagePrefix);
} else if (fieldType == Set.class) {
testSetFieldType(field, messagePrefix);
}
} else if (!ViewUtil.isView(field)) {
testFieldType(fieldType, messagePrefix, FieldUtils.isFinal(field));
}
}
private void testListFieldType(Field field, String messagePrefix) {
Class<?> listType = null;
try {
listType = GenericUtils.getGenericClass(field);
} catch (Exception x) {
// silent
}
if (listType != null) {
messagePrefix = "Generic of " + messagePrefix;
testFieldType(listType, messagePrefix, false);
} else {
problems.add("Could not evaluate generic of " + messagePrefix);
}
}
private void testSetFieldType(Field field, String messagePrefix) {
@SuppressWarnings("rawtypes")
Class setType = null;
try {
setType = GenericUtils.getGenericClass(field);
} catch (Exception x) {
// silent
}
if (setType != null) {
if (!Enum.class.isAssignableFrom(setType)) {
problems.add("Set type must be an enum class: " + messagePrefix);
}
@SuppressWarnings("unchecked")
List<?> values = EnumUtils.itemList(setType);
if (values.size() > 32) {
problems.add("Set enum must not have more than 32 elements: " + messagePrefix);
}
} else {
problems.add("Could not evaluate generic of " + messagePrefix);
}
}
private void testFieldType(Class<?> fieldType, String messagePrefix, boolean listsAllowed) {
if (!FieldUtils.isAllowedPrimitive(fieldType)) {
if (fieldType.isPrimitive()) {
problems.add(messagePrefix + " has invalid Type");
}
if (Modifier.isAbstract(fieldType.getModifiers())) {
problems.add(messagePrefix + " must not be of an abstract Type");
}
if (mainModelClasses.contains(fieldType)) {
problems.add(messagePrefix + " may not reference the other main model class " + fieldType.getSimpleName());
}
if (fieldType.isArray()) {
problems.add(messagePrefix + " is an array which is not allowed");
}
testClass(fieldType, listsAllowed);
}
}
private void testSize(Field field) {
PropertyInterface property = Properties.getProperty(field);
try {
AnnotationUtil.getSize(property);
} catch (IllegalArgumentException x) {
problems.add("Missing size for: " + property.getDeclaringClass().getName() + "." + property.getFieldPath());
}
}
private void testNoMethodsForPublicField(Field field) {
PropertyInterface property = Properties.getProperty(field);
if (property != null) {
if (property.getClass().getSimpleName().startsWith("Method")) {
problems.add("A public attribute must not have getter or setter methods: " + field.getDeclaringClass().getName() + "." + field.getName());
}
} else {
problems.add("No property for " + field.getName());
}
}
private void testResources(Class<?> clazz) {
for (PropertyInterface property : FlatProperties.getProperties(clazz).values()) {
if (StringUtils.equals(property.getFieldName(), "id", "version")) continue;
String resourceText = Resources.getObjectFieldName(Resources.getResourceBundle(), property);
if (resourceText.startsWith("!!")) {
System.out.println(clazz.getSimpleName() + "." + resourceText.substring(2) + " = ");
}
}
}
}
|
package org.gjt.fredde.silence.format.xm;
/**
* A class that stores channel data
*
* @version $Id: Channel.java,v 1.3 2000/10/01 17:06:38 fredde Exp $
* @author Fredrik Ehnbom
*/
class Channel {
private Xm xm;
public Channel(Xm xm) {
this.xm = xm;
}
private int currentNote = 0;
private int currentInstrument = 0;
private int currentVolume = 0;
private int currentEffect = 0;
private int currentEffectParam = 0;
private double currentPitch = 0;
private double currentPos = 0;
private final double calcPitch(int note) {
note += xm.instrument[currentInstrument].sample[0].relativenote;
double period = 10*12*16*4 - note*16*4 - xm.instrument[currentInstrument].sample[0].finetune/2;
double freq = 8363 * Math.pow(2, ((6 * 12 * 16 * 4 - period) / (12 * 16 * 4)));
double per = 1 / ((double) xm.deviceSampleRate / freq);
return per;
}
final int update(Pattern pattern, int patternpos) {
int check = pattern.data[patternpos++];
if ((check & 0x80) != 0) {
// note
if ((check & 0x1) != 0) {
currentNote = pattern.data[patternpos++];
currentPitch = calcPitch(currentNote);
currentPos = 0;
}
// instrument
if ((check & 0x2) != 0) currentInstrument = pattern.data[patternpos++] - 1;
// volume
if ((check & 0x4) != 0) currentVolume = pattern.data[patternpos++];
// effect
if ((check & 0x8) != 0) currentEffect = pattern.data[patternpos++];
else currentEffect = 0;
// effect param
if ((check & 0x10) != 0) currentEffectParam = pattern.data[patternpos++];
else currentEffectParam = 0;
} else {
currentNote = check;
currentInstrument = pattern.data[patternpos++] - 1;
currentVolume = pattern.data[patternpos++];
currentEffect = pattern.data[patternpos++];
currentEffectParam = pattern.data[patternpos++];
currentPitch = calcPitch(currentNote);
currentPos = 0;
}
switch (currentEffect) {
case 0x0F: // set tempo
if (currentEffectParam > 0x20) {
xm.default_bpm = currentEffectParam;
xm.samples_per_tick = (5 * xm.deviceSampleRate) / (2 * xm.default_bpm);
} else {
xm.default_tempo = currentEffectParam;
xm.tempo = xm.default_tempo;
}
break;
}
return patternpos;
}
final void play(int[] buffer, int off, int len) {
if (currentNote == 97 || currentNote == 0) return;
for (int i = off; i < off+len; i++) {
buffer[i] += (xm.instrument[currentInstrument].sample[0].sampleData[(int) currentPos] * 128 & 65535) | (xm.instrument[currentInstrument].sample[0].sampleData[(int) currentPos] * 128 << 16);
currentPos += currentPitch;
if ( ((int) currentPos) >= xm.instrument[currentInstrument].sample[0].sampleData.length) {
currentPos = 0;
}
}
}
}
/*
* ChangeLog:
* $Log: Channel.java,v $
* Revision 1.3 2000/10/01 17:06:38 fredde
* basic playing abilities added
*
* Revision 1.2 2000/09/29 19:39:48 fredde
* no need to be public
*
* Revision 1.1.1.1 2000/09/25 16:34:34 fredde
* initial commit
*
*/
|
package necromunda;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Observable;
import java.util.Set;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
public class Necromunda extends Observable {
public enum SelectionMode {
DEPLOY,
SELECT,
MOVE,
CLIMB,
TARGET,
REROLL
}
public enum Phase {
MOVEMENT("Movement"),
SHOOTING("Shooting"),
HAND_TO_HAND("Hand to Hand"),
RECOVERY("Recovery");
private String literal;
private Phase(String literal) {
this.literal = literal;
}
@Override
public String toString() {
return literal;
}
}
public static final float RUN_SPOT_DISTANCE = 8;
public static final float UNPIN_BY_INITIATIVE_DISTANCE = 2;
public static final float SUSTAINED_FIRE_RADIUS = 4;
public static final float STRAY_SHOT_RADIUS = 0.5f;
public static Necromunda game;
private static String statusMessage;
private List<Gang> gangs;
private List<Building> buildings;
private Fighter selectedFighter;
private LinkedList<Fighter> deployQueue;
private SelectionMode selectionMode;
private Gang currentGang;
private int turn;
private Phase phase;
private JFrame necromundaFrame;
public static final int[][] STRENGTH_RESISTANCE_MAP = {
{4, 5, 6, 6, 7, 7, 7, 7, 7, 7},
{3, 4, 5, 6, 6, 7, 7, 7, 7, 7},
{2, 3, 4, 5, 6, 6, 7, 7, 7, 7},
{2, 2, 3, 4, 5, 6, 6, 7, 7, 7},
{2, 2, 2, 3, 4, 5, 6, 6, 7, 7},
{2, 2, 2, 2, 3, 4, 5, 6, 6, 7},
{2, 2, 2, 2, 2, 3, 4, 5, 6, 6},
{2, 2, 2, 2, 2, 2, 3, 4, 5, 6},
{2, 2, 2, 2, 2, 2, 2, 3, 4, 5},
{2, 2, 2, 2, 2, 2, 2, 2, 3, 4},
};
/**
* @param args
*/
public static void main(String[] args) {
Necromunda game = Necromunda.getInstance();
}
public Necromunda() {
gangs = new ArrayList<Gang>();
selectionMode = SelectionMode.DEPLOY;
turn = 1;
statusMessage = "";
buildings = createBuildings();
deployQueue = new LinkedList<Fighter>();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
initialiseGUI();
}
});
}
public static Necromunda getInstance() {
if (game == null) {
game = new Necromunda();
}
return game;
}
private List<Building> createBuildings() {
List<Building> buildings = new ArrayList<Building>();
buildings.add(new Building(FastMath.PI / 4, new Vector3f(8, 0, 8), "01"));
buildings.add(new Building(FastMath.PI / -8, new Vector3f(40, 0, 8), "01"));
buildings.add(new Building(FastMath.PI / 2, new Vector3f(6, 0, 40), "01"));
buildings.add(new Building(0, new Vector3f(24, 0, 22), "03"));
buildings.add(new Building(0, new Vector3f(38, 0, 40), "01"));
buildings.add(new Building(FastMath.PI / 8 * 3, new Vector3f(8, 0, 24), "02"));
buildings.add(new Building(FastMath.PI / 8 * -3, new Vector3f(40, 0, 24), "02"));
return buildings;
}
private void initialiseGUI() {
GangGenerationPanel gangGenerationPanel = new GangGenerationPanel(this);
necromundaFrame = new JFrame("Necromunda");
necromundaFrame.setSize(1000, 800);
necromundaFrame.setResizable(false);
necromundaFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
necromundaFrame.setLocationRelativeTo(null);
necromundaFrame.add(gangGenerationPanel);
necromundaFrame.setVisible(true);
}
public void fighterDeployed() {
selectedFighter = deployQueue.poll();
if (selectedFighter == null) {
currentGang = gangs.get(0);
currentGang.turnStarted();
selectionMode = SelectionMode.SELECT;
phase = Phase.MOVEMENT;
}
}
public void endTurn() {
currentGang.turnEnded();
if (((gangs.indexOf(currentGang) + 1) % gangs.size()) == 0) {
turn++;
}
currentGang = getNextGang();
currentGang.turnStarted();
selectedFighter = null;
selectionMode = SelectionMode.SELECT;
phase = Phase.MOVEMENT;
}
private Gang getNextGang() {
Gang gang = null;
int gangIndex = gangs.indexOf(currentGang);
if ((gangIndex + 1) == gangs.size()) {
gang = gangs.get(0);
}
else {
gang = gangs.get(gangIndex + 1);
}
return gang;
}
public void nextPhase() {
switch (phase) {
case MOVEMENT:
phase = Phase.SHOOTING;
break;
case SHOOTING:
case HAND_TO_HAND:
case RECOVERY:
}
selectionMode = SelectionMode.SELECT;
}
public void updateStatus() {
setChanged();
notifyObservers();
}
public void commitGeneratedGangs(Enumeration<?> gangs) {
while (gangs.hasMoreElements()) {
Gang nextGang = (Gang)gangs.nextElement();
deployQueue.addAll(nextGang.getGangMembers());
if (getCurrentGang() == null) {
setCurrentGang(nextGang);
setSelectedFighter(deployQueue.poll());
}
getGangs().add(nextGang);
}
}
public Gang getCurrentGang() {
return currentGang;
}
public void setCurrentGang(Gang currentGang) {
this.currentGang = currentGang;
}
public Fighter getSelectedFighter() {
return selectedFighter;
}
public void setSelectedFighter(Fighter selectedFighter) {
this.selectedFighter = selectedFighter;
}
public List<Gang> getGangs() {
return gangs;
}
public JFrame getNecromundaFrame() {
return necromundaFrame;
}
public SelectionMode getSelectionMode() {
return selectionMode;
}
public void setSelectionMode(SelectionMode selectionMode) {
this.selectionMode = selectionMode;
}
public List<Building> getBuildings() {
return buildings;
}
public int getTurn() {
return turn;
}
public Phase getPhase() {
return phase;
}
public void setPhase(Phase phase) {
this.phase = phase;
}
public static String getStatusMessage() {
return statusMessage;
}
public static void setStatusMessage(String statusMessage) {
Necromunda.statusMessage = statusMessage;
}
public static void appendToStatusMessage(String statusMessage) {
if (Necromunda.statusMessage.equals("")) {
Necromunda.statusMessage = statusMessage;
}
else {
Necromunda.statusMessage = String.format("%s %s", Necromunda.statusMessage, statusMessage);
}
}
public List<Fighter> getHostileGangers() {
return currentGang.getHostileGangers(gangs);
}
}
|
import java.lang.module.FindException;
import java.lang.module.ModuleDescriptor.Version;
import java.lang.module.ModuleFinder;
import java.lang.module.ResolutionException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.spi.ToolProvider;
interface bach {
static void main(String... args) {
var cache = Path.of(".bach/cache");
if (args.length == 2) {
if ("version".equals(args[0])) {
version(cache, Version.parse(args[1]));
return;
}
}
var bach = find("bach", ModuleFinder.of(cache));
if (bach.isEmpty()) {
System.err.println("Bach not found in directoy: " + cache);
System.exit(-1);
}
var status = bach.get().run(System.out, System.err, args);
System.exit(status);
}
static void version(Path cache, Version version) {
var module = "com.github.sormuras.bach";
if (Files.isDirectory(cache))
try (var stream = Files.newDirectoryStream(cache, module + '*')) {
stream.forEach(bach::delete);
}
catch (Exception exception) { throw new Error("version() failed", exception); }
var jar = module + '@' + version + ".jar";
var source = "https://github.com/sormuras/bach/releases/download/" + version + '/' + jar;
load(source, cache.resolve(jar));
}
private static void delete(Path path) {
try { Files.deleteIfExists(path); }
catch (Exception exception) { throw new Error("delete() failed", exception); }
}
private static void load(String source, Path target) {
System.out.println(" " + target + " << " + source);
try (var stream = new URL(source).openStream()) {
if (target.getParent() != null) Files.createDirectories(target.getParent());
Files.copy(stream, target);
}
catch (Exception exception) { throw new Error("load() failed", exception); }
}
private static Optional<ToolProvider> find(String name, ModuleFinder finder) {
try {
var boot = ModuleLayer.boot();
var configuration = boot.configuration().resolveAndBind(ModuleFinder.of(), finder, Set.of());
var parent = ClassLoader.getSystemClassLoader();
var controller = ModuleLayer.defineModulesWithOneLoader(configuration, List.of(boot), parent);
var layer = controller.layer();
var serviceLoader = ServiceLoader.load(layer, ToolProvider.class);
return serviceLoader.stream()
.map(ServiceLoader.Provider::get)
.filter(tool -> tool.name().equals(name))
.findFirst();
} catch (FindException | ResolutionException exception) {
throw new Error("Loading tool provider failed for name: " + name, exception);
}
}
}
|
import java.util.*;
/**
* A map of the tunnel system.
*/
public class Map
{
public Map (Vector<String> input, boolean debug)
{
_theMap = new Vector<Cell>();
_keys = new Vector<Character>();
_doors = new Vector<Character>();
_debug = debug;
createMap(input);
}
public Coordinate getEntrance ()
{
return _entrance;
}
/**
* Return the content of the Cell represented by the Coordinate.
*/
public char getContent (Coordinate coord)
{
int index = _theMap.indexOf(new Cell(coord));
Cell theCell = _theMap.get(index);
return theCell.getContents(); // assume no error
}
/*
* Is this Coordinate in range and can be moved into?
*/
public boolean validPosition (Coordinate coord)
{
if ((coord.getX() >= 0) && (coord.getY() >= 0))
{
if ((coord.getX() < _maxX) && (coord.getY() < _maxY))
{
int index = _theMap.indexOf(new Cell(coord));
if (index != -1)
{
Cell theCell = _theMap.get(index);
if (theCell != null)
return !theCell.isWall();
}
}
}
return false;
}
public int numberOfKeys ()
{
return _keys.size();
}
public int numberOfDoors ()
{
return _doors.size();
}
@Override
public String toString ()
{
Enumeration<Cell> iter = _theMap.elements();
int index = 1;
String str = "Map <"+_maxX+", "+_maxY+">:\n\n";
while (iter.hasMoreElements())
{
str += iter.nextElement().getContents();
if (index++ == _maxX)
{
str += "\n";
index = 1;
}
}
return str;
}
// create the map from input
private void createMap (Vector<String> input)
{
Enumeration<String> iter = input.elements();
int y = -1;
_maxX = input.get(0).length(); // all lines are the same length (check?)
while (iter.hasMoreElements())
{
y++;
String line = iter.nextElement();
for (int x = 0; x < _maxX; x++)
{
Cell theCell = new Cell(new Coordinate(x, y), line.charAt(x));
if (theCell.isEntrance())
_entrance = theCell.position(); // should be only one!
else
{
if (theCell.isKey())
_keys.add(theCell.getContents());
else
{
if (theCell.isDoor())
_doors.add(theCell.getContents());
}
}
if (_debug)
System.out.println(theCell);
_theMap.add(theCell);
}
}
_maxY = y+1;
}
private Vector<Cell> _theMap;
private int _maxX;
private int _maxY;
private Coordinate _entrance;
private Vector<Character> _keys;
private Vector<Character> _doors;
private boolean _debug;
}
|
/**
* @author ShengMin Zhang
* @notes
* My coding style is different when coding for an actual application.
* For example, I would put a class inside a package, handle exceptions, proper encapsulation and etc.
* Here as well as in any other algorithm contests, I prefer simplicity and less typing. :P
*
* @revison 1.0
* - Input size is small enough that I can try all possibilities
*
* Estimated time:
* less than 1s because each cube has at most 2*3*4 = 24 possible arrangments, there are 4 cubes, so 4 * 24 = 96 combinations
* there are 4! ways to stack those 4 cubes for any given combination, so 4! * 96 = 2304 possibilities to consider, which is much smaller than 10^7, so should be able to complete in <1s
*
* Actual time: less than 2s probably because of printing, duplicate checking, copying, and initialization of enum set
*
*/
import java.io.*;
import java.util.*;
enum Side {
FRONT,
LEFT,
BACK,
RIGHT,
TOP,
BOTTOM;
}
enum Color {
B,
R,
G,
Y;
}
class Cube {
final Color[] colors;
final Color[] originalColors;
final int id;
/**
* FRONT, LEFT, BACK, RIGHT, TOP, BOTTOM in that order
*/
Cube(int id, Color[] colors) {
this.id = id;
this.originalColors = colors;
this.colors = new Color[colors.length];
reset();
}
/**
* reset the colors to original colors
*/
Cube reset() {
for(int i = colors.length - 1; i >= 0; i
colors[i] = originalColors[i];
}
return this;
}
void swap(Side a, Side b){
Color colorA = colors[a.ordinal()];
Color colorB = colors[b.ordinal()];
colors[a.ordinal()] = colorB;
colors[b.ordinal()] = colorA;
}
/**
* Rotate the cube around Y-axis clockwise
*/
Cube rotateLeft(){
Color first = colors[0];
for(int i = 0; i < 3; i++) {
colors[i] = colors[i+1];
}
colors[3] = first;
return this;
}
/**
* Turn the cube upside down
*/
Cube flip(){
swap(Side.TOP, Side.BOTTOM);
swap(Side.FRONT, Side.BACK);
return this;
}
/**
* Rotate the original cube so that the side is the top side
*/
Cube setTop(Side side) {
switch(side) {
case LEFT:
case RIGHT:
// will do flip, so no need to seperate those two cases
swap(Side.TOP, Side.LEFT);
swap(Side.LEFT, Side.BOTTOM);
swap(Side.BOTTOM, Side.RIGHT);
break;
case FRONT:
case BACK:
swap(Side.TOP, Side.FRONT);
swap(Side.FRONT, Side.BOTTOM);
swap(Side.BOTTOM, Side.BACK);
break;
}
return this;
}
void print(PrintWriter pw){
pw.printf("Cube %d :", id);
for(int i = 0; i < colors.length; i++){
for(int j = 0; j < 7; j++) pw.print(' ');
pw.print(colors[i]);
}
pw.println();
}
}
public class CubeSolution {
static final Side[] TOPS = new Side[]{ Side.TOP, Side.LEFT, Side.FRONT };
PrintWriter pw;
Cube[] originalCubes = new Cube[] {
new Cube(1, new Color[]{ Color.R, Color.G, Color.B, Color.Y, Color.B, Color.Y }),
new Cube(2, new Color[]{ Color.R, Color.G, Color.G, Color.Y, Color.B, Color.B }),
new Cube(3, new Color[]{ Color.Y, Color.R, Color.B, Color.G, Color.Y, Color.R }),
new Cube(4, new Color[]{ Color.Y, Color.B, Color.G, Color.R, Color.R, Color.R })
};
Cube[] cubes = new Cube[originalCubes.length];
int[] indices = new int[originalCubes.length];
boolean[] usedIndex = new boolean[originalCubes.length];
void print() {
pw.println("
for(Cube cube: cubes){
cube.print(pw);
}
pw.println("
pw.println();
}
boolean check() {
for(int j = 0; j < 4; j++) {
Set<Color> seen = EnumSet.noneOf(Color.class);
for(int i = cubes.length - 1; i >= 0; i
Color color = cubes[i].colors[j];
if(seen.contains(color)) {
return false;
} else {
seen.add(color);
}
}
}
return true;
}
void permute(int level) {
if(level == cubes.length) {
rotateCubes(0);
return;
}
for(int i = 0; i < cubes.length; i++) {
if(usedIndex[i]) {
continue;
}
indices[level] = i;
usedIndex[i] = true;
permute(level+1);
usedIndex[i] = false;
}
}
void rotateCubes(int level) {
if(level == originalCubes.length) {
for(int i = 0; i < indices.length; i++){
cubes[i] = originalCubes[indices[i]];
}
if(check()) {
print();
}
return;
}
Cube cube = originalCubes[level];
for(int i = 0; i < TOPS.length; i++) {
cube.reset();
cube.setTop(TOPS[i]);
for(int flip = 0; flip < 2; flip++) {
if(flip != 0) cube.flip();
for(int j = 0; j < 4; j++) {
cube.rotateLeft();
rotateCubes(level+1);
}
}
}
}
void run() throws Exception {
// initial set up
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
permute(0);
pw.close();
}
public static void main(String[] args) throws Exception {
new CubeSolution().run();
}
}
|
package org.jivesoftware.smack;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.filter.ThreadFilter;
import org.jivesoftware.smack.filter.PacketFilter;
/**
* A chat is a series of messages sent between two users. Each chat has
* a unique ID, which is used to track which messages are part of the chat.
*
* @see XMPPConnection#createChat(String)
* @author Matt Tucker
*/
public class Chat {
/**
* A prefix helps to make sure that ID's are unique across mutliple instances.
*/
private static String prefix = StringUtils.randomString(5);
/**
* Keeps track of the current increment, which is appended to the prefix to
* forum a unique ID.
*/
private static long id = 0;
/**
* Returns the next unique id. Each id made up of a short alphanumeric
* prefix along with a unique numeric value.
*
* @return the next id.
*/
private static synchronized String nextID() {
return prefix + Long.toString(id++);
}
private XMPPConnection connection;
private String chatID;
private String participant;
private PacketFilter messageFilter;
private PacketCollector messageCollector;
/**
* Creates a new chat with the specified user.
*
* @param connection the connection the chat will use.
* @param participant the user to chat with.
*/
public Chat(XMPPConnection connection, String participant) {
this.connection = connection;
this.participant = participant;
// Automatically assign the next chat ID.
chatID = nextID();
messageFilter = new ThreadFilter(chatID);
messageCollector = connection.createPacketCollector(messageFilter);
}
/**
* Creates a new chat with the specified user and chat ID (the XMPP "thread).
*
* @param connection the connection the chat will use.
* @param participant the user to chat with.
* @param chatID the chat ID to use.
*/
public Chat(XMPPConnection connection, String participant, String chatID) {
this.connection = connection;
this.participant = participant;
this.chatID = chatID;
messageFilter = new ThreadFilter(chatID);
messageCollector = connection.createPacketCollector(messageFilter);
}
/**
* Returns the unique id of this chat, which corresponds to the
* <tt>thread</tt> field of XMPP messages.
*
* @return the unique ID of this chat.
*/
public String getChatID() {
return chatID;
}
/**
* Returns the name of the user the chat is with.
*
* @return the name of the user the chat is occuring with.
*/
public String getParticipant() {
return participant;
}
/**
* Sends the specified text as a message to the other chat participant.
* This is a convenience method for:
*
* <pre>
* Message message = chat.createMessage();
* message.setBody(messageText);
* chat.sendMessage(message);
* </pre>
*
* @param text the text to send.
* @throws XMPPException if sending the message fails.
*/
public void sendMessage(String text) throws XMPPException {
Message message = createMessage();
message.setBody(text);
connection.sendPacket(message);
}
/**
* Creates a new Message to the chat participant. The message returned
* will have its thread property set with this chat ID.
*
* @return a new message addressed to the chat participant and
* using the correct thread value.
* @see #sendMessage(Message)
*/
public Message createMessage() {
Message message = new Message(participant, Message.Type.CHAT);
message.setThread(chatID);
return message;
}
/**
* Sends a message to the other chat participant. The thread ID, recipient,
* and message type of the message will automatically set to those of this chat
* in case the Message was not created using the {@link #createMessage() createMessage}
* method.
*
* @param message the message to send.
* @throws XMPPException if an error occurs sending the message.
*/
public void sendMessage(Message message) throws XMPPException {
// Force the recipient, message type, and thread ID since the user elected
// to send the message through this chat object.
message.setTo(participant);
message.setType(Message.Type.CHAT);
message.setThread(chatID);
connection.sendPacket(message);
}
/**
* Polls for and returns the next message, or <tt>null</tt> if there isn't
* a message immediately available. This method provides significantly different
* functionalty than the {@link #nextMessage()} method since it's non-blocking.
* In other words, the method call will always return immediately, whereas the
* nextMessage method will return only when a message is available (or after
* a specific timeout).
*
* @return the next message if one is immediately available and
* <tt>null</tt> otherwise.
*/
public Message pollMessage() {
return (Message)messageCollector.pollResult();
}
/**
* Returns the next available message in the chat. The method call will block
* (not return) until a message is available.
*
* @return the next message.
*/
public Message nextMessage() {
return (Message)messageCollector.nextResult();
}
/**
* Returns the next available message in the chat. The method call will block
* (not return) until a packet is available or the <tt>timeout</tt> has elapased.
* If the timeout elapses without a result, <tt>null</tt> will be returned.
*
* @param timeout the maximum amount of time to wait for the next message.
* @return the next message, or <tt>null</tt> if the timeout elapses without a
* message becoming available.
*/
public Message nextMessage(long timeout) {
return (Message)messageCollector.nextResult(timeout);
}
/**
* Adds a packet listener that will be notified of any new messages in the
* chat.
*
* @param listener a packet listener.
*/
public void addMessageListener(PacketListener listener) {
connection.addPacketListener(listener, messageFilter);
}
}
|
import java.util.*;
import java.io.*;
public class Util
{
public static char RANGE_DELIMITER = '-';
public static char PASSWORD_DELIMITER = ':';
public static char SPACE = ' ';
public static Vector<PasswordData> loadData (String inputFile, boolean debug)
{
/*
* Open the data file and read it in.
*/
BufferedReader reader = null;
Vector<PasswordData> results = new Vector<PasswordData>();
try
{
reader = new BufferedReader(new FileReader(inputFile));
String line = null;
while ((line = reader.readLine()) != null)
{
/*
* Parse the line just read ...
*
* <min>-<max> <letter>: <password>
*
* Example: 5-10 b: bhbjlkbbbbbbb
*/
int rangeDelimiter = line.indexOf(RANGE_DELIMITER);
int space = line.indexOf(SPACE);
String minimum = line.substring(0, rangeDelimiter);
String maximum = line.substring(rangeDelimiter +1, space);
int passwordDelimiter = line.indexOf(PASSWORD_DELIMITER);
String letter = line.substring(space +1, passwordDelimiter);
String password = line.substring(passwordDelimiter +1).trim();
if (debug)
{
System.out.println("\nLoaded < "+minimum+", "+maximum+" >");
System.out.println("Letter: "+letter);
System.out.println("Password to check: "+password);
}
PasswordPolicy policy = new PasswordPolicy(Integer.parseInt(minimum), Integer.parseInt(maximum), letter.charAt(0));
}
}
catch (Throwable ex)
{
ex.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (Throwable ex)
{
}
}
return null;
}
private Util ()
{
}
}
|
package org.jgroups;
import java.io.*;
import java.util.Vector;
/**
* A view that is sent as a result of a merge.
* Whenever a group splits into subgroups, e.g., due to a network partition,
* and later the subgroups merge back together, a MergeView instead of a View
* will be received by the application. The MergeView class is a subclass of
* View and contains as additional instance variable: the list of views that
* were merged. For example, if the group denoted by view V1:(p,q,r,s,t)
* splits into subgroups V2:(p,q,r) and V2:(s,t), the merged view might be
* V3:(p,q,r,s,t). In this case the MergeView would contain a list of 2 views:
* V2:(p,q,r) and V2:(s,t).
*/
public class MergeView extends View {
protected Vector<View> subgroups=null; // subgroups that merged into this single view (a list of Views)
/**
* Used by externalization
*/
public MergeView() {
}
/**
* Creates a new view
*
* @param vid The view id of this view (can not be null)
* @param members Contains a list of all the members in the view, can be empty but not null.
* @param subgroups A list of Views representing the former subgroups
*/
public MergeView(ViewId vid, Vector<Address> members, Vector<View> subgroups) {
super(vid, members);
this.subgroups=subgroups;
}
/**
* Creates a new view
*
* @param creator The creator of this view (can not be null)
* @param id The lamport timestamp of this view
* @param members Contains a list of all the members in the view, can be empty but not null.
* @param subgroups A list of Views representing the former subgroups
*/
public MergeView(Address creator, long id, Vector<Address> members, Vector<View> subgroups) {
super(creator, id, members);
this.subgroups=subgroups;
}
public Vector<View> getSubgroups() {
return subgroups;
}
/**
* creates a copy of this view
*
* @return a copy of this view
*/
public Object clone() {
ViewId vid2=vid != null ? (ViewId)vid.clone() : null;
Vector<Address> members2=members != null ? (Vector<Address>)members.clone() : null;
Vector<View> subgroups2=subgroups != null ? (Vector<View>)subgroups.clone() : null;
return new MergeView(vid2, members2, subgroups2);
}
public View copy() {
return (MergeView)clone();
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append("MergeView::").append(super.toString()).append(", subgroups=").append(subgroups);
return sb.toString();
}
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeObject(subgroups);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
subgroups=(Vector<View>)in.readObject();
}
public void writeTo(DataOutputStream out) throws IOException {
super.writeTo(out);
// write subgroups
int len=subgroups != null? subgroups.size() : 0;
out.writeShort(len);
if(len == 0)
return;
for(View v: subgroups) {
if(v instanceof MergeView)
out.writeBoolean(true);
else
out.writeBoolean(false);
v.writeTo(out);
}
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
super.readFrom(in);
short len=in.readShort();
if(len > 0) {
View v;
subgroups=new Vector<View>();
for(int i=0; i < len; i++) {
boolean is_merge_view=in.readBoolean();
v=is_merge_view? new MergeView() : new View();
v.readFrom(in);
subgroups.add(v);
}
}
}
public int serializedSize() {
int retval=super.serializedSize();
retval+=Global.SHORT_SIZE; // for size of subgroups vector
if(subgroups == null)
return retval;
for(View v: subgroups) {
retval+=Global.BYTE_SIZE; // boolean for View or MergeView
retval+=v.serializedSize();
}
return retval;
}
}
|
package org.jgroups.util;
import org.jgroups.*;
import org.jgroups.auth.AuthToken;
import org.jgroups.blocks.Connection;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.jmx.JmxConfigurator;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.protocols.*;
import org.jgroups.protocols.pbcast.FLUSH;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.stack.IpAddress;
import org.jgroups.stack.ProtocolStack;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.security.MessageDigest;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* Collection of various utility routines that can not be assigned to other classes.
* @author Bela Ban
* @version $Id: Util.java,v 1.254 2010/02/26 15:37:52 belaban Exp $
*/
public class Util {
private static NumberFormat f;
private static Map<Class,Byte> PRIMITIVE_TYPES=new HashMap<Class,Byte>(15);
private static final byte TYPE_NULL = 0;
private static final byte TYPE_STREAMABLE = 1;
private static final byte TYPE_SERIALIZABLE = 2;
private static final byte TYPE_BOOLEAN = 10;
private static final byte TYPE_BYTE = 11;
private static final byte TYPE_CHAR = 12;
private static final byte TYPE_DOUBLE = 13;
private static final byte TYPE_FLOAT = 14;
private static final byte TYPE_INT = 15;
private static final byte TYPE_LONG = 16;
private static final byte TYPE_SHORT = 17;
private static final byte TYPE_STRING = 18;
private static final byte TYPE_BYTEARRAY = 19;
// constants
public static final int MAX_PORT=65535; // highest port allocatable
static boolean resolve_dns=false;
static boolean JGROUPS_COMPAT=false;
private static short COUNTER=1;
private static Pattern METHOD_NAME_TO_ATTR_NAME_PATTERN=Pattern.compile("[A-Z]+");
private static Pattern ATTR_NAME_TO_METHOD_NAME_PATTERN=Pattern.compile("_.");
/**
* Global thread group to which all (most!) JGroups threads belong
*/
private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups") {
public void uncaughtException(Thread t, Throwable e) {
LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e);
}
};
public static ThreadGroup getGlobalThreadGroup() {
return GLOBAL_GROUP;
}
private static Method NETWORK_INTERFACE_IS_UP=null;
private static Method NETWORK_INTERFACE_IS_LOOPBACK=null;
static {
try {
resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue();
}
catch (SecurityException ex){
resolve_dns=false;
}
f=NumberFormat.getNumberInstance();
f.setGroupingUsed(false);
// f.setMinimumFractionDigits(2);
f.setMaximumFractionDigits(2);
try {
String tmp=Util.getProperty(new String[]{Global.MARSHALLING_COMPAT}, null, null, false, "false");
JGROUPS_COMPAT=Boolean.valueOf(tmp).booleanValue();
}
catch (SecurityException ex){
}
PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN));
PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE));
PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR));
PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE));
PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT));
PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT));
PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG));
PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT));
PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING));
PRIMITIVE_TYPES.put(byte[].class, new Byte(TYPE_BYTEARRAY));
try {
NETWORK_INTERFACE_IS_UP=NetworkInterface.class.getMethod("isUp");
}
catch(Throwable e) {
}
try {
NETWORK_INTERFACE_IS_LOOPBACK=NetworkInterface.class.getMethod("isLoopback");
}
catch(Throwable e) {
}
}
public static void assertTrue(boolean condition) {
assert condition;
}
public static void assertTrue(String message, boolean condition) {
if(message != null)
assert condition : message;
else
assert condition;
}
public static void assertFalse(boolean condition) {
assertFalse(null, condition);
}
public static void assertFalse(String message, boolean condition) {
if(message != null)
assert !condition : message;
else
assert !condition;
}
public static void assertEquals(String message, Object val1, Object val2) {
if(message != null) {
assert val1.equals(val2) : message;
}
else {
assert val1.equals(val2);
}
}
public static void assertEquals(Object val1, Object val2) {
assertEquals(null, val1, val2);
}
public static void assertNotNull(String message, Object val) {
if(message != null)
assert val != null : message;
else
assert val != null;
}
public static void assertNotNull(Object val) {
assertNotNull(null, val);
}
public static void assertNull(String message, Object val) {
if(message != null)
assert val == null : message;
else
assert val == null;
}
/**
* Blocks until all channels have the same view
* @param timeout How long to wait (max in ms)
* @param interval Check every interval ms
* @param channels The channels which should form the view. The expected view size is channels.length.
* Must be non-null
*/
public static void blockUntilViewsReceived(long timeout, long interval, Channel ... channels) throws TimeoutException {
final int expected_size=channels.length;
if(interval > timeout)
throw new IllegalArgumentException("interval needs to be smaller than timeout");
final long end_time=System.currentTimeMillis() + timeout;
while(System.currentTimeMillis() < end_time) {
boolean all_ok=true;
for(Channel ch: channels) {
View view=ch.getView();
if(view == null || view.size() != expected_size) {
all_ok=false;
break;
}
}
if(all_ok)
return;
Util.sleep(interval);
}
throw new TimeoutException();
}
public static void addFlush(Channel ch, FLUSH flush) {
if(ch == null || flush == null)
throw new IllegalArgumentException("ch and flush have to be non-null");
ProtocolStack stack=ch.getProtocolStack();
stack.insertProtocolAtTop(flush);
}
/**
* Utility method. If the dest address is IPv6, convert scoped link-local addrs into unscoped ones
* @param sock
* @param dest
* @param sock_conn_timeout
* @throws IOException
*/
public static void connect(Socket sock, SocketAddress dest, int sock_conn_timeout) throws IOException {
if(dest instanceof InetSocketAddress) {
InetAddress addr=((InetSocketAddress)dest).getAddress();
if(addr instanceof Inet6Address) {
Inet6Address tmp=(Inet6Address)addr;
if(tmp.getScopeId() != 0) {
dest=new InetSocketAddress(InetAddress.getByAddress(tmp.getAddress()), ((InetSocketAddress)dest).getPort());
}
}
}
sock.connect(dest, sock_conn_timeout);
}
public static void close(InputStream inp) {
if(inp != null)
try {inp.close();} catch(IOException e) {}
}
public static void close(OutputStream out) {
if(out != null) {
try {out.close();} catch(IOException e) {}
}
}
public static void close(Socket s) {
if(s != null) {
try {s.close();} catch(Exception ex) {}
}
}
public static void close(ServerSocket s) {
if(s != null) {
try {s.close();} catch(Exception ex) {}
}
}
public static void close(DatagramSocket my_sock) {
if(my_sock != null) {
try {my_sock.close();} catch(Throwable t) {}
}
}
public static void close(Channel ch) {
if(ch != null) {
try {ch.close();} catch(Throwable t) {}
}
}
public static void close(Channel ... channels) {
if(channels != null) {
for(Channel ch: channels)
Util.close(ch);
}
}
public static void close(Connection conn) {
if(conn != null) {
try {conn.close();} catch(Throwable t) {}
}
}
/** Drops messages to/from other members and then closes the channel. Note that this member won't get excluded from
* the view until failure detection has kicked in and the new coord installed the new view */
public static void shutdown(Channel ch) throws Exception {
DISCARD discard=new DISCARD();
discard.setLocalAddress(ch.getAddress());
discard.setDiscardAll(true);
ProtocolStack stack=ch.getProtocolStack();
TP transport=stack.getTransport();
stack.insertProtocol(discard, ProtocolStack.ABOVE, transport.getClass());
//abruptly shutdown FD_SOCK just as in real life when member gets killed non gracefully
FD_SOCK fd = (FD_SOCK) ch.getProtocolStack().findProtocol("FD_SOCK");
if(fd != null)
fd.stopServerSocket(false);
View view=ch.getView();
if (view != null) {
ViewId vid = view.getViewId();
List<Address> members = Arrays.asList(ch.getAddress());
ViewId new_vid = new ViewId(ch.getAddress(), vid.getId() + 1);
View new_view = new View(new_vid, members);
// inject view in which the shut down member is the only element
GMS gms = (GMS) stack.findProtocol(GMS.class);
gms.installView(new_view);
}
Util.close(ch);
}
public static byte setFlag(byte bits, byte flag) {
return bits |= flag;
}
public static boolean isFlagSet(byte bits, byte flag) {
return (bits & flag) == flag;
}
public static byte clearFlags(byte bits, byte flag) {
return bits &= ~flag;
}
/**
* Creates an object from a byte buffer
*/
public static Object objectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
if(JGROUPS_COMPAT)
return oldObjectFromByteBuffer(buffer);
return objectFromByteBuffer(buffer, 0, buffer.length);
}
public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
if(JGROUPS_COMPAT)
return oldObjectFromByteBuffer(buffer, offset, length);
Object retval=null;
InputStream in=null;
ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset, length);
byte b=(byte)in_stream.read();
try {
switch(b) {
case TYPE_NULL:
return null;
case TYPE_STREAMABLE:
in=new DataInputStream(in_stream);
retval=readGenericStreamable((DataInputStream)in);
break;
case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable
in=new ObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=((ObjectInputStream)in).readObject();
break;
case TYPE_BOOLEAN:
in=new DataInputStream(in_stream);
retval=Boolean.valueOf(((DataInputStream)in).readBoolean());
break;
case TYPE_BYTE:
in=new DataInputStream(in_stream);
retval=Byte.valueOf(((DataInputStream)in).readByte());
break;
case TYPE_CHAR:
in=new DataInputStream(in_stream);
retval=Character.valueOf(((DataInputStream)in).readChar());
break;
case TYPE_DOUBLE:
in=new DataInputStream(in_stream);
retval=Double.valueOf(((DataInputStream)in).readDouble());
break;
case TYPE_FLOAT:
in=new DataInputStream(in_stream);
retval=Float.valueOf(((DataInputStream)in).readFloat());
break;
case TYPE_INT:
in=new DataInputStream(in_stream);
retval=Integer.valueOf(((DataInputStream)in).readInt());
break;
case TYPE_LONG:
in=new DataInputStream(in_stream);
retval=Long.valueOf(((DataInputStream)in).readLong());
break;
case TYPE_SHORT:
in=new DataInputStream(in_stream);
retval=Short.valueOf(((DataInputStream)in).readShort());
break;
case TYPE_STRING:
in=new DataInputStream(in_stream);
if(((DataInputStream)in).readBoolean()) { // large string
ObjectInputStream ois=new ObjectInputStream(in);
try {
return ois.readObject();
}
finally {
ois.close();
}
}
else {
retval=((DataInputStream)in).readUTF();
}
break;
case TYPE_BYTEARRAY:
in=new DataInputStream(in_stream);
int len=((DataInputStream)in).readInt();
byte[] tmp=new byte[len];
((DataInputStream)in).readFully(tmp, 0, tmp.length);
retval=tmp;
break;
default:
throw new IllegalArgumentException("type " + b + " is invalid");
}
return retval;
}
finally {
Util.close(in);
}
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] objectToByteBuffer(Object obj) throws Exception {
if(JGROUPS_COMPAT)
return oldObjectToByteBuffer(obj);
byte[] result;
final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512);
if(obj == null) {
out_stream.write(TYPE_NULL);
out_stream.flush();
return out_stream.toByteArray();
}
OutputStream out=null;
Byte type;
try {
if(obj instanceof Streamable) { // use Streamable if we can
out_stream.write(TYPE_STREAMABLE);
out=new ExposedDataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, (DataOutputStream)out);
}
else if((type=PRIMITIVE_TYPES.get(obj.getClass())) != null) {
out_stream.write(type.byteValue());
out=new ExposedDataOutputStream(out_stream);
switch(type.byteValue()) {
case TYPE_BOOLEAN:
((DataOutputStream)out).writeBoolean(((Boolean)obj).booleanValue());
break;
case TYPE_BYTE:
((DataOutputStream)out).writeByte(((Byte)obj).byteValue());
break;
case TYPE_CHAR:
((DataOutputStream)out).writeChar(((Character)obj).charValue());
break;
case TYPE_DOUBLE:
((DataOutputStream)out).writeDouble(((Double)obj).doubleValue());
break;
case TYPE_FLOAT:
((DataOutputStream)out).writeFloat(((Float)obj).floatValue());
break;
case TYPE_INT:
((DataOutputStream)out).writeInt(((Integer)obj).intValue());
break;
case TYPE_LONG:
((DataOutputStream)out).writeLong(((Long)obj).longValue());
break;
case TYPE_SHORT:
((DataOutputStream)out).writeShort(((Short)obj).shortValue());
break;
case TYPE_STRING:
String str=(String)obj;
if(str.length() > Short.MAX_VALUE) {
((DataOutputStream)out).writeBoolean(true);
ObjectOutputStream oos=new ObjectOutputStream(out);
try {
oos.writeObject(str);
}
finally {
oos.close();
}
}
else {
((DataOutputStream)out).writeBoolean(false);
((DataOutputStream)out).writeUTF(str);
}
break;
case TYPE_BYTEARRAY:
byte[] buf=(byte[])obj;
((DataOutputStream)out).writeInt(buf.length);
out.write(buf, 0, buf.length);
break;
default:
throw new IllegalArgumentException("type " + type + " is invalid");
}
}
else { // will throw an exception if object is not serializable
out_stream.write(TYPE_SERIALIZABLE);
out=new ObjectOutputStream(out_stream);
((ObjectOutputStream)out).writeObject(obj);
}
}
finally {
Util.close(out);
}
result=out_stream.toByteArray();
return result;
}
public static Buffer objectToBuffer(Object obj) throws Exception {
if(JGROUPS_COMPAT)
return oldObjectToBuffer(obj);
final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512);
if(obj == null) {
out_stream.write(TYPE_NULL);
out_stream.flush();
return out_stream.getBuffer();
}
OutputStream out=null;
Byte type;
try {
if(obj instanceof Streamable) { // use Streamable if we can
out_stream.write(TYPE_STREAMABLE);
out=new ExposedDataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, (DataOutputStream)out);
}
else if((type=PRIMITIVE_TYPES.get(obj.getClass())) != null) {
out_stream.write(type.byteValue());
out=new ExposedDataOutputStream(out_stream);
switch(type.byteValue()) {
case TYPE_BOOLEAN:
((DataOutputStream)out).writeBoolean(((Boolean)obj).booleanValue());
break;
case TYPE_BYTE:
((DataOutputStream)out).writeByte(((Byte)obj).byteValue());
break;
case TYPE_CHAR:
((DataOutputStream)out).writeChar(((Character)obj).charValue());
break;
case TYPE_DOUBLE:
((DataOutputStream)out).writeDouble(((Double)obj).doubleValue());
break;
case TYPE_FLOAT:
((DataOutputStream)out).writeFloat(((Float)obj).floatValue());
break;
case TYPE_INT:
((DataOutputStream)out).writeInt(((Integer)obj).intValue());
break;
case TYPE_LONG:
((DataOutputStream)out).writeLong(((Long)obj).longValue());
break;
case TYPE_SHORT:
((DataOutputStream)out).writeShort(((Short)obj).shortValue());
break;
case TYPE_STRING:
String str=(String)obj;
if(str.length() > Short.MAX_VALUE) {
((DataOutputStream)out).writeBoolean(true);
ObjectOutputStream oos=new ObjectOutputStream(out);
try {
oos.writeObject(str);
}
finally {
oos.close();
}
}
else {
((DataOutputStream)out).writeBoolean(false);
((DataOutputStream)out).writeUTF(str);
}
break;
case TYPE_BYTEARRAY:
byte[] buf=(byte[])obj;
((DataOutputStream)out).writeInt(buf.length);
out.write(buf, 0, buf.length);
break;
default:
throw new IllegalArgumentException("type " + type + " is invalid");
}
}
else { // will throw an exception if object is not serializable
out_stream.write(TYPE_SERIALIZABLE);
out=new ObjectOutputStream(out_stream);
((ObjectOutputStream)out).writeObject(obj);
}
}
finally {
Util.close(out);
}
return out_stream.getBuffer();
}
public static void objectToStream(Object obj, DataOutputStream out) throws Exception {
if(obj == null) {
out.write(TYPE_NULL);
return;
}
Byte type;
try {
if(obj instanceof Streamable) { // use Streamable if we can
out.write(TYPE_STREAMABLE);
writeGenericStreamable((Streamable)obj, out);
}
else if((type=PRIMITIVE_TYPES.get(obj.getClass())) != null) {
out.write(type.byteValue());
switch(type.byteValue()) {
case TYPE_BOOLEAN:
out.writeBoolean(((Boolean)obj).booleanValue());
break;
case TYPE_BYTE:
out.writeByte(((Byte)obj).byteValue());
break;
case TYPE_CHAR:
out.writeChar(((Character)obj).charValue());
break;
case TYPE_DOUBLE:
out.writeDouble(((Double)obj).doubleValue());
break;
case TYPE_FLOAT:
out.writeFloat(((Float)obj).floatValue());
break;
case TYPE_INT:
out.writeInt(((Integer)obj).intValue());
break;
case TYPE_LONG:
out.writeLong(((Long)obj).longValue());
break;
case TYPE_SHORT:
out.writeShort(((Short)obj).shortValue());
break;
case TYPE_STRING:
String str=(String)obj;
if(str.length() > Short.MAX_VALUE) {
out.writeBoolean(true);
ObjectOutputStream oos=new ObjectOutputStream(out);
try {
oos.writeObject(str);
}
finally {
oos.close();
}
}
else {
out.writeBoolean(false);
out.writeUTF(str);
}
break;
case TYPE_BYTEARRAY:
byte[] buf=(byte[])obj;
out.writeInt(buf.length);
out.write(buf, 0, buf.length);
break;
default:
throw new IllegalArgumentException("type " + type + " is invalid");
}
}
else { // will throw an exception if object is not serializable
out.write(TYPE_SERIALIZABLE);
ObjectOutputStream tmp=new ObjectOutputStream(out);
tmp.writeObject(obj);
}
}
finally {
Util.close(out);
}
}
public static Object objectFromStream(DataInputStream in) throws Exception {
if(in == null) return null;
Object retval=null;
byte b=(byte)in.read();
switch(b) {
case TYPE_NULL:
return null;
case TYPE_STREAMABLE:
retval=readGenericStreamable(in);
break;
case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable
ObjectInputStream tmp=new ObjectInputStream(in);
retval=tmp.readObject();
break;
case TYPE_BOOLEAN:
retval=Boolean.valueOf(in.readBoolean());
break;
case TYPE_BYTE:
retval=Byte.valueOf(in.readByte());
break;
case TYPE_CHAR:
retval=Character.valueOf(in.readChar());
break;
case TYPE_DOUBLE:
retval=Double.valueOf(in.readDouble());
break;
case TYPE_FLOAT:
retval=Float.valueOf(in.readFloat());
break;
case TYPE_INT:
retval=Integer.valueOf(in.readInt());
break;
case TYPE_LONG:
retval=Long.valueOf(in.readLong());
break;
case TYPE_SHORT:
retval=Short.valueOf(in.readShort());
break;
case TYPE_STRING:
if(in.readBoolean()) { // large string
ObjectInputStream ois=new ObjectInputStream(in);
try {
retval=ois.readObject();
}
finally {
ois.close();
}
}
else {
retval=in.readUTF();
}
break;
case TYPE_BYTEARRAY:
int len=in.readInt();
byte[] tmpbuf=new byte[len];
in.readFully(tmpbuf, 0, tmpbuf.length);
retval=tmpbuf;
break;
default:
throw new IllegalArgumentException("type " + b + " is invalid");
}
return retval;
}
/** For backward compatibility in JBoss 4.0.2 */
public static Object oldObjectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
return oldObjectFromByteBuffer(buffer, 0, buffer.length);
}
public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
Object retval=null;
try { // to read the object as an Externalizable
ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset, length);
ObjectInputStream in=new ObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=in.readObject();
in.close();
}
catch(StreamCorruptedException sce) {
try { // is it Streamable?
ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(in_stream);
retval=readGenericStreamable(in);
in.close();
}
catch(Exception ee) {
IOException tmp=new IOException("unmarshalling failed");
tmp.initCause(ee);
throw tmp;
}
}
if(retval == null)
return null;
return retval;
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] oldObjectToByteBuffer(Object obj) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512);
if(obj instanceof Streamable) { // use Streamable if we can
DataOutputStream out=new ExposedDataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, out);
out.close();
}
else {
ObjectOutputStream out=new ObjectOutputStream(out_stream);
out.writeObject(obj);
out.close();
}
result=out_stream.toByteArray();
return result;
}
public static Buffer oldObjectToBuffer(Object obj) throws Exception {
final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512);
if(obj instanceof Streamable) { // use Streamable if we can
DataOutputStream out=new ExposedDataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, out);
out.close();
}
else {
ObjectOutputStream out=new ObjectOutputStream(out_stream);
out.writeObject(obj);
out.close();
}
return out_stream.getBuffer();
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
return retval;
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
return retval;
}
public static byte[] streamableToByteBuffer(Streamable obj) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new ExposedDataOutputStream(out_stream);
obj.writeTo(out);
result=out_stream.toByteArray();
out.close();
return result;
}
public static byte[] collectionToByteBuffer(Collection<Address> c) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new ExposedDataOutputStream(out_stream);
Util.writeAddresses(c, out);
result=out_stream.toByteArray();
out.close();
return result;
}
public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{
Util.writeString(token.getName(), out);
token.writeTo(out);
}
public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
try{
String type = Util.readString(in);
Object obj = Class.forName(type).newInstance();
AuthToken token = (AuthToken) obj;
token.readFrom(in);
return token;
}
catch(ClassNotFoundException cnfe){
return null;
}
}
public static void writeView(View view, DataOutputStream out) throws IOException {
if(view == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
out.writeBoolean(view instanceof MergeView);
view.writeTo(out);
}
public static View readView(DataInputStream in) throws IOException, InstantiationException, IllegalAccessException {
if(in.readBoolean() == false)
return null;
boolean isMergeView=in.readBoolean();
View view;
if(isMergeView)
view=new MergeView();
else
view=new View();
view.readFrom(in);
return view;
}
public static void writeAddress(Address addr, DataOutputStream out) throws IOException {
byte flags=0;
boolean streamable_addr=true;
if(addr == null) {
flags=Util.setFlag(flags, Address.NULL);
out.writeByte(flags);
return;
}
if(addr instanceof UUID) {
flags=Util.setFlag(flags, Address.UUID_ADDR);
}
else if(addr instanceof IpAddress) {
flags=Util.setFlag(flags, Address.IP_ADDR);
}
else {
streamable_addr=false;
}
out.writeByte(flags);
if(streamable_addr)
addr.writeTo(out);
else
writeOtherAddress(addr, out);
}
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
byte flags=in.readByte();
if(Util.isFlagSet(flags, Address.NULL))
return null;
Address addr;
if(Util.isFlagSet(flags, Address.UUID_ADDR)) {
addr=new UUID();
addr.readFrom(in);
}
else if(Util.isFlagSet(flags, Address.IP_ADDR)) {
addr=new IpAddress();
addr.readFrom(in);
}
else {
addr=readOtherAddress(in);
}
return addr;
}
public static int size(Address addr) {
int retval=Global.BYTE_SIZE; // flags
if(addr != null) {
if(addr instanceof UUID || addr instanceof IpAddress)
retval+=addr.size();
else {
retval+=Global.SHORT_SIZE; // magic number
retval+=addr.size();
}
}
return retval;
}
public static int size(View view) {
int retval=Global.BYTE_SIZE; // presence
if(view != null)
retval+=view.serializedSize() + Global.BYTE_SIZE; // merge view or regular view
return retval;
}
private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
short magic_number=in.readShort();
Class cl=ClassConfigurator.get(magic_number);
if(cl == null)
throw new RuntimeException("class for magic number " + magic_number + " not found");
Address addr=(Address)cl.newInstance();
addr.readFrom(in);
return addr;
}
private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException {
short magic_number=ClassConfigurator.getMagicNumber(addr.getClass());
// write the class info
if(magic_number == -1)
throw new RuntimeException("magic number " + magic_number + " not found");
out.writeShort(magic_number);
addr.writeTo(out);
}
/**
* Writes a Vector of Addresses. Can contain 65K addresses at most
* @param v A Collection<Address>
* @param out
* @throws IOException
*/
public static void writeAddresses(Collection<? extends Address> v, DataOutputStream out) throws IOException {
if(v == null) {
out.writeShort(-1);
return;
}
out.writeShort(v.size());
for(Address addr: v) {
Util.writeAddress(addr, out);
}
}
public static Collection<? extends Address> readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException {
short length=in.readShort();
if(length < 0) return null;
Collection<Address> retval=(Collection<Address>)cl.newInstance();
Address addr;
for(int i=0; i < length; i++) {
addr=Util.readAddress(in);
retval.add(addr);
}
return retval;
}
/**
* Returns the marshalled size of a Collection of Addresses.
* <em>Assumes elements are of the same type !</em>
* @param addrs Collection<Address>
* @return long size
*/
public static long size(Collection<? extends Address> addrs) {
int retval=Global.SHORT_SIZE; // number of elements
if(addrs != null && !addrs.isEmpty()) {
Address addr=addrs.iterator().next();
retval+=size(addr) * addrs.size();
}
return retval;
}
public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException {
if(obj == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
obj.writeTo(out);
}
public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Streamable retval=null;
if(in.readBoolean() == false)
return null;
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException {
short magic_number;
String classname;
if(obj == null) {
out.write(0);
return;
}
out.write(1);
magic_number=ClassConfigurator.getMagicNumber(obj.getClass());
// write the magic number or the class name
if(magic_number == -1) {
out.writeBoolean(false);
classname=obj.getClass().getName();
out.writeUTF(classname);
}
else {
out.writeBoolean(true);
out.writeShort(magic_number);
}
// write the contents
obj.writeTo(out);
}
public static Streamable readGenericStreamable(DataInputStream in) throws IOException {
Streamable retval=null;
int b=in.read();
if(b == 0)
return null;
boolean use_magic_number=in.readBoolean();
String classname;
Class clazz;
try {
if(use_magic_number) {
short magic_number=in.readShort();
clazz=ClassConfigurator.get(magic_number);
if (clazz==null) {
throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found.");
}
}
else {
classname=in.readUTF();
clazz=ClassConfigurator.get(classname);
if (clazz==null) {
throw new ClassNotFoundException(classname);
}
}
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
catch(Exception ex) {
throw new IOException("failed reading object: " + ex.toString());
}
}
public static void writeObject(Object obj, DataOutputStream out) throws Exception {
if(obj == null || !(obj instanceof Streamable)) {
byte[] buf=objectToByteBuffer(obj);
out.writeShort(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.writeShort(-1);
writeGenericStreamable((Streamable)obj, out);
}
}
public static Object readObject(DataInputStream in) throws Exception {
short len=in.readShort();
Object retval=null;
if(len == -1) {
retval=readGenericStreamable(in);
}
else {
byte[] buf=new byte[len];
in.readFully(buf, 0, len);
retval=objectFromByteBuffer(buf);
}
return retval;
}
public static void writeString(String s, DataOutputStream out) throws IOException {
if(s != null) {
out.write(1);
out.writeUTF(s);
}
else {
out.write(0);
}
}
public static String readString(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1)
return in.readUTF();
return null;
}
public static void writeAsciiString(String str, DataOutputStream out) throws IOException {
if(str == null) {
out.write(-1);
return;
}
int length=str.length();
if(length > Byte.MAX_VALUE)
throw new IllegalArgumentException("string is > " + Byte.MAX_VALUE);
out.write(length);
out.writeBytes(str);
}
public static String readAsciiString(DataInputStream in) throws IOException {
byte length=(byte)in.read();
if(length == -1)
return null;
byte[] tmp=new byte[length];
in.readFully(tmp, 0, tmp.length);
return new String(tmp, 0, tmp.length);
}
public static String parseString(DataInputStream in) {
return parseString(in, false);
}
public static String parseString(DataInputStream in, boolean break_on_newline) {
StringBuilder sb=new StringBuilder();
int ch;
// read white space
while(true) {
try {
ch=in.read();
if(ch == -1) {
return null; // eof
}
if(Character.isWhitespace(ch)) {
if(break_on_newline && ch == '\n')
return null;
}
else {
sb.append((char)ch);
break;
}
}
catch(IOException e) {
break;
}
}
while(true) {
try {
ch=in.read();
if(ch == -1)
break;
if(Character.isWhitespace(ch))
break;
else {
sb.append((char)ch);
}
}
catch(IOException e) {
break;
}
}
return sb.toString();
}
public static String readStringFromStdin(String message) throws Exception {
System.out.print(message);
System.out.flush();
System.in.skip(System.in.available());
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
return reader.readLine().trim();
}
public static long readLongFromStdin(String message) throws Exception {
String tmp=readStringFromStdin(message);
return Long.parseLong(tmp);
}
public static double readDoubleFromStdin(String message) throws Exception {
String tmp=readStringFromStdin(message);
return Double.parseDouble(tmp);
}
public static int readIntFromStdin(String message) throws Exception {
String tmp=readStringFromStdin(message);
return Integer.parseInt(tmp);
}
public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException {
writeByteBuffer(buf, 0, buf.length, out);
}
public static void writeByteBuffer(byte[] buf, int offset, int length, DataOutputStream out) throws IOException {
if(buf != null) {
out.write(1);
out.writeInt(length);
out.write(buf, offset, length);
}
else {
out.write(0);
}
}
public static byte[] readByteBuffer(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1) {
b=in.readInt();
byte[] buf=new byte[b];
in.readFully(buf, 0, buf.length);
return buf;
}
return null;
}
public static Buffer messageToByteBuffer(Message msg) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new ExposedDataOutputStream(output);
out.writeBoolean(msg != null);
if(msg != null)
msg.writeTo(out);
out.flush();
Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception {
ByteArrayInputStream input=new ExposedByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
if(!in.readBoolean())
return null;
Message msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
return msg;
}
/**
* Marshalls a list of messages.
* @param xmit_list LinkedList<Message>
* @return Buffer
* @throws IOException
*/
public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new ExposedDataOutputStream(output);
Buffer retval=null;
out.writeInt(xmit_list.size());
for(Message msg: xmit_list) {
msg.writeTo(out);
}
out.flush();
retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static List<Message> byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception {
List<Message> retval=null;
ByteArrayInputStream input=new ExposedByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
int size=in.readInt();
if(size == 0)
return null;
Message msg;
retval=new LinkedList<Message>();
for(int i=0; i < size; i++) {
msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
retval.add(msg);
}
return retval;
}
public static boolean match(Object obj1, Object obj2) {
if(obj1 == null && obj2 == null)
return true;
if(obj1 != null)
return obj1.equals(obj2);
else
return obj2.equals(obj1);
}
public static boolean sameViewId(ViewId one, ViewId two) {
return one.getId() == two.getId() && one.getCoordAddress().equals(two.getCoordAddress());
}
public static boolean match(long[] a1, long[] a2) {
if(a1 == null && a2 == null)
return true;
if(a1 == null || a2 == null)
return false;
if(a1 == a2) // identity
return true;
// at this point, a1 != null and a2 != null
if(a1.length != a2.length)
return false;
for(int i=0; i < a1.length; i++) {
if(a1[i] != a2[i])
return false;
}
return true;
}
/** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */
public static void sleep(long timeout) {
try {
Thread.sleep(timeout);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void sleep(long timeout, int nanos) {
try {
Thread.sleep(timeout,nanos);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will
* sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the
* thread never relinquishes control and therefore the sleep(x) is exactly x ms long.
*/
public static void sleep(long msecs, boolean busy_sleep) {
if(!busy_sleep) {
sleep(msecs);
return;
}
long start=System.currentTimeMillis();
long stop=start + msecs;
while(stop > start) {
start=System.currentTimeMillis();
}
}
public static int keyPress(String msg) {
System.out.println(msg);
try {
int ret=System.in.read();
System.in.skip(System.in.available());
return ret;
}
catch(IOException e) {
return 0;
}
}
/** Returns a random value in the range [1 - range] */
public static long random(long range) {
return (long)((Math.random() * range) % range) + 1;
}
/** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */
public static void sleepRandom(long timeout) {
if(timeout <= 0) {
return;
}
long r=(int)((Math.random() * 100000) % timeout) + 1;
sleep(r);
}
/** Sleeps between floor and ceiling milliseconds, chosen randomly */
public static void sleepRandom(long floor, long ceiling) {
if(ceiling - floor<= 0) {
return;
}
long diff = ceiling - floor;
long r=(int)((Math.random() * 100000) % diff) + floor;
sleep(r);
}
/**
Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8,
chances are that in 80% of all cases, true will be returned and false in 20%.
*/
public static boolean tossWeightedCoin(double probability) {
long r=random(100);
long cutoff=(long)(probability * 100);
return r < cutoff;
}
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch(Exception ex) {
}
return "localhost";
}
public static void dumpStack(boolean exit) {
try {
throw new Exception("Dumping stack:");
}
catch(Exception e) {
e.printStackTrace();
if(exit)
System.exit(0);
}
}
public static String dumpThreads() {
StringBuilder sb=new StringBuilder();
ThreadMXBean bean=ManagementFactory.getThreadMXBean();
long[] ids=bean.getAllThreadIds();
ThreadInfo[] threads=bean.getThreadInfo(ids, 20);
for(int i=0; i < threads.length; i++) {
ThreadInfo info=threads[i];
if(info == null)
continue;
sb.append(info.getThreadName()).append(":\n");
StackTraceElement[] stack_trace=info.getStackTrace();
for(int j=0; j < stack_trace.length; j++) {
StackTraceElement el=stack_trace[j];
sb.append(" at ").append(el.getClassName()).append(".").append(el.getMethodName());
sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")");
sb.append("\n");
}
sb.append("\n\n");
}
return sb.toString();
}
public static boolean interruptAndWaitToDie(Thread t) {
return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME);
}
public static boolean interruptAndWaitToDie(Thread t, long timeout) {
if(t == null)
throw new IllegalArgumentException("Thread can not be null");
t.interrupt(); // interrupts the sleep()
try {
t.join(timeout);
}
catch(InterruptedException e){
Thread.currentThread().interrupt(); // set interrupt flag again
}
return t.isAlive();
}
/**
* Debugging method used to dump the content of a protocol queue in a
* condensed form. Useful to follow the evolution of the queue's content in
* time.
*/
public static String dumpQueue(Queue q) {
StringBuilder sb=new StringBuilder();
LinkedList values=q.values();
if(values.isEmpty()) {
sb.append("empty");
}
else {
for(Object o: values) {
String s=null;
if(o instanceof Event) {
Event event=(Event)o;
int type=event.getType();
s=Event.type2String(type);
if(type == Event.VIEW_CHANGE)
s+=" " + event.getArg();
if(type == Event.MSG)
s+=" " + event.getArg();
if(type == Event.MSG) {
s+="[";
Message m=(Message)event.getArg();
Map<String,Header> headers=new HashMap<String,Header>(m.getHeaders());
for(Map.Entry<String,Header> entry: headers.entrySet()) {
String headerKey=entry.getKey();
Header value=entry.getValue();
String headerToString=null;
if(value instanceof FD.FdHeader) {
headerToString=value.toString();
}
else
if(value instanceof PingHeader) {
headerToString=headerKey + "-";
if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) {
headerToString+="GMREQ";
}
else
if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) {
headerToString+="GMRSP";
}
else {
headerToString+="UNKNOWN";
}
}
else {
headerToString=headerKey + "-" + (value == null ? "null" : value.toString());
}
s+=headerToString;
s+=" ";
}
s+="]";
}
}
else {
s=o.toString();
}
sb.append(s).append("\n");
}
}
return sb.toString();
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
public static String getStackTrace(Throwable t) {
return printStackTrace(t);
}
public static String print(Throwable t) {
return printStackTrace(t);
}
public static void crash() {
System.exit(-1);
}
public static String printEvent(Event evt) {
Message msg;
if(evt.getType() == Event.MSG) {
msg=(Message)evt.getArg();
if(msg != null) {
if(msg.getLength() > 0)
return printMessage(msg);
else
return msg.printObjectHeaders();
}
}
return evt.toString();
}
/** Tries to read an object from the message's buffer and prints it */
public static String printMessage(Message msg) {
if(msg == null)
return "";
if(msg.getLength() == 0)
return null;
try {
return msg.getObject().toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static String mapToString(Map<? extends Object,? extends Object> map) {
if(map == null)
return "null";
StringBuilder sb=new StringBuilder();
for(Map.Entry<? extends Object,? extends Object> entry: map.entrySet()) {
Object key=entry.getKey();
Object val=entry.getValue();
sb.append(key).append("=");
if(val == null)
sb.append("null");
else
sb.append(val);
sb.append("\n");
}
return sb.toString();
}
/** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it.
Returns empty string if object is not a method call */
public static String printMethodCall(Message msg) {
Object obj;
if(msg == null)
return "";
if(msg.getLength() == 0)
return "";
try {
obj=msg.getObject();
return obj.toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static void printThreads() {
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println("
for(int i=0; i < threads.length; i++) {
System.out.println("#" + i + ": " + threads[i]);
}
System.out.println("
}
public static String activeThreads() {
StringBuilder sb=new StringBuilder();
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
sb.append("
for(int i=0; i < threads.length; i++) {
sb.append("#").append(i).append(": ").append(threads[i]).append('\n');
}
sb.append("
return sb.toString();
}
public static String printBytes(long bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
public static String format(double value) {
return f.format(value);
}
public static long readBytesLong(String input) {
Tuple<String,Long> tuple=readBytes(input);
double num=Double.parseDouble(tuple.getVal1());
return (long)(num * tuple.getVal2());
}
public static int readBytesInteger(String input) {
Tuple<String,Long> tuple=readBytes(input);
double num=Double.parseDouble(tuple.getVal1());
return (int)(num * tuple.getVal2());
}
public static double readBytesDouble(String input) {
Tuple<String,Long> tuple=readBytes(input);
double num=Double.parseDouble(tuple.getVal1());
return num * tuple.getVal2();
}
private static Tuple<String,Long> readBytes(String input) {
input=input.trim().toLowerCase();
int index=-1;
long factor=1;
if((index=input.indexOf("k")) != -1)
factor=1000;
else if((index=input.indexOf("kb")) != -1)
factor=1000;
else if((index=input.indexOf("m")) != -1)
factor=1000000;
else if((index=input.indexOf("mb")) != -1)
factor=1000000;
else if((index=input.indexOf("g")) != -1)
factor=1000000000;
else if((index=input.indexOf("gb")) != -1)
factor=1000000000;
String str=index != -1? input.substring(0, index) : input;
return new Tuple<String,Long>(str, factor);
}
public static String printBytes(double bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
public static List<String> split(String input, int separator) {
List<String> retval=new ArrayList<String>();
if(input == null)
return retval;
int index=0, end;
while(true) {
index=input.indexOf(separator, index);
if(index == -1)
break;
index++;
end=input.indexOf(separator, index);
if(end == -1)
retval.add(input.substring(index));
else
retval.add(input.substring(index, end));
}
return retval;
}
/* public static String[] components(String path, String separator) {
if(path == null || path.length() == 0)
return null;
String[] tmp=path.split(separator + "+"); // multiple separators could be present
if(tmp == null)
return null;
if(tmp.length == 0)
return null;
if(tmp[0].length() == 0) {
tmp[0]=separator;
if(tmp.length > 1) {
String[] retval=new String[tmp.length -1];
retval[0]=tmp[0] + tmp[1];
System.arraycopy(tmp, 2, retval, 1, tmp.length-2);
return retval;
}
return tmp;
}
return tmp;
}*/
public static String[] components(String path, String separator) {
if(path == null || path.length() == 0)
return null;
String[] tmp=path.split(separator + "+"); // multiple separators could be present
if(tmp == null)
return null;
if(tmp.length == 0)
return null;
if(tmp[0].length() == 0)
tmp[0]=separator;
return tmp;
}
/**
Fragments a byte buffer into smaller fragments of (max.) frag_size.
Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments
of 248 bytes each and 1 fragment of 32 bytes.
@return An array of byte buffers (<code>byte[]</code>).
*/
public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) {
byte[] retval[];
int accumulated_size=0;
byte[] fragment;
int tmp_size=0;
int num_frags;
int index=0;
num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1;
retval=new byte[num_frags][];
while(accumulated_size < length) {
if(accumulated_size + frag_size <= length)
tmp_size=frag_size;
else
tmp_size=length - accumulated_size;
fragment=new byte[tmp_size];
System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size);
retval[index++]=fragment;
accumulated_size+=tmp_size;
}
return retval;
}
public static byte[][] fragmentBuffer(byte[] buf, int frag_size) {
return fragmentBuffer(buf, frag_size, buf.length);
}
/**
* Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and
* return them in a list. Example:<br/>
* Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}).
* This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment
* starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length
* of 2 bytes.
* @param frag_size
* @return List. A List<Range> of offset/length pairs
*/
public static List<Range> computeFragOffsets(int offset, int length, int frag_size) {
List<Range> retval=new ArrayList<Range>();
long total_size=length + offset;
int index=offset;
int tmp_size=0;
Range r;
while(index < total_size) {
if(index + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - index);
r=new Range(index, tmp_size);
retval.add(r);
index+=tmp_size;
}
return retval;
}
public static List<Range> computeFragOffsets(byte[] buf, int frag_size) {
return computeFragOffsets(0, buf.length, frag_size);
}
/**
Concatenates smaller fragments into entire buffers.
@param fragments An array of byte buffers (<code>byte[]</code>)
@return A byte buffer
*/
public static byte[] defragmentBuffer(byte[] fragments[]) {
int total_length=0;
byte[] ret;
int index=0;
if(fragments == null) return null;
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
total_length+=fragments[i].length;
}
ret=new byte[total_length];
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
System.arraycopy(fragments[i], 0, ret, index, fragments[i].length);
index+=fragments[i].length;
}
return ret;
}
public static void printFragments(byte[] frags[]) {
for(int i=0; i < frags.length; i++)
System.out.println('\'' + new String(frags[i]) + '\'');
}
public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) {
boolean first=true;
StringBuilder sb=new StringBuilder();
for(T el: list) {
if(first) {
first=false;
}
else {
sb.append(delimiter);
}
sb.append(el);
}
return sb.toString();
}
public static <T> String printMapWithDelimiter(Map<T,T> map, String delimiter) {
boolean first=true;
StringBuilder sb=new StringBuilder();
for(Map.Entry<T,T> entry: map.entrySet()) {
if(first)
first=false;
else
sb.append(delimiter);
sb.append(entry.getKey()).append("=").append(entry.getValue());
}
return sb.toString();
}
public static String array2String(long[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(short[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(int[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(boolean[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(Object[] array) {
return Arrays.toString(array);
}
/** Returns true if all elements of c match obj */
public static boolean all(Collection c, Object obj) {
for(Iterator iterator=c.iterator(); iterator.hasNext();) {
Object o=iterator.next();
if(!o.equals(obj))
return false;
}
return true;
}
/**
* Returns a list of members which left from view one to two
* @param one
* @param two
* @return
*/
public static List<Address> leftMembers(View one, View two) {
if(one == null || two == null)
return null;
List<Address> retval=new ArrayList<Address>(one.getMembers());
retval.removeAll(two.getMembers());
return retval;
}
public static List<Address> leftMembers(Collection<Address> old_list, Collection<Address> new_list) {
if(old_list == null || new_list == null)
return null;
List<Address> retval=new ArrayList<Address>(old_list);
retval.removeAll(new_list);
return retval;
}
public static List<Address> newMembers(List<Address> old_list, List<Address> new_list) {
if(old_list == null || new_list == null)
return null;
List<Address> retval=new ArrayList<Address>(new_list);
retval.removeAll(old_list);
return retval;
}
/**
* Selects a random subset of members according to subset_percentage and returns them.
* Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member.
*/
public static Vector<Address> pickSubset(Vector<Address> members, double subset_percentage) {
Vector<Address> ret=new Vector<Address>(), tmp_mbrs;
int num_mbrs=members.size(), subset_size, index;
if(num_mbrs == 0) return ret;
subset_size=(int)Math.ceil(num_mbrs * subset_percentage);
tmp_mbrs=(Vector<Address>)members.clone();
for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i
index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size());
ret.addElement(tmp_mbrs.elementAt(index));
tmp_mbrs.removeElementAt(index);
}
return ret;
}
public static boolean containsViewId(Collection<View> views, ViewId vid) {
for(View view: views) {
ViewId tmp=view.getVid();
if(Util.sameViewId(vid, tmp))
return true;
}
return false;
}
/**
* Determines the members which take part in a merge. The resulting list consists of all merge coordinators
* and members outside a merge partition, e.g. for views A={B,A,C}, B={B,C} and C={B,C}, the merge coordinator
* is B, but the merge participants are B and A.
* @param map
* @return
*/
public static Collection<Address> determineMergeParticipants(Map<Address,View> map) {
Set<Address> coords=new HashSet<Address>();
Set<Address> all_addrs=new HashSet<Address>();
if(map == null)
return Collections.emptyList();
for(View view: map.values())
all_addrs.addAll(view.getMembers());
for(View view: map.values()) {
Address coord=view.getCreator();
if(coord != null)
coords.add(coord);
}
for(Address coord: coords) {
View view=map.get(coord);
Collection<Address> mbrs=view != null? view.getMembers() : null;
if(mbrs != null)
all_addrs.removeAll(mbrs);
}
coords.addAll(all_addrs);
return coords;
}
/**
* This is the same or a subset of {@link #determineMergeParticipants(java.util.Map)} and contains only members
* which are currently sub-partition coordinators.
* @param map
* @return
*/
public static Collection<Address> determineMergeCoords(Map<Address,View> map) {
Set<Address> retval=new HashSet<Address>();
if(map != null) {
for(View view: map.values()) {
Address coord=view.getCreator();
if(coord != null)
retval.add(coord);
}
}
return retval;
}
public static Object pickRandomElement(List list) {
if(list == null) return null;
int size=list.size();
int index=(int)((Math.random() * size * 10) % size);
return list.get(index);
}
public static Object pickRandomElement(Object[] array) {
if(array == null) return null;
int size=array.length;
int index=(int)((Math.random() * size * 10) % size);
return array[index];
}
public static View createView(Address coord, long id, Address ... members) {
Vector<Address> mbrs=new Vector<Address>();
mbrs.addAll(Arrays.asList(members));
return new View(coord, id, mbrs);
}
public static Address createRandomAddress() {
UUID retval=UUID.randomUUID();
String name=generateLocalName();
UUID.add(retval, name);
return retval;
}
/**
* Returns all members that left between 2 views. All members that are element of old_mbrs but not element of
* new_mbrs are returned.
*/
public static Vector<Address> determineLeftMembers(Vector<Address> old_mbrs, Vector<Address> new_mbrs) {
Vector<Address> retval=new Vector<Address>();
Address mbr;
if(old_mbrs == null || new_mbrs == null)
return retval;
for(int i=0; i < old_mbrs.size(); i++) {
mbr=old_mbrs.elementAt(i);
if(!new_mbrs.contains(mbr))
retval.addElement(mbr);
}
return retval;
}
public static String printViews(Collection<View> views) {
StringBuilder sb=new StringBuilder();
boolean first=true;
for(View view: views) {
if(first)
first=false;
else
sb.append(", ");
sb.append(view.getVid());
}
return sb.toString();
}
public static <T> String print(Collection<T> objs) {
StringBuilder sb=new StringBuilder();
boolean first=true;
for(T obj: objs) {
if(first)
first=false;
else
sb.append(", ");
sb.append(obj);
}
return sb.toString();
}
public static <T> String print(Map<T,T> map) {
StringBuilder sb=new StringBuilder();
boolean first=true;
for(Map.Entry<T,T> entry: map.entrySet()) {
if(first)
first=false;
else
sb.append(", ");
sb.append(entry.getKey()).append("=").append(entry.getValue());
}
return sb.toString();
}
public static String printPingData(List<PingData> rsps) {
StringBuilder sb=new StringBuilder();
if(rsps != null) {
int total=rsps.size();
int servers=0, clients=0, coords=0;
for(PingData rsp: rsps) {
if(rsp.isCoord())
coords++;
if(rsp.isServer())
servers++;
else
clients++;
}
sb.append(total + " total (" + servers + " servers (" + coords + " coord), " + clients + " clients)");
}
return sb.toString();
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, OutputStream out) throws Exception {
if(buf.length > 1) {
out.write(buf, 0, 1);
out.write(buf, 1, buf.length - 1);
}
else {
out.write(buf, 0, 0);
out.write(buf);
}
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception {
if(length > 1) {
out.write(buf, offset, 1);
out.write(buf, offset+1, length - 1);
}
else {
out.write(buf, offset, 0);
out.write(buf, offset, length);
}
}
/**
* if we were to register for OP_WRITE and send the remaining data on
* readyOps for this channel we have to either block the caller thread or
* queue the message buffers that may arrive while waiting for OP_WRITE.
* Instead of the above approach this method will continuously write to the
* channel until the buffer sent fully.
*/
public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException {
int written = 0;
int toWrite = buf.limit();
while (written < toWrite) {
written += out.write(buf);
}
}
public static long sizeOf(String classname) {
Object inst;
byte[] data;
try {
inst=Util.loadClass(classname, null).newInstance();
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static long sizeOf(Object inst) {
byte[] data;
try {
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static int sizeOf(Streamable inst) {
try {
ByteArrayOutputStream output=new ExposedByteArrayOutputStream();
DataOutputStream out=new ExposedDataOutputStream(output);
inst.writeTo(out);
out.flush();
byte[] data=output.toByteArray();
return data.length;
}
catch(Exception ex) {
return -1;
}
}
/**
* Tries to load the class from the current thread's context class loader. If
* not successful, tries to load the class from the current instance.
* @param classname Desired class.
* @param clazz Class object used to obtain a class loader
* if no context class loader is available.
* @return Class, or null on failure.
*/
public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException {
ClassLoader loader;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
throw new ClassNotFoundException(classname);
}
public static Field[] getAllDeclaredFields(final Class clazz) {
return getAllDeclaredFieldsWithAnnotations(clazz);
}
public static Field[] getAllDeclaredFieldsWithAnnotations(final Class clazz, Class<? extends Annotation> ... annotations) {
List<Field> list=new ArrayList<Field>(30);
for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) {
Field[] fields=curr.getDeclaredFields();
if(fields != null) {
for(Field field: fields) {
if(annotations != null && annotations.length > 0) {
for(Class<? extends Annotation> annotation: annotations) {
if(field.isAnnotationPresent(annotation))
list.add(field);
}
}
else
list.add(field);
}
}
}
Field[] retval=new Field[list.size()];
for(int i=0; i < list.size(); i++)
retval[i]=list.get(i);
return retval;
}
public static Method[] getAllDeclaredMethods(final Class clazz) {
return getAllDeclaredMethodsWithAnnotations(clazz);
}
public static Method[] getAllDeclaredMethodsWithAnnotations(final Class clazz, Class<? extends Annotation> ... annotations) {
List<Method> list=new ArrayList<Method>(30);
for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) {
Method[] methods=curr.getDeclaredMethods();
if(methods != null) {
for(Method method: methods) {
if(annotations != null && annotations.length > 0) {
for(Class<? extends Annotation> annotation: annotations) {
if(method.isAnnotationPresent(annotation))
list.add(method);
}
}
else
list.add(method);
}
}
}
Method[] retval=new Method[list.size()];
for(int i=0; i < list.size(); i++)
retval[i]=list.get(i);
return retval;
}
public static Field getField(final Class clazz, String field_name) {
if(clazz == null || field_name == null)
return null;
Field field=null;
for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) {
try {
return curr.getDeclaredField(field_name);
}
catch(NoSuchFieldException e) {
}
}
return field;
}
public static InputStream getResourceAsStream(String name, Class clazz) {
ClassLoader loader;
InputStream retval=null;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
retval=loader.getResourceAsStream(name);
if(retval != null)
return retval;
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
retval=loader.getResourceAsStream(name);
if(retval != null)
return retval;
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
return retval;
}
/** Checks whether 2 Addresses are on the same host */
public static boolean sameHost(Address one, Address two) {
InetAddress a, b;
String host_a, host_b;
if(one == null || two == null) return false;
if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) {
return false;
}
a=((IpAddress)one).getIpAddress();
b=((IpAddress)two).getIpAddress();
if(a == null || b == null) return false;
host_a=a.getHostAddress();
host_b=b.getHostAddress();
// System.out.println("host_a=" + host_a + ", host_b=" + host_b);
return host_a.equals(host_b);
}
public static boolean fileExists(String fname) {
return (new File(fname)).exists();
}
/**
* Parses comma-delimited longs; e.g., 2000,4000,8000.
* Returns array of long, or null.
*/
public static long[] parseCommaDelimitedLongs(String s) {
StringTokenizer tok;
Vector<Long> v=new Vector<Long>();
Long l;
long[] retval=null;
if(s == null) return null;
tok=new StringTokenizer(s, ",");
while(tok.hasMoreTokens()) {
l=new Long(tok.nextToken());
v.addElement(l);
}
if(v.isEmpty()) return null;
retval=new long[v.size()];
for(int i=0; i < v.size(); i++)
retval[i]=v.elementAt(i).longValue();
return retval;
}
/** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */
public static List<String> parseCommaDelimitedStrings(String l) {
return parseStringList(l, ",");
}
/**
* Input is "daddy[8880],sindhu[8880],camille[5555]. Returns a list of IpAddresses
*/
public static List<IpAddress> parseCommaDelimitedHosts(String hosts, int port_range) throws UnknownHostException {
StringTokenizer tok=new StringTokenizer(hosts, ",");
String t;
IpAddress addr;
Set<IpAddress> retval=new HashSet<IpAddress>();
while(tok.hasMoreTokens()) {
t=tok.nextToken().trim();
String host=t.substring(0, t.indexOf('['));
host=host.trim();
int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']')));
for(int i=port;i < port + port_range;i++) {
addr=new IpAddress(host, i);
retval.add(addr);
}
}
return Collections.unmodifiableList(new LinkedList<IpAddress>(retval));
}
/**
* Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of
* InetSocketAddress
*/
public static List<InetSocketAddress> parseCommaDelimitedHosts2(String hosts, int port_range)
throws UnknownHostException {
StringTokenizer tok=new StringTokenizer(hosts, ",");
String t;
InetSocketAddress addr;
Set<InetSocketAddress> retval=new HashSet<InetSocketAddress>();
while(tok.hasMoreTokens()) {
t=tok.nextToken().trim();
String host=t.substring(0, t.indexOf('['));
host=host.trim();
int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']')));
for(int i=port;i < port + port_range;i++) {
addr=new InetSocketAddress(host, i);
retval.add(addr);
}
}
return Collections.unmodifiableList(new LinkedList<InetSocketAddress>(retval));
}
public static List<String> parseStringList(String l, String separator) {
List<String> tmp=new LinkedList<String>();
StringTokenizer tok=new StringTokenizer(l, separator);
String t;
while(tok.hasMoreTokens()) {
t=tok.nextToken();
tmp.add(t.trim());
}
return tmp;
}
public static String parseString(ByteBuffer buf) {
return parseString(buf, true);
}
public static String parseString(ByteBuffer buf, boolean discard_whitespace) {
StringBuilder sb=new StringBuilder();
char ch;
// read white space
while(buf.remaining() > 0) {
ch=(char)buf.get();
if(!Character.isWhitespace(ch)) {
buf.position(buf.position() -1);
break;
}
}
if(buf.remaining() == 0)
return null;
while(buf.remaining() > 0) {
ch=(char)buf.get();
if(!Character.isWhitespace(ch)) {
sb.append(ch);
}
else
break;
}
// read white space
if(discard_whitespace) {
while(buf.remaining() > 0) {
ch=(char)buf.get();
if(!Character.isWhitespace(ch)) {
buf.position(buf.position() -1);
break;
}
}
}
return sb.toString();
}
public static int readNewLine(ByteBuffer buf) {
char ch;
int num=0;
while(buf.remaining() > 0) {
ch=(char)buf.get();
num++;
if(ch == '\n')
break;
}
return num;
}
/**
* Reads and discards all characters from the input stream until a \r\n or EOF is encountered
* @param in
* @return
*/
public static int discardUntilNewLine(InputStream in) {
int ch;
int num=0;
while(true) {
try {
ch=in.read();
if(ch == -1)
break;
num++;
if(ch == '\n')
break;
}
catch(IOException e) {
break;
}
}
return num;
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
*
* @exception IOException If an I/O error occurs
*/
public static String readLine(InputStream in) throws IOException {
StringBuilder sb=new StringBuilder(35);
int ch;
while(true) {
ch=in.read();
if(ch == -1)
return null;
if(ch == '\r') {
;
}
else {
if(ch == '\n')
break;
else {
sb.append((char)ch);
}
}
}
return sb.toString();
}
public static void writeString(ByteBuffer buf, String s) {
for(int i=0; i < s.length(); i++)
buf.put((byte)s.charAt(i));
}
/**
*
* @param s
* @return List<NetworkInterface>
*/
public static List<NetworkInterface> parseInterfaceList(String s) throws Exception {
List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10);
if(s == null)
return null;
StringTokenizer tok=new StringTokenizer(s, ",");
String interface_name;
NetworkInterface intf;
while(tok.hasMoreTokens()) {
interface_name=tok.nextToken();
// try by name first (e.g. (eth0")
intf=NetworkInterface.getByName(interface_name);
// next try by IP address or symbolic name
if(intf == null)
intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name));
if(intf == null)
throw new Exception("interface " + interface_name + " not found");
if(!interfaces.contains(intf)) {
interfaces.add(intf);
}
}
return interfaces;
}
public static String print(List<NetworkInterface> interfaces) {
StringBuilder sb=new StringBuilder();
boolean first=true;
for(NetworkInterface intf: interfaces) {
if(first) {
first=false;
}
else {
sb.append(", ");
}
sb.append(intf.getName());
}
return sb.toString();
}
public static String shortName(String hostname) {
if(hostname == null) return null;
int index=hostname.indexOf('.');
if(index > 0 && !Character.isDigit(hostname.charAt(0)))
return hostname.substring(0, index);
else
return hostname;
}
public static boolean startFlush(Channel c, List<Address> flushParticipants, int numberOfAttempts, long randomSleepTimeoutFloor,long randomSleepTimeoutCeiling) {
boolean successfulFlush = false;
int attemptCount = 0;
while(attemptCount < numberOfAttempts){
successfulFlush = c.startFlush(flushParticipants, false);
if(successfulFlush)
break;
Util.sleepRandom(randomSleepTimeoutFloor,randomSleepTimeoutCeiling);
attemptCount++;
}
return successfulFlush;
}
public static boolean startFlush(Channel c, List<Address> flushParticipants) {
return startFlush(c,flushParticipants,4,1000,5000);
}
public static boolean startFlush(Channel c, int numberOfAttempts, long randomSleepTimeoutFloor,long randomSleepTimeoutCeiling) {
boolean successfulFlush = false;
int attemptCount = 0;
while(attemptCount < numberOfAttempts){
successfulFlush = c.startFlush(false);
if(successfulFlush)
break;
Util.sleepRandom(randomSleepTimeoutFloor,randomSleepTimeoutCeiling);
attemptCount++;
}
return successfulFlush;
}
public static boolean startFlush(Channel c) {
return startFlush(c,4,1000,5000);
}
public static String shortName(InetAddress hostname) {
if(hostname == null) return null;
StringBuilder sb=new StringBuilder();
if(resolve_dns)
sb.append(hostname.getHostName());
else
sb.append(hostname.getHostAddress());
return sb.toString();
}
public static String generateLocalName() {
String retval=null;
try {
retval=shortName(InetAddress.getLocalHost().getHostName());
}
catch(UnknownHostException e) {
retval="localhost";
}
long counter=Util.random(Short.MAX_VALUE *2);
return retval + "-" + counter;
}
public synchronized static short incrCounter() {
short retval=COUNTER++;
if(COUNTER >= Short.MAX_VALUE)
COUNTER=1;
return retval;
}
/** Finds first available port starting at start_port and returns server socket */
public static ServerSocket createServerSocket(int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port, 50, bind_addr);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
/**
* Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use,
* start_port will be incremented until a socket can be created.
* @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound.
* @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already
* in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.
*/
public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception {
DatagramSocket sock=null;
if(addr == null) {
if(port == 0) {
return new DatagramSocket();
}
else {
while(port < MAX_PORT) {
try {
return new DatagramSocket(port);
}
catch(BindException bind_ex) { // port already used
port++;
}
}
}
}
else {
if(port == 0) port=1024;
while(port < MAX_PORT) {
try {
return new DatagramSocket(port, addr);
}
catch(BindException bind_ex) { // port already used
port++;
}
}
}
return sock; // will never be reached, but the stupid compiler didn't figure it out...
}
public static MulticastSocket createMulticastSocket(int port) throws IOException {
return createMulticastSocket(null, port, null);
}
public static MulticastSocket createMulticastSocket(InetAddress mcast_addr, int port, Log log) throws IOException {
if(mcast_addr != null && !mcast_addr.isMulticastAddress())
throw new IllegalArgumentException("mcast_addr (" + mcast_addr + ") is not a valid multicast address");
SocketAddress saddr=new InetSocketAddress(mcast_addr, port);
MulticastSocket retval=null;
try {
retval=new MulticastSocket(saddr);
}
catch(IOException ex) {
if(log != null && log.isWarnEnabled()) {
StringBuilder sb=new StringBuilder();
String type=mcast_addr != null ? mcast_addr instanceof Inet4Address? "IPv4" : "IPv6" : "n/a";
sb.append("could not bind to " + mcast_addr + " (" + type + " address)");
sb.append("; make sure your mcast_addr is of the same type as the preferred IP stack (IPv4 or IPv6)");
sb.append(" by checking the value of the system properties java.net.preferIPv4Stack and java.net.preferIPv6Addresses.");
sb.append("\nWill ignore mcast_addr, but this may lead to cross talking " +
"(see http:
sb.append("\nException was: " + ex);
log.warn(sb.toString());
}
}
if(retval == null)
retval=new MulticastSocket(port);
return retval;
}
/**
* Returns the address of the interface to use defined by bind_addr and bind_interface
* @param props
* @return
* @throws UnknownHostException
* @throws SocketException
*/
public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException {
return getBindAddress(props, StackType.IPv4);
}
public static InetAddress getBindAddress(Properties props, StackType ip_version) throws UnknownHostException, SocketException {
// determine the desired values for bind_addr_str and bind_interface_str
boolean ignore_systemprops=Util.isBindAddressPropertyIgnored();
String bind_addr_str =Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr",
ignore_systemprops, null);
String bind_interface_str =Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface",
ignore_systemprops, null);
InetAddress bind_addr=null;
NetworkInterface bind_intf=null ;
// 1. if bind_addr_str specified, get bind_addr and check version
if(bind_addr_str != null) {
bind_addr=InetAddress.getByName(bind_addr_str);
// check that bind_addr_host has correct IP version
boolean hasCorrectVersion = ((bind_addr instanceof Inet4Address && ip_version == StackType.IPv4) ||
(bind_addr instanceof Inet6Address && ip_version == StackType.IPv6)) ;
if (!hasCorrectVersion)
throw new IllegalArgumentException("bind_addr " + bind_addr_str + " has incorrect IP version") ;
}
// 2. if bind_interface_str specified, get interface and check that it has correct version
if(bind_interface_str != null) {
bind_intf=NetworkInterface.getByName(bind_interface_str);
if(bind_intf != null) {
// check that the interface supports the IP version
boolean supportsVersion = interfaceHasIPAddresses(bind_intf, ip_version) ;
if (!supportsVersion)
throw new IllegalArgumentException("bind_interface " + bind_interface_str + " has incorrect IP version") ;
}
else {
// (bind_intf == null)
throw new UnknownHostException("network interface " + bind_interface_str + " not found");
}
}
// 3. intf and bind_addr are both are specified, bind_addr needs to be on intf
if (bind_intf != null && bind_addr != null) {
boolean hasAddress = false ;
// get all the InetAddresses defined on the interface
Enumeration addresses = bind_intf.getInetAddresses() ;
while (addresses != null && addresses.hasMoreElements()) {
// get the next InetAddress for the current interface
InetAddress address = (InetAddress) addresses.nextElement() ;
// check if address is on interface
if (bind_addr.equals(address)) {
hasAddress = true ;
break ;
}
}
if (!hasAddress) {
throw new IllegalArgumentException("network interface " + bind_interface_str + " does not contain address " + bind_addr_str);
}
}
// 4. if only interface is specified, get first non-loopback address on that interface,
else if (bind_intf != null) {
bind_addr = getFirstNonLoopbackAddress(bind_intf, ip_version) ;
}
// 5. if neither bind address nor bind interface is specified, get the first non-loopback
// address on any interface
else if (bind_addr == null) {
bind_addr = getFirstNonLoopbackAddress(ip_version) ;
}
// if we reach here, if bind_addr == null, we have tried to obtain a bind_addr but were not successful
// in such a case, using a loopback address of the correct version is our only option
boolean localhost = false;
if (bind_addr == null) {
bind_addr = getLocalhost(ip_version);
localhost = true;
}
//check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine
//in some Linux setups NetworkInterface.getByInetAddress(InetAddress.getLocalHost()) returns null, so skip
//the check in that case
if(!localhost && NetworkInterface.getByInetAddress(bind_addr) == null) {
throw new UnknownHostException("Invalid bind address " + bind_addr);
}
if(props != null) {
props.remove("bind_addr");
props.remove("bind_interface");
}
return bind_addr;
}
/**
* Method used by PropertyConverters.BindInterface to check that a bind_address is
* consistent with a specified interface
*
* Idea:
* 1. We are passed a bind_addr, which may be null
* 2. If non-null, check that bind_addr is on bind_interface - if not, throw exception,
* otherwise, return the original bind_addr
* 3. If null, get first non-loopback address on bind_interface, using stack preference to
* get the IP version. If no non-loopback address, then just return null (i.e. the
* bind_interface did not influence the decision).
*
*/
public static InetAddress validateBindAddressFromInterface(InetAddress bind_addr, String bind_interface_str) throws UnknownHostException, SocketException {
NetworkInterface bind_intf=null ;
// 1. if bind_interface_str is null, or empty, no constraint on bind_addr
if (bind_interface_str == null || bind_interface_str.trim().length() == 0)
return bind_addr;
// 2. get the preferred IP version for the JVM - it will be IPv4 or IPv6
StackType ip_version = getIpStackType();
// 3. if bind_interface_str specified, get interface and check that it has correct version
bind_intf=NetworkInterface.getByName(bind_interface_str);
if(bind_intf != null) {
// check that the interface supports the IP version
boolean supportsVersion = interfaceHasIPAddresses(bind_intf, ip_version) ;
if (!supportsVersion)
throw new IllegalArgumentException("bind_interface " + bind_interface_str + " has incorrect IP version") ;
}
else {
// (bind_intf == null)
throw new UnknownHostException("network interface " + bind_interface_str + " not found");
}
// 3. intf and bind_addr are both are specified, bind_addr needs to be on intf
if (bind_addr != null) {
boolean hasAddress = false ;
// get all the InetAddresses defined on the interface
Enumeration addresses = bind_intf.getInetAddresses() ;
while (addresses != null && addresses.hasMoreElements()) {
// get the next InetAddress for the current interface
InetAddress address = (InetAddress) addresses.nextElement() ;
// check if address is on interface
if (bind_addr.equals(address)) {
hasAddress = true ;
break ;
}
}
if (!hasAddress) {
String bind_addr_str = bind_addr.getHostAddress();
throw new IllegalArgumentException("network interface " + bind_interface_str + " does not contain address " + bind_addr_str);
}
}
// 4. if only interface is specified, get first non-loopback address on that interface,
else {
bind_addr = getFirstNonLoopbackAddress(bind_intf, ip_version) ;
}
//check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine
//in some Linux setups NetworkInterface.getByInetAddress(InetAddress.getLocalHost()) returns null, so skip
//the check in that case
if(bind_addr != null && NetworkInterface.getByInetAddress(bind_addr) == null) {
throw new UnknownHostException("Invalid bind address " + bind_addr);
}
// if bind_addr == null, we have tried to obtain a bind_addr but were not successful
// in such a case, return the original value of null so the default will be applied
return bind_addr;
}
public static boolean checkForLinux() {
return checkForPresence("os.name", "linux");
}
public static boolean checkForHp() {
return checkForPresence("os.name", "hp");
}
public static boolean checkForSolaris() {
return checkForPresence("os.name", "sun");
}
public static boolean checkForWindows() {
return checkForPresence("os.name", "win");
}
public static boolean checkForMac() {
return checkForPresence("os.name", "mac");
}
private static boolean checkForPresence(String key, String value) {
try {
String tmp=System.getProperty(key);
return tmp != null && tmp.trim().toLowerCase().startsWith(value);
}
catch(Throwable t) {
return false;
}
}
public static void prompt(String s) {
System.out.println(s);
System.out.flush();
try {
while(System.in.available() > 0)
System.in.read();
System.in.read();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static int getJavaVersion() {
String version=System.getProperty("java.version");
int retval=0;
if(version != null) {
if(version.startsWith("1.2"))
return 12;
if(version.startsWith("1.3"))
return 13;
if(version.startsWith("1.4"))
return 14;
if(version.startsWith("1.5"))
return 15;
if(version.startsWith("5"))
return 15;
if(version.startsWith("1.6"))
return 16;
if(version.startsWith("6"))
return 16;
}
return retval;
}
public static <T> Vector<T> unmodifiableVector(Vector<? extends T> v) {
if(v == null) return null;
return new UnmodifiableVector(v);
}
public static String memStats(boolean gc) {
StringBuilder sb=new StringBuilder();
Runtime rt=Runtime.getRuntime();
if(gc)
rt.gc();
long free_mem, total_mem, used_mem;
free_mem=rt.freeMemory();
total_mem=rt.totalMemory();
used_mem=total_mem - free_mem;
sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem);
sb.append("\nTotal mem: ").append(total_mem);
return sb.toString();
}
/** IP related utilities */
public static InetAddress getIPv4Localhost() throws UnknownHostException {
return getLocalhost(StackType.IPv4) ;
}
public static InetAddress getIPv6Localhost() throws UnknownHostException {
return getLocalhost(StackType.IPv6) ;
}
public static InetAddress getLocalhost(StackType ip_version) throws UnknownHostException {
if (ip_version == StackType.IPv4)
return InetAddress.getByName("127.0.0.1") ;
else
return InetAddress.getByName("::1") ;
}
/**
* Returns the first non-loopback address on any interface on the current host.
*
* @param ip_version Constraint on IP version of address to be returned, 4 or 6
*/
public static InetAddress getFirstNonLoopbackAddress(StackType ip_version) throws SocketException {
InetAddress address = null ;
Enumeration intfs = NetworkInterface.getNetworkInterfaces();
while(intfs.hasMoreElements()) {
NetworkInterface intf=(NetworkInterface)intfs.nextElement();
// if(!intf.isUp() || intf.isLoopback())
if(Util.isDownOrLoopback(intf))
continue;
address = getFirstNonLoopbackAddress(intf, ip_version) ;
if (address != null) {
return address ;
}
}
return null ;
}
public static boolean isDownOrLoopback(NetworkInterface intf) {
boolean is_up=true, is_loopback=false;
if(NETWORK_INTERFACE_IS_UP != null) {
try {
Boolean retval=(Boolean)NETWORK_INTERFACE_IS_UP.invoke(intf);
if(retval != null)
is_up=retval.booleanValue();
}
catch(Throwable t) {
}
}
if(NETWORK_INTERFACE_IS_LOOPBACK != null) {
try {
Boolean retval=(Boolean)NETWORK_INTERFACE_IS_LOOPBACK.invoke(intf);
if(retval != null)
is_loopback=retval.booleanValue();
}
catch(Throwable t) {
}
}
return !is_up || is_loopback;
}
/**
* Returns the first non-loopback address on the given interface on the current host.
*
* @param intf the interface to be checked
* @param ip_version Constraint on IP version of address to be returned, 4 or 6
*/
public static InetAddress getFirstNonLoopbackAddress(NetworkInterface intf, StackType ip_version) throws SocketException {
if (intf == null)
throw new IllegalArgumentException("Network interface pointer is null") ;
for(Enumeration addresses=intf.getInetAddresses(); addresses.hasMoreElements();) {
InetAddress address=(InetAddress)addresses.nextElement();
if(!address.isLoopbackAddress()) {
if ((address instanceof Inet4Address && ip_version == StackType.IPv4) ||
(address instanceof Inet6Address && ip_version == StackType.IPv6))
return address;
}
}
return null ;
}
/**
* A function to check if an interface supports an IP version (i.e has addresses
* defined for that IP version).
*
* @param intf
* @return
*/
public static boolean interfaceHasIPAddresses(NetworkInterface intf, StackType ip_version) throws SocketException,UnknownHostException {
boolean supportsVersion = false ;
if (intf != null) {
// get all the InetAddresses defined on the interface
Enumeration addresses = intf.getInetAddresses() ;
while (addresses != null && addresses.hasMoreElements()) {
// get the next InetAddress for the current interface
InetAddress address = (InetAddress) addresses.nextElement() ;
// check if we find an address of correct version
if ((address instanceof Inet4Address && (ip_version == StackType.IPv4)) ||
(address instanceof Inet6Address && (ip_version == StackType.IPv6))) {
supportsVersion = true ;
break ;
}
}
}
else {
throw new UnknownHostException("network interface " + intf + " not found") ;
}
return supportsVersion ;
}
/**
* Tries to determine the type of IP stack from the available interfaces and their addresses and from the
* system properties (java.net.preferIPv4Stack and java.net.preferIPv6Addresses)
* @return StackType.IPv4 for an IPv4 only stack, StackYTypeIPv6 for an IPv6 only stack, and StackType.Unknown
* if the type cannot be detected
*/
public static StackType getIpStackType() {
boolean isIPv4StackAvailable = isStackAvailable(true) ;
boolean isIPv6StackAvailable = isStackAvailable(false) ;
// if only IPv4 stack available
if (isIPv4StackAvailable && !isIPv6StackAvailable) {
return StackType.IPv4;
}
// if only IPv6 stack available
else if (isIPv6StackAvailable && !isIPv4StackAvailable) {
return StackType.IPv6;
}
// if dual stack
else if (isIPv4StackAvailable && isIPv6StackAvailable) {
// get the System property which records user preference for a stack on a dual stack machine
if(Boolean.getBoolean(Global.IPv4)) // has preference over java.net.preferIPv6Addresses
return StackType.IPv4;
if(Boolean.getBoolean(Global.IPv6))
return StackType.IPv6;
return StackType.IPv6;
}
return StackType.Unknown;
}
public static boolean isStackAvailable(boolean ipv4) {
Collection<InetAddress> all_addrs=getAllAvailableAddresses();
for(InetAddress addr: all_addrs)
if(ipv4 && addr instanceof Inet4Address || (!ipv4 && addr instanceof Inet6Address))
return true;
return false;
}
public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException {
List<NetworkInterface> retval=new ArrayList<NetworkInterface>(10);
NetworkInterface intf;
for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
intf=(NetworkInterface)en.nextElement();
retval.add(intf);
}
return retval;
}
public static Collection<InetAddress> getAllAvailableAddresses() {
Set<InetAddress> retval=new HashSet<InetAddress>();
Enumeration en;
try {
en=NetworkInterface.getNetworkInterfaces();
if(en == null)
return retval;
while(en.hasMoreElements()) {
NetworkInterface intf=(NetworkInterface)en.nextElement();
Enumeration<InetAddress> addrs=intf.getInetAddresses();
while(addrs.hasMoreElements())
retval.add(addrs.nextElement());
}
}
catch(SocketException e) {
e.printStackTrace();
}
return retval;
}
/**
* Returns a value associated wither with one or more system properties, or found in the props map
* @param system_props
* @param props List of properties read from the configuration file
* @param prop_name The name of the property, will be removed from props if found
* @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from
* props (not system_props)
* @param default_value Used to return a default value if the properties or system properties didn't have the value
* @return The value, or null if not found
*/
public static String getProperty(String[] system_props, Properties props, String prop_name,
boolean ignore_sysprops, String default_value) {
String retval=null;
if(props != null && prop_name != null) {
retval=props.getProperty(prop_name);
props.remove(prop_name);
}
if(!ignore_sysprops) {
String tmp, prop;
if(system_props != null) {
for(int i=0; i < system_props.length; i++) {
prop=system_props[i];
if(prop != null) {
try {
tmp=System.getProperty(prop);
if(tmp != null)
return tmp; // system properties override config file definitions
}
catch(SecurityException ex) {}
}
}
}
}
if(retval == null)
return default_value;
return retval;
}
public static boolean isBindAddressPropertyIgnored() {
try {
String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY);
if(tmp == null) {
tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY_OLD);
if(tmp == null)
return false;
}
tmp=tmp.trim().toLowerCase();
return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on"));
}
catch(SecurityException ex) {
return false;
}
}
public static boolean isCoordinator(JChannel ch) {
if(ch == null) return false;
View view=ch.getView();
if(view == null)
return false;
Address local_addr=ch.getAddress();
if(local_addr == null)
return false;
Vector<Address> mbrs=view.getMembers();
return !(mbrs == null || mbrs.isEmpty()) && local_addr.equals(mbrs.firstElement());
}
public static MBeanServer getMBeanServer() {
ArrayList servers = MBeanServerFactory.findMBeanServer(null);
if (servers != null && !servers.isEmpty()) {
// return 'jboss' server if available
for (int i = 0; i < servers.size(); i++) {
MBeanServer srv = (MBeanServer) servers.get(i);
if ("jboss".equalsIgnoreCase(srv.getDefaultDomain()))
return srv;
}
// return first available server
return (MBeanServer) servers.get(0);
}
else {
//if it all fails, create a default
return MBeanServerFactory.createMBeanServer();
}
}
public static void registerChannel(JChannel channel, String name) {
MBeanServer server=Util.getMBeanServer();
if(server != null) {
try {
JmxConfigurator.registerChannel(channel,
server,
(name != null? name : "jgroups"),
channel.getClusterName(),
true);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public static String generateList(Collection c, String separator) {
if(c == null) return null;
StringBuilder sb=new StringBuilder();
boolean first=true;
for(Iterator it=c.iterator(); it.hasNext();) {
if(first) {
first=false;
}
else {
sb.append(separator);
}
sb.append(it.next());
}
return sb.toString();
}
/**
* Go through the input string and replace any occurance of ${p} with the
* props.getProperty(p) value. If there is no such property p defined, then
* the ${p} reference will remain unchanged.
*
* If the property reference is of the form ${p:v} and there is no such
* property p, then the default value v will be returned.
*
* If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the
* primary and the secondary properties will be tried in turn, before
* returning either the unchanged input, or the default value.
*
* The property ${/} is replaced with System.getProperty("file.separator")
* value and the property ${:} is replaced with
* System.getProperty("path.separator").
*
* @param string -
* the string with possible ${} references
* @param props -
* the source for ${x} property ref values, null means use
* System.getProperty()
* @return the input string with all property references replaced if any. If
* there are no valid references the input string will be returned.
* @throws {@link java.security.AccessControlException}
* when not authorised to retrieved system properties
*/
public static String replaceProperties(final String string, final Properties props) {
/** File separator value */
final String FILE_SEPARATOR=File.separator;
/** Path separator value */
final String PATH_SEPARATOR=File.pathSeparator;
/** File separator alias */
final String FILE_SEPARATOR_ALIAS="/";
/** Path separator alias */
final String PATH_SEPARATOR_ALIAS=":";
// States used in property parsing
final int NORMAL=0;
final int SEEN_DOLLAR=1;
final int IN_BRACKET=2;
final char[] chars=string.toCharArray();
StringBuilder buffer=new StringBuilder();
boolean properties=false;
int state=NORMAL;
int start=0;
for(int i=0;i < chars.length;++i) {
char c=chars[i];
// Dollar sign outside brackets
if(c == '$' && state != IN_BRACKET)
state=SEEN_DOLLAR;
// Open bracket immediatley after dollar
else if(c == '{' && state == SEEN_DOLLAR) {
buffer.append(string.substring(start, i - 1));
state=IN_BRACKET;
start=i - 1;
}
// No open bracket after dollar
else if(state == SEEN_DOLLAR)
state=NORMAL;
// Closed bracket after open bracket
else if(c == '}' && state == IN_BRACKET) {
// No content
if(start + 2 == i) {
buffer.append("${}"); // REVIEW: Correct?
}
else // Collect the system property
{
String value=null;
String key=string.substring(start + 2, i);
// check for alias
if(FILE_SEPARATOR_ALIAS.equals(key)) {
value=FILE_SEPARATOR;
}
else if(PATH_SEPARATOR_ALIAS.equals(key)) {
value=PATH_SEPARATOR;
}
else {
// check from the properties
if(props != null)
value=props.getProperty(key);
else
value=System.getProperty(key);
if(value == null) {
// Check for a default value ${key:default}
int colon=key.indexOf(':');
if(colon > 0) {
String realKey=key.substring(0, colon);
if(props != null)
value=props.getProperty(realKey);
else
value=System.getProperty(realKey);
if(value == null) {
// Check for a composite key, "key1,key2"
value=resolveCompositeKey(realKey, props);
// Not a composite key either, use the specified default
if(value == null)
value=key.substring(colon + 1);
}
}
else {
// No default, check for a composite key, "key1,key2"
value=resolveCompositeKey(key, props);
}
}
}
if(value != null) {
properties=true;
buffer.append(value);
}
}
start=i + 1;
state=NORMAL;
}
}
// No properties
if(properties == false)
return string;
// Collect the trailing characters
if(start != chars.length)
buffer.append(string.substring(start, chars.length));
// Done
return buffer.toString();
}
/**
* Try to resolve a "key" from the provided properties by checking if it is
* actually a "key1,key2", in which case try first "key1", then "key2". If
* all fails, return null.
*
* It also accepts "key1," and ",key2".
*
* @param key
* the key to resolve
* @param props
* the properties to use
* @return the resolved key or null
*/
private static String resolveCompositeKey(String key, Properties props) {
String value=null;
// Look for the comma
int comma=key.indexOf(',');
if(comma > -1) {
// If we have a first part, try resolve it
if(comma > 0) {
// Check the first part
String key1=key.substring(0, comma);
if(props != null)
value=props.getProperty(key1);
else
value=System.getProperty(key1);
}
// Check the second part, if there is one and first lookup failed
if(value == null && comma < key.length() - 1) {
String key2=key.substring(comma + 1);
if(props != null)
value=props.getProperty(key2);
else
value=System.getProperty(key2);
}
}
// Return whatever we've found or null
return value;
}
// /**
// * Replaces variables with values from system properties. If a system property is not found, the property is
// * removed from the output string
// * @param input
// * @return
// */
// public static String substituteVariables(String input) throws Exception {
// Collection<Configurator.ProtocolConfiguration> configs=Configurator.parseConfigurations(input);
// for(Configurator.ProtocolConfiguration config: configs) {
// for(Iterator<Map.Entry<String,String>> it=config.getProperties().entrySet().iterator(); it.hasNext();) {
// Map.Entry<String,String> entry=it.next();
// return null;
/**
* Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns
* the same string, otherwise a copy of the string with variables substituted
* @param val
* @return A string with vars replaced, or the same string if no vars found
*/
public static String substituteVariable(String val) {
if(val == null)
return val;
String retval=val, prev;
while(retval.contains("${")) { // handle multiple variables in val
prev=retval;
retval=_substituteVar(retval);
if(retval.equals(prev))
break;
}
return retval;
}
private static String _substituteVar(String val) {
int start_index, end_index;
start_index=val.indexOf("${");
if(start_index == -1)
return val;
end_index=val.indexOf("}", start_index+2);
if(end_index == -1)
throw new IllegalArgumentException("missing \"}\" in " + val);
String tmp=getProperty(val.substring(start_index +2, end_index));
if(tmp == null)
return val;
StringBuilder sb=new StringBuilder();
sb.append(val.substring(0, start_index));
sb.append(tmp);
sb.append(val.substring(end_index+1));
return sb.toString();
}
public static String getProperty(String s) {
String var, default_val, retval=null;
int index=s.indexOf(":");
if(index >= 0) {
var=s.substring(0, index);
default_val=s.substring(index+1);
if(default_val != null && default_val.length() > 0)
default_val=default_val.trim();
// retval=System.getProperty(var, default_val);
retval=_getProperty(var, default_val);
}
else {
var=s;
// retval=System.getProperty(var);
retval=_getProperty(var, null);
}
return retval;
}
/**
* Parses a var which might be comma delimited, e.g. bla,foo:1000: if 'bla' is set, return its value. Else,
* if 'foo' is set, return its value, else return "1000"
* @param var
* @param default_value
* @return
*/
private static String _getProperty(String var, String default_value) {
if(var == null)
return null;
List<String> list=parseCommaDelimitedStrings(var);
if(list == null || list.isEmpty()) {
list=new ArrayList<String>(1);
list.add(var);
}
String retval=null;
for(String prop: list) {
try {
retval=System.getProperty(prop);
if(retval != null)
return retval;
}
catch(Throwable e) {
}
}
return default_value;
}
/**
* Used to convert a byte array in to a java.lang.String object
* @param bytes the bytes to be converted
* @return the String representation
*/
private static String getString(byte[] bytes) {
StringBuilder sb=new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
sb.append(0x00FF & b);
if (i + 1 < bytes.length) {
sb.append("-");
}
}
return sb.toString();
}
/**
* Converts a java.lang.String in to a MD5 hashed String
* @param source the source String
* @return the MD5 hashed version of the string
*/
public static String md5(String source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
return null;
}
}
/**
* Converts a java.lang.String in to a SHA hashed String
* @param source the source String
* @return the MD5 hashed version of the string
*/
public static String sha(String source) {
try {
MessageDigest md = MessageDigest.getInstance("SHA");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String methodNameToAttributeName(String methodName) {
methodName=methodName.startsWith("get") || methodName.startsWith("set")? methodName.substring(3): methodName;
methodName=methodName.startsWith("is")? methodName.substring(2) : methodName;
// Pattern p=Pattern.compile("[A-Z]+");
Matcher m=METHOD_NAME_TO_ATTR_NAME_PATTERN.matcher(methodName);
StringBuffer sb=new StringBuffer();
while(m.find()) {
int start=m.start(), end=m.end();
String str=methodName.substring(start, end).toLowerCase();
if(str.length() > 1) {
String tmp1=str.substring(0, str.length() -1);
String tmp2=str.substring(str.length() -1);
str=tmp1 + "_" + tmp2;
}
if(start == 0) {
m.appendReplacement(sb, str);
}
else
m.appendReplacement(sb, "_" + str);
}
m.appendTail(sb);
return sb.toString();
}
public static String attributeNameToMethodName(String attr_name) {
if(attr_name.contains("_")) {
// Pattern p=Pattern.compile("_.");
Matcher m=ATTR_NAME_TO_METHOD_NAME_PATTERN.matcher(attr_name);
StringBuffer sb=new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, attr_name.substring(m.end() - 1, m.end()).toUpperCase());
}
m.appendTail(sb);
char first=sb.charAt(0);
if(Character.isLowerCase(first)) {
sb.setCharAt(0, Character.toUpperCase(first));
}
return sb.toString();
}
else {
if(Character.isLowerCase(attr_name.charAt(0))) {
return attr_name.substring(0, 1).toUpperCase() + attr_name.substring(1);
}
else {
return attr_name;
}
}
}
/**
* Runs a task on a separate thread
* @param task
* @param factory
* @param group
* @param thread_name
*/
public static void runAsync(Runnable task, ThreadFactory factory, ThreadGroup group, String thread_name) {
Thread thread=factory.newThread(group, task, thread_name);
thread.start();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.