answer
stringlengths 17
10.2M
|
|---|
package org.hive2hive.core.encryption;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.hive2hive.core.log.H2HLogger;
import org.hive2hive.core.log.H2HLoggerFactory;
/**
* This class provides special encryption and decryption functionalities for files.
*
* @author Christian
*
*/
public final class FileEncryptionUtil {
private static final H2HLogger logger = H2HLoggerFactory.getLogger(FileEncryptionUtil.class);
private static final String DELIMITER = "DELIMITERDELIMITER";
private FileEncryptionUtil() {
}
/**
* Generates a SHA-256 checksum based on the binary representation of a file.
*
* @param filePath The path of the file which shall be check summed.
* @return The checksum of the file.
* @throws IOException
*/
public static String generateChecksum(Path filePath) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
FileInputStream fis = new FileInputStream(filePath.toFile());
int position = 0;
byte[] buffer = new byte[1024];
while ((position = fis.read(buffer)) != 1) {
digest.update(buffer, 0, position);
}
fis.close();
byte[] digestBytes = digest.digest();
return EncryptionUtil.toHex(digestBytes);
} catch (NoSuchAlgorithmException e) {
logger.error("Exception while creating checksum;", e);
}
return null;
}
public static String serializePath(Path path) {
if (path.getNameCount() < 2) {
return path.toString();
} else {
StringBuffer buffer = new StringBuffer(path.getName(0).toString());
for (int i = 1; i < path.getNameCount(); i++) {
buffer.append(DELIMITER);
buffer.append(path.getName(i).toString());
}
return buffer.toString();
}
}
public static Path deserializePath(String serializedPath) {
String[] pathParts = serializedPath.split(DELIMITER);
if (pathParts.length > 1) {
String tail[] = new String[pathParts.length - 1];
System.arraycopy(pathParts, 1, tail, 0, pathParts.length - 1);
return Paths.get("", pathParts);
} else if (pathParts.length == 1) {
return Paths.get(pathParts[0]);
}
return null;
}
private static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
int numBytes;
byte[] buffer = new byte[64];
while ((numBytes = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, numBytes);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
|
package cz.metacentrum.perun.core.impl;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;
import java.util.List;
/**
* Class holding configuration of perun apps brandings and apps' domains.
*
* @author Vojtech Sassmann <vojtech.sassmann@gmail.com>
*/
public class PerunAppsConfig {
private static PerunAppsConfig instance;
private List<Brand> brands;
public static PerunAppsConfig getInstance() {
return instance;
}
public static void setInstance(PerunAppsConfig instance) {
PerunAppsConfig.instance = instance;
}
@JsonGetter("brands")
public List<Brand> getBrands() {
return brands;
}
@JsonSetter("brands")
public void setBrands(List<Brand> brands) {
this.brands = brands;
}
public static Brand getBrandContainingDomain(String domain) {
for (Brand brand : instance.getBrands()) {
PerunAppsConfig.NewApps newApps = brand.getNewApps();
if (brand.getOldGuiDomain().equals(domain) || newApps.getAdmin().equals(domain) || newApps.getProfile().equals(domain)
|| newApps.getPublications().equals(domain) || newApps.getPwdReset().equals(domain)) {
return brand;
}
}
return null;
}
/**
* Class holding data for a single branding.
*/
public static class Brand {
private String name;
private String oldGuiDomain;
private NewApps newApps;
@JsonGetter("name")
public String getName() {
return name;
}
@JsonSetter("name")
public void setName(String name) {
this.name = name;
}
@JsonGetter("newApps")
public NewApps getNewApps() {
return newApps;
}
@JsonSetter("new_apps")
public void setNewApps(NewApps newApps) {
this.newApps = newApps;
}
@JsonGetter("oldGuiDomain")
public String getOldGuiDomain() {
return oldGuiDomain;
}
@JsonSetter("old_gui_domain")
public void setOldGuiDomain(String oldGuiDomain) {
this.oldGuiDomain = oldGuiDomain;
}
@Override
public String toString() {
return "Brand{" +
"name='" + name + '\'' +
", oldGuiDomain='" + oldGuiDomain + '\'' +
", newApps=" + newApps +
'}';
}
}
/**
* Class holding domains of new gui applications.
*/
public static class NewApps {
private String admin;
private String profile;
private String pwdReset;
private String publications;
@JsonGetter("admin")
public String getAdmin() {
return admin;
}
@JsonSetter("admin")
public void setAdmin(String admin) {
this.admin = admin;
}
@JsonGetter("profile")
public String getProfile() {
return profile;
}
@JsonSetter("profile")
public void setProfile(String profile) {
this.profile = profile;
}
@JsonGetter("pwdReset")
public String getPwdReset() {
return pwdReset;
}
@JsonSetter("pwd_reset")
public void setPwdReset(String pwdReset) {
this.pwdReset = pwdReset;
}
@JsonGetter("publications")
public String getPublications() {
return publications;
}
@JsonSetter("publications")
public void setPublications(String publications) {
this.publications = publications;
}
@Override
public String toString() {
return "NewApps{" +
"admin='" + admin + '\'' +
", profile='" + profile + '\'' +
'}';
}
}
@Override
public String toString() {
return "PerunAppsConfig{" +
"brands=" + brands +
'}';
}
}
|
package fr.aumgn.bukkitutils.playerid;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public final class PlayerId {
private static final Map<String, PlayerId> accounts =
new HashMap<String, PlayerId>();
public static PlayerId get(OfflinePlayer player) {
return get(player.getName());
}
public static PlayerId get(String name) {
String lname = name.toLowerCase(Locale.ENGLISH);
if (!accounts.containsKey(lname)) {
accounts.put(lname, new PlayerId(lname));
}
return accounts.get(lname);
}
private final String name;
private PlayerId(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getDisplayName() {
Player player = getPlayer();
if (player != null) {
return player.getDisplayName();
} else {
return getName();
}
}
public boolean isOnline() {
return (getPlayer() != null);
}
public boolean isOffline() {
return (getPlayer() == null);
}
public Player getPlayer() {
return Bukkit.getPlayerExact(name);
}
public OfflinePlayer getOfflinePlayer() {
return Bukkit.getOfflinePlayer(name);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof PlayerId)) {
return false;
}
return name.equals(((PlayerId) other).name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
}
|
package hudson.plugins.analysis.util;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.api.BlameCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.blame.BlameResult;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.jenkinsci.plugins.gitclient.Git;
import org.jenkinsci.plugins.gitclient.GitClient;
import org.jenkinsci.plugins.gitclient.RepositoryCallback;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.model.TaskListener;
import hudson.remoting.VirtualChannel;
public class GitBlamer extends AbstractBlamer {
private final String pathToGit;
/**
* Creates a new blamer for Git.
*
* @param pathToGit path to git binary
* @param environment {@link EnvVars environment} of the build
* @param workspace workspace of the build
* @param listener task listener to print logging statements to
*/
public GitBlamer(final String pathToGit, final EnvVars environment, FilePath workspace, final TaskListener listener) {
super(environment, workspace, listener);
this.pathToGit = pathToGit;
log("Using GitBlamer to create author and commit information for all warnings.%n");
log("Getting blame results for all files in %s.%n", workspace);
}
@Override
protected Map<String, BlameRequest> blame(final Map<String, BlameRequest> linesOfConflictingFiles) throws InterruptedException, IOException {
return fillBlameResults(linesOfConflictingFiles, loadBlameResultsForFiles(linesOfConflictingFiles));
}
private Map<String, BlameResult> loadBlameResultsForFiles(final Map<String, BlameRequest> linesOfConflictingFiles)
throws InterruptedException, IOException {
GitClient git = Git.with(getListener(), getEnvironment()).in(getWorkspace()).using(pathToGit).getClient();
return git.withRepository(new BlameCallback(this, getHead(git), linesOfConflictingFiles.values()));
}
private ObjectId getHead(final GitClient git) throws InterruptedException {
String gitCommit = getEnvironment().get("GIT_COMMIT");
ObjectId headCommit;
if (StringUtils.isBlank(gitCommit)) {
log("No GIT_COMMIT environment variable found, using HEAD.%n");
headCommit = git.revParse("HEAD");
}
else {
headCommit = git.revParse(gitCommit);
}
return headCommit;
}
private Map<String, BlameRequest> fillBlameResults(final Map<String, BlameRequest> linesOfConflictingFiles,
final Map<String, BlameResult> blameResults) {
for (String fileName : linesOfConflictingFiles.keySet()) {
BlameRequest request = linesOfConflictingFiles.get(fileName);
BlameResult blame = blameResults.get(request.getFileName());
if (blame == null) {
log("No blame details found for %s.%n", fileName);
}
else {
for (int line : request) {
int lineIndex = line - 1; // first line is index 0
if (lineIndex < blame.getResultContents().size()) {
PersonIdent who = blame.getSourceAuthor(lineIndex);
if (who == null) {
log("No author information found for line %d in file %s.%n", lineIndex, fileName);
}
else {
request.setName(line, who.getName());
request.setEmail(line, who.getEmailAddress());
}
RevCommit commit = blame.getSourceCommit(lineIndex);
if (commit == null) {
log("No commit ID found for line %d in file %s.%n", lineIndex, fileName);
}
else {
request.setCommit(line, commit.getName());
}
}
}
}
}
return linesOfConflictingFiles;
}
private static class BlameCallback implements RepositoryCallback<Map<String, BlameResult>> {
private GitBlamer gitBlamer;
private ObjectId headCommit;
private Collection<BlameRequest> requests;
public BlameCallback(final GitBlamer gitBlamer, final ObjectId headCommit, final Collection<BlameRequest> requests) {
this.gitBlamer = gitBlamer;
this.headCommit = headCommit;
this.requests = requests;
}
@Override
public Map<String, BlameResult> invoke(final Repository repo, final VirtualChannel channel) throws IOException, InterruptedException {
Map<String, BlameResult> blameResults = new HashMap<String, BlameResult>();
if (headCommit == null) {
gitBlamer.error("Could not retrieve HEAD commit, aborting.");
return blameResults;
}
for (BlameRequest request : requests) {
BlameCommand blame = new BlameCommand(repo);
String fileName = request.getFileName();
blame.setFilePath(fileName);
blame.setStartCommit(headCommit);
try {
BlameResult result = blame.call();
if (result == null) {
gitBlamer.log("No blame results for request <%s>.%n", request);
}
else {
blameResults.put(fileName, result);
}
if (Thread.interrupted()) {
String message = "Thread was interrupted while computing blame information.";
gitBlamer.log(message);
throw new InterruptedException(message);
}
}
catch (GitAPIException e) {
String message = "Error running git blame on " + fileName + " with revision: " + headCommit;
gitBlamer.error(message);
}
}
return blameResults;
}
}
// /**
// * Get a repository browser link for the specified commit.
// *
// * @param commitId the id of the commit to be linked.
// * @return The link or {@code null} if one is not available.
// */
// public URL urlForCommitId(final String commitId) {
// if (commitUrlsAttempted) {
// return commitUrls == null ? null : commitUrls.get(commitId);
// commitUrlsAttempted = true;
// Run<?, ?> run = getOwner();
// if (run.getParent() instanceof AbstractProject) {
// AbstractProject aProject = (AbstractProject) run.getParent();
// SCM scm = aProject.getScm();
// //SCM scm = getOwner().getParent().getScm();
// if ((scm == null) || (scm instanceof NullSCM)) {
// scm = aProject.getRootProject().getScm();
// final HashSet<String> commitIds = new HashSet<String>(getAnnotations().size());
// for (final FileAnnotation annot : getAnnotations()) {
// commitIds.add(annot.getCommitId());
// commitIds.remove(null);
// try {
// commitUrls = computeUrlsForCommitIds(scm, commitIds);
// if (commitUrls != null) {
// return commitUrls.get(commitId);
// catch (NoClassDefFoundError e) {
// // Git wasn't installed, ignore
// return null;
// /**
// * Creates links for the specified commitIds using the repository browser.
// *
// * @param scm the {@code SCM} of the owning project.
// * @param commitIds the commit ids in question.
// * @return a mapping of the links or {@code null} if the {@code SCM} isn't a
// * {@code GitSCM} or if a repository browser isn't set or if it isn't a
// * {@code GitRepositoryBrowser}.
// */
// @SuppressWarnings("REC_CATCH_EXCEPTION")
// public static Map<String, URL> computeUrlsForCommitIds(final SCM scm, final Set<String> commitIds) {
// if (!(scm instanceof GitSCM)) {
// return null;
// if (commitIds.isEmpty()) {
// return null;
// GitSCM gscm = (GitSCM) scm;
// GitRepositoryBrowser browser = gscm.getBrowser();
// if (browser == null) {
// RepositoryBrowser<?> ebrowser = gscm.getEffectiveBrowser();
// if (ebrowser instanceof GitRepositoryBrowser) {
// browser = (GitRepositoryBrowser) ebrowser;
// else {
// return null;
// // This is a dirty hack because the only way to create changesets is to do it by parsing git log messages
// // Because what we're doing is fairly dangerous (creating minimal commit messages) just give up if there is an error
// try {
// HashMap<String, URL> result = new HashMap<String, URL>((int) (commitIds.size() * 1.5f));
// for (final String commitId : commitIds) {
// GitChangeSet cs = new GitChangeSet(Collections.singletonList("commit " + commitId), true);
// if (cs.getId() != null) {
// result.put(commitId, browser.getChangeSetLink(cs));
// return result;
// // CHECKSTYLE:OFF
// catch (Exception e) {
// // CHECKSTYLE:ON
// // TODO: log?
// return null;
// /**
// * Get a {@code User} that corresponds to this author.
// *
// * @return a {@code User} or {@code null} if one can't be created.
// */
// public User getUser() {
// if (userAttempted) {
// return user;
// userAttempted = true;
// if ("".equals(authorName)) {
// return null;
// Run<?, ?> run = getOwner();
// if (run.getParent() instanceof AbstractProject) {
// AbstractProject aProject = (AbstractProject) run.getParent();
// SCM scm = aProject.getScm();
// if ((scm == null) || (scm instanceof NullSCM)) {
// scm = aProject.getRootProject().getScm();
// try {
// user = findOrCreateUser(authorName, authorEmail, scm);
// catch (NoClassDefFoundError e) {
// // Git wasn't installed, ignore
// return user;
// /**
// * Returns user of the change set. Stolen from hudson.plugins.git.GitChangeSet.
// *
// * @param fullName user name.
// * @param email user email.
// * @param scm the SCM of the owning project.
// * @return {@link User} or {@code null} if the {@Code SCM} isn't a {@code GitSCM}.
// */
// public static User findOrCreateUser(final String fullName, final String email, final SCM scm) {
// if (!(scm instanceof GitSCM)) {
// return null;
// GitSCM gscm = (GitSCM) scm;
// boolean createAccountBasedOnEmail = gscm.isCreateAccountBasedOnEmail();
// User user;
// if (createAccountBasedOnEmail) {
// user = User.get(email, false);
// if (user == null) {
// try {
// user = User.get(email, true);
// user.setFullName(fullName);
// user.addProperty(new Mailer.UserProperty(email));
// user.save();
// catch (IOException e) {
// // add logging statement?
// else {
// user = User.get(fullName, false);
// if (user == null) {
// user = User.get(email.split("@")[0], true);
// return user;
}
|
package xyz.hotchpotch.jutaime.throwable.matchers;
import java.util.Objects;
import org.hamcrest.Matcher;
import xyz.hotchpotch.jutaime.throwable.Testee;
/**
* {@code Matcher} <br>
* {@code Matcher} {@code cause.getCause() == null}
* <br>
* <br>
* root cause<br>
* <br>
* <br>
* {@code Matcher} <br>
* <br>
* <br>
* {@code Matcher} <br>
*
* @author nmby
*/
public class InChain extends InChainBase {
// ++++++++++++++++ static members ++++++++++++++++
/**
* {@code Matcher} <br>
* {@code Matcher} <br>
*
* @param expectedType
* @return {@code Matcher}
* @throws NullPointerException {@code expectedType} {@code null}
*/
public static Matcher<Testee> inChain(Class<? extends Throwable> expectedType) {
return new InChain(Objects.requireNonNull(expectedType));
}
/**
* {@code Matcher} <br>
* {@code Matcher} <br>
*
* @param expectedType
* @param expectedMessage {@code null}
* @return {@code Matcher}
* @throws NullPointerException {@code expectedType} {@code null}
*/
public static Matcher<Testee> inChain(Class<? extends Throwable> expectedType, String expectedMessage) {
return new InChain(Objects.requireNonNull(expectedType), expectedMessage);
}
/**
* {@code matcher}
* {@code Matcher} <br>
*
* @param matcher {@code Matcher}
* @return {@code Matcher}
* @throws NullPointerException {@code matcher} {@code null}
*/
public static Matcher<Testee> inChain(Matcher<Throwable> matcher) {
return new InChain(Objects.requireNonNull(matcher));
}
// ++++++++++++++++ instance members ++++++++++++++++
private InChain(Class<? extends Throwable> expectedType) {
super(false, expectedType);
}
private InChain(Class<? extends Throwable> expectedType, String expectedMessage) {
super(false, expectedType, expectedMessage);
}
private InChain(Matcher<Throwable> matcher) {
super(matcher);
}
}
|
package innovimax.mixthem.interfaces;
import innovimax.mixthem.exceptions.MixException;
/**
* This interface provides for joining two lines
* @author Innovimax
* @version 1.0
*/
public interface IJoinLine {
/**
* Joins two lines on the default first field.
* @param line1 The first line to be joined
* @param line2 The second line to be joined
* @return The result of joining lines, or null if no join possible
* @throws MixException - If an joining error occurs
*/
String join(String line1, String line2) throws MixException;
/**
* Joins two lines on a common field
* @param line1 The first line to be joined
* @param line2 The second line to be joined
* @param index The index of the common field
* @return The result of joining lines, or null if no join possible
* @throws MixException - If an joining error occurs
*/
String join(String line1, String line2, int index) throws MixException;
/**
* Joins two lines on a common field that has a different index.
* @param line1 The first line to be joined
* @param line2 The second line to be joined
* @param index1 The index of the common field in the first line
* @param index2 The index of the common field in the second line
* @return The result of joining lines, or null if no join possible
* @throws MixException - If an joining error occurs
*/
String join(String line1, String line2, int index1, int index2) throws MixException;
}
|
package intermidia.BoWCalculator;
import java.util.Enumeration;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.StringToWordVector;
public class BoWCalculator
{
public static void main( String[] args ) throws Exception
{
DataSource dataSource = new DataSource(args[0]);
Instances input = dataSource.getDataSet(0);
/* System.out.println(instances.size());
for(Instance instance : instances)
{
System.out.println(instance.value(0) + " - " + instance.stringValue(1));
}
*/
StringToWordVector bowFilter = new StringToWordVector(500);
bowFilter.setInputFormat(input);
bowFilter.setOutputWordCounts(true);
bowFilter.setWordsToKeep(10);
Instances output = Filter.useFilter(input, bowFilter);
System.out.println(output);
/* for(Instance instance : output)
{
System.out.println(instance.value(0) + " - " + instance.stringValue(1));
}*/
/*Instance bow = bowFilter.output();*/
/*System.out.println(bow);*/
}
}
|
package io.antielectron.framework.js;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.JSObject;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BooleanSupplier;
/**
* TODO Document
* @author Evan Geng
*/
public class JSGlobals {
private final Map<String, Object> globals = new HashMap<>();
private final Map<Browser, BooleanSupplier> boundBrowsers = new HashMap<>();
public void put(String name, Object value) {
globals.put(name, value);
boundBrowsers.entrySet().removeIf(e -> {
if (!e.getValue().getAsBoolean())
return true;
inject(e.getKey(), name, value);
return false;
});
}
public void putExecution(String code) {
put(Integer.toString(code.hashCode()), new ScriptExecution(code));
}
public void clear() {
globals.clear();
}
public void clearBindings() {
boundBrowsers.clear();
}
public void bind(BooleanSupplier activeCheck, Browser browser) {
if (activeCheck.getAsBoolean()) {
boundBrowsers.put(browser, activeCheck);
injectTo(browser);
}
}
public void injectTo(Browser browser) {
globals.forEach((k, v) -> inject(browser, k, v));
}
private void inject(Browser browser, String key, Object value) {
if (value instanceof ScriptExecution)
browser.executeJavaScript(((ScriptExecution)value).script);
else
globalsOf(browser).setProperty(key, value);
}
private static JSObject globalsOf(Browser browser) {
return browser.executeJavaScriptAndReturnValue("window").asObject();
}
private static class ScriptExecution {
final String script;
ScriptExecution(String script) {
this.script = script;
}
}
}
|
package io.qameta.htmlelements.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Name {
String value();
}
|
package jp.ac.nii.prl.mape.controller.model;
import java.util.Collection;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class AP {
@GeneratedValue
@Id
@JsonIgnore
private Long id;
private String name;
@ElementCollection
private List<String> predecessors;
@OneToOne
private Analyser analyser;
@OneToOne
private Planner planner;
@OneToOne
private CombinedAP combinedAP;
public Analyser getAnalyser() {
return analyser;
}
public CombinedAP getCombinedAP() {
return combinedAP;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public Planner getPlanner() {
return planner;
}
public Collection<String> getPredecessors() {
return predecessors;
}
public void setAnalyser(Analyser analyser) {
this.analyser = analyser;
}
public void setCombinedAP(CombinedAP combinedAP) {
this.combinedAP = combinedAP;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPlanner(Planner planner) {
this.planner = planner;
}
public void setPredecessors(List<String> predecessors) {
this.predecessors = predecessors;
}
public boolean hasCombinedAP() {
return combinedAP != null;
}
}
|
package landmaster.plustic.modules;
import java.util.*;
import landmaster.plustic.*;
import landmaster.plustic.api.*;
import landmaster.plustic.config.*;
import landmaster.plustic.tools.*;
import landmaster.plustic.tools.stats.*;
import net.minecraft.item.*;
import net.minecraft.util.*;
import net.minecraftforge.event.*;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.*;
import slimeknights.tconstruct.library.*;
import slimeknights.tconstruct.library.materials.*;
import slimeknights.tconstruct.library.modifiers.*;
import slimeknights.tconstruct.library.tinkering.*;
import slimeknights.tconstruct.library.tools.*;
import slimeknights.tconstruct.tools.*;
@Mod.EventBusSubscriber(modid = ModInfo.MODID)
public class ModuleTools {
public static ToolKatana katana;
public static ToolLaserGun laserGun;
public static ToolPart pipe_piece;
public static ToolPart laser_medium;
public static ToolPart battery_cell;
private static final List<ToolCore> tools = new ArrayList<>();
private static final List<IToolPart> toolParts = new ArrayList<>();
public static void init() {}
@SubscribeEvent
public static void initItems(RegistryEvent.Register<Item> event) {
pipe_piece = new ToolPart(Material.VALUE_Ingot * 4);
pipe_piece.setUnlocalizedName("pipe_piece").setRegistryName("pipe_piece");
event.getRegistry().register(pipe_piece);
TinkerRegistry.registerToolPart(pipe_piece);
PlusTiC.proxy.registerToolPartModel(pipe_piece);
toolParts.add(pipe_piece);
laser_medium = new ToolPart(Material.VALUE_Ingot * 3);
laser_medium.setUnlocalizedName("laser_medium").setRegistryName("laser_medium");
event.getRegistry().register(laser_medium);
TinkerRegistry.registerToolPart(laser_medium);
PlusTiC.proxy.registerToolPartModel(laser_medium);
toolParts.add(laser_medium);
battery_cell = new ToolPart(Material.VALUE_Ingot * 3);
battery_cell.setUnlocalizedName("battery_cell").setRegistryName("battery_cell");
event.getRegistry().register(battery_cell);
TinkerRegistry.registerToolPart(battery_cell);
PlusTiC.proxy.registerToolPartModel(battery_cell);
toolParts.add(battery_cell);
if (Config.laserGun) {
laserGun = new ToolLaserGun();
event.getRegistry().register(laserGun);
TinkerRegistry.registerToolForgeCrafting(laserGun);
PlusTiC.proxy.registerToolModel(laserGun);
tools.add(laserGun);
// Vanilla Tinkers Laser material stats
TinkerRegistry.addMaterialStats(TinkerMaterials.prismarine, new LaserMediumMaterialStats(2.5f, 20));
TinkerRegistry.addMaterialStats(TinkerMaterials.blaze, new BatteryCellMaterialStats(85000),
new LaserMediumMaterialStats(3.2f, 17));
TinkerRegistry.addMaterialStats(TinkerMaterials.endrod, new BatteryCellMaterialStats(260000),
new LaserMediumMaterialStats(8.6f, 38));
TinkerRegistry.addMaterialStats(TinkerMaterials.copper, new BatteryCellMaterialStats(55000));
TinkerRegistry.addMaterialStats(TinkerMaterials.silver, new BatteryCellMaterialStats(75000));
TinkerRegistry.addMaterialStats(TinkerMaterials.manyullyn, new BatteryCellMaterialStats(120000));
}
if (Config.katana) {
katana = new ToolKatana();
event.getRegistry().register(katana);
TinkerRegistry.registerToolForgeCrafting(katana);
PlusTiC.proxy.registerToolModel(katana);
tools.add(katana);
}
for (final IToolPart part: getPlusTiCToolParts()) {
for (final ToolCore tool: getPlusTiCTools()) {
for (final PartMaterialType pmt: tool.getRequiredComponents()) {
if (pmt.getPossibleParts().contains(part)) {
TinkerRegistry.registerStencilTableCrafting(Pattern.setTagForPart(new ItemStack(TinkerTools.pattern), (Item)part));
}
}
}
}
// for added PlusTiC tools
// TODO add more modifier jsons
for (IModifier modifier: new IModifier[] { TinkerModifiers.modBeheading, TinkerModifiers.modDiamond, TinkerModifiers.modEmerald }) {
PlusTiC.proxy.registerModifierModel(modifier,
new ResourceLocation(ModInfo.MODID, "models/item/modifiers/"+modifier.getIdentifier()));
}
}
public static List<ToolCore> getPlusTiCTools() {
return Collections.unmodifiableList(tools);
}
public static List<IToolPart> getPlusTiCToolParts() {
return Collections.unmodifiableList(toolParts);
}
}
|
package me.prettyprint.cassandra.model;
import static me.prettyprint.cassandra.utils.Assert.notNull;
import org.apache.cassandra.thrift.Clock;
import org.apache.cassandra.thrift.Column;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Hector Column definition.
*
* @param <N> The type of the column name
* @param <V> The type of the column value
*
* @author Ran Tavory (rantav@gmail.com)
*
*/
public final class HColumn<N,V> {
private N name;
private V value;
private Clock clock;
private final Serializer<N> nameSerializer;
private final Serializer<V> valueSerializer;
/*package*/ HColumn(N name, V value, Clock clock, Serializer<N> nameSerializer,
Serializer<V> valueSerializer) {
this(nameSerializer, valueSerializer);
notNull(name, "name is null");
notNull(value, "value is null");
this.name = name;
this.value = value;
this.clock = clock;
}
/*package*/ HColumn(Column thriftColumn, Serializer<N> nameSerializer,
Serializer<V> valueSerializer) {
this(nameSerializer, valueSerializer);
notNull(thriftColumn, "thriftColumn is null");
name = nameSerializer.fromBytes(thriftColumn.getName());
value = valueSerializer.fromBytes(thriftColumn.getValue());
clock = thriftColumn.clock;
}
/*package*/ HColumn(Serializer<N> nameSerializer, Serializer<V> valueSerializer) {
notNull(nameSerializer, "nameSerializer is null");
notNull(valueSerializer, "valueSerializer is null");
this.nameSerializer = nameSerializer;
this.valueSerializer = valueSerializer;
}
public HColumn<N,V> setName(N name) {
notNull(name, "name is null");
this.name = name;
return this;
}
public HColumn<N,V> setValue(V value) {
notNull(value, "value is null");
this.value = value;
return this;
}
HColumn<N,V> setClock(Clock clock) {
this.clock = clock;
return this;
}
public N getName() {
return name;
}
public V getValue() {
return value;
}
Clock getClock() {
return clock;
}
public Column toThrift() {
return new Column(nameSerializer.toBytes(name), valueSerializer.toBytes(value), clock);
}
public HColumn<N, V> fromThrift(Column c) {
notNull(c, "column is null");
name = nameSerializer.fromBytes(c.name);
value = valueSerializer.fromBytes(c.value);
return this;
}
public Serializer<N> getNameSerializer() {
return nameSerializer;
}
public Serializer<V> getValueSerializer() {
return valueSerializer;
}
public byte[] getValueBytes() {
return valueSerializer.toBytes(getValue());
}
public byte[] getNameBytes() {
return nameSerializer.toBytes(getName());
}
@Override
public String toString() {
return "HColumn(" + name + "=" + value + ")";
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(name).append(value).append(clock).toHashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
@SuppressWarnings("unchecked")
HColumn<N,V> other = (HColumn<N,V>) obj;
return new EqualsBuilder().appendSuper(super.equals(obj)).append(name, other.name).
append(value, other.value).append(clock, other.clock).isEquals();
}
}
|
package net.finmath.functions;
import java.util.Calendar;
import net.finmath.rootfinder.NewtonsMethod;
/**
* This class implements some functions as static class methods.
* It provides functions like the Black-Scholes formula,
* the inverse of the Back-Scholes formula with respect to (implied) volatility,
* the corresponding functions for caplets and swaptions.
*
* @author Christian Fries
* @version 1.7
* @date 27.04.2012
*/
public class AnalyticFormulas {
// Suppress default constructor for non-instantiability
private AnalyticFormulas() {
// This constructor will never be invoked
}
/**
* Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a log-normal process with constant log-volatility.
*
* @param forward The forward of the underlying.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @param payoffUnit The payoff unit (e.g., the discount factor)
* @return Returns the value of a European call option under the Black-Scholes model.
*/
public static double blackScholesGeneralizedOptionValue(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double payoffUnit)
{
if((optionStrike <= 0.0) || (optionMaturity <= 0.0))
{
return Math.max(forward - optionStrike,0) * payoffUnit;
}
else
{
// Calculate analytic value
double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit;
return valueAnalytic;
}
}
/**
* Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0), where S follows a log-normal process with constant log-volatility.
*
* @param initialStockValue The spot value of the underlying.
* @param riskFreeRate The risk free rate r (df = exp(-r T)).
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @return Returns the value of a European call option under the Black-Scholes model.
*/
public static double blackScholesOptionValue(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
return blackScholesGeneralizedOptionValue(
initialStockValue * Math.exp(riskFreeRate * optionMaturity), // forward
volatility,
optionMaturity,
optionStrike,
Math.exp(-riskFreeRate * optionMaturity) // payoff unit
);
}
/**
* Calculates the Black-Scholes option value of an atm call option.
*
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param forward The forward, i.e., the expectation of the index under the measure associated with payoff unit.
* @param payoffUnit The payoff unit, i.e., the discount factor or the anuity associated with the payoff.
* @return Returns the value of a European at-the-money call option under the Black-Scholes model
*/
public static double blackScholesATMOptionValue(
double volatility,
double optionMaturity,
double forward,
double payoffUnit)
{
// Calculate analytic value
double dPlus = 0.5 * volatility * Math.sqrt(optionMaturity);
double dMinus = -dPlus;
double valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit;
return valueAnalytic;
}
/**
* Calculates the Black-Scholes option value of a call option.
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return Returns the value of a European call option under the Black-Scholes model
*/
public static double blackScholesDigitalOptionValue(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 1.0;
}
else
{
// Calculate analytic value
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);
return valueAnalytic;
}
}
/**
* Calculates the delta of a digital option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The delta of the digital option
*/
public static double blackScholesDigitalOptionDelta(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate delta
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);
return delta;
}
}
/**
* Calculates the delta of a call option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The delta of the option
*/
public static double blackScholesOptionDelta(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(initialStockValue < 0) {
return blackScholesOptionDelta(-initialStockValue, riskFreeRate, volatility, optionMaturity, -optionMaturity);
}
else if(initialStockValue == 0)
{
// Limit case (where dPlus = +/- infty)
if(optionStrike < 0) return 1.0; // dPlus = +infinity
else if(optionStrike > 0) return 0.0; // dPlus = -infinity
else return Double.NaN; // Undefined
}
else if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 1.0;
}
else
{
// Calculate delta
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double delta = NormalDistribution.cumulativeDistribution(dPlus);
return delta;
}
}
/**
* This static method calculated the gamma of a call option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The gamma of the option
*/
public static double blackScholesOptionGamma(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate gamma
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double gamma = Math.exp(-0.5*dPlus*dPlus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility);
return gamma;
}
}
/**
* This static method calculated the vega of a call option under a Black-Scholes model
*
* @param initialStockValue The initial value of the underlying, i.e., the spot.
* @param riskFreeRate The risk free rate of the bank account numerarie.
* @param volatility The Black-Scholes volatility.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike.
* @return The vega of the option
*/
public static double blackScholesOptionVega(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate vega
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double vega = Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) * initialStockValue * Math.sqrt(optionMaturity);
return vega;
}
}
/**
* Calculates the Black-Scholes option implied volatility of a call, i.e., the payoff
* <p><i>max(S(T)-K,0)</i></p>, where <i>S</i> follows a log-normal process with constant log-volatility.
*
* @param forward The forward of the underlying.
* @param optionMaturity The option maturity T.
* @param optionStrike The option strike. If the option strike is ≤ 0.0 the method returns the value of the forward contract paying S(T)-K in T.
* @param payoffUnit The payoff unit (e.g., the discount factor)
* @param optionValue The option value.
* @return Returns the implied volatility of a European call option under the Black-Scholes model.
*/
public static double blackScholesOptionImpliedVolatility(
double forward,
double optionMaturity,
double optionStrike,
double payoffUnit,
double optionValue)
{
// Limit the maximum number of iterations, to ensure this calculation returns fast, e.g. in cases when there is no such thing as an implied vol
// TODO: An exception should be thrown, when there is no implied volatility for the given value.
int maxIterations = 500;
double maxAccuracy = 1E-15;
if(optionStrike <= 0.0)
{
// Actually it is not an option
return 0.0;
}
else
{
// Calculate an lower and upper bound for the volatility
double p = NormalDistribution.inverseCumulativeDistribution((optionValue/payoffUnit+optionStrike)/(forward+optionStrike)) / Math.sqrt(optionMaturity);
double q = 2.0 * Math.abs(Math.log(forward/optionStrike)) / optionMaturity;
double volatilityLowerBound = p + Math.sqrt(Math.max(p * p - q, 0.0));
double volatilityUpperBound = p + Math.sqrt( p * p + q );
// If strike is close to forward the two bounds are close to the analytic solution
if(Math.abs(volatilityLowerBound - volatilityUpperBound) < maxAccuracy) return (volatilityLowerBound+volatilityUpperBound) / 2.0;
// Solve for implied volatility
NewtonsMethod solver = new NewtonsMethod(0.5*(volatilityLowerBound+volatilityUpperBound) /* guess */);
while(solver.getAccuracy() > maxAccuracy && !solver.isDone() && solver.getNumberOfIterations() < maxIterations) {
double volatility = solver.getNextPoint();
// Calculate analytic value
double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit;
double derivativeAnalytic = forward * Math.sqrt(optionMaturity) * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0*Math.PI) * payoffUnit;
double error = valueAnalytic - optionValue;
solver.setValueAndDerivative(error,derivativeAnalytic);
}
return solver.getBestPoint();
}
}
/**
* Calculate the value of a caplet assuming the Black'76 model.
*
* @param forward The forward (spot).
* @param volatility The Black'76 volatility.
* @param optionMaturity The option maturity
* @param optionStrike The option strike.
* @param periodLength The period length of the underlying forward rate.
* @param discountFactor The discount factor corresponding to the payment date (option maturity + period length).
* @return Returns the value of a caplet under the Black'76 model
*/
public static double blackModelCapletValue(
double forward,
double volatility,
double optionMaturity,
double optionStrike,
double periodLength,
double discountFactor)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor);
}
/**
* Calculate the value of a digital caplet assuming the Black'76 model.
*
* @param forward The forward (spot).
* @param volatility The Black'76 volatility.
* @param periodLength The period length of the underlying forward rate.
* @param discountFactor The discount factor corresponding to the payment date (option maturity + period length).
* @param optionMaturity The option maturity
* @param optionStrike The option strike.
* @return Returns the price of a digital caplet under the Black'76 model
*/
public static double blackModelDgitialCapletValue(
double forward,
double volatility,
double periodLength,
double discountFactor,
double optionMaturity,
double optionStrike)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor;
}
/**
* Calculate the value of a swaption assuming the Black'76 model.
*
* @param forwardSwaprate The forward (spot)
* @param volatility The Black'76 volatility.
* @param optionMaturity The option maturity.
* @param optionStrike The option strike.
* @param swapAnnuity The swap annuity corresponding to the underlying swap.
* @return Returns the value of a Swaption under the Black'76 model
*/
public static double blackModelSwaptionValue(
double forwardSwaprate,
double volatility,
double optionMaturity,
double optionStrike,
double swapAnnuity)
{
// May be interpreted as a special version of the Black-Scholes Formula
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
}
/**
* Calculate the value of a CMS option using the Black-Scholes model for the swap rate together with
* the Hunt-Kennedy convexity adjustment.
*
* @param forwardSwaprate The forward swap rate
* @param volatility Volatility of the log of the swap rate
* @param swapAnnuity The swap annuity
* @param optionMaturity The option maturity
* @param swapMaturity The swap maturity
* @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
* @param optionStrike The option strike
* @return Value of the CMS option
*/
public static double huntKennedyCMSOptionValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double valueUnadjusted = blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity);
double valueAdjusted = blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity);
return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted;
}
/**
* Calculate the value of a CMS strike using the Black-Scholes model for the swap rate together with
* the Hunt-Kennedy convexity adjustment.
*
* @param forwardSwaprate The forward swap rate
* @param volatility Volatility of the log of the swap rate
* @param swapAnnuity The swap annuity
* @param optionMaturity The option maturity
* @param swapMaturity The swap maturity
* @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
* @param optionStrike The option strike
* @return Value of the CMS strike
*/
public static double huntKennedyCMSFloorValue(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit,
double optionStrike)
{
double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);
// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)
return huntKennedyCMSOptionValue + optionStrike * payoffUnit;
}
/**
* Calculate the adjusted forward swaprate corresponding to a change of payoff unit from the given swapAnnuity to the given payoffUnit
* using the Black-Scholes model for the swap rate together with the Hunt-Kennedy convexity adjustment.
*
* @param forwardSwaprate The forward swap rate
* @param volatility Volatility of the log of the swap rate
* @param swapAnnuity The swap annuity
* @param optionMaturity The option maturity
* @param swapMaturity The swap maturity
* @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date
* @return Convexity adjusted forward rate
*/
public static double huntKennedyCMSAdjustedRate(
double forwardSwaprate,
double volatility,
double swapAnnuity,
double optionMaturity,
double swapMaturity,
double payoffUnit)
{
double a = 1.0/swapMaturity;
double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate;
double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity);
double rateUnadjusted = forwardSwaprate;
double rateAdjusted = forwardSwaprate * convexityAdjustment;
return (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit;
}
/**
* Re-implementation of the Excel PRICE function (a rather primitive bond price formula).
* The re-implementation is not exact, because this function does not consider daycount conventions.
*
* @param settlementDate Valuation date.
* @param maturityDate Maturity date of the bond.
* @param coupon Coupon payment.
* @param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency).
* @param redemption Redemption (notional repayment).
* @param frequency Frequency (1,2,4).
* @return price Clean price.
*/
public static double price(
java.util.Date settlementDate,
java.util.Date maturityDate,
double coupon,
double yield,
double redemption,
int frequency)
{
double price = 0.0;
if(maturityDate.after(settlementDate)) {
price += redemption;
}
Calendar paymentDate = Calendar.getInstance();
paymentDate.setTime(maturityDate);
while(paymentDate.after(settlementDate)) {
price += coupon;
// Disocunt back
price /= 1.0 + yield / frequency;
paymentDate.add(Calendar.MONTH, -12/frequency);
}
Calendar periodEndDate = (Calendar)paymentDate.clone();
periodEndDate.add(Calendar.MONTH, +12/frequency);
// Accrue running period
double accrualPeriod = (paymentDate.getTimeInMillis() - settlementDate.getTime()) / (periodEndDate.getTimeInMillis() - paymentDate.getTimeInMillis());
price *= Math.pow(1.0 + yield / frequency, accrualPeriod);
price -= coupon * accrualPeriod;
return price;
}
/**
* Re-implementation of the Excel PRICE function (a rather primitive bond price formula).
* The re-implementation is not exact, because this function does not consider daycount conventions.
* We assume we have (int)timeToMaturity/frequency future periods and the running period has
* an accrual period of timeToMaturity - frequency * ((int)timeToMaturity/frequency).
*
* @param timeToMaturity The time to maturity.
* @param coupon Coupon payment.
* @param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency).
* @param redemption Redemption (notional repayment).
* @param frequency Frequency (1,2,4).
* @return price Clean price.
*/
public static double price(
double timeToMaturity,
double coupon,
double yield,
double redemption,
int frequency)
{
double price = 0.0;
if(timeToMaturity > 0) {
price += redemption;
}
double paymentTime = timeToMaturity;
while(paymentTime > 0) {
price += coupon;
// Discount back
price = price / (1.0 + yield / frequency);
paymentTime -= 1.0 / frequency;
}
// Accrue running period
double accrualPeriod = 0.0- paymentTime;
price *= Math.pow(1.0 + yield / frequency, accrualPeriod);
price -= coupon * accrualPeriod;
return price;
}
}
|
package net.jforum.dao.oracle;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import net.jforum.JForumExecutionContext;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.generic.GenericSummaryDAO;
import net.jforum.entities.Post;
import net.jforum.exceptions.DatabaseException;
import net.jforum.util.DbUtils;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import org.apache.log4j.Logger;
/**
* @author Andowson Chang
* @version $Id$
*/
public class OracleSummaryDAO extends GenericSummaryDAO
{
private static final Logger LOGGER = Logger.getLogger(OracleSummaryDAO.class);
/**
* @see net.jforum.dao.SummaryDAO#selectLastPosts(Date, Date)
*/
public List<Post> selectLastPosts(Date firstDate, Date lastDate)
{
String query = SystemGlobals.getSql("SummaryDAO.selectPosts");
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = JForumExecutionContext.getConnection().prepareStatement(query);
pstmt.setTimestamp(1, new Timestamp(firstDate.getTime()));
pstmt.setTimestamp(2, new Timestamp(lastDate.getTime()));
List<Post> posts = new ArrayList<Post>();
rs = pstmt.executeQuery();
while (rs.next()) {
posts.add(this.fillPost(rs));
}
return posts;
}
catch (SQLException e) {
throw new DatabaseException(e);
}
finally {
DbUtils.close(rs, pstmt);
}
}
private Post fillPost(ResultSet rs) throws SQLException
{
Post post = new Post();
post.setId(rs.getInt("post_id"));
post.setTopicId(rs.getInt("topic_id"));
post.setForumId(rs.getInt("forum_id"));
post.setUserId(rs.getInt("user_id"));
Timestamp postTime = rs.getTimestamp("post_time");
post.setTime(postTime);
post.setSubject(rs.getString("post_subject"));
post.setText(OracleUtils.readBlobUTF16BinaryStream(rs, "post_text"));
post.setPostUsername(rs.getString("username"));
SimpleDateFormat df = new SimpleDateFormat(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT), Locale.getDefault());
post.setFormattedTime(df.format(postTime));
post.setKarma(DataAccessDriver.getInstance().newKarmaDAO().getPostKarma(post.getId()));
LOGGER.debug("Add to Weekly Summary: post.id="+ post.getId() +" post.subject="+ post.getSubject());
return post;
}
}
|
package net.sf.jabref.gui.groups;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CompoundEdit;
import net.sf.jabref.Globals;
import net.sf.jabref.gui.BasePanel;
import net.sf.jabref.gui.IconTheme;
import net.sf.jabref.gui.JabRefFrame;
import net.sf.jabref.gui.SidePaneComponent;
import net.sf.jabref.gui.SidePaneManager;
import net.sf.jabref.gui.help.HelpAction;
import net.sf.jabref.gui.keyboard.KeyBinding;
import net.sf.jabref.gui.maintable.MainTableDataModel;
import net.sf.jabref.gui.undo.NamedCompound;
import net.sf.jabref.gui.worker.AbstractWorker;
import net.sf.jabref.logic.help.HelpFile;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.FieldChange;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.groups.AbstractGroup;
import net.sf.jabref.model.groups.AllEntriesGroup;
import net.sf.jabref.model.groups.ExplicitGroup;
import net.sf.jabref.model.groups.GroupTreeNode;
import net.sf.jabref.model.groups.event.GroupUpdatedEvent;
import net.sf.jabref.model.metadata.MetaData;
import net.sf.jabref.model.search.SearchMatcher;
import net.sf.jabref.model.search.matchers.MatcherSet;
import net.sf.jabref.model.search.matchers.MatcherSets;
import net.sf.jabref.model.search.matchers.NotMatcher;
import net.sf.jabref.preferences.JabRefPreferences;
import com.google.common.eventbus.Subscribe;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* The whole UI component holding the groups tree and the buttons
*/
public class GroupSelector extends SidePaneComponent implements TreeSelectionListener {
private static final Log LOGGER = LogFactory.getLog(GroupSelector.class);
private final GroupsTree groupsTree;
private DefaultTreeModel groupsTreeModel;
private GroupTreeNodeViewModel groupsRoot;
protected final JabRefFrame frame;
private final JPopupMenu groupsContextMenu = new JPopupMenu();
private final JPopupMenu settings = new JPopupMenu();
private final JRadioButtonMenuItem hideNonHits;
private final JRadioButtonMenuItem grayOut;
private final JRadioButtonMenuItem andCb = new JRadioButtonMenuItem(Localization.lang("Intersection"), true);
private final JRadioButtonMenuItem floatCb = new JRadioButtonMenuItem(Localization.lang("Float"), true);
private final JCheckBoxMenuItem invCb = new JCheckBoxMenuItem(Localization.lang("Inverted"), false);
private final JCheckBoxMenuItem showOverlappingGroups = new JCheckBoxMenuItem(
Localization.lang("Highlight overlapping groups"));
private final JCheckBoxMenuItem showNumberOfElements = new JCheckBoxMenuItem(
Localization.lang("Show number of elements contained in each group"));
private final JCheckBoxMenuItem autoAssignGroup = new JCheckBoxMenuItem(
Localization.lang("Automatically assign new entry to selected groups"));
private final JCheckBoxMenuItem editModeCb = new JCheckBoxMenuItem(Localization.lang("Edit group membership"),
false);
private boolean editModeIndicator;
private static final String MOVE_ONE_GROUP = Localization.lang("Please select exactly one group to move.");
private final JMenu moveSubmenu = new JMenu(Localization.lang("Move"));
private final JMenu sortSubmenu = new JMenu(Localization.lang("Sort alphabetically"));
private final AbstractAction editGroupAction = new EditGroupAction();
private final NodeAction editGroupPopupAction = new EditGroupAction();
private final NodeAction addGroupPopupAction = new AddGroupAction();
private final NodeAction addSubgroupPopupAction = new AddSubgroupAction();
private final NodeAction removeGroupAndSubgroupsPopupAction = new RemoveGroupAndSubgroupsAction();
private final NodeAction removeSubgroupsPopupAction = new RemoveSubgroupsAction();
private final NodeAction removeGroupKeepSubgroupsPopupAction = new RemoveGroupKeepSubgroupsAction();
private final NodeAction moveNodeUpPopupAction = new MoveNodeUpAction();
private final NodeAction moveNodeDownPopupAction = new MoveNodeDownAction();
private final NodeAction moveNodeLeftPopupAction = new MoveNodeLeftAction();
private final NodeAction moveNodeRightPopupAction = new MoveNodeRightAction();
private final NodeAction expandSubtreePopupAction = new ExpandSubtreeAction();
private final NodeAction collapseSubtreePopupAction = new CollapseSubtreeAction();
private final NodeAction sortDirectSubgroupsPopupAction = new SortDirectSubgroupsAction();
private final NodeAction sortAllSubgroupsPopupAction = new SortAllSubgroupsAction();
private final AddToGroupAction addToGroup = new AddToGroupAction(false);
private final AddToGroupAction moveToGroup = new AddToGroupAction(true);
private final RemoveFromGroupAction removeFromGroup = new RemoveFromGroupAction();
private final ToggleAction toggleAction;
/**
* The first element for each group defines which field to use for the quicksearch. The next two define the name and
* regexp for the group.
*/
public GroupSelector(JabRefFrame frame, SidePaneManager manager) {
super(manager, IconTheme.JabRefIcon.TOGGLE_GROUPS.getIcon(), Localization.lang("Groups"));
toggleAction = new ToggleAction(Localization.menuTitle("Toggle groups interface"),
Localization.lang("Toggle groups interface"),
Globals.getKeyPrefs().getKey(KeyBinding.TOGGLE_GROUPS_INTERFACE),
IconTheme.JabRefIcon.TOGGLE_GROUPS);
this.frame = frame;
hideNonHits = new JRadioButtonMenuItem(Localization.lang("Hide non-hits"),
!Globals.prefs.getBoolean(JabRefPreferences.GRAY_OUT_NON_HITS));
grayOut = new JRadioButtonMenuItem(Localization.lang("Gray out non-hits"),
Globals.prefs.getBoolean(JabRefPreferences.GRAY_OUT_NON_HITS));
ButtonGroup nonHits = new ButtonGroup();
nonHits.add(hideNonHits);
nonHits.add(grayOut);
floatCb.addChangeListener(event -> Globals.prefs.putBoolean(JabRefPreferences.GROUP_FLOAT_SELECTIONS, floatCb.isSelected()));
andCb.addChangeListener(event -> Globals.prefs.putBoolean(JabRefPreferences.GROUP_INTERSECT_SELECTIONS, andCb.isSelected()));
invCb.addChangeListener(event -> Globals.prefs.putBoolean(JabRefPreferences.GROUP_INVERT_SELECTIONS, invCb.isSelected()));
showOverlappingGroups.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
Globals.prefs.putBoolean(JabRefPreferences.GROUP_SHOW_OVERLAPPING, showOverlappingGroups.isSelected());
if (!showOverlappingGroups.isSelected()) {
groupsTree.setOverlappingGroups(Collections.emptyList());
}
}
});
grayOut.addChangeListener(event -> Globals.prefs.putBoolean(JabRefPreferences.GRAY_OUT_NON_HITS, grayOut.isSelected()));
JRadioButtonMenuItem highlCb = new JRadioButtonMenuItem(Localization.lang("Highlight"), false);
if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_FLOAT_SELECTIONS)) {
floatCb.setSelected(true);
highlCb.setSelected(false);
} else {
highlCb.setSelected(true);
floatCb.setSelected(false);
}
JRadioButtonMenuItem orCb = new JRadioButtonMenuItem(Localization.lang("Union"), false);
if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_INTERSECT_SELECTIONS)) {
andCb.setSelected(true);
orCb.setSelected(false);
} else {
orCb.setSelected(true);
andCb.setSelected(false);
}
showNumberOfElements.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
Globals.prefs.putBoolean(JabRefPreferences.GROUP_SHOW_NUMBER_OF_ELEMENTS,
showNumberOfElements.isSelected());
if (groupsTree != null) {
groupsTree.invalidate();
groupsTree.repaint();
}
}
});
autoAssignGroup.addChangeListener(event -> Globals.prefs.putBoolean(JabRefPreferences.AUTO_ASSIGN_GROUP, autoAssignGroup.isSelected()));
invCb.setSelected(Globals.prefs.getBoolean(JabRefPreferences.GROUP_INVERT_SELECTIONS));
showOverlappingGroups.setSelected(Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_OVERLAPPING));
editModeIndicator = Globals.prefs.getBoolean(JabRefPreferences.EDIT_GROUP_MEMBERSHIP_MODE);
editModeCb.setSelected(editModeIndicator);
showNumberOfElements.setSelected(Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_NUMBER_OF_ELEMENTS));
autoAssignGroup.setSelected(Globals.prefs.getBoolean(JabRefPreferences.AUTO_ASSIGN_GROUP));
JButton openSettings = new JButton(IconTheme.JabRefIcon.PREFERENCES.getSmallIcon());
settings.add(andCb);
settings.add(orCb);
settings.addSeparator();
settings.add(invCb);
settings.addSeparator();
settings.add(editModeCb);
settings.addSeparator();
settings.add(grayOut);
settings.add(hideNonHits);
settings.addSeparator();
settings.add(showOverlappingGroups);
settings.addSeparator();
settings.add(showNumberOfElements);
settings.add(autoAssignGroup);
openSettings.addActionListener(e -> {
if (!settings.isVisible()) {
JButton src = (JButton) e.getSource();
showNumberOfElements
.setSelected(Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_NUMBER_OF_ELEMENTS));
autoAssignGroup.setSelected(Globals.prefs.getBoolean(JabRefPreferences.AUTO_ASSIGN_GROUP));
settings.show(src, 0, openSettings.getHeight());
}
});
editModeCb.addActionListener(e -> setEditMode(editModeCb.getState()));
JButton newButton = new JButton(IconTheme.JabRefIcon.ADD_NOBOX.getSmallIcon());
int butSize = newButton.getIcon().getIconHeight() + 5;
Dimension butDim = new Dimension(butSize, butSize);
newButton.setPreferredSize(butDim);
newButton.setMinimumSize(butDim);
JButton helpButton = new HelpAction(Localization.lang("Help on groups"), HelpFile.GROUP)
.getHelpButton();
helpButton.setPreferredSize(butDim);
helpButton.setMinimumSize(butDim);
JButton autoGroup = new JButton(IconTheme.JabRefIcon.AUTO_GROUP.getSmallIcon());
autoGroup.setPreferredSize(butDim);
autoGroup.setMinimumSize(butDim);
openSettings.setPreferredSize(butDim);
openSettings.setMinimumSize(butDim);
Insets butIns = new Insets(0, 0, 0, 0);
helpButton.setMargin(butIns);
openSettings.setMargin(butIns);
newButton.addActionListener(e -> {
GroupDialog gd = new GroupDialog(frame, null);
gd.setVisible(true);
if (gd.okPressed()) {
AbstractGroup newGroup = gd.getResultingGroup();
groupsRoot.addNewGroup(newGroup, panel.getUndoManager());
panel.markBaseChanged();
frame.output(Localization.lang("Created group \"%0\".", newGroup.getName()));
}
});
andCb.addActionListener(e -> valueChanged(null));
orCb.addActionListener(e -> valueChanged(null));
invCb.addActionListener(e -> valueChanged(null));
showOverlappingGroups.addActionListener(e -> valueChanged(null));
autoGroup.addActionListener(e -> {
AutoGroupDialog gd = new AutoGroupDialog(frame, panel, groupsRoot,
Globals.prefs.get(JabRefPreferences.GROUPS_DEFAULT_FIELD), " .,",
Globals.prefs.get(JabRefPreferences.KEYWORD_SEPARATOR));
gd.setVisible(true);
// gd does the operation itself
});
floatCb.addActionListener(e -> valueChanged(null));
highlCb.addActionListener(e -> valueChanged(null));
hideNonHits.addActionListener(e -> valueChanged(null));
grayOut.addActionListener(e -> valueChanged(null));
newButton.setToolTipText(Localization.lang("New group"));
andCb.setToolTipText(Localization.lang("Display only entries belonging to all selected groups."));
orCb.setToolTipText(Localization.lang("Display all entries belonging to one or more of the selected groups."));
autoGroup.setToolTipText(Localization.lang("Automatically create groups for database."));
openSettings.setToolTipText(Localization.lang("Settings"));
invCb.setToolTipText("<html>" + Localization.lang("Show entries <b>not</b> in group selection") + "</html>");
showOverlappingGroups.setToolTipText(
Localization.lang("Highlight groups that contain entries contained in any currently selected group"));
floatCb.setToolTipText(Localization.lang("Move entries in group selection to the top"));
highlCb.setToolTipText(Localization.lang("Gray out entries not in group selection"));
editModeCb.setToolTipText(Localization.lang("Click group to toggle membership of selected entries"));
ButtonGroup bgr = new ButtonGroup();
bgr.add(andCb);
bgr.add(orCb);
ButtonGroup visMode = new ButtonGroup();
visMode.add(floatCb);
visMode.add(highlCb);
JPanel rootPanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
rootPanel.setLayout(gbl);
GridBagConstraints con = new GridBagConstraints();
con.fill = GridBagConstraints.BOTH;
con.weightx = 1;
con.gridwidth = 1;
con.gridy = 0;
con.gridx = 0;
gbl.setConstraints(newButton, con);
rootPanel.add(newButton);
con.gridx = 1;
gbl.setConstraints(autoGroup, con);
rootPanel.add(autoGroup);
con.gridx = 2;
gbl.setConstraints(openSettings, con);
rootPanel.add(openSettings);
con.gridx = 3;
con.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(helpButton, con);
rootPanel.add(helpButton);
groupsTree = new GroupsTree(this);
groupsTree.addTreeSelectionListener(this);
JScrollPane groupsTreePane = new JScrollPane(groupsTree, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
groupsTreePane.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
con.gridwidth = GridBagConstraints.REMAINDER;
con.weighty = 1;
con.gridx = 0;
con.gridwidth = 4;
con.gridy = 1;
gbl.setConstraints(groupsTreePane, con);
rootPanel.add(groupsTreePane);
add(rootPanel, BorderLayout.CENTER);
setEditMode(editModeIndicator);
definePopup();
NodeAction moveNodeUpAction = new MoveNodeUpAction();
moveNodeUpAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.CTRL_MASK));
NodeAction moveNodeDownAction = new MoveNodeDownAction();
moveNodeDownAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.CTRL_MASK));
NodeAction moveNodeLeftAction = new MoveNodeLeftAction();
moveNodeLeftAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.CTRL_MASK));
NodeAction moveNodeRightAction = new MoveNodeRightAction();
moveNodeRightAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK));
setGroups(GroupTreeNode.fromGroup(new AllEntriesGroup(Localization.lang("All entries"))));
}
private void definePopup() {
// These key bindings are just to have the shortcuts displayed
// in the popup menu. The actual keystroke processing is in
// BasePanel (entryTable.addKeyListener(...)).
groupsContextMenu.add(editGroupPopupAction);
groupsContextMenu.add(addGroupPopupAction);
groupsContextMenu.add(addSubgroupPopupAction);
groupsContextMenu.addSeparator();
groupsContextMenu.add(removeGroupAndSubgroupsPopupAction);
groupsContextMenu.add(removeGroupKeepSubgroupsPopupAction);
groupsContextMenu.add(removeSubgroupsPopupAction);
groupsContextMenu.addSeparator();
groupsContextMenu.add(expandSubtreePopupAction);
groupsContextMenu.add(collapseSubtreePopupAction);
groupsContextMenu.addSeparator();
groupsContextMenu.add(moveSubmenu);
sortSubmenu.add(sortDirectSubgroupsPopupAction);
sortSubmenu.add(sortAllSubgroupsPopupAction);
groupsContextMenu.add(sortSubmenu);
moveSubmenu.add(moveNodeUpPopupAction);
moveSubmenu.add(moveNodeDownPopupAction);
moveSubmenu.add(moveNodeLeftPopupAction);
moveSubmenu.add(moveNodeRightPopupAction);
groupsContextMenu.addSeparator();
groupsContextMenu.add(addToGroup);
groupsContextMenu.add(moveToGroup);
groupsContextMenu.add(removeFromGroup);
groupsTree.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopup(e);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopup(e);
}
}
@Override
public void mouseClicked(MouseEvent e) {
TreePath path = groupsTree.getPathForLocation(e.getPoint().x, e.getPoint().y);
if (path == null) {
return;
}
GroupTreeNodeViewModel node = (GroupTreeNodeViewModel) path.getLastPathComponent();
// the root node is "AllEntries" and cannot be edited
if (node.getNode().isRoot()) {
return;
}
if ((e.getClickCount() == 2) && (e.getButton() == MouseEvent.BUTTON1)) { // edit
editGroupAction.actionPerformed(null); // dummy event
} else if ((e.getClickCount() == 1) && (e.getButton() == MouseEvent.BUTTON1)) {
annotationEvent(node);
}
}
});
// be sure to remove a possible border highlight when the popup menu
// disappears
groupsContextMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// nothing to do
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
groupsTree.setHighlightBorderCell(null);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
groupsTree.setHighlightBorderCell(null);
}
});
}
private void showPopup(MouseEvent e) {
final TreePath path = groupsTree.getPathForLocation(e.getPoint().x, e.getPoint().y);
addGroupPopupAction.setEnabled(true);
addSubgroupPopupAction.setEnabled(path != null);
editGroupPopupAction.setEnabled(path != null);
removeGroupAndSubgroupsPopupAction.setEnabled(path != null);
removeGroupKeepSubgroupsPopupAction.setEnabled(path != null);
moveSubmenu.setEnabled(path != null);
expandSubtreePopupAction.setEnabled(path != null);
collapseSubtreePopupAction.setEnabled(path != null);
removeSubgroupsPopupAction.setEnabled(path != null);
sortSubmenu.setEnabled(path != null);
addToGroup.setEnabled(false);
moveToGroup.setEnabled(false);
removeFromGroup.setEnabled(false);
if (path != null) { // some path dependent enabling/disabling
GroupTreeNodeViewModel node = (GroupTreeNodeViewModel) path.getLastPathComponent();
editGroupPopupAction.setNode(node);
addSubgroupPopupAction.setNode(node);
removeGroupAndSubgroupsPopupAction.setNode(node);
removeSubgroupsPopupAction.setNode(node);
removeGroupKeepSubgroupsPopupAction.setNode(node);
expandSubtreePopupAction.setNode(node);
collapseSubtreePopupAction.setNode(node);
sortDirectSubgroupsPopupAction.setNode(node);
sortAllSubgroupsPopupAction.setNode(node);
groupsTree.setHighlightBorderCell(node);
if (node.canBeEdited()) {
editGroupPopupAction.setEnabled(false);
addGroupPopupAction.setEnabled(false);
removeGroupAndSubgroupsPopupAction.setEnabled(false);
removeGroupKeepSubgroupsPopupAction.setEnabled(false);
} else {
editGroupPopupAction.setEnabled(true);
addGroupPopupAction.setEnabled(true);
addGroupPopupAction.setNode(node);
removeGroupAndSubgroupsPopupAction.setEnabled(true);
removeGroupKeepSubgroupsPopupAction.setEnabled(true);
}
expandSubtreePopupAction
.setEnabled(groupsTree.isCollapsed(path) || groupsTree.hasCollapsedDescendant(path));
collapseSubtreePopupAction
.setEnabled(groupsTree.isExpanded(path) || groupsTree.hasExpandedDescendant(path));
sortSubmenu.setEnabled(!node.isLeaf());
removeSubgroupsPopupAction.setEnabled(!node.isLeaf());
moveNodeUpPopupAction.setEnabled(node.canMoveUp());
moveNodeDownPopupAction.setEnabled(node.canMoveDown());
moveNodeLeftPopupAction.setEnabled(node.canMoveLeft());
moveNodeRightPopupAction.setEnabled(node.canMoveRight());
moveSubmenu.setEnabled(moveNodeUpPopupAction.isEnabled() || moveNodeDownPopupAction.isEnabled()
|| moveNodeLeftPopupAction.isEnabled() || moveNodeRightPopupAction.isEnabled());
moveNodeUpPopupAction.setNode(node);
moveNodeDownPopupAction.setNode(node);
moveNodeLeftPopupAction.setNode(node);
moveNodeRightPopupAction.setNode(node);
// add/remove entries to/from group
List<BibEntry> selection = frame.getCurrentBasePanel().getSelectedEntries();
if (!selection.isEmpty()) {
if (node.canAddEntries(selection)) {
addToGroup.setNode(node);
addToGroup.setBasePanel(panel);
addToGroup.setEnabled(true);
moveToGroup.setNode(node);
moveToGroup.setBasePanel(panel);
moveToGroup.setEnabled(true);
}
if (node.canRemoveEntries(selection)) {
removeFromGroup.setNode(node);
removeFromGroup.setBasePanel(panel);
removeFromGroup.setEnabled(true);
}
}
} else {
editGroupPopupAction.setNode(null);
addGroupPopupAction.setNode(null);
addSubgroupPopupAction.setNode(null);
removeGroupAndSubgroupsPopupAction.setNode(null);
removeSubgroupsPopupAction.setNode(null);
removeGroupKeepSubgroupsPopupAction.setNode(null);
moveNodeUpPopupAction.setNode(null);
moveNodeDownPopupAction.setNode(null);
moveNodeLeftPopupAction.setNode(null);
moveNodeRightPopupAction.setNode(null);
expandSubtreePopupAction.setNode(null);
collapseSubtreePopupAction.setNode(null);
sortDirectSubgroupsPopupAction.setNode(null);
sortAllSubgroupsPopupAction.setNode(null);
}
groupsContextMenu.show(groupsTree, e.getPoint().x, e.getPoint().y);
}
private void setEditMode(boolean editMode) {
Globals.prefs.putBoolean(JabRefPreferences.EDIT_GROUP_MEMBERSHIP_MODE, editModeIndicator);
editModeIndicator = editMode;
if (editMode) {
groupsTree.setBorder(BorderFactory
.createTitledBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.RED), "Edit mode",
TitledBorder.RIGHT, TitledBorder.TOP, Font.getFont("Default"), Color.RED));
this.setTitle("<html><font color='red'>Groups Edit mode</font></html>");
} else {
groupsTree.setBorder(BorderFactory.createEmptyBorder(5,10,0,0));
this.setTitle(Localization.lang("Groups"));
}
groupsTree.revalidate();
groupsTree.repaint();
}
private void annotationEvent(GroupTreeNodeViewModel node) {
if (editModeIndicator) {
LOGGER.info("Performing annotation " + node.getName());
List<BibEntry> entries = panel.getSelectedEntries();
node.changeEntriesTo(entries, panel.getUndoManager());
panel.markBaseChanged();
panel.updateEntryEditorIfShowing();
updateShownEntriesAccordingToSelectedGroups();
}
}
@Override
public void valueChanged(TreeSelectionEvent e) {
if (panel == null) {
return; // ignore this event (happens for example if the file was closed)
}
if (getLeafsOfSelection().stream().allMatch(GroupTreeNodeViewModel::isAllEntriesGroup)) {
panel.getMainTable().getTableModel().updateGroupingState(MainTableDataModel.DisplayOption.DISABLED);
if (showOverlappingGroups.isSelected()) {
groupsTree.setOverlappingGroups(Collections.emptyList());
}
frame.output(Localization.lang("Displaying no groups") + ".");
return;
}
if (!editModeIndicator) {
updateShownEntriesAccordingToSelectedGroups();
}
}
private void updateShownEntriesAccordingToSelectedGroups() {
final MatcherSet searchRules = MatcherSets
.build(andCb.isSelected() ? MatcherSets.MatcherType.AND : MatcherSets.MatcherType.OR);
for(GroupTreeNodeViewModel node : getLeafsOfSelection()) {
SearchMatcher searchRule = node.getNode().getSearchMatcher();
searchRules.addRule(searchRule);
}
SearchMatcher searchRule = invCb.isSelected() ? new NotMatcher(searchRules) : searchRules;
GroupingWorker worker = new GroupingWorker(searchRule);
worker.getWorker().run();
worker.getCallBack().update();
}
private List<GroupTreeNodeViewModel> getLeafsOfSelection() {
TreePath[] selection = groupsTree.getSelectionPaths();
if((selection == null) || (selection.length == 0)) {
return new ArrayList<>();
}
List<GroupTreeNodeViewModel> selectedLeafs = new ArrayList<>(selection.length);
for (TreePath path : selection) {
selectedLeafs.add((GroupTreeNodeViewModel) path.getLastPathComponent());
}
return selectedLeafs;
}
private GroupTreeNodeViewModel getFirstSelectedNode() {
TreePath path = groupsTree.getSelectionPath();
if (path != null) {
return (GroupTreeNodeViewModel) path.getLastPathComponent();
}
return null;
}
class GroupingWorker extends AbstractWorker {
private final SearchMatcher matcher;
private final List<BibEntry> matches = new ArrayList<>();
private final boolean showOverlappingGroupsP;
public GroupingWorker(SearchMatcher matcher) {
this.matcher = matcher;
showOverlappingGroupsP = showOverlappingGroups.isSelected();
}
@Override
public void run() {
for (BibEntry entry : panel.getDatabase().getEntries()) {
boolean hit = matcher.isMatch(entry);
entry.setGroupHit(hit);
if (hit && showOverlappingGroupsP) {
matches.add(entry);
}
}
}
@Override
public void update() {
// Show the result in the chosen way:
if (hideNonHits.isSelected()) {
panel.getMainTable().getTableModel().updateGroupingState(MainTableDataModel.DisplayOption.FILTER);
} else if (grayOut.isSelected()) {
panel.getMainTable().getTableModel().updateGroupingState(MainTableDataModel.DisplayOption.FLOAT);
}
panel.getMainTable().getTableModel().updateSortOrder();
panel.getMainTable().getTableModel().updateGroupFilter();
panel.getMainTable().scrollTo(0);
if (showOverlappingGroupsP) {
showOverlappingGroups(matches);
}
frame.output(Localization.lang("Updated group selection") + ".");
}
}
/**
* Revalidate the groups tree (e.g. after the data stored in the model has been changed) and maintain the current
* selection and expansion state.
*/
public void revalidateGroups() {
if (SwingUtilities.isEventDispatchThread()) {
revalidateGroups(null);
} else {
SwingUtilities.invokeLater(() -> revalidateGroups(null));
}
}
/**
* Revalidate the groups tree (e.g. after the data stored in the model has been changed) and maintain the current
* selection and expansion state.
*
* @param node If this is non-null, the view is scrolled to make it visible.
*/
private void revalidateGroups(GroupTreeNodeViewModel node) {
revalidateGroups(groupsTree.getSelectionPaths(), getExpandedPaths(), node);
}
/**
* Revalidate the groups tree (e.g. after the data stored in the model has been changed) and set the specified
* selection and expansion state.
*/
public void revalidateGroups(TreePath[] selectionPaths, Enumeration<TreePath> expandedNodes) {
revalidateGroups(selectionPaths, expandedNodes, null);
}
/**
* Revalidate the groups tree (e.g. after the data stored in the model has been changed) and set the specified
* selection and expansion state.
*
* @param node If this is non-null, the view is scrolled to make it visible.
*/
private void revalidateGroups(TreePath[] selectionPaths, Enumeration<TreePath> expandedNodes,
GroupTreeNodeViewModel node) {
groupsTree.clearSelection();
if (selectionPaths != null) {
groupsTree.setSelectionPaths(selectionPaths);
}
// tree is completely collapsed here
if (expandedNodes != null) {
while (expandedNodes.hasMoreElements()) {
groupsTree.expandPath(expandedNodes.nextElement());
}
}
groupsTree.revalidate();
if (node != null) {
groupsTree.scrollPathToVisible(node.getTreePath());
}
}
@Override
public void componentOpening() {
valueChanged(null);
Globals.prefs.putBoolean(JabRefPreferences.GROUP_SIDEPANE_VISIBLE, Boolean.TRUE);
}
@Override
public int getRescalingWeight() {
return 1;
}
@Override
public void componentClosing() {
if (panel != null) {// panel may be null if no file is open any more
panel.getMainTable().getTableModel().updateGroupingState(MainTableDataModel.DisplayOption.DISABLED);
}
getToggleAction().setSelected(false);
Globals.prefs.putBoolean(JabRefPreferences.GROUP_SIDEPANE_VISIBLE, Boolean.FALSE);
}
private void setGroups(GroupTreeNode groupsRoot) {
this.groupsRoot = new GroupTreeNodeViewModel(groupsRoot);
groupsTreeModel = new DefaultTreeModel(this.groupsRoot);
this.groupsRoot.subscribeToDescendantChanged(groupsTreeModel::nodeStructureChanged);
groupsTree.setModel(groupsTreeModel);
if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_EXPAND_TREE)) {
this.groupsRoot.expandSubtree(groupsTree);
}
}
/**
* Adds the specified node as a child of the current root. The group contained in <b>newGroups </b> must not be of
* type AllEntriesGroup, since every tree has exactly one AllEntriesGroup (its root). The <b>newGroups </b> are
* inserted directly, i.e. they are not deepCopy()'d.
*/
public void addGroups(GroupTreeNode newGroups, CompoundEdit ce) {
// TODO: This shouldn't be a method of GroupSelector
// paranoia: ensure that there are never two instances of AllEntriesGroup
if (newGroups.getGroup() instanceof AllEntriesGroup) {
return; // this should be impossible anyway
}
newGroups.moveTo(groupsRoot.getNode());
UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot,
new GroupTreeNodeViewModel(newGroups), UndoableAddOrRemoveGroup.ADD_NODE);
ce.addEdit(undo);
}
private abstract class NodeAction extends AbstractAction {
private GroupTreeNodeViewModel node;
public NodeAction(String s) {
super(s);
}
public void setNode(GroupTreeNodeViewModel node) {
this.node = node;
}
/**
* Returns the node to use in this action. If a node has been set explicitly (via setNode), it is returned.
* Otherwise, the first node in the current selection is returned. If all this fails, null is returned.
*/
public GroupTreeNodeViewModel getNodeToUse() {
if (node != null) {
return node;
}
return getFirstSelectedNode();
}
}
private class EditGroupAction extends NodeAction {
public EditGroupAction() {
super(Localization.lang("Edit group"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupTreeNodeViewModel node = getNodeToUse();
final AbstractGroup oldGroup = node.getNode().getGroup();
final GroupDialog gd = new GroupDialog(frame, oldGroup);
gd.setVisible(true);
if (gd.okPressed()) {
AbstractGroup newGroup = gd.getResultingGroup();
int i = JOptionPane.showConfirmDialog(panel.frame(),
Localization.lang("Assign the original group's entries to this group?"),
Localization.lang("Change of Grouping Method"),
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
boolean keepPreviousAssignments = (i == JOptionPane.YES_OPTION) &&
WarnAssignmentSideEffects.warnAssignmentSideEffects(newGroup, panel.frame());
boolean removePreviousAssignents = (oldGroup instanceof ExplicitGroup) && (newGroup instanceof ExplicitGroup);
AbstractUndoableEdit undoAddPreviousEntries = null;
UndoableModifyGroup undo = new UndoableModifyGroup(GroupSelector.this, groupsRoot, node, newGroup);
List<FieldChange> addChange = node.getNode().setGroup(newGroup, keepPreviousAssignments,
removePreviousAssignents, panel.getDatabase().getEntries());
if (!addChange.isEmpty()) {
undoAddPreviousEntries = UndoableChangeEntriesOfGroup.getUndoableEdit(null, addChange);
}
groupsTreeModel.reload();
revalidateGroups(node);
// Store undo information.
if (undoAddPreviousEntries == null) {
panel.getUndoManager().addEdit(undo);
} else {
NamedCompound nc = new NamedCompound("Modify Group");
nc.addEdit(undo);
nc.addEdit(undoAddPreviousEntries);
nc.end();
panel.getUndoManager().addEdit(nc);
}
panel.markBaseChanged();
frame.output(Localization.lang("Modified group \"%0\".", newGroup.getName()));
}
}
}
private class AddGroupAction extends NodeAction {
public AddGroupAction() {
super(Localization.lang("Add group"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupDialog gd = new GroupDialog(frame, null);
gd.setVisible(true);
if (!gd.okPressed()) {
return; // ignore
}
final AbstractGroup newGroup = gd.getResultingGroup();
final GroupTreeNode newNode = GroupTreeNode.fromGroup(newGroup);
final GroupTreeNodeViewModel node = getNodeToUse();
if (node == null) {
groupsRoot.getNode().addChild(newNode);
} else {
((GroupTreeNodeViewModel)node.getParent()).getNode().addChild(newNode, node.getNode().getPositionInParent() + 1);
}
UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot,
new GroupTreeNodeViewModel(newNode), UndoableAddOrRemoveGroup.ADD_NODE);
groupsTree.expandPath((node == null ? groupsRoot : node).getTreePath());
// Store undo information.
panel.getUndoManager().addEdit(undo);
panel.markBaseChanged();
frame.output(Localization.lang("Added group \"%0\".", newGroup.getName()));
}
}
private class AddSubgroupAction extends NodeAction {
public AddSubgroupAction() {
super(Localization.lang("Add subgroup"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupDialog gd = new GroupDialog(frame, null);
gd.setVisible(true);
if (!gd.okPressed()) {
return; // ignore
}
final AbstractGroup newGroup = gd.getResultingGroup();
final GroupTreeNode newNode = GroupTreeNode.fromGroup(newGroup);
final GroupTreeNodeViewModel node = getNodeToUse();
node.getNode().addChild(newNode);
UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot,
new GroupTreeNodeViewModel(newNode), UndoableAddOrRemoveGroup.ADD_NODE);
groupsTree.expandPath(node.getTreePath());
// Store undo information.
panel.getUndoManager().addEdit(undo);
panel.markBaseChanged();
frame.output(Localization.lang("Added group \"%0\".", newGroup.getName()));
}
}
private class RemoveGroupAndSubgroupsAction extends NodeAction {
public RemoveGroupAndSubgroupsAction() {
super(Localization.lang("Remove group and subgroups"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupTreeNodeViewModel node = getNodeToUse();
final AbstractGroup group = node.getNode().getGroup();
int conf = JOptionPane.showConfirmDialog(frame,
Localization.lang("Remove group \"%0\" and its subgroups?", group.getName()),
Localization.lang("Remove group and subgroups"), JOptionPane.YES_NO_OPTION);
if (conf == JOptionPane.YES_OPTION) {
final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node,
UndoableAddOrRemoveGroup.REMOVE_NODE_AND_CHILDREN);
node.getNode().removeFromParent();
// Store undo information.
panel.getUndoManager().addEdit(undo);
panel.markBaseChanged();
frame.output(Localization.lang("Removed group \"%0\" and its subgroups.", group.getName()));
}
}
}
private class RemoveSubgroupsAction extends NodeAction {
public RemoveSubgroupsAction() {
super(Localization.lang("Remove subgroups"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupTreeNodeViewModel node = getNodeToUse();
int conf = JOptionPane.showConfirmDialog(frame,
Localization.lang("Remove all subgroups of \"%0\"?", node.getName()),
Localization.lang("Remove subgroups"), JOptionPane.YES_NO_OPTION);
if (conf == JOptionPane.YES_OPTION) {
final UndoableModifySubtree undo = new UndoableModifySubtree(getGroupTreeRoot(),
node, "Remove subgroups");
node.getNode().removeAllChildren();
//revalidateGroups();
// Store undo information.
panel.getUndoManager().addEdit(undo);
panel.markBaseChanged();
frame.output(Localization.lang("Removed all subgroups of group \"%0\".", node.getName()));
}
}
}
private class RemoveGroupKeepSubgroupsAction extends NodeAction {
public RemoveGroupKeepSubgroupsAction() {
super(Localization.lang("Remove group, keep subgroups"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupTreeNodeViewModel node = getNodeToUse();
final AbstractGroup group = node.getNode().getGroup();
int conf = JOptionPane.showConfirmDialog(frame, Localization.lang("Remove group \"%0\"?", group.getName()),
Localization.lang("Remove group"), JOptionPane.YES_NO_OPTION);
if (conf == JOptionPane.YES_OPTION) {
final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node,
UndoableAddOrRemoveGroup.REMOVE_NODE_KEEP_CHILDREN);
final GroupTreeNodeViewModel parent = (GroupTreeNodeViewModel)node.getParent();
node.getNode().removeFromParent();
node.getNode().moveAllChildrenTo(parent.getNode(), parent.getIndex(node));
// Store undo information.
panel.getUndoManager().addEdit(undo);
panel.markBaseChanged();
frame.output(Localization.lang("Removed group \"%0\".", group.getName()));
}
}
}
public TreePath getSelectionPath() {
return groupsTree.getSelectionPath();
}
private class SortDirectSubgroupsAction extends NodeAction {
public SortDirectSubgroupsAction() {
super(Localization.lang("Immediate subgroups"));
}
@Override
public void actionPerformed(ActionEvent ae) {
final GroupTreeNodeViewModel node = getNodeToUse();
final UndoableModifySubtree undo = new UndoableModifySubtree(getGroupTreeRoot(), node,
Localization.lang("sort subgroups"));
groupsTree.sort(node, false);
panel.getUndoManager().addEdit(undo);
panel.markBaseChanged();
frame.output(Localization.lang("Sorted immediate subgroups."));
}
}
private class SortAllSubgroupsAction extends NodeAction {
public SortAllSubgroupsAction() {
super(Localization.lang("All subgroups (recursively)"));
}
@Override
public void actionPerformed(ActionEvent ae) {
final GroupTreeNodeViewModel node = getNodeToUse();
final UndoableModifySubtree undo = new UndoableModifySubtree(getGroupTreeRoot(), node,
Localization.lang("sort subgroups"));
groupsTree.sort(node, true);
panel.getUndoManager().addEdit(undo);
panel.markBaseChanged();
frame.output(Localization.lang("Sorted all subgroups recursively."));
}
}
private class ExpandSubtreeAction extends NodeAction {
public ExpandSubtreeAction() {
super(Localization.lang("Expand subtree"));
}
@Override
public void actionPerformed(ActionEvent ae) {
getNodeToUse().expandSubtree(groupsTree);
revalidateGroups();
}
}
private class CollapseSubtreeAction extends NodeAction {
public CollapseSubtreeAction() {
super(Localization.lang("Collapse subtree"));
}
@Override
public void actionPerformed(ActionEvent ae) {
getNodeToUse().collapseSubtree(groupsTree);
revalidateGroups();
}
}
private class MoveNodeUpAction extends NodeAction {
public MoveNodeUpAction() {
super(Localization.lang("Up"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupTreeNodeViewModel node = getNodeToUse();
moveNodeUp(node, false);
}
}
private class MoveNodeDownAction extends NodeAction {
public MoveNodeDownAction() {
super(Localization.lang("Down"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupTreeNodeViewModel node = getNodeToUse();
moveNodeDown(node, false);
}
}
private class MoveNodeLeftAction extends NodeAction {
public MoveNodeLeftAction() {
super(Localization.lang("Left"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupTreeNodeViewModel node = getNodeToUse();
moveNodeLeft(node, false);
}
}
private class MoveNodeRightAction extends NodeAction {
public MoveNodeRightAction() {
super(Localization.lang("Right"));
}
@Override
public void actionPerformed(ActionEvent e) {
final GroupTreeNodeViewModel node = getNodeToUse();
moveNodeRight(node, false);
}
}
/**
* @param node The node to move
* @return true if move was successful, false if not.
*/
public boolean moveNodeUp(GroupTreeNodeViewModel node, boolean checkSingleSelection) {
if (checkSingleSelection && (groupsTree.getSelectionCount() != 1)) {
frame.output(MOVE_ONE_GROUP);
return false; // not possible
}
Optional<MoveGroupChange> moveChange;
if (!node.canMoveUp() || (! (moveChange = node.moveUp()).isPresent())) {
frame.output(Localization.lang("Cannot move group \"%0\" up.", node.getNode().getGroup().getName()));
return false; // not possible
}
// update selection/expansion state (not really needed when
// moving among siblings, but I'm paranoid)
revalidateGroups(groupsTree.refreshPaths(groupsTree.getSelectionPaths()),
groupsTree.refreshPaths(getExpandedPaths()));
concludeMoveGroup(moveChange.get(), node);
return true;
}
/**
* @param node The node to move
* @return true if move was successful, false if not.
*/
public boolean moveNodeDown(GroupTreeNodeViewModel node, boolean checkSingleSelection) {
if (checkSingleSelection && (groupsTree.getSelectionCount() != 1)) {
frame.output(MOVE_ONE_GROUP);
return false; // not possible
}
Optional<MoveGroupChange> moveChange;
if (!node.canMoveDown() || (! (moveChange = node.moveDown()).isPresent())) {
frame.output(Localization.lang("Cannot move group \"%0\" down.", node.getNode().getGroup().getName()));
return false; // not possible
}
// update selection/expansion state (not really needed when
// moving among siblings, but I'm paranoid)
revalidateGroups(groupsTree.refreshPaths(groupsTree.getSelectionPaths()),
groupsTree.refreshPaths(getExpandedPaths()));
concludeMoveGroup(moveChange.get(), node);
return true;
}
/**
* @param node The node to move
* @return true if move was successful, false if not.
*/
public boolean moveNodeLeft(GroupTreeNodeViewModel node, boolean checkSingleSelection) {
if (checkSingleSelection && (groupsTree.getSelectionCount() != 1)) {
frame.output(MOVE_ONE_GROUP);
return false; // not possible
}
Optional<MoveGroupChange> moveChange;
if (!node.canMoveLeft() || (! (moveChange = node.moveLeft()).isPresent())) {
frame.output(Localization.lang("Cannot move group \"%0\" left.", node.getNode().getGroup().getName()));
return false; // not possible
}
// update selection/expansion state
revalidateGroups(groupsTree.refreshPaths(groupsTree.getSelectionPaths()),
groupsTree.refreshPaths(getExpandedPaths()));
concludeMoveGroup(moveChange.get(), node);
return true;
}
/**
* @param node The node to move
* @return true if move was successful, false if not.
*/
public boolean moveNodeRight(GroupTreeNodeViewModel node, boolean checkSingleSelection) {
if (checkSingleSelection && (groupsTree.getSelectionCount() != 1)) {
frame.output(MOVE_ONE_GROUP);
return false; // not possible
}
Optional<MoveGroupChange> moveChange;
if (!node.canMoveRight() || (! (moveChange = node.moveRight()).isPresent())) {
frame.output(Localization.lang("Cannot move group \"%0\" right.", node.getNode().getGroup().getName()));
return false; // not possible
}
// update selection/expansion state
revalidateGroups(groupsTree.refreshPaths(groupsTree.getSelectionPaths()),
groupsTree.refreshPaths(getExpandedPaths()));
concludeMoveGroup(moveChange.get(), node);
return true;
}
/**
* Concludes the moving of a group tree node by storing the specified undo information, marking the change, and
* setting the status line.
*
* @param moveChange Undo information for the move operation.
* @param node The node that has been moved.
*/
public void concludeMoveGroup(MoveGroupChange moveChange, GroupTreeNodeViewModel node) {
panel.getUndoManager().addEdit(new UndoableMoveGroup(this.groupsRoot, moveChange));
panel.markBaseChanged();
frame.output(Localization.lang("Moved group \"%0\".", node.getNode().getGroup().getName()));
}
public void concludeAssignment(AbstractUndoableEdit undo, GroupTreeNode node, int assignedEntries) {
if (undo == null) {
frame.output(Localization.lang("The group \"%0\" already contains the selection.",
node.getGroup().getName()));
return;
}
panel.getUndoManager().addEdit(undo);
panel.markBaseChanged();
panel.updateEntryEditorIfShowing();
final String groupName = node.getGroup().getName();
if (assignedEntries == 1) {
frame.output(Localization.lang("Assigned 1 entry to group \"%0\".", groupName));
} else {
frame.output(Localization.lang("Assigned %0 entries to group \"%1\".", String.valueOf(assignedEntries),
groupName));
}
}
public GroupTreeNodeViewModel getGroupTreeRoot() {
return groupsRoot;
}
public Enumeration<TreePath> getExpandedPaths() {
return groupsTree.getExpandedDescendants(groupsRoot.getTreePath());
}
/**
* panel may be null to indicate that no file is currently open.
*/
@Override
public void setActiveBasePanel(BasePanel panel) {
super.setActiveBasePanel(panel);
if (panel == null) { // hide groups
frame.getSidePaneManager().hide(GroupSelector.class);
return;
}
MetaData metaData = panel.getBibDatabaseContext().getMetaData();
if (metaData.getGroups().isPresent()) {
setGroups(metaData.getGroups().get());
} else {
GroupTreeNode newGroupsRoot = GroupTreeNode
.fromGroup(new AllEntriesGroup(Localization.lang("All entries")));
metaData.setGroups(newGroupsRoot);
setGroups(newGroupsRoot);
}
metaData.registerListener(this);
synchronized (getTreeLock()) {
validateTree();
}
}
/**
* Highlight all groups that contain any/all of the specified entries. If entries is null or has zero length,
* highlight is cleared.
*/
public void showMatchingGroups(List<BibEntry> list, boolean requireAll) {
if ((list == null) || (list.isEmpty())) { // nothing selected
groupsTree.setMatchingGroups(Collections.emptyList());
groupsTree.revalidate();
return;
}
List<GroupTreeNode> nodeList = groupsRoot.getNode().getContainingGroups(list, requireAll);
groupsTree.setMatchingGroups(nodeList);
// ensure that all highlighted nodes are visible
for (GroupTreeNode node : nodeList) {
node.getParent().ifPresent(
parentNode -> groupsTree.expandPath(new GroupTreeNodeViewModel(parentNode).getTreePath()));
}
groupsTree.revalidate();
}
/**
* Show groups that, if selected, would show at least one of the entries in the specified list.
*/
private void showOverlappingGroups(List<BibEntry> matches) {
List<GroupTreeNode> nodes = groupsRoot.getNode().getMatchingGroups(matches);
groupsTree.setOverlappingGroups(nodes);
}
public GroupsTree getGroupsTree() {
return this.groupsTree;
}
@Subscribe
public void listen(GroupUpdatedEvent updateEvent) {
setGroups(updateEvent.getMetaData().getGroups().orElse(null));
}
@Override
public void grabFocus() {
groupsTree.grabFocus();
}
@Override
public ToggleAction getToggleAction() {
return toggleAction;
}
}
|
package nl.topicus.jdbc.statement;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;
import com.google.rpc.Code;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.select.Select;
import nl.topicus.jdbc.CloudSpannerConnection;
import nl.topicus.jdbc.CloudSpannerDriver;
import nl.topicus.jdbc.MetaDataStore.TableKeyMetaData;
import nl.topicus.jdbc.exception.CloudSpannerSQLException;
public class DeleteWorker extends AbstractTablePartWorker
{
final Delete delete;
public DeleteWorker(CloudSpannerConnection connection, Delete delete, boolean allowExtendedMode) throws SQLException
{
super(connection, createSelect(connection, delete), allowExtendedMode, DMLOperation.DELETE);
this.delete = delete;
}
private static Select createSelect(CloudSpannerConnection connection, Delete delete) throws SQLException
{
TableKeyMetaData table = connection.getTable(CloudSpannerDriver.unquoteIdentifier(delete.getTable().getName()));
List<String> keyCols = table.getKeyColumns().stream()
.map(x -> CloudSpannerDriver.quoteIdentifier(delete.getTable().getName()) + "."
+ CloudSpannerDriver.quoteIdentifier(x))
.collect(Collectors.toList());
StringBuilder sql = new StringBuilder();
sql.append("SELECT ").append(String.join(", ", keyCols));
sql.append("\nFROM ").append(CloudSpannerDriver.quoteIdentifier(delete.getTable().getName()));
sql.append("\nWHERE ").append(delete.getWhere().toString());
try
{
return (Select) CCJSqlParserUtil.parse(sql.toString());
}
catch (JSQLParserException e)
{
throw new CloudSpannerSQLException("Could not parse generated SELECT statement: " + sql,
Code.INVALID_ARGUMENT);
}
}
@Override
protected List<String> getColumnNames() throws SQLException
{
String unquotedTableName = CloudSpannerDriver.unquoteIdentifier(getTable().getName());
return ConverterUtils.getQuotedColumnNames(connection, null, null, unquotedTableName);
}
@Override
protected String createSQL() throws SQLException
{
TableKeyMetaData table = connection.getTable(CloudSpannerDriver.unquoteIdentifier(getTable().getName()));
List<String> keyCols = table.getKeyColumns().stream().map(CloudSpannerDriver::quoteIdentifier)
.collect(Collectors.toList());
String sql = "DELETE FROM " + CloudSpannerDriver.quoteIdentifier(delete.getTable().getName()) + " WHERE ";
boolean first = true;
for (String key : keyCols)
{
if (!first)
sql = sql + " AND ";
sql = sql + key + "=?";
first = false;
}
return sql;
}
@Override
protected Table getTable()
{
return delete.getTable();
}
}
|
package org.almibe.multipage.skins;
import javafx.beans.property.ObjectProperty;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import org.almibe.multipage.Page;
public class PageTabNode extends GridPane {
private final Page page;
private final Label text = new Label();
private final Image closeIcon = new Image(getClass().getResourceAsStream("tango/emblem-unreadable16.png"));
private final ImageView closeButton = new ImageView(closeIcon);
private final ObjectProperty<Page> selectedPage;
public PageTabNode(Page page, ObjectProperty<Page> selectedPage, TabAreaNode tabAreaNode) {
super();
this.page = page;
this.selectedPage = selectedPage;
text.textProperty().bind(page.textProperty());
getColumnConstraints().add(new ColumnConstraints(20));
GridPane.setConstraints(page.getImageView(), 0, 0);
getColumnConstraints().add(new ColumnConstraints(200));
GridPane.setConstraints(text, 1, 0);
getColumnConstraints().add(new ColumnConstraints(20));
GridPane.setConstraints(closeButton, 2, 0);
getChildren().addAll(page.getImageView(), text, closeButton);
setPadding(new Insets(10d));
setBorder(createBorder());
this.setOnMouseClicked(event -> {
this.selectedPage.set(page);
});
closeButton.setOnMouseClicked(event -> {
if (page.getOnCloseRequest() != null) {
page.getOnCloseRequest().handle(event);
if (event.isConsumed()) {
return;
}
}
tabAreaNode.removePage(page);
event.consume();
});
selectedPage.addListener((observable, oldValue, newValue) -> {
if (page == oldValue) {
this.backgroundProperty().setValue(new Background(new BackgroundFill(Color.WHITESMOKE, CornerRadii.EMPTY, Insets.EMPTY)));
text.setFont(Font.font(text.getFont().getFamily(), FontWeight.NORMAL, text.getFont().getSize()));
}
if (page == newValue) {
this.backgroundProperty().setValue(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
text.setFont(Font.font(text.getFont().getFamily(), FontWeight.BOLD, text.getFont().getSize()));
}
});
}
private Border createBorder() {
return new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID,
new CornerRadii(0d, 0d, 0d, 0d, false), new BorderWidths(0,1,0,1)));
}
public Page getPage() {
return page;
}
}
|
package org.animotron.statement.operator;
import javolution.util.FastList;
import org.animotron.graph.AnimoGraph;
import org.animotron.graph.GraphOperation;
import org.animotron.graph.index.Order;
import org.animotron.graph.index.Result;
import org.animotron.io.PipedInput;
import org.animotron.io.PipedOutput;
import org.animotron.manipulator.Evaluator;
import org.animotron.manipulator.PFlow;
import org.animotron.manipulator.QCAVector;
import org.animotron.statement.Statement;
import org.animotron.statement.Statements;
import org.animotron.statement.Suffix;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.kernel.Traversal;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import static org.animotron.Properties.*;
import static org.animotron.graph.AnimoGraph.getDb;
import static org.animotron.graph.RelationshipTypes.REF;
import static org.animotron.graph.RelationshipTypes.RESULT;
import static org.neo4j.graphdb.Direction.INCOMING;
import static org.neo4j.graphdb.Direction.OUTGOING;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public class Utils {
public static TraversalDescription td_RESULT =
Traversal.description().
breadthFirst().
relationships(RESULT, OUTGOING );
//.evaluator(Evaluators.excludeStartPosition());
public static TraversalDescription td_eval_IS =
Traversal.description().
breadthFirst().
relationships(AN._, OUTGOING);
//relationships(IC._.relationshipType(), OUTGOING);
public static TraversalDescription upIS =
Traversal.description().
breadthFirst().
relationships(AN._, INCOMING);
//relationships(IC._.relationshipType(), OUTGOING);
// public static PipedInput<ACQVector> getREFs(PFlow pf, final Node node) {
// PipedOutput<ACQVector> out = new PipedOutput<ACQVector>();
// PipedInput<ACQVector> in = out.getInputStream();
// //System.out.println(node);
// try {
// try {
// Relationship theNode = THE.__((String)THE._.reference(node));
// if (theNode != null) {
// List<Relationship> res = new FastList<Relationship>();
// res.add(theNode);
// return res;
// } catch (Exception e) {
// Relationship first = null;
// List<Relationship> list = new FastList<Relationship>();
// IndexHits<Relationship> hits = Order.queryDown(node);
// try {
// for (Relationship res : hits) {
// if (first == null) first = res;
// if (res.isType(org.animotron.statement.operator.REF._))
// list = getTheRelationships(pf, res, list);
// if (first != null && list.isEmpty())
// getTheRelationships(pf, first, list);
// } finally {
// hits.close();
// return list;
// } catch (Exception e) {
// pf.sendException(e);
// return null;
@Deprecated
public static List<Relationship> getSuffixes(final Node node) {
List<Relationship> list = null;
IndexHits<Relationship> hits = Order.queryDown(node);
try {
for (Relationship res : hits) {
Statement s = Statements.relationshipType(res);
if (s instanceof Suffix) {
if (list == null) list = new FastList<Relationship>();
list.add(res);
}
}
} finally {
hits.close();
}
return list;
}
public static PipedInput<QCAVector> getByREF(final PFlow pf) {
return getByREF(pf, pf.getVector());
}
public static PipedInput<QCAVector> getByREF(final PFlow pf, final QCAVector vector) {
PipedOutput<QCAVector> out = new PipedOutput<QCAVector>();
PipedInput<QCAVector> in = out.getInputStream();
Node node = vector.getClosest().getEndNode();
//System.out.println(node);
try {
try {
Relationship theNode = THE.__((String)THE._.reference(node));
if (theNode != null) {
out.write(vector.answered(theNode));
out.close();
return in;
}
} catch (Exception e) {
}
Relationship first = null;
IndexHits<Relationship> hits = Order.queryDown(node);
try {
for (Relationship res : hits) {
if (res.isType(org.animotron.statement.operator.REF._) || first == null) {
evaluable(pf, vector.question(res), out);
if (first == null)
first = res;
} else
break;
}
// if (first != null && out.isEmpty())
// evaluable(pf, first, out, op);
} finally {
hits.close();
}
out.close();
return in;
} catch (Exception e) {
pf.sendException(e);
}
return null;
}
private static PipedOutput<QCAVector> evaluable(final PFlow pf, final QCAVector v, final PipedOutput<QCAVector> out) throws InterruptedException, IOException {
Relationship r = v.getClosest();
Statement s = Statements.relationshipType(r);
if (s instanceof Query || s instanceof Evaluable) {
//System.out.println("+++++++++++++++++++++++++++++++++++++++++ get evaluable");
PipedInput<QCAVector> in = Evaluator._.execute(v);
for (QCAVector e : in) {
Statement aS = Statements.relationshipType(e.getAnswer());
if (!(aS instanceof Evaluable && !(s instanceof Shift))) {
// if (result.isType(REF)
// || result.isType(org.animotron.statement.operator.REF._)
// || result.isType(THE._)
out.write(e);
} else {
for (QCAVector rr : eval(e)) {
out.write(rr);
}
}
}
//System.out.println("end++++++++++++++++++++++++++++++++++++++ get evaluable");
} else {
out.write(v.getContext().get(0).answered(r));
}
return out;
}
public static PipedInput<QCAVector> getTheRelationships(PFlow pf, QCAVector v) throws IOException {
PipedOutput<QCAVector> out = new PipedOutput<QCAVector>();
PipedInput<QCAVector> in = out.getInputStream();
getTheRelationships(pf, v, out);
out.close();
return in;
}
public static void getTheRelationships(PFlow pf, QCAVector v, PipedOutput<QCAVector> out) {
try {
Statement s = Statements.relationshipType(v.getClosest());
if (s instanceof AN) {
try {
s = Statements.name((String) THE._.reference(v.getClosest()));
} catch (Exception e) {
out.write(v.answered(v.getClosest()));
return;
}
}
if (s instanceof Query || s instanceof Evaluable) {
//System.out.println("+++++++++++++++++++++++++++++++++++++++++ get evaluable");
PipedInput<QCAVector> in = Evaluator._.execute(v);
for (QCAVector e : in) {
Relationship result = e.getUnrelaxedAnswer();
if (result.isType(REF)
|| result.isType(org.animotron.statement.operator.REF._)
|| result.isType(THE._)
) {
out.write(e);
} else {
for (QCAVector rr : eval(e)) {
out.write(rr);
}
}
}
//System.out.println("end++++++++++++++++++++++++++++++++++++++ get evaluable");
} else {
out.write(v.answered(v.getClosest()));
}
} catch (Exception e) {
pf.sendException(e);
}
}
public static PipedInput<QCAVector> eval(QCAVector vector) throws IOException {
final PipedOutput<QCAVector> out = new PipedOutput<QCAVector>();
PipedInput<QCAVector> in = out.getInputStream();
Relationship op = vector.getClosest();
QCAVector prev = null;
IndexHits<Relationship> hits = Order.queryDown(op.getEndNode());
for (Relationship rr : hits) {
if (rr.isType(REF) || rr.isType(org.animotron.statement.operator.REF._)) continue;
Statement _s = Statements.relationshipType(rr);
if (_s instanceof Query || _s instanceof Evaluable) {
prev = vector.question(rr, prev);
PipedInput<QCAVector> _in = Evaluator._.execute(prev);
for (QCAVector ee : _in) {
//XXX: ee should be context too???
out.write(new QCAVector(op, vector, ee.getUnrelaxedAnswer()));
}
} else {
out.write(new QCAVector(op, vector, rr));
}
}
out.close();
return in;
}
@Deprecated
public static Node getSingleREF(final Node node) {
try {
try {
Node theNode = THE._((String)THE._.reference(node));
if (theNode != null)
return theNode;
} catch (Exception e) {
}
final Relationship res = Order.first(1, node)[0];
return res.getEndNode();
} catch (IndexOutOfBoundsException e) {
}
return null;
}
@Deprecated
public static Relationship getByREF(final Relationship r) {
final Relationship res = Order.first(1, r.getEndNode())[0];
return res;
}
public static boolean results(PFlow pf) {
return false;
//return results(pf.getOP(), pf, pf.getPathHash());
}
public static boolean results(PFlow pf, byte[] hash) {
return false;
//return results(pf.getOP(), pf, hash);
}
public static boolean results(Relationship op, PFlow pf) {
return false;
//return results(op, pf, pf.getPathHash());
}
public static boolean results(Relationship op, PFlow pf, byte[] hash) {
return false;
// boolean haveSome = false;
// //System.out.println("check index "+r+" "+pf.getPathHash()[0]+" "+pf.getPFlowPath());
// for (QCAVector v : Result.get(hash, op)) {
// pf.sendAnswer(v);
// haveSome = true;
// return haveSome;
}
public static boolean haveContext(PFlow pf) {
return haveContext(pf.getOPNode());
}
public static boolean haveContext(Node node) {
return CONTEXT.has(node);
}
public static Relationship relax(Relationship relation) {
Relationship r = relation;
while (true) {
try {
r = getDb().getRelationshipById(
(Long)r.getProperty(RID.name())
);
} catch (Exception ex) {
break;
}
}
return r;
}
public static long relaxedId(Relationship relation) {
try {
return (Long)relation.getProperty(RID.name());
} catch (Exception ex) {
}
return -1;
}
public static Relationship createResult(final PFlow pf, final Node node, final Relationship r, final RelationshipType rType) {
return createResult(pf, null, node, r, rType, pf.getPathHash());
}
public static Relationship createResult(final PFlow pf, final List<QCAVector> context, final Node node, final Relationship r, final RelationshipType rType) {
return createResult(pf, context, node, r, rType, pf.getPathHash());
}
public static Relationship createResult(final PFlow pf, final Node node, final Relationship r, final RelationshipType rType, final byte[] hash) {
return createResult(pf, null, node, r, rType, hash);
}
public static Relationship createResult(final PFlow pf, final List<QCAVector> context, final Node node, final Relationship r, final RelationshipType rType, final byte[] hash) {
return AnimoGraph.execute(new GraphOperation<Relationship>() {
@Override
public Relationship execute() {
//check if it exist
Relationship res = Result.getIfExist(node, r, rType);
if (res != null) {
Result.add(res, hash);
//for debug
//CID.set(res, context.getId());
return res;
}
//adding if not
res = node.createRelationshipTo(r.getEndNode(), rType);
//store to relationship arrow
RID.set(res, r.getId());
//for debug
// if (context != null) {
// if (context.size() > 1) System.out.println("WARNING ... more then one context for CID");
// //XXX: rewrite!
// for (QCAVector c : context) {
// try {
// CID.set(res, c.mashup());
// } catch (Exception e) {
Result.add(res, hash);
//System.out.println("add to index "+r+" "+pf.getPathHash()[0]+" "+pf.getPFlowPath());
return res;
}
});
}
public static void debug(Statement st, Relationship op, Set<Node> thes) {
System.out.print(st.name()+" "+op.getId()+" ");
if (thes.isEmpty())
System.out.print("no the-nodes in bag!");
else {
for (Node theNode : thes) {
try {
System.out.print("'"+name(theNode)+"'");
} catch (Exception e) {
System.out.print("???");
}
System.out.print(" ["+theNode+"], ");
}
}
System.out.println();
}
public static String name(Node theNode) {
return (String)NAME.get(theNode);
}
}
|
package com.yandex.money.api.methods.wallet;
import com.google.gson.annotations.SerializedName;
import com.yandex.money.api.model.Error;
import com.yandex.money.api.model.SimpleResponse;
import com.yandex.money.api.model.SimpleStatus;
import com.yandex.money.api.net.FirstApiRequest;
import com.yandex.money.api.net.providers.HostsProvider;
import static com.yandex.money.api.util.Common.checkNotEmpty;
import static com.yandex.money.api.util.Common.checkNotNull;
/**
* Incoming transfer accept result.
*/
public class IncomingTransferAccept extends SimpleResponse {
@SuppressWarnings("WeakerAccess")
@SerializedName("protection_code_attempts_available")
public final Integer protectionCodeAttemptsAvailable;
@SuppressWarnings("WeakerAccess")
@SerializedName("ext_action_uri")
public final String extActionUri;
/**
* Constructor.
*
* @param status status of request
* @param error error code if noth
* @param protectionCodeAttemptsAvailable number of attempts available after invalid protection code submission
* @param extActionUri address to perform external action for successful acceptance
*/
public IncomingTransferAccept(SimpleStatus status, Error error, Integer protectionCodeAttemptsAvailable,
String extActionUri) {
super(status, error);
switch (status) {
case REFUSED:
switch (error) {
case EXT_ACTION_REQUIRED:
checkNotNull(extActionUri, "extActionUri");
break;
}
break;
}
this.protectionCodeAttemptsAvailable = protectionCodeAttemptsAvailable;
this.extActionUri = extActionUri;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
IncomingTransferAccept that = (IncomingTransferAccept) o;
//noinspection SimplifiableIfStatement
if (protectionCodeAttemptsAvailable != null ? !protectionCodeAttemptsAvailable.equals(that.protectionCodeAttemptsAvailable) : that.protectionCodeAttemptsAvailable != null)
return false;
return extActionUri != null ? extActionUri.equals(that.extActionUri) : that.extActionUri == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (protectionCodeAttemptsAvailable != null ? protectionCodeAttemptsAvailable.hashCode() : 0);
result = 31 * result + (extActionUri != null ? extActionUri.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "IncomingTransferAccept{" +
"status=" + status +
", error=" + error +
", protectionCodeAttemptsAvailable=" + protectionCodeAttemptsAvailable +
", extActionUri='" + extActionUri + '\'' +
'}';
}
/**
* Requests to perform {@link IncomingTransferAccept}.
* <p/>
* Authorized session required.
*/
public static final class Request extends FirstApiRequest<IncomingTransferAccept> {
/**
* Constructor.
*
* @param operationId unique operation id
* @param protectionCode protection code if transfer is protected
*/
public Request(String operationId, String protectionCode) {
super(IncomingTransferAccept.class);
addParameter("operation_id", checkNotEmpty(operationId, "operationId"));
addParameter("protection_code", protectionCode);
}
@Override
protected String requestUrlBase(HostsProvider hostsProvider) {
return hostsProvider.getMoneyApi() + "/incoming-transfer-accept";
}
}
}
|
package org.apdplat.superword.tools;
import org.apache.commons.lang.StringUtils;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* ICIBA:
* YOUDAO:
* COLLINS:
* @author
*/
public class WordLinker {
private WordLinker(){}
public volatile static String dictionary = "ICIBA";
private static final String EM_PRE = "<span style=\"color:red\">";
private static final String EM_SUF = "</span>";
private static final String ICIBA = "http:
private static final String YOUDAO = "http://dict.youdao.com/search?q=";
private static final String COLLINS = "http:
public static String toLink(String word){
return toLink(word, "");
}
public static String toLink(String word, String emphasize){
return toLink(word, emphasize, EM_PRE, EM_SUF);
}
public static String toLink(String word, String emphasize, String emPre, String emSuf){
switch (dictionary){
case ICIBA: return linkToICIBA(word, emphasize, emPre, emSuf);
case YOUDAO: return linkToYOUDAO(word, emphasize, emPre, emSuf);
case COLLINS: return linkToCOLLINS(word, emphasize, emPre, emSuf);
}
//default
return linkToICIBA(word, emphasize, emPre, emSuf);
}
private static String linkToICIBA(String word, String emphasize, String emPre, String emSuf){
return linkTo(word, emphasize, emPre, emSuf, ICIBA);
}
private static String linkToYOUDAO(String word, String emphasize, String emPre, String emSuf){
return linkTo(word, emphasize, emPre, emSuf, YOUDAO);
}
private static String linkToCOLLINS(String word, String emphasize, String emPre, String emSuf){
return linkTo(word, emphasize, emPre, emSuf, COLLINS);
}
private static String linkTo(String word, String emphasize, String emPre, String emSuf, String webSite){
StringBuilder p = new StringBuilder();
for (char c : emphasize.toCharArray()) {
p.append("[")
.append(Character.toUpperCase(c))
.append(Character.toLowerCase(c))
.append("]{1}");
}
Pattern pattern = Pattern.compile(p.toString());
StringBuilder html = new StringBuilder();
html.append("<a target=\"_blank\" href=\"")
.append(webSite)
.append("\">");
if(StringUtils.isNotBlank(emphasize)) {
Set<String> targets = new HashSet<>();
Matcher matcher = pattern.matcher(word);
while(matcher.find()){
String target = matcher.group();
targets.add(target);
}
for(String target : targets){
word = word.replaceAll(target, emPre+target+emSuf);
}
}
html.append(word).append("</a>");
return html.toString();
}
}
|
package org.apdplat.word.segmentation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import org.apdplat.word.util.DirectoryWatcher;
import org.apdplat.word.util.WordConfTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* stopwords.path
*
* System.setProperty("stopwords.path", "classpath:stopwords.txt");
* Java
* java -Dstopwords.path=classpath:stopwords.txt
*
* word.conf
* stopwords.path=classpath:stopwords.txt
* stopwords.txt
* @author
*/
public class StopWord {
private static final Logger LOGGER = LoggerFactory.getLogger(StopWord.class);
private static final Set<String> stopwords = new HashSet<>();
private static final Set<String> fileWatchers = new HashSet<>();
private static final DirectoryWatcher dictionaryDirectoryWatcher = new DirectoryWatcher(new DirectoryWatcher.WatcherCallback(){
private long lastExecute = System.currentTimeMillis();
@Override
public void execute(WatchEvent.Kind<?> kind, String path) {
if(System.currentTimeMillis() - lastExecute > 1000){
lastExecute = System.currentTimeMillis();
LOGGER.info(""+kind.name()+" ,"+path);
synchronized(StopWord.class){
LOGGER.info("");
stopwords.clear();
LOGGER.info("");
loadStopWords();
}
}
}
}, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
static{
loadStopWords();
}
/**
*
* @param word
* @return
*/
private static boolean isStopChar(String word){
if(word.length() == 1){
char _char = word.charAt(0);
if(_char < 48){
return true;
}
if(_char > 57 && _char < 19968){
return true;
}
if(_char > 40869){
return true;
}
}
return false;
}
/**
*
* @param word
* @return
*/
public static boolean is(String word){
if(word == null){
return false;
}
word = word.trim();
return isStopChar(word) || stopwords.contains(word);
}
public static void main(String[] args){
LOGGER.info("");
for(String w : stopwords){
LOGGER.info(w);
}
}
public static void loadStopWords(){
LOGGER.info("");
long start = System.currentTimeMillis();
String stopwordsPath = System.getProperty("stopwords.path");
if(stopwordsPath == null){
stopwordsPath = WordConfTools.get("stopwords.path", "classpath:stopwords.txt");
}
LOGGER.info("stopwords.path="+stopwordsPath);
loadStopWords(stopwordsPath.trim());
long cost = System.currentTimeMillis() - start;
LOGGER.info(""+cost+" "+stopwords.size());
}
/**
*
* @param stopwordsPath
*/
private static void loadStopWords(String dicPaths) {
String[] dics = dicPaths.split("[,]");
for(String dic : dics){
try{
dic = dic.trim();
if(dic.startsWith("classpath:")){
loadClasspathDic(dic.replace("classpath:", ""));
}else{
loadNoneClasspathDic(dic);
}
}catch(Exception e){
LOGGER.error(""+dic, e);
}
}
}
private static void loadClasspathDic(String dic) throws IOException{
Enumeration<URL> ps = Thread.currentThread().getContextClassLoader().getResources(dic);
while(ps.hasMoreElements()) {
URL url=ps.nextElement();
if(url.getFile().contains(".jar!")){
//jar
load("classpath:"+dic);
continue;
}
File file=new File(url.getFile());
boolean dir = file.isDirectory();
if(dir){
loadAndWatchDir(file.toPath());
}else{
load(file.getAbsolutePath());
watchFile(file);
}
}
}
private static void loadNoneClasspathDic(String dic) throws IOException {
Path path = Paths.get(dic);
boolean exist = Files.exists(path);
if(!exist){
LOGGER.error(""+dic);
return;
}
boolean isDir = Files.isDirectory(path);
if(isDir){
loadAndWatchDir(path);
}else{
load(dic);
watchFile(path.toFile());
}
}
private static void loadAndWatchDir(Path path) {
dictionaryDirectoryWatcher.watchDirectoryTree(path);
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
load(file.toAbsolutePath().toString());
return FileVisitResult.CONTINUE;
}
});
} catch (IOException ex) {
LOGGER.error(""+path, ex);
}
}
private static void load(String path) {
try{
InputStream in = null;
LOGGER.info(""+path);
if(path.startsWith("classpath:")){
in = StopWord.class.getClassLoader().getResourceAsStream(path.replace("classpath:", ""));
}else{
in = new FileInputStream(path);
}
try(BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf-8"))){
String line;
while((line = reader.readLine()) != null){
line = line.trim();
if("".equals(line) || line.startsWith("
continue;
}
if(!isStopChar(line)){
stopwords.add(line);
}
}
}
}catch(Exception e){
LOGGER.error(""+path, e);
}
}
private static void watchFile(final File file) {
LOGGER.info(""+file.toString());
if(fileWatchers.contains(file.toString())){
return;
}
fileWatchers.add(file.toString());
DirectoryWatcher dictionaryFileWatcher = new DirectoryWatcher(new DirectoryWatcher.WatcherCallback(){
private long lastExecute = System.currentTimeMillis();
@Override
public void execute(WatchEvent.Kind<?> kind, String path) {
if(System.currentTimeMillis() - lastExecute > 1000){
lastExecute = System.currentTimeMillis();
if(!path.equals(file.toString())){
return;
}
LOGGER.info(""+kind.name()+" ,"+path);
synchronized(StopWord.class){
LOGGER.info("");
stopwords.clear();
LOGGER.info("");
loadStopWords();
}
}
}
}, StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
dictionaryFileWatcher.watchDirectory(file.getParent());
}
}
|
package org.jboss.netty.handler.ssl;
import static org.jboss.netty.channel.Channels.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelDownstreamHandler;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.DownstreamMessageEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.util.internal.ImmediateExecutor;
public class SslHandler extends FrameDecoder implements ChannelDownstreamHandler {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(SslHandler.class);
private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0);
private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile(
"^.*(?:connection.*reset|connection.*closed|broken.*pipe).*$",
Pattern.CASE_INSENSITIVE);
private static SslBufferPool defaultBufferPool;
/**
* Returns the default {@link SslBufferPool} used when no pool is
* specified in the constructor.
*/
public static synchronized SslBufferPool getDefaultBufferPool() {
if (defaultBufferPool == null) {
defaultBufferPool = new SslBufferPool();
}
return defaultBufferPool;
}
private final SSLEngine engine;
private final SslBufferPool bufferPool;
private final Executor delegatedTaskExecutor;
private final boolean startTls;
final Object handshakeLock = new Object();
private boolean initialHandshake;
private boolean handshaking;
private volatile boolean handshaken;
private volatile ChannelFuture handshakeFuture;
private final AtomicBoolean sentFirstMessage = new AtomicBoolean();
private final AtomicBoolean sentCloseNotify = new AtomicBoolean();
int ignoreClosedChannelException;
final Object ignoreClosedChannelExceptionLock = new Object();
private final Queue<PendingWrite> pendingUnencryptedWrites = new LinkedList<PendingWrite>();
private final Queue<MessageEvent> pendingEncryptedWrites = new LinkedList<MessageEvent>();
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
*/
public SslHandler(SSLEngine engine) {
this(engine, getDefaultBufferPool(), ImmediateExecutor.INSTANCE);
}
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
* @param bufferPool the {@link SslBufferPool} where this handler will
* acquire the buffers required by the {@link SSLEngine}
*/
public SslHandler(SSLEngine engine, SslBufferPool bufferPool) {
this(engine, bufferPool, ImmediateExecutor.INSTANCE);
}
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
* @param startTls {@code true} if the first write request shouldn't be
* encrypted by the {@link SSLEngine}
*/
public SslHandler(SSLEngine engine, boolean startTls) {
this(engine, getDefaultBufferPool(), startTls);
}
/**
* Creates a new instance.
*
* @param engine the {@link SSLEngine} this handler will use
* @param bufferPool the {@link SslBufferPool} where this handler will
* acquire the buffers required by the {@link SSLEngine}
* @param startTls {@code true} if the first write request shouldn't be
* encrypted by the {@link SSLEngine}
*/
public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls) {
this(engine, bufferPool, startTls, ImmediateExecutor.INSTANCE);
}
/**
* Creates a new instance.
*
* @param engine
* the {@link SSLEngine} this handler will use
* @param delegatedTaskExecutor
* the {@link Executor} which will execute the delegated task
* that {@link SSLEngine#getDelegatedTask()} will return
*/
public SslHandler(SSLEngine engine, Executor delegatedTaskExecutor) {
this(engine, getDefaultBufferPool(), delegatedTaskExecutor);
}
/**
* Creates a new instance.
*
* @param engine
* the {@link SSLEngine} this handler will use
* @param bufferPool
* the {@link SslBufferPool} where this handler will acquire
* the buffers required by the {@link SSLEngine}
* @param delegatedTaskExecutor
* the {@link Executor} which will execute the delegated task
* that {@link SSLEngine#getDelegatedTask()} will return
*/
public SslHandler(SSLEngine engine, SslBufferPool bufferPool, Executor delegatedTaskExecutor) {
this(engine, bufferPool, false, delegatedTaskExecutor);
}
/**
* Creates a new instance.
*
* @param engine
* the {@link SSLEngine} this handler will use
* @param startTls
* {@code true} if the first write request shouldn't be encrypted
* by the {@link SSLEngine}
* @param delegatedTaskExecutor
* the {@link Executor} which will execute the delegated task
* that {@link SSLEngine#getDelegatedTask()} will return
*/
public SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExecutor) {
this(engine, getDefaultBufferPool(), startTls, delegatedTaskExecutor);
}
/**
* Creates a new instance.
*
* @param engine
* the {@link SSLEngine} this handler will use
* @param bufferPool
* the {@link SslBufferPool} where this handler will acquire
* the buffers required by the {@link SSLEngine}
* @param startTls
* {@code true} if the first write request shouldn't be encrypted
* by the {@link SSLEngine}
* @param delegatedTaskExecutor
* the {@link Executor} which will execute the delegated task
* that {@link SSLEngine#getDelegatedTask()} will return
*/
public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Executor delegatedTaskExecutor) {
if (engine == null) {
throw new NullPointerException("engine");
}
if (bufferPool == null) {
throw new NullPointerException("bufferPool");
}
if (delegatedTaskExecutor == null) {
throw new NullPointerException("delegatedTaskExecutor");
}
this.engine = engine;
this.bufferPool = bufferPool;
this.delegatedTaskExecutor = delegatedTaskExecutor;
this.startTls = startTls;
}
/**
* Returns the {@link SSLEngine} which is used by this handler.
*/
public SSLEngine getEngine() {
return engine;
}
/**
* Starts an SSL / TLS handshake for the specified channel.
*
* @return a {@link ChannelFuture} which is notified when the handshake
* succeeds or fails.
*/
public ChannelFuture handshake(Channel channel) throws SSLException {
ChannelFuture handshakeFuture;
synchronized (handshakeLock) {
if (handshaking) {
return this.handshakeFuture;
} else {
engine.beginHandshake();
runDelegatedTasks();
handshakeFuture = this.handshakeFuture = newHandshakeFuture(channel);
handshaking = true;
}
}
wrapNonAppData(context(channel), channel);
return handshakeFuture;
}
/**
* Sends an SSL {@code close_notify} message to the specified channel and
* destroys the underlying {@link SSLEngine}.
*/
public ChannelFuture close(Channel channel) throws SSLException {
ChannelHandlerContext ctx = context(channel);
engine.closeOutbound();
return wrapNonAppData(ctx, channel);
}
private ChannelHandlerContext context(Channel channel) {
return channel.getPipeline().getContext(getClass());
}
public void handleDownstream(
final ChannelHandlerContext context, final ChannelEvent evt) throws Exception {
if (evt instanceof ChannelStateEvent) {
ChannelStateEvent e = (ChannelStateEvent) evt;
switch (e.getState()) {
case OPEN:
case CONNECTED:
case BOUND:
if (Boolean.FALSE.equals(e.getValue()) || e.getValue() == null) {
closeOutboundAndChannel(context, e);
return;
}
}
}
if (!(evt instanceof MessageEvent)) {
context.sendDownstream(evt);
return;
}
MessageEvent e = (MessageEvent) evt;
if (!(e.getMessage() instanceof ChannelBuffer)) {
context.sendDownstream(evt);
return;
}
// Do not encrypt the first write request if this handler is
// created with startTLS flag turned on.
if (startTls && sentFirstMessage.compareAndSet(false, true)) {
context.sendDownstream(evt);
return;
}
// Otherwise, all messages are encrypted.
ChannelBuffer msg = (ChannelBuffer) e.getMessage();
PendingWrite pendingWrite =
new PendingWrite(evt.getFuture(), msg.toByteBuffer(msg.readerIndex(), msg.readableBytes()));
synchronized (pendingUnencryptedWrites) {
boolean offered = pendingUnencryptedWrites.offer(pendingWrite);
assert offered;
}
wrap(context, evt.getChannel());
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx,
ChannelStateEvent e) throws Exception {
// Make sure the handshake future is notified when a connection has
// been closed during handshake.
synchronized (handshakeLock) {
if (handshaking) {
handshakeFuture.setFailure(new ClosedChannelException());
}
}
try {
super.channelDisconnected(ctx, e);
} finally {
unwrap(ctx, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0);
engine.closeOutbound();
if (!sentCloseNotify.get() && handshaken) {
try {
engine.closeInbound();
} catch (SSLException ex) {
logger.debug("Failed to clean up SSLEngine.", ex);
}
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
if (cause instanceof ClosedChannelException) {
synchronized (ignoreClosedChannelExceptionLock) {
if (ignoreClosedChannelException > 0) {
ignoreClosedChannelException
logger.debug(
"Swallowing an exception raised while " +
"writing non-app data", cause);
return;
}
}
} else if (engine.isOutboundDone()) {
String message = String.valueOf(cause.getMessage()).toLowerCase();
if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
// It is safe to ignore the 'connection reset by peer' or
// 'broken pipe' error after sending closure_notify.
logger.debug(
"Swallowing a 'connection reset by peer / " +
"broken pipe' error occurred while writing " +
"'closure_notify'", cause);
// Close the connection explicitly just in case the transport
// did not close the connection automatically.
Channels.close(ctx, succeededFuture(e.getChannel()));
return;
}
}
}
ctx.sendUpstream(e);
}
@Override
protected Object decode(
final ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
if (buffer.readableBytes() < 2) {
return null;
}
int packetLength = buffer.getShort(buffer.readerIndex()) & 0xFFFF;
if ((packetLength & 0x8000) != 0) {
// Detected a SSLv2 packet
packetLength &= 0x7FFF;
packetLength += 2;
} else if (buffer.readableBytes() < 5) {
return null;
} else {
// Detected a SSLv3 / TLSv1 packet
packetLength = (buffer.getShort(buffer.readerIndex() + 3) & 0xFFFF) + 5;
}
if (buffer.readableBytes() < packetLength) {
return null;
}
ChannelBuffer frame;
try {
frame = unwrap(ctx, channel, buffer, buffer.readerIndex(), packetLength);
} finally {
buffer.skipBytes(packetLength);
}
return frame;
}
private ChannelFuture wrap(ChannelHandlerContext context, Channel channel)
throws SSLException {
ChannelFuture future = null;
ChannelBuffer msg;
ByteBuffer outNetBuf = bufferPool.acquire();
boolean success = true;
boolean offered = false;
boolean needsUnwrap = false;
try {
loop:
for (;;) {
// Acquire a lock to make sure unencrypted data is polled
// in order and their encrypted counterpart is offered in
// order.
synchronized (pendingUnencryptedWrites) {
PendingWrite pendingWrite = pendingUnencryptedWrites.peek();
if (pendingWrite == null) {
break;
}
ByteBuffer outAppBuf = pendingWrite.outAppBuf;
SSLEngineResult result = null;
try {
synchronized (handshakeLock) {
result = engine.wrap(outAppBuf, outNetBuf);
}
} finally {
if (!outAppBuf.hasRemaining()) {
pendingUnencryptedWrites.remove();
}
}
if (result.bytesProduced() > 0) {
outNetBuf.flip();
msg = ChannelBuffers.buffer(outNetBuf.remaining());
msg.writeBytes(outNetBuf.array(), 0, msg.capacity());
outNetBuf.clear();
if (pendingWrite.outAppBuf.hasRemaining()) {
// pendingWrite's future shouldn't be notified if
// only partial data is written.
future = succeededFuture(channel);
} else {
future = pendingWrite.future;
}
MessageEvent encryptedWrite = new DownstreamMessageEvent(
channel, future, msg, channel.getRemoteAddress());
if (Thread.holdsLock(pendingEncryptedWrites)) {
offered = pendingEncryptedWrites.offer(encryptedWrite);
} else {
synchronized (pendingEncryptedWrites) {
offered = pendingEncryptedWrites.offer(encryptedWrite);
}
}
assert offered;
} else {
HandshakeStatus handshakeStatus = result.getHandshakeStatus();
switch (handshakeStatus) {
case NEED_WRAP:
if (outAppBuf.hasRemaining()) {
break;
} else {
break loop;
}
case NEED_UNWRAP:
needsUnwrap = true;
break loop;
case NEED_TASK:
runDelegatedTasks();
break;
case FINISHED:
case NOT_HANDSHAKING:
if (handshakeStatus == HandshakeStatus.FINISHED) {
setHandshakeSuccess(channel);
}
if (result.getStatus() == Status.CLOSED) {
success = false;
}
break loop;
default:
throw new IllegalStateException(
"Unknown handshake status: " +
result.getHandshakeStatus());
}
}
}
}
} catch (SSLException e) {
success = false;
setHandshakeFailure(channel, e);
throw e;
} finally {
bufferPool.release(outNetBuf);
if (offered) {
flushPendingEncryptedWrites(context);
}
if (!success) {
IllegalStateException cause =
new IllegalStateException("SSLEngine already closed");
// Mark all remaining pending writes as failure if anything
// wrong happened before the write requests are wrapped.
// Please note that we do not call setFailure while a lock is
// acquired, to avoid a potential dead lock.
for (;;) {
PendingWrite pendingWrite;
synchronized (pendingUnencryptedWrites) {
pendingWrite = pendingUnencryptedWrites.poll();
if (pendingWrite == null) {
break;
}
}
pendingWrite.future.setFailure(cause);
}
}
}
if (needsUnwrap) {
unwrap(context, channel, ChannelBuffers.EMPTY_BUFFER, 0, 0);
}
if (future == null) {
future = succeededFuture(channel);
}
return future;
}
private void flushPendingEncryptedWrites(ChannelHandlerContext ctx) {
// Avoid possible dead lock and data integrity issue
// which is caused by cross communication between more than one channel
// in the same VM.
if (Thread.holdsLock(pendingEncryptedWrites)) {
return;
}
synchronized (pendingEncryptedWrites) {
if (pendingEncryptedWrites.isEmpty()) {
return;
}
}
synchronized (pendingEncryptedWrites) {
MessageEvent e;
while ((e = pendingEncryptedWrites.poll()) != null) {
ctx.sendDownstream(e);
}
}
}
private ChannelFuture wrapNonAppData(ChannelHandlerContext ctx, Channel channel) throws SSLException {
ChannelFuture future = null;
ByteBuffer outNetBuf = bufferPool.acquire();
SSLEngineResult result;
try {
for (;;) {
synchronized (handshakeLock) {
result = engine.wrap(EMPTY_BUFFER, outNetBuf);
}
if (result.bytesProduced() > 0) {
outNetBuf.flip();
ChannelBuffer msg = ChannelBuffers.buffer(outNetBuf.remaining());
msg.writeBytes(outNetBuf.array(), 0, msg.capacity());
outNetBuf.clear();
future = future(channel);
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future)
throws Exception {
if (future.getCause() instanceof ClosedChannelException) {
synchronized (ignoreClosedChannelExceptionLock) {
ignoreClosedChannelException ++;
}
}
}
});
write(ctx, future, msg);
}
switch (result.getHandshakeStatus()) {
case FINISHED:
setHandshakeSuccess(channel);
runDelegatedTasks();
break;
case NEED_TASK:
runDelegatedTasks();
break;
case NEED_UNWRAP:
if (!Thread.holdsLock(handshakeLock)) {
// unwrap shouldn't be called when this method was
// called by unwrap - unwrap will keep running after
// this method returns.
unwrap(ctx, channel, ChannelBuffers.EMPTY_BUFFER, 0, 0);
}
break;
case NOT_HANDSHAKING:
case NEED_WRAP:
break;
default:
throw new IllegalStateException(
"Unexpected handshake status: " +
result.getHandshakeStatus());
}
if (result.bytesProduced() == 0) {
break;
}
}
} catch (SSLException e) {
setHandshakeFailure(channel, e);
throw e;
} finally {
bufferPool.release(outNetBuf);
}
if (future == null) {
future = succeededFuture(channel);
}
return future;
}
private ChannelBuffer unwrap(
ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, int offset, int length) throws SSLException {
ByteBuffer inNetBuf = buffer.toByteBuffer(offset, length);
ByteBuffer outAppBuf = bufferPool.acquire();
try {
boolean needsWrap = false;
loop:
for (;;) {
SSLEngineResult result;
synchronized (handshakeLock) {
if (initialHandshake && !engine.getUseClientMode() &&
!engine.isInboundDone() && !engine.isOutboundDone()) {
handshake(channel);
initialHandshake = false;
}
try {
result = engine.unwrap(inNetBuf, outAppBuf);
} catch (SSLException e) {
throw e;
}
switch (result.getHandshakeStatus()) {
case NEED_UNWRAP:
if (inNetBuf.hasRemaining() && !engine.isInboundDone()) {
break;
} else {
break loop;
}
case NEED_WRAP:
wrapNonAppData(ctx, channel);
break;
case NEED_TASK:
runDelegatedTasks();
break;
case FINISHED:
setHandshakeSuccess(channel);
needsWrap = true;
break loop;
case NOT_HANDSHAKING:
needsWrap = true;
break loop;
default:
throw new IllegalStateException(
"Unknown handshake status: " +
result.getHandshakeStatus());
}
}
}
if (needsWrap) {
// wrap() acquires pendingUnencryptedWrites first and then
// handshakeLock. If handshakeLock is already hold by the
// current thread, calling wrap() will lead to a dead lock
// i.e. pendingUnencryptedWrites -> handshakeLock vs.
// handshakeLock -> pendingUnencryptedLock -> handshakeLock
if (!Thread.holdsLock(handshakeLock)) {
wrap(ctx, channel);
}
}
outAppBuf.flip();
if (outAppBuf.hasRemaining()) {
ChannelBuffer frame = ChannelBuffers.buffer(outAppBuf.remaining());
frame.writeBytes(outAppBuf.array(), 0, frame.capacity());
return frame;
} else {
return null;
}
} catch (SSLException e) {
setHandshakeFailure(channel, e);
throw e;
} finally {
bufferPool.release(outAppBuf);
}
}
private void runDelegatedTasks() {
for (;;) {
final Runnable task;
synchronized (handshakeLock) {
task = engine.getDelegatedTask();
}
if (task == null) {
break;
}
delegatedTaskExecutor.execute(new Runnable() {
public void run() {
synchronized (handshakeLock) {
task.run();
}
}
});
}
}
private void setHandshakeSuccess(Channel channel) {
synchronized (handshakeLock) {
handshaking = false;
handshaken = true;
if (handshakeFuture == null) {
handshakeFuture = newHandshakeFuture(channel);
}
}
handshakeFuture.setSuccess();
}
private void setHandshakeFailure(Channel channel, SSLException cause) {
synchronized (handshakeLock) {
if (!handshaking) {
return;
}
handshaking = false;
handshaken = false;
if (handshakeFuture == null) {
handshakeFuture = newHandshakeFuture(channel);
}
}
handshakeFuture.setFailure(cause);
}
private void closeOutboundAndChannel(
final ChannelHandlerContext context, final ChannelStateEvent e) throws SSLException {
if (!e.getChannel().isConnected()) {
context.sendDownstream(e);
return;
}
unwrap(context, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0);
if (!engine.isInboundDone()) {
if (sentCloseNotify.compareAndSet(false, true)) {
engine.closeOutbound();
ChannelFuture closeNotifyFuture = wrapNonAppData(context, e.getChannel());
closeNotifyFuture.addListener(
new ClosingChannelFutureListener(context, e));
return;
}
}
context.sendDownstream(e);
}
private static ChannelFuture newHandshakeFuture(Channel channel) {
ChannelFuture future = future(channel);
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future)
throws Exception {
if (!future.isSuccess()) {
fireExceptionCaught(future.getChannel(), future.getCause());
}
}
});
return future;
}
private static final class PendingWrite {
final ChannelFuture future;
final ByteBuffer outAppBuf;
PendingWrite(ChannelFuture future, ByteBuffer outAppBuf) {
this.future = future;
this.outAppBuf = outAppBuf;
}
}
private static final class ClosingChannelFutureListener implements ChannelFutureListener {
private final ChannelHandlerContext context;
private final ChannelStateEvent e;
ClosingChannelFutureListener(
ChannelHandlerContext context, ChannelStateEvent e) {
this.context = context;
this.e = e;
}
public void operationComplete(ChannelFuture closeNotifyFuture) throws Exception {
if (!(closeNotifyFuture.getCause() instanceof ClosedChannelException)) {
Channels.close(context, e.getFuture());
}
}
}
}
|
package org.lightmare.deploy;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import org.lightmare.cache.MetaContainer;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
/**
* Manager class for application deployment
*
* @author levan
*
*/
public class LoaderPoolManager {
// Amount of deployment thread pool
private static final int LOADER_POOL_SIZE = 5;
// Name prefix of deployment threads
private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-";
// Lock for pool reopening
private static final Lock LOCK = new ReentrantLock();
// Thread sleep time while it's waiting unlock
private static final long THREAD_SLEEP_TIME = 100L;
private static final Logger LOG = Logger.getLogger(LoaderPoolManager.class);
/**
* Gets class loader for existing {@link org.lightmare.deploy.MetaCreator}
* instance
*
* @return {@link ClassLoader}
*/
protected static ClassLoader getCurrent() {
ClassLoader current;
MetaCreator creator = MetaContainer.getCreator();
ClassLoader creatorLoader;
if (ObjectUtils.notNull(creator)) {
// Gets class loader for this deployment
creatorLoader = creator.getCurrent();
if (ObjectUtils.notNull(creatorLoader)) {
current = creatorLoader;
} else {
// Gets default, context class loader for current thread
current = LibraryLoader.getContextClassLoader();
}
} else {
// Gets default, context class loader for current thread
current = LibraryLoader.getContextClassLoader();
}
return current;
}
/**
* Implementation of {@link ThreadFactory} interface for application loading
*
* @author levan
*
*/
private static final class LoaderThreadFactory implements ThreadFactory {
/**
* Constructs and sets thread name
*
* @param thread
*/
private void nameThread(Thread thread) {
String name = StringUtils
.concat(LOADER_THREAD_NAME, thread.getId());
thread.setName(name);
}
/**
* Sets priority of {@link Thread} instance
*
* @param thread
*/
private void setPriority(Thread thread) {
thread.setPriority(Thread.MAX_PRIORITY);
}
/**
* Sets {@link ClassLoader} to passed {@link Thread} instance
*
* @param thread
*/
private void setContextClassLoader(Thread thread) {
ClassLoader parent = getCurrent();
thread.setContextClassLoader(parent);
}
/**
* Configures (sets name, priority and {@link ClassLoader}) passed
* {@link Thread} instance
*
* @param thread
*/
private void configureThread(Thread thread) {
nameThread(thread);
setPriority(thread);
setContextClassLoader(thread);
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
configureThread(thread);
return thread;
}
}
// Thread pool for deploying and removal of beans and temporal resources
private static ExecutorService LOADER_POOL;
/**
* Checks if loader {@link ExecutorService} is null or is shut down or is
* terminated
*
* @return <code>boolean</code>
*/
private static boolean invalid() {
return LOADER_POOL == null || LOADER_POOL.isShutdown()
|| LOADER_POOL.isTerminated();
}
/**
* Checks and if not valid reopens deploy {@link ExecutorService} instance
*
* @return {@link ExecutorService}
*/
protected static ExecutorService getLoaderPool() {
if (invalid()) {
LOCK.lock();
try {
if (invalid()) {
LOADER_POOL = Executors.newFixedThreadPool(
LOADER_POOL_SIZE, new LoaderThreadFactory());
}
} finally {
LOCK.unlock();
}
}
return LOADER_POOL;
}
/**
* Submit passed {@link Runnable} implementation in loader pool
*
* @param runnable
*/
public static void submit(Runnable runnable) {
getLoaderPool().submit(runnable);
}
/**
* Submits passed {@link Callable} implementation in loader pool
*
* @param callable
* @return {@link Future}<code><T></code>
*/
public static <T> Future<T> submit(Callable<T> callable) {
Future<T> future = getLoaderPool().submit(callable);
return future;
}
/**
* Clears existing {@link ExecutorService}s from loader threads
*/
public static void reload() {
boolean locked = LOCK.tryLock();
while (ObjectUtils.notTrue(locked)) {
locked = LOCK.tryLock();
}
try {
if (locked) {
if (ObjectUtils.notNull(LOADER_POOL)) {
LOADER_POOL.shutdown();
LOADER_POOL = null;
}
}
} finally {
LOCK.unlock();
}
getLoaderPool();
}
}
|
package org.lightmare.jpa.jta;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import javax.ejb.EJBException;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.hibernate.cfg.NotYetImplementedException;
import org.lightmare.cache.MetaData;
import org.lightmare.cache.TransactionHolder;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Class to manage {@link javax.transaction.UserTransaction} for
* {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls
*
* @author levan
*
*/
public class BeanTransactions {
private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction";
private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction";
private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented";
/**
* Inner class to cache {@link EntityTransaction}s and {@link EntityManager}
* s in one {@link Collection} for {@link UserTransaction} implementation
*
* @author levan
*
*/
protected static class TransactionData {
EntityManager em;
EntityTransaction entityTransaction;
}
private static TransactionData createTransactionData(
EntityTransaction entityTransaction, EntityManager em) {
TransactionData transactionData = new TransactionData();
transactionData.em = em;
transactionData.entityTransaction = entityTransaction;
return transactionData;
}
/**
* Gets existing transaction from cache
*
* @param entityTransactions
* @return {@link UserTransaction}
*/
public static UserTransaction getTransaction(
EntityTransaction... entityTransactions) {
UserTransaction transaction = TransactionHolder.getTransaction();
if (transaction == null) {
transaction = UserTransactionFactory.get(entityTransactions);
TransactionHolder.setTransaction(transaction);
} else {
// If entityTransactions array is available then adds it to
// UserTransaction object
UserTransactionFactory.join(transaction, entityTransactions);
}
return transaction;
}
/**
* Gets existing transaction from cache
*
* @param entityTransactions
* @return {@link UserTransaction}
*/
public static UserTransaction getTransaction(Collection<EntityManager> ems) {
UserTransaction transaction = TransactionHolder.getTransaction();
if (transaction == null) {
transaction = UserTransactionFactory.get();
TransactionHolder.setTransaction(transaction);
}
Collection<TransactionData> entityTransactions = getEntityTransactions(ems);
TransactionManager.addEntityTransactions(transaction,
entityTransactions);
return transaction;
}
/**
* Gets appropriated {@link TransactionAttributeType} for instant
* {@link Method} of {@link javax.ejb.Stateless} bean
*
* @param metaData
* @param method
* @return {@link TransactionAttributeType}
*/
public static TransactionAttributeType getTransactionType(
MetaData metaData, Method method) {
TransactionAttributeType type;
if (method == null) {
type = null;
} else {
TransactionAttributeType attrType = metaData
.getTransactionAttrType();
TransactionManagementType manType = metaData
.getTransactionManType();
TransactionAttribute attr = method
.getAnnotation(TransactionAttribute.class);
if (manType.equals(TransactionManagementType.CONTAINER)) {
if (attr == null) {
type = attrType;
} else {
type = attr.value();
}
} else {
type = null;
}
}
return type;
}
/**
* Gets status of passed transaction by {@link UserTransaction#getStatus()}
* method call
*
* @param transaction
* @return <code>int</code>
* @throws IOException
*/
private static int getStatus(UserTransaction transaction)
throws IOException {
int status;
try {
status = transaction.getStatus();
} catch (SystemException ex) {
throw new IOException(ex);
}
return status;
}
/**
* Checks if transaction is active and if it is not begins transaction
*
* @param entityTransaction
*/
private static void beginEntityTransaction(
EntityTransaction entityTransaction) {
if (ObjectUtils.notTrue(entityTransaction.isActive())) {
entityTransaction.begin();
}
}
/**
* Gets {@link EntityTransaction} from passed {@link EntityManager} and
* begins it
*
* @param em
* @return {@link EntityTransaction}
*/
private static EntityTransaction getEntityTransaction(EntityManager em) {
EntityTransaction entityTransaction;
if (em == null) {
entityTransaction = null;
} else {
entityTransaction = em.getTransaction();
beginEntityTransaction(entityTransaction);
}
return entityTransaction;
}
/**
* Gets {@link EntityTransaction} for each {@link EntityManager} and begins
* it
*
* @param ems
* @return {@link Collection}<EntityTransaction>
*/
private static Collection<TransactionData> getEntityTransactions(
Collection<EntityManager> ems) {
Collection<TransactionData> entityTransactions;
if (CollectionUtils.valid(ems)) {
entityTransactions = new ArrayList<TransactionData>();
for (EntityManager em : ems) {
EntityTransaction entityTransaction = getEntityTransaction(em);
TransactionData transactionData = createTransactionData(
entityTransaction, em);
entityTransactions.add(transactionData);
}
} else {
entityTransactions = null;
}
return entityTransactions;
}
/**
* Decides whether create or join {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param type
* @param transaction
* @param em
* @throws IOException
*/
private static void addTransaction(BeanHandler handler,
TransactionAttributeType type, UserTransaction transaction,
Collection<EntityManager> ems) throws IOException {
Collection<TransactionData> entityTransactions;
TransactionManager.addCaller(transaction, handler);
if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) {
TransactionManager.addEntityManagers(transaction, ems);
} else if (type.equals(TransactionAttributeType.REQUIRED)) {
entityTransactions = getEntityTransactions(ems);
TransactionManager.addEntityTransactions(transaction,
entityTransactions);
} else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) {
entityTransactions = getEntityTransactions(ems);
TransactionManager.addReqNewTransactions(transaction,
entityTransactions);
} else if (type.equals(TransactionAttributeType.MANDATORY)) {
int status = getStatus(transaction);
if (status == 0) {
TransactionManager.addEntityManagers(transaction, ems);
throw new EJBException(MANDATORY_ERROR);
} else {
entityTransactions = getEntityTransactions(ems);
TransactionManager.addEntityTransactions(transaction,
entityTransactions);
}
} else if (type.equals(TransactionAttributeType.NEVER)) {
try {
int status = getStatus(transaction);
if (status > 0) {
throw new EJBException(NEVER_ERROR);
}
} finally {
TransactionManager.addEntityManagers(transaction, ems);
}
} else if (type.equals(TransactionAttributeType.SUPPORTS)) {
try {
throw new NotYetImplementedException(SUPPORTS_ERROR);
} finally {
TransactionManager.addEntityManagers(transaction, ems);
}
}
}
/**
* Defines which {@link TransactionAttribute} is used on bean {@link Class}
* and decides whether create or join {@link UserTransaction} by this
* annotation
*
* @param handler
* @param method
* @param entityTransaction
* @throws IOException
*/
public static TransactionAttributeType addTransaction(BeanHandler handler,
Method method, Collection<EntityManager> ems) throws IOException {
TransactionAttributeType type;
MetaData metaData = handler.getMetaData();
type = getTransactionType(metaData, method);
UserTransaction transaction = getTransaction();
if (ObjectUtils.notNull(type)) {
addTransaction(handler, type, transaction, ems);
} else {
TransactionManager.addEntityManagers(transaction, ems);
}
return type;
}
/**
* Calls {@link UserTransaction#rollback()} method of passed
* {@link UserTransaction} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void rollback(UserTransaction transaction)
throws IOException {
try {
transaction.rollback();
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Calls {@link UserTransactionImpl#rollbackReqNews()} method of passed
* {@link UserTransaction} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void rollbackReqNew(UserTransactionImpl transaction)
throws IOException {
try {
transaction.rollbackReqNews();
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Rollbacks passed {@link UserTransaction} by
* {@link TransactionAttributeType} distinguishes only
* {@link TransactionAttributeType#REQUIRES_NEW} case or uses standard
* rollback for all other
*
* @param type
* @param handler
* @throws IOException
*/
private static void rollbackTransaction(TransactionAttributeType type,
BeanHandler handler) throws IOException {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
if (type.equals(TransactionAttributeType.REQUIRES_NEW)) {
rollbackReqNew(transaction);
} else {
rollback(transaction);
}
}
/**
* Decides which rollback method to call of {@link UserTransaction}
* implementation by {@link TransactionAttribute} annotation
*
* @param handler
* @param method
* @throws IOException
*/
public static void rollbackTransaction(BeanHandler handler, Method method)
throws IOException {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
if (ObjectUtils.notNull(type)) {
rollbackTransaction(type, handler);
} else {
closeEntityManagers();
}
}
/**
* Decides whether commit or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param type
* @param handler
* @throws IOException
*/
private static void commitTransaction(TransactionAttributeType type,
BeanHandler handler) throws IOException {
UserTransaction transaction = getTransaction();
if (type.equals(TransactionAttributeType.REQUIRED)) {
boolean check = TransactionManager
.checkCaller(transaction, handler);
if (check) {
TransactionManager.commit(transaction);
}
} else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) {
TransactionManager.commitReqNew(transaction);
} else {
TransactionManager.closeEntityManagers(transaction);
}
}
/**
* Decides whether commit or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param method
* @throws IOException
*/
public static void commitTransaction(BeanHandler handler, Method method)
throws IOException {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
if (ObjectUtils.notNull(type)) {
commitTransaction(type, handler);
} else {
closeEntityManagers();
}
}
/**
* Closes cached {@link EntityManager}s after method call
*/
public static void closeEntityManagers() {
UserTransaction transaction = getTransaction();
TransactionManager.closeEntityManagers(transaction);
}
/**
* Removes {@link UserTransaction} attribute from cache if passed
* {@link BeanHandler} is first in EJB injection method chain
*
* @param handler
* @param type
*/
private static void remove(BeanHandler handler,
TransactionAttributeType type) {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
boolean check = transaction.checkCaller(handler);
if (check) {
TransactionHolder.removeTransaction();
}
}
/**
* Removes {@link UserTransaction} attribute from cache if
* {@link TransactionAttributeType} is null or if passed {@link BeanHandler}
* is first in EJB injection method chain
*
* @param handler
* @param method
*/
public static void remove(BeanHandler handler, Method method) {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
if (ObjectUtils.notNull(type)) {
remove(handler, type);
} else {
TransactionHolder.removeTransaction();
}
}
}
|
package org.lightmare.jpa.jta;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import javax.ejb.EJBException;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.hibernate.cfg.NotYetImplementedException;
import org.lightmare.cache.MetaData;
import org.lightmare.cache.TransactionHolder;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Class to manage {@link javax.transaction.UserTransaction} for
* {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls
*
* @author levan
*
*/
public class BeanTransactions {
private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction";
private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction";
private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented";
/**
* Inner class to cache {@link EntityTransaction}s and {@link EntityManager}
* s in one {@link Collection} for {@link UserTransaction} implementation
*
* @author levan
*
*/
private static class TransactionData {
EntityManager em;
EntityTransaction entityTransaction;
}
private static TransactionData createTransactionData(
EntityTransaction entityTransaction, EntityManager em) {
TransactionData transactionData = new TransactionData();
transactionData.em = em;
transactionData.entityTransaction = entityTransaction;
return transactionData;
}
/**
* Gets existing transaction from cache
*
* @param entityTransactions
* @return {@link UserTransaction}
*/
public static UserTransaction getTransaction(
EntityTransaction... entityTransactions) {
UserTransaction transaction = TransactionHolder.getTransaction();
if (transaction == null) {
transaction = new UserTransactionImpl(entityTransactions);
TransactionHolder.setTransaction(transaction);
}
// If entityTransactions array is available then adds it to
// UserTransaction object
if (CollectionUtils.valid(entityTransactions)) {
UserTransactionImpl userTransactionImpl = ObjectUtils.cast(
transaction, UserTransactionImpl.class);
userTransactionImpl.addTransactions(entityTransactions);
}
return transaction;
}
/**
* Gets existing transaction from cache
*
* @param entityTransactions
* @return {@link UserTransaction}
*/
public static UserTransaction getTransaction(Collection<EntityManager> ems) {
UserTransaction transaction = TransactionHolder.getTransaction();
if (transaction == null) {
transaction = new UserTransactionImpl();
TransactionHolder.setTransaction(transaction);
}
Collection<TransactionData> entityTransactions = getEntityTransactions(ems);
addEntityTransactions((UserTransactionImpl) transaction,
entityTransactions);
return transaction;
}
/**
* Gets appropriated {@link TransactionAttributeType} for instant
* {@link Method} of {@link javax.ejb.Stateless} bean
*
* @param metaData
* @param method
* @return {@link TransactionAttributeType}
*/
public static TransactionAttributeType getTransactionType(
MetaData metaData, Method method) {
TransactionAttributeType type;
if (method == null) {
type = null;
} else {
TransactionAttributeType attrType = metaData
.getTransactionAttrType();
TransactionManagementType manType = metaData
.getTransactionManType();
TransactionAttribute attr = method
.getAnnotation(TransactionAttribute.class);
if (manType.equals(TransactionManagementType.CONTAINER)) {
if (attr == null) {
type = attrType;
} else {
type = attr.value();
}
} else {
type = null;
}
}
return type;
}
/**
* Gets status of passed transaction by {@link UserTransaction#getStatus()}
* method call
*
* @param transaction
* @return <code>int</code>
* @throws IOException
*/
private static int getStatus(UserTransaction transaction)
throws IOException {
int status;
try {
status = transaction.getStatus();
} catch (SystemException ex) {
throw new IOException(ex);
}
return status;
}
/**
* Checks if transaction is active and if it is not vegins transaction
*
* @param entityTransaction
*/
private static void beginEntityTransaction(
EntityTransaction entityTransaction) {
if (!entityTransaction.isActive()) {
entityTransaction.begin();
}
}
private static EntityTransaction getEntityTransaction(EntityManager em) {
EntityTransaction entityTransaction;
if (em == null) {
entityTransaction = null;
} else {
entityTransaction = em.getTransaction();
beginEntityTransaction(entityTransaction);
}
return entityTransaction;
}
private static Collection<TransactionData> getEntityTransactions(
Collection<EntityManager> ems) {
Collection<TransactionData> entityTransactions;
if (CollectionUtils.valid(ems)) {
entityTransactions = new ArrayList<TransactionData>();
for (EntityManager em : ems) {
EntityTransaction entityTransaction = getEntityTransaction(em);
TransactionData transactionData = createTransactionData(
entityTransaction, em);
entityTransactions.add(transactionData);
}
} else {
entityTransactions = null;
}
return entityTransactions;
}
private static void addEntityTransaction(UserTransactionImpl transaction,
EntityTransaction entityTransaction, EntityManager em) {
if (ObjectUtils.notNull(entityTransaction)) {
transaction.addTransaction(entityTransaction);
}
if (ObjectUtils.notNull(em)) {
transaction.addEntityManager(em);
}
}
private static void addEntityTransactions(UserTransactionImpl transaction,
Collection<TransactionData> entityTransactions) {
if (CollectionUtils.valid(entityTransactions)) {
for (TransactionData transactionData : entityTransactions) {
addEntityTransaction(transaction,
transactionData.entityTransaction, transactionData.em);
}
}
}
private static void addEntityManager(UserTransactionImpl transaction,
EntityManager em) {
if (ObjectUtils.notNull(em)) {
transaction.addEntityManager(em);
}
}
private static void addEntityManagers(UserTransactionImpl transaction,
Collection<EntityManager> ems) {
if (CollectionUtils.valid(ems)) {
for (EntityManager em : ems) {
addEntityManager(transaction, em);
}
}
}
private static void addReqNewTransaction(UserTransactionImpl transaction,
EntityTransaction entityTransaction, EntityManager em) {
if (ObjectUtils.notNull(entityTransaction)) {
transaction.pushReqNew(entityTransaction);
}
if (ObjectUtils.notNull(em)) {
transaction.pushReqNewEm(em);
}
}
private static void addReqNewTransactions(UserTransactionImpl transaction,
Collection<TransactionData> entityTransactions) {
if (CollectionUtils.valid(entityTransactions)) {
for (TransactionData transactionData : entityTransactions) {
addReqNewTransaction(transaction,
transactionData.entityTransaction, transactionData.em);
}
}
}
private static void addCaller(UserTransactionImpl transaction,
BeanHandler handler) {
Object caller = transaction.getCaller();
if (caller == null) {
transaction.setCaller(handler);
}
}
/**
* Decides whether create or join {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param type
* @param transaction
* @param em
* @throws IOException
*/
private static void addTransaction(BeanHandler handler,
TransactionAttributeType type, UserTransactionImpl transaction,
Collection<EntityManager> ems) throws IOException {
Collection<TransactionData> entityTransactions;
addCaller(transaction, handler);
if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) {
addEntityManagers(transaction, ems);
} else if (type.equals(TransactionAttributeType.REQUIRED)) {
entityTransactions = getEntityTransactions(ems);
addEntityTransactions(transaction, entityTransactions);
} else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) {
entityTransactions = getEntityTransactions(ems);
addReqNewTransactions(transaction, entityTransactions);
} else if (type.equals(TransactionAttributeType.MANDATORY)) {
int status = getStatus(transaction);
if (status == 0) {
addEntityManagers(transaction, ems);
throw new EJBException(MANDATORY_ERROR);
} else {
entityTransactions = getEntityTransactions(ems);
addEntityTransactions(transaction, entityTransactions);
}
} else if (type.equals(TransactionAttributeType.NEVER)) {
try {
int status = getStatus(transaction);
if (status > 0) {
throw new EJBException(NEVER_ERROR);
}
} finally {
addEntityManagers(transaction, ems);
}
} else if (type.equals(TransactionAttributeType.SUPPORTS)) {
try {
throw new NotYetImplementedException(SUPPORTS_ERROR);
} finally {
addEntityManagers(transaction, ems);
}
}
}
/**
* Defines which {@link TransactionAttribute} is used on bean {@link Class}
* and decides whether create or join {@link UserTransaction} by this
* annotation
*
* @param handler
* @param method
* @param entityTransaction
* @throws IOException
*/
public static TransactionAttributeType addTransaction(BeanHandler handler,
Method method, Collection<EntityManager> ems) throws IOException {
MetaData metaData = handler.getMetaData();
TransactionAttributeType type = getTransactionType(metaData, method);
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
if (ObjectUtils.notNull(type)) {
addTransaction(handler, type, transaction, ems);
} else {
addEntityManagers(transaction, ems);
}
return type;
}
/**
* Commits passed {@link UserTransaction} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void commit(UserTransaction transaction) throws IOException {
try {
transaction.commit();
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (RollbackException ex) {
throw new IOException(ex);
} catch (HeuristicMixedException ex) {
throw new IOException(ex);
} catch (HeuristicRollbackException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Commits all {@link TransactionAttributeType.REQUIRES_NEW} transactions
* for passed {@link UserTransactionImpl} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void commitReqNew(UserTransactionImpl transaction)
throws IOException {
try {
transaction.commitReqNew();
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (RollbackException ex) {
throw new IOException(ex);
} catch (HeuristicMixedException ex) {
throw new IOException(ex);
} catch (HeuristicRollbackException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Calls {@link UserTransaction#rollback()} method of passed
* {@link UserTransaction} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void rollback(UserTransaction transaction)
throws IOException {
try {
transaction.rollback();
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Decides whether rollback or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param method
* @throws IOException
*/
public static void rollbackTransaction(BeanHandler handler, Method method)
throws IOException {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
try {
if (ObjectUtils.notNull(type)) {
rollback(transaction);
} else {
transaction.closeEntityManagers();
}
} catch (IOException ex) {
transaction.closeEntityManagers();
throw ex;
}
}
/**
* Decides whether commit or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param type
* @param handler
* @throws IOException
*/
public static void commitTransaction(TransactionAttributeType type,
BeanHandler handler) throws IOException {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
if (type.equals(TransactionAttributeType.REQUIRED)) {
boolean check = transaction.checkCaller(handler);
if (check) {
commit(transaction);
}
} else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) {
commitReqNew(transaction);
} else {
transaction.closeEntityManagers();
}
}
/**
* Decides whether commit or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param method
* @throws IOException
*/
public static void commitTransaction(BeanHandler handler, Method method)
throws IOException {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
if (ObjectUtils.notNull(type)) {
commitTransaction(type, handler);
} else {
closeEntityManagers();
}
}
/**
* Closes cached {@link EntityManager}s after method calll
*/
public static void closeEntityManagers() {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
transaction.closeEntityManagers();
}
/**
* Removes {@link UserTransaction} attribute from cache if passed
* {@link BeanHandler} is first in EJB injection method chain
*
* @param handler
* @param type
*/
private static void remove(BeanHandler handler,
TransactionAttributeType type) {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
boolean check = transaction.checkCaller(handler);
if (check) {
TransactionHolder.removeTransaction();
}
}
/**
* Removes {@link UserTransaction} attribute from cache if
* {@link TransactionAttributeType} is null or if passed {@link BeanHandler}
* is first in EJB injection method chain
*
* @param handler
* @param method
*/
public static void remove(BeanHandler handler, Method method) {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
if (ObjectUtils.notNull(type)) {
remove(handler, type);
} else {
TransactionHolder.removeTransaction();
}
}
}
|
package org.lightmare.jpa.jta;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import javax.ejb.EJBException;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.hibernate.cfg.NotYetImplementedException;
import org.lightmare.cache.MetaData;
import org.lightmare.cache.TransactionContainer;
import org.lightmare.ejb.handlers.BeanHandler;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Class to manage {@link javax.transaction.UserTransaction} for
* {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls
*
* @author levan
*
*/
public class BeanTransactions {
private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction";
private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction";
private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented";
/**
* Inner class to cache {@link EntityTransaction}s and {@link EntityManager}
* s in one {@link Collection} for {@link UserTransaction} implementation
*
* @author levan
*
*/
private static class TransactionData {
EntityManager em;
EntityTransaction entityTransaction;
}
private static TransactionData createTransactionData(
EntityTransaction entityTransaction, EntityManager em) {
TransactionData transactionData = new TransactionData();
transactionData.em = em;
transactionData.entityTransaction = entityTransaction;
return transactionData;
}
/**
* Gets existing transaction from cache
*
* @param entityTransactions
* @return {@link UserTransaction}
*/
public static UserTransaction getTransaction(
EntityTransaction... entityTransactions) {
UserTransaction transaction = TransactionContainer.getTransaction();
if (transaction == null) {
transaction = new UserTransactionImpl(entityTransactions);
TransactionContainer.setTransaction(transaction);
}
// If entityTransactions array is available then adds it to
// UserTransaction object
if (CollectionUtils.available(entityTransactions)) {
UserTransactionImpl userTransactionImpl = ObjectUtils.cast(
transaction, UserTransactionImpl.class);
userTransactionImpl.addTransactions(entityTransactions);
}
return transaction;
}
/**
* Gets existing transaction from cache
*
* @param entityTransactions
* @return {@link UserTransaction}
*/
public static UserTransaction getTransaction(Collection<EntityManager> ems) {
UserTransaction transaction = TransactionContainer.getTransaction();
if (transaction == null) {
transaction = new UserTransactionImpl();
TransactionContainer.setTransaction(transaction);
}
Collection<TransactionData> entityTransactions = getEntityTransactions(ems);
addEntityTransactions((UserTransactionImpl) transaction,
entityTransactions);
return transaction;
}
/**
* Gets appropriated {@link TransactionAttributeType} for instant
* {@link Method} of {@link javax.ejb.Stateless} bean
*
* @param metaData
* @param method
* @return {@link TransactionAttributeType}
*/
public static TransactionAttributeType getTransactionType(
MetaData metaData, Method method) {
TransactionAttributeType type;
if (method == null) {
type = null;
} else {
TransactionAttributeType attrType = metaData
.getTransactionAttrType();
TransactionManagementType manType = metaData
.getTransactionManType();
TransactionAttribute attr = method
.getAnnotation(TransactionAttribute.class);
if (manType.equals(TransactionManagementType.CONTAINER)) {
if (attr == null) {
type = attrType;
} else {
type = attr.value();
}
} else {
type = null;
}
}
return type;
}
/**
* Gets status of passed transaction by {@link UserTransaction#getStatus()}
* method call
*
* @param transaction
* @return <code>int</code>
* @throws IOException
*/
private static int getStatus(UserTransaction transaction)
throws IOException {
int status;
try {
status = transaction.getStatus();
} catch (SystemException ex) {
throw new IOException(ex);
}
return status;
}
/**
* Checks if transaction is active and if it is not vegins transaction
*
* @param entityTransaction
*/
private static void beginEntityTransaction(
EntityTransaction entityTransaction) {
if (!entityTransaction.isActive()) {
entityTransaction.begin();
}
}
private static EntityTransaction getEntityTransaction(EntityManager em) {
EntityTransaction entityTransaction;
if (em == null) {
entityTransaction = null;
} else {
entityTransaction = em.getTransaction();
beginEntityTransaction(entityTransaction);
}
return entityTransaction;
}
private static Collection<TransactionData> getEntityTransactions(
Collection<EntityManager> ems) {
Collection<TransactionData> entityTransactions;
if (CollectionUtils.available(ems)) {
entityTransactions = new ArrayList<TransactionData>();
for (EntityManager em : ems) {
EntityTransaction entityTransaction = getEntityTransaction(em);
TransactionData transactionData = createTransactionData(
entityTransaction, em);
entityTransactions.add(transactionData);
}
} else {
entityTransactions = null;
}
return entityTransactions;
}
private static void addEntityTransaction(UserTransactionImpl transaction,
EntityTransaction entityTransaction, EntityManager em) {
if (ObjectUtils.notNull(entityTransaction)) {
transaction.addTransaction(entityTransaction);
}
if (ObjectUtils.notNull(em)) {
transaction.addEntityManager(em);
}
}
private static void addEntityTransactions(UserTransactionImpl transaction,
Collection<TransactionData> entityTransactions) {
if (ObjectUtils.available(entityTransactions)) {
for (TransactionData transactionData : entityTransactions) {
addEntityTransaction(transaction,
transactionData.entityTransaction, transactionData.em);
}
}
}
private static void addEntityManager(UserTransactionImpl transaction,
EntityManager em) {
if (ObjectUtils.notNull(em)) {
transaction.addEntityManager(em);
}
}
private static void addEntityManagers(UserTransactionImpl transaction,
Collection<EntityManager> ems) {
if (ObjectUtils.available(ems)) {
for (EntityManager em : ems) {
addEntityManager(transaction, em);
}
}
}
private static void addReqNewTransaction(UserTransactionImpl transaction,
EntityTransaction entityTransaction, EntityManager em) {
if (ObjectUtils.notNull(entityTransaction)) {
transaction.pushReqNew(entityTransaction);
}
if (ObjectUtils.notNull(em)) {
transaction.pushReqNewEm(em);
}
}
private static void addReqNewTransactions(UserTransactionImpl transaction,
Collection<TransactionData> entityTransactions) {
if (ObjectUtils.available(entityTransactions)) {
for (TransactionData transactionData : entityTransactions) {
addReqNewTransaction(transaction,
transactionData.entityTransaction, transactionData.em);
}
}
}
private static void addCaller(UserTransactionImpl transaction,
BeanHandler handler) {
Object caller = transaction.getCaller();
if (caller == null) {
transaction.setCaller(handler);
}
}
/**
* Decides whether create or join {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param type
* @param transaction
* @param em
* @throws IOException
*/
private static void addTransaction(BeanHandler handler,
TransactionAttributeType type, UserTransactionImpl transaction,
Collection<EntityManager> ems) throws IOException {
Collection<TransactionData> entityTransactions;
addCaller(transaction, handler);
if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) {
addEntityManagers(transaction, ems);
} else if (type.equals(TransactionAttributeType.REQUIRED)) {
entityTransactions = getEntityTransactions(ems);
addEntityTransactions(transaction, entityTransactions);
} else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) {
entityTransactions = getEntityTransactions(ems);
addReqNewTransactions(transaction, entityTransactions);
} else if (type.equals(TransactionAttributeType.MANDATORY)) {
int status = getStatus(transaction);
if (status == 0) {
addEntityManagers(transaction, ems);
throw new EJBException(MANDATORY_ERROR);
} else {
entityTransactions = getEntityTransactions(ems);
addEntityTransactions(transaction, entityTransactions);
}
} else if (type.equals(TransactionAttributeType.NEVER)) {
try {
int status = getStatus(transaction);
if (status > 0) {
throw new EJBException(NEVER_ERROR);
}
} finally {
addEntityManagers(transaction, ems);
}
} else if (type.equals(TransactionAttributeType.SUPPORTS)) {
try {
throw new NotYetImplementedException(SUPPORTS_ERROR);
} finally {
addEntityManagers(transaction, ems);
}
}
}
/**
* Defines which {@link TransactionAttribute} is used on bean {@link Class}
* and decides whether create or join {@link UserTransaction} by this
* annotation
*
* @param handler
* @param method
* @param entityTransaction
* @throws IOException
*/
public static TransactionAttributeType addTransaction(BeanHandler handler,
Method method, Collection<EntityManager> ems) throws IOException {
MetaData metaData = handler.getMetaData();
TransactionAttributeType type = getTransactionType(metaData, method);
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
if (ObjectUtils.notNull(type)) {
addTransaction(handler, type, transaction, ems);
} else {
addEntityManagers(transaction, ems);
}
return type;
}
/**
* Commits passed {@link UserTransaction} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void commit(UserTransaction transaction) throws IOException {
try {
transaction.commit();
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (RollbackException ex) {
throw new IOException(ex);
} catch (HeuristicMixedException ex) {
throw new IOException(ex);
} catch (HeuristicRollbackException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Commits all {@link TransactionAttributeType.REQUIRES_NEW} transactions
* for passed {@link UserTransactionImpl} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void commitReqNew(UserTransactionImpl transaction)
throws IOException {
try {
transaction.commitReqNew();
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (RollbackException ex) {
throw new IOException(ex);
} catch (HeuristicMixedException ex) {
throw new IOException(ex);
} catch (HeuristicRollbackException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Calls {@link UserTransaction#rollback()} method of passed
* {@link UserTransaction} with {@link IOException} throw
*
* @param transaction
* @throws IOException
*/
private static void rollback(UserTransaction transaction)
throws IOException {
try {
transaction.rollback();
} catch (IllegalStateException ex) {
throw new IOException(ex);
} catch (SecurityException ex) {
throw new IOException(ex);
} catch (SystemException ex) {
throw new IOException(ex);
}
}
/**
* Decides whether rollback or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param method
* @throws IOException
*/
public static void rollbackTransaction(BeanHandler handler, Method method)
throws IOException {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
try {
if (ObjectUtils.notNull(type)) {
rollback(transaction);
} else {
transaction.closeEntityManagers();
}
} catch (IOException ex) {
transaction.closeEntityManagers();
throw ex;
}
}
/**
* Decides whether commit or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param type
* @param handler
* @throws IOException
*/
public static void commitTransaction(TransactionAttributeType type,
BeanHandler handler) throws IOException {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
if (type.equals(TransactionAttributeType.REQUIRED)) {
boolean check = transaction.checkCaller(handler);
if (check) {
commit(transaction);
}
} else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) {
commitReqNew(transaction);
} else {
transaction.closeEntityManagers();
}
}
/**
* Decides whether commit or not {@link UserTransaction} by
* {@link TransactionAttribute} annotation
*
* @param handler
* @param method
* @throws IOException
*/
public static void commitTransaction(BeanHandler handler, Method method)
throws IOException {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
if (ObjectUtils.notNull(type)) {
commitTransaction(type, handler);
} else {
closeEntityManagers();
}
}
/**
* Closes cached {@link EntityManager}s after method calll
*/
public static void closeEntityManagers() {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
transaction.closeEntityManagers();
}
/**
* Removes {@link UserTransaction} attribute from cache if passed
* {@link BeanHandler} is first in EJB injection method chain
*
* @param handler
* @param type
*/
private static void remove(BeanHandler handler,
TransactionAttributeType type) {
UserTransactionImpl transaction = (UserTransactionImpl) getTransaction();
boolean check = transaction.checkCaller(handler);
if (check) {
TransactionContainer.removeTransaction();
}
}
/**
* Removes {@link UserTransaction} attribute from cache if
* {@link TransactionAttributeType} is null or if passed {@link BeanHandler}
* is first in EJB injection method chain
*
* @param handler
* @param method
*/
public static void remove(BeanHandler handler, Method method) {
TransactionAttributeType type = getTransactionType(
handler.getMetaData(), method);
if (ObjectUtils.notNull(type)) {
remove(handler, type);
} else {
TransactionContainer.removeTransaction();
}
}
}
|
package org.liquidengine.legui.demo;
import static org.liquidengine.legui.component.optional.align.HorizontalAlign.CENTER;
import static org.liquidengine.legui.component.optional.align.HorizontalAlign.LEFT;
import static org.liquidengine.legui.component.optional.align.HorizontalAlign.RIGHT;
import static org.liquidengine.legui.component.optional.align.VerticalAlign.BASELINE;
import static org.liquidengine.legui.component.optional.align.VerticalAlign.BOTTOM;
import static org.liquidengine.legui.component.optional.align.VerticalAlign.MIDDLE;
import static org.liquidengine.legui.component.optional.align.VerticalAlign.TOP;
import static org.liquidengine.legui.event.MouseClickEvent.MouseClickAction.CLICK;
import static org.liquidengine.legui.event.MouseClickEvent.MouseClickAction.PRESS;
import static org.liquidengine.legui.event.MouseClickEvent.MouseClickAction.RELEASE;
import static org.liquidengine.legui.input.Mouse.MouseButton.MOUSE_BUTTON_LEFT;
import org.joml.Vector2f;
import org.joml.Vector4f;
import org.liquidengine.legui.animation.Animation;
import org.liquidengine.legui.component.Button;
import org.liquidengine.legui.component.CheckBox;
import org.liquidengine.legui.component.Component;
import org.liquidengine.legui.component.Dialog;
import org.liquidengine.legui.component.ImageView;
import org.liquidengine.legui.component.Label;
import org.liquidengine.legui.component.Panel;
import org.liquidengine.legui.component.PasswordInput;
import org.liquidengine.legui.component.ProgressBar;
import org.liquidengine.legui.component.RadioButton;
import org.liquidengine.legui.component.RadioButtonGroup;
import org.liquidengine.legui.component.ScrollBar;
import org.liquidengine.legui.component.ScrollablePanel;
import org.liquidengine.legui.component.SelectBox;
import org.liquidengine.legui.component.Slider;
import org.liquidengine.legui.component.TextArea;
import org.liquidengine.legui.component.TextInput;
import org.liquidengine.legui.component.ToggleButton;
import org.liquidengine.legui.component.Tooltip;
import org.liquidengine.legui.component.Widget;
import org.liquidengine.legui.component.event.slider.SliderChangeValueEvent;
import org.liquidengine.legui.component.event.slider.SliderChangeValueEventListener;
import org.liquidengine.legui.component.optional.Orientation;
import org.liquidengine.legui.component.optional.align.HorizontalAlign;
import org.liquidengine.legui.component.optional.align.VerticalAlign;
import org.liquidengine.legui.event.CursorEnterEvent;
import org.liquidengine.legui.event.FocusEvent;
import org.liquidengine.legui.event.KeyEvent;
import org.liquidengine.legui.event.MouseClickEvent;
import org.liquidengine.legui.icon.Icon;
import org.liquidengine.legui.icon.ImageIcon;
import org.liquidengine.legui.image.BufferedImage;
import org.liquidengine.legui.listener.CursorEnterEventListener;
import org.liquidengine.legui.listener.FocusEventListener;
import org.liquidengine.legui.listener.KeyEventListener;
import org.liquidengine.legui.listener.MouseClickEventListener;
import org.liquidengine.legui.style.Style;
import org.liquidengine.legui.style.Style.DisplayType;
import org.liquidengine.legui.style.Style.PositionType;
import org.liquidengine.legui.style.border.SimpleLineBorder;
import org.liquidengine.legui.style.color.ColorConstants;
import org.liquidengine.legui.style.font.FontRegistry;
import org.liquidengine.legui.style.shadow.Shadow;
import org.liquidengine.legui.theme.Theme;
import org.liquidengine.legui.theme.Themes;
import org.liquidengine.legui.util.TextUtil;
import org.lwjgl.glfw.GLFW;
public class ExampleGui extends Panel {
private final Label mouseTargetLabel;
private final Label mouseLabel;
private final Label upsLabel;
private final Label focusedGuiLabel;
private final TextArea textArea;
private final TextInput textInput;
private final Label debugLabel;
private ImageView imageView;
public ExampleGui() {
this(800, 600);
}
public ExampleGui(int width, int height) {
super(0, 0, width, height);
//@formatter:off
Panel p1 = new Panel(1 * 20, 10, 10, 10);
this.add(p1);
p1.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println);
Panel p2 = new Panel(2 * 20, 10, 10, 10);
this.add(p2);
p2.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println);
Panel p3 = new Panel(3 * 20, 10, 10, 10);
this.add(p3);
p3.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println);
Panel p4 = new Panel(4 * 20, 10, 10, 10);
this.add(p4);
p4.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println);
Panel p5 = new Panel(5 * 20, 10, 10, 10);
this.add(p5);
p5.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println);
Panel p6 = new Panel(6 * 20, 10, 10, 10);
this.add(p6);
p6.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println);
Panel p7 = new Panel(7 * 20, 10, 10, 10);
this.add(p7);
p7.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println);
Panel p8 = new Panel(8 * 20, 10, 10, 10);
this.add(p8);
p8.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println);
Panel p9 = new Panel(9 * 20, 10, 10, 10);
this.add(p9);
p9.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println);
this.add(mouseTargetLabel = new Label("Hello Label 1", 10, height - 30, width - 20, 20));
focusedGuiLabel = new Label("Hello Label 2", 10, height - 50, width - 20, 20);
focusedGuiLabel.getStyle().setBorder(new SimpleLineBorder(ColorConstants.red(), 1));
this.add(focusedGuiLabel);
this.add(debugLabel = new Label("Debug Label", 10, height - 75, width - 20, 20));
this.add(mouseLabel = new Label("Hello Label 3", 130, 30, 100, 20));
this.add(upsLabel = new Label("Hello Label 4", 130, 60, 100, 20));
this.add(createImageWrapperWidgetWithImage());
this.add(createButtonWithTooltip());
CheckBox checkBox1 = new CheckBox(20, 200, 50, 20);
this.add(checkBox1);
this.add(createCheckboxWithAnimation(checkBox1));
ProgressBar progressBar = new ProgressBar(250, 10, 100, 10);
progressBar.setValue(50);
this.add(progressBar);
{
RadioButtonGroup radioButtonGroup = new RadioButtonGroup();
RadioButton radioButton1 = new RadioButton(250, 30, 100, 20);
RadioButton radioButton2 = new RadioButton(250, 60, 100, 20);
radioButton1.setChecked(true);
radioButton2.setChecked(false);
radioButton1.setRadioButtonGroup(radioButtonGroup);
radioButton2.setRadioButtonGroup(radioButtonGroup);
this.add(radioButton1);
this.add(radioButton2);
}
Slider slider1 = new Slider(250, 90, 100, 20, 30);
this.add(slider1);
Slider slider2 = new Slider(220, 90, 20, 100, 50);
slider2.setOrientation(Orientation.VERTICAL);
this.add(slider2);
textInput = new TextInput(250, 130, 100, 30);
textInput.getTextState().setHorizontalAlign(RIGHT);
textInput.getListenerMap().addListener(KeyEvent.class, (KeyEventListener) event -> {
if (event.getKey() == GLFW.GLFW_KEY_F1 && event.getAction() == GLFW.GLFW_RELEASE) {
textInput.getTextState().setHorizontalAlign(LEFT);
} else if (event.getKey() == GLFW.GLFW_KEY_F2 && event.getAction() == GLFW.GLFW_RELEASE) {
textInput.getTextState().setHorizontalAlign(CENTER);
} else if (event.getKey() == GLFW.GLFW_KEY_F3 && event.getAction() == GLFW.GLFW_RELEASE) {
textInput.getTextState().setHorizontalAlign(RIGHT);
}
});
this.add(textInput);
Widget widget = new Widget("Hello widget", 250, 170, 100, 100);
widget.setTitleHeight(20);
widget.getTitleContainer().getStyle().getBackground().setColor(ColorConstants.lightGreen());
widget.getTitleTextState().setTextColor(ColorConstants.black());
Widget inner = new Widget();
inner.setResizable(false);
inner.getStyle().setPosition(PositionType.RELATIVE);
inner.getStyle().getFlexStyle().setFlexGrow(1);
inner.getStyle().setMargin(10f);
inner.getContainer().getStyle().getBackground().setColor(ColorConstants.lightGreen());
widget.getContainer().getStyle().setDisplay(DisplayType.FLEX);
widget.getContainer().add(inner);
this.add(widget);
Button turnWidVisible = new Button("", 360, 280, 20, 20);
turnWidVisible.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> {
if (CLICK == (event.getAction())) {
widget.show();
}
});
Icon bgIm = new ImageIcon(new BufferedImage("org/liquidengine/legui/demo/1.png"));
bgIm.setSize(new Vector2f(20, 20));
turnWidVisible.getStyle().getBackground().setIcon(bgIm);
Icon hbgIm = new ImageIcon(new BufferedImage("org/liquidengine/legui/demo/2.png"));
hbgIm.setSize(new Vector2f(20, 20));
// turnWidVisible.setHoveredBackgroundIcon(hbgIm);
Icon pbIm = new ImageIcon(new BufferedImage("org/liquidengine/legui/demo/3.png"));
pbIm.setSize(new Vector2f(20, 20));
// turnWidVisible.setPressedBackgroundIcon(pbIm);
this.add(turnWidVisible);
Widget widget2 = new Widget("Hello 2 widget", 250, 310, 100, 100);
widget2.setTitleHeight(20);
widget2.setCloseButtonColor(ColorConstants.white());
widget2.getCloseButton().getStyle().getBackground().setColor(ColorConstants.black());
widget2.getTitleContainer().getStyle().getBackground().setColor(ColorConstants.lightGreen());
widget2.getTitleTextState().setTextColor(ColorConstants.black());
widget2.setDraggable(false);
widget2.setMinimizable(true);
Button turnDraggable = new Button("Draggable", 10, 10, 80, 20);
turnDraggable.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> {
if (event.getAction() == CLICK) {
Dialog dialog = new Dialog("Question:", 300, 100);
Label questionLabel = new Label("Are you sure want to turn " + (widget2.isDraggable() ? "off" : "on") + "this widget draggable?", 10, 10, 200,
20);
Button yesButton = new Button("Yes", 10, 50, 50, 20);
Button noButton = new Button("No", 70, 50, 50, 20);
yesButton.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) e -> {
if (CLICK == e.getAction()) {
widget2.setDraggable(!widget2.isDraggable());
dialog.close();
}
});
noButton.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) e -> {
if (CLICK == e.getAction()) {
dialog.close();
}
});
dialog.getContainer().add(questionLabel);
dialog.getContainer().add(yesButton);
dialog.getContainer().add(noButton);
dialog.show(event.getFrame());
}
});
widget2.getContainer().add(turnDraggable);
this.add(widget2);
Button turnWidVisible2 = new Button("", 360, 310, 20, 20);
turnWidVisible2.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> {
if (CLICK == event.getAction()) {
widget2.show();
}
});
this.add(turnWidVisible2);
Widget widget3 = new Widget("Hello 2 widget", 250, 420, 100, 100);
widget3.setTitleHeight(20);
widget3.setTitleEnabled(false);
widget3.getTitleContainer().getStyle().getBackground().setColor(ColorConstants.lightGreen());
widget3.setCloseable(false);
widget3.setMinimizable(true);
widget3.getTitleTextState().setTextColor(ColorConstants.black());
this.add(widget3);
Button turnWidVisible3 = new Button("", 360, 340, 20, 20);
turnWidVisible3.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> {
if (CLICK == event.getAction()) {
widget3.show();
}
});
this.add(turnWidVisible3);
widget3.getContainer().add(new Panel(5, 5, 20, 20));
widget3.getContainer().add(new Panel(30, 5, 20, 20));
widget3.getContainer().add(new Panel(30, 30, 20, 20));
widget3.getContainer().add(new Panel(5, 30, 20, 20));
Button b = new Button(55, 5, 40, 20);
b.getTextState().setFont(FontRegistry.MATERIAL_ICONS_REGULAR);
b.getTextState().setVerticalAlign(MIDDLE);
b.getTextState().setHorizontalAlign(CENTER);
b.getTextState().setFontSize(20);
String up = TextUtil.cpToStr(0xE5D8);
String down = TextUtil.cpToStr(0xE5DB);
b.getTextState().setText(down);
b.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> {
if (event.getAction() == CLICK) {
widget3.setTitleEnabled(!widget3.isTitleEnabled());
b.getTextState().setText(widget3.isTitleEnabled() ? up : down);
// widget3.setResizable(!widget3.isResizable());
}
});
widget3.getContainer().add(b);
Button b2 = new Button(55, 30, 40, 20);
b2.getTextState().setVerticalAlign(MIDDLE);
b2.getTextState().setHorizontalAlign(CENTER);
b2.getTextState().setFontSize(20);
String up2 = "-";
String down2 = "+";
b2.getTextState().setText(down2);
b2.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> {
if (event.getAction() == CLICK) {
widget3.setCloseable(!widget3.isCloseable());
b2.getTextState().setText(widget3.isCloseable() ? up2 : down2);
}
});
widget3.getContainer().add(b2);
widget3.getStyle().setMinWidth(100f);
widget3.getStyle().setMinHeight(50f);
widget3.getStyle().setMaxWidth(400f);
widget3.getStyle().setMaxHeight(150f);
ScrollBar scrollBar1 = new ScrollBar(360, 170, 20, 100, 20);
scrollBar1.setOrientation(Orientation.VERTICAL);
scrollBar1.setVisibleAmount(20);
scrollBar1.setArrowsEnabled(true);
scrollBar1.getStyle().getBackground().setColor(ColorConstants.white());
scrollBar1.setScrollColor(ColorConstants.darkGray());
scrollBar1.setArrowColor(ColorConstants.darkGray());
scrollBar1.getStyle().setBorder(new SimpleLineBorder(ColorConstants.red(), 1));
this.add(scrollBar1);
ScrollBar scrollBar11 = new ScrollBar(385, 170, 7, 100, 20);
scrollBar11.setOrientation(Orientation.VERTICAL);
scrollBar11.setVisibleAmount(20);
scrollBar11.setArrowsEnabled(false);
scrollBar11.getStyle().getBackground().setColor(ColorConstants.white());
scrollBar11.setScrollColor(ColorConstants.darkGray());
scrollBar11.getStyle().setBorder(new SimpleLineBorder(ColorConstants.darkGray(), 1));
scrollBar11.getStyle().setBorderRadius(null);
this.add(scrollBar11);
ScrollBar scrollBar2 = new ScrollBar(250, 280, 100, 20, 20);
scrollBar2.setOrientation(Orientation.HORIZONTAL);
scrollBar2.setVisibleAmount(20);
scrollBar2.setArrowsEnabled(true);
scrollBar2.getStyle().setBorder(new SimpleLineBorder(ColorConstants.black(), 1));
scrollBar2.getStyle().getBackground().setColor(ColorConstants.darkGray());
scrollBar2.setScrollColor(ColorConstants.white());
scrollBar2.setArrowColor(ColorConstants.white());
this.add(scrollBar2);
Panel panel1 = new Panel(420, 170, 100, 100);
panel1.getStyle().getBackground().setColor(ColorConstants.blue());
this.add(panel1);
Panel panel2 = new Panel(470, 170, 100, 100);
panel2.getStyle().getBackground().setColor(ColorConstants.green());
this.add(panel2);
createButtonWithTooltip().getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> {
MouseClickEvent.MouseClickAction action = event.getAction();
if (CLICK == action) {
mouseTargetLabel.getStyle().setDisplay(mouseTargetLabel.isVisible() ? Style.DisplayType.NONE : Style.DisplayType.MANUAL);
}
if (RELEASE == action) {
System.out.println("RELEASE");
}
if (PRESS == action) {
System.out.println("PRESS");
}
});
ScrollablePanel scrollablePanel = new ScrollablePanel(420, 10, 250, 150);
scrollablePanel.getStyle().getBackground().setColor(1, 1, 1, 1);
scrollablePanel.getContainer().setSize(300, 200);
ScrollablePanel scp = new ScrollablePanel(10, 10, 150, 100);
scp.getContainer().setSize(300, 300);
scp.getContainer().add(new TextInput("Hello Scrollable", 10, 10, 150, 20));
scrollablePanel.getContainer().add(scp);
this.add(scrollablePanel);
slider2.getListenerMap().addListener(SliderChangeValueEvent.class, (SliderChangeValueEventListener) event -> {
scrollablePanel.setHorizontalScrollBarHeight(event.getNewValue() / 2f + 10);
});
slider1.getListenerMap().addListener(SliderChangeValueEvent.class, (SliderChangeValueEventListener) event -> {
scrollablePanel.getHorizontalScrollBar().setArrowSize(event.getNewValue() / 4f + 10);
});
textArea = new TextArea(420, 280, 150, 100);
textArea.getTextState().setText("ABC DEF GH\r\nI JKL MNO PQR\nSTU VWXYZ");
textArea.setCaretPosition(12);
textArea.getTextState().setHorizontalAlign(CENTER);
textArea.getTextState().setVerticalAlign(BOTTOM);
this.add(textArea);
textArea.getTextAreaField().getListenerMap().addListener(KeyEvent.class, (KeyEventListener) event -> {
if (event.getKey() == GLFW.GLFW_KEY_F1 && event.getAction() == GLFW.GLFW_RELEASE) {
textArea.getTextState().setHorizontalAlign(LEFT);
} else if (event.getKey() == GLFW.GLFW_KEY_F2 && event.getAction() == GLFW.GLFW_RELEASE) {
textArea.getTextState().setHorizontalAlign(CENTER);
} else if (event.getKey() == GLFW.GLFW_KEY_F3 && event.getAction() == GLFW.GLFW_RELEASE) {
textArea.getTextState().setHorizontalAlign(RIGHT);
} else if (event.getKey() == GLFW.GLFW_KEY_F5 && event.getAction() == GLFW.GLFW_RELEASE) {
textArea.getTextState().setVerticalAlign(TOP);
} else if (event.getKey() == GLFW.GLFW_KEY_F6 && event.getAction() == GLFW.GLFW_RELEASE) {
textArea.getTextState().setVerticalAlign(MIDDLE);
} else if (event.getKey() == GLFW.GLFW_KEY_F7 && event.getAction() == GLFW.GLFW_RELEASE) {
textArea.getTextState().setVerticalAlign(BOTTOM);
} else if (event.getKey() == GLFW.GLFW_KEY_F8 && event.getAction() == GLFW.GLFW_RELEASE) {
textArea.getTextState().setVerticalAlign(BASELINE);
}
});
Label passLabel = new Label("Password:", 420, 390, 150, 15);
this.add(passLabel);
PasswordInput caretp = new PasswordInput(420, 405, 150, 20);
caretp.getTextState().setHorizontalAlign(CENTER);
this.add(caretp);
TextInput inpur = new TextInput(420, 430, 50, 35);
inpur.getTextState().setText("00");
inpur.getTextState().setFontSize(35);
inpur.getTextState().setHorizontalAlign(CENTER);
inpur.getTextState().setVerticalAlign(MIDDLE);
inpur.getStyle().getBackground().setColor(ColorConstants.white());
this.add(inpur);
SelectBox selectBox = new SelectBox(20, 260, 100, 20);
selectBox.addElement("Just");
selectBox.addElement("Hello");
selectBox.addElement("World");
final int[] i = {1};
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.addElement("World" + i[0]++);
selectBox.setVisibleCount(5);
selectBox.setElementHeight(20);
this.add(selectBox);
Button sbb = new Button("Add element", 130, 260, 70, 20);
sbb.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> {
if (event.getAction() == CLICK) {
selectBox.addElement("WorlD " + i[0]++);
}
});
this.add(sbb);
this.add(createToggleButtonWithLongTooltip());
//@formatter:on
this.add(createSwitchThemeButton());
this.add(createShadowWidget());
}
private Widget createImageWrapperWidgetWithImage() {
Widget imageWrapper = new Widget(20, 30, 100, 100);
imageWrapper.setTitleEnabled(true);
imageView = new ImageView(new BufferedImage("org/liquidengine/legui/demo/1.jpg"));
imageView.setPosition(15, 5);
imageView.setSize(70, 70);
imageView.getStyle().setBorderRadius(10f);
imageWrapper.getContainer().add(imageView);
imageWrapper.setCloseable(false);
return imageWrapper;
}
private Button createButtonWithTooltip() {
Button button = new Button(20, 170, 50, 20); /*button.getStyle().getBackground().setColor(new Vector4f(1));*/
button.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) System.out::println);
button.setTooltip(new Tooltip("Just button"));
button.getTooltip().setPosition(0, 25);
button.getTooltip().getSize().set(50, 60);
button.getTooltip().getStyle().setPadding(4f);
int idv[] = {0};
button.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) (MouseClickEvent event) -> {
if (event.getAction().equals(CLICK)) {
idv[0]++;
HorizontalAlign h;
VerticalAlign v;
int hh = idv[0] % 3;
int vv = (idv[0] / 3) % 3;
switch (hh) {
case 0:
h = LEFT;
break;
case 1:
h = CENTER;
break;
case 2:
default:
h = RIGHT;
break;
}
switch (vv) {
case 0:
v = TOP;
break;
case 1:
v = MIDDLE;
break;
case 2:
default:
v = BOTTOM;
break;
}
System.out.println(h + " " + v);
button.getTooltip().getTextState().setHorizontalAlign(h);
button.getTooltip().getTextState().setVerticalAlign(v);
}
});
return button;
}
private CheckBox createCheckboxWithAnimation(CheckBox checkBox1) {
CheckBox checkBox2 = new CheckBox(20, 230, 50, 20);
checkBox2.getStyle().getBackground().setColor(new Vector4f(1, 0, 0, 1));
checkBox2.setChecked(true);
checkBox2.getListenerMap().addListener(CursorEnterEvent.class, (CursorEnterEventListener) event -> {
boolean entered = event.isEntered();
Vector4f newColor = ColorConstants.green();
if (entered) {
createColorAnimationOnHover(event.getTargetComponent(), newColor, checkBox2).startAnimation();
}
});
checkBox2.getListenerMap().addListener(CursorEnterEvent.class, (CursorEnterEventListener) event -> {
boolean entered = event.isEntered();
Vector4f newColor = ColorConstants.red();
if (entered) {
createColorAnimationOnHover(event.getTargetComponent(), newColor, checkBox1).startAnimation();
}
});
return checkBox2;
}
private ToggleButton createToggleButtonWithLongTooltip() {
ToggleButton toggleButton = new ToggleButton("", 100, 170, 40, 20);
Icon bgImageNormal = new ImageIcon(new BufferedImage("org/liquidengine/legui/demo/toggle.png"));
toggleButton.getListenerMap().addListener(CursorEnterEvent.class, (CursorEnterEventListener) System.out::println);
toggleButton.setTooltip(new Tooltip("Just toggle button with long tooltipText text"));
toggleButton.getListenerMap().addListener(CursorEnterEvent.class, (CursorEnterEventListener) event -> {
if (event.isEntered()) {
getColorAnimation(toggleButton, ColorConstants.blue()).startAnimation();
} else {
getColorAnimation(toggleButton, ColorConstants.red()).startAnimation();
}
});
toggleButton.getListenerMap().addListener(MouseClickEvent.class,
(MouseClickEventListener) event -> getSlideImageOnClick(toggleButton, bgImageNormal).startAnimation());
toggleButton.getTooltip().setPosition(45, 0);
toggleButton.getTooltip().getSize().set(140, 40);
toggleButton.getTooltip().getStyle().getBackground().setColor(ColorConstants.darkGray());
toggleButton.getTooltip().getTextState().setTextColor(ColorConstants.white());
toggleButton.getTooltip().getStyle().setPadding(4f);
int id[] = {0};
toggleButton.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> {
if (event.getAction().equals(CLICK)) {
id[0]++;
HorizontalAlign h = LEFT;
VerticalAlign v = TOP;
int hh = id[0] % 3;
int vv = (id[0] / 3) % 3;
switch (hh) {
case 0:
h = LEFT;
break;
case 1:
h = CENTER;
break;
case 2:
h = RIGHT;
break;
}
switch (vv) {
case 0:
v = TOP;
break;
case 1:
v = MIDDLE;
break;
case 2:
v = BOTTOM;
break;
}
System.out.println(h + " " + v);
toggleButton.getTooltip().getTextState().setHorizontalAlign(h);
toggleButton.getTooltip().getTextState().setVerticalAlign(v);
}
});
bgImageNormal.setSize(new Vector2f(100 * 40 / 60, 20));
bgImageNormal.setPosition(new Vector2f(40 - 100 * 40 / 60, 0));
toggleButton.getStyle().getBackground().setIcon(bgImageNormal);
return toggleButton;
}
private Button createSwitchThemeButton() {
final Theme[] current = {Themes.getDefaultTheme()};
final Theme[] list = { Themes.FLAT_DARK, Themes.FLAT_PETERRIVER,Themes.FLAT_PETERRIVER_DARK, Themes.FLAT_WHITE };
final int[] themeIndex = {0};
String text = "Switch theme ";
Button switchTheme = new Button(text, 600, 400, 120, 30);
switchTheme.getListenerMap().addListener(MouseClickEvent.class, switchThemeClickListener(current, list, themeIndex, switchTheme));
return switchTheme;
}
private Widget createShadowWidget() {
Widget shadowWidget = new Widget(20, 310, 200, 120);
shadowWidget.getTitleTextState().setText("Shadow test widget");
shadowWidget.setCloseable(false);
shadowWidget.setResizable(false);
shadowWidget.getStyle().setShadow(new Shadow());
shadowWidget.getStyle().getShadow().setColor(ColorConstants.red());
Slider hOffsetSlider = new Slider(110, 5 + 20 * 0, 80, 10);
shadowWidget.getContainer().add(hOffsetSlider);
hOffsetSlider.setValue(50f);
hOffsetSlider.addSliderChangeValueEventListener((e)-> {shadowWidget.getStyle().getShadow().sethOffset(hOffsetSlider.getValue() - 50f);});
Label hOffsetLabel = new Label(10, 5 + 20 * 0, 90, 10);
hOffsetLabel.getTextState().setText("HOffset: ");
shadowWidget.getContainer().add(hOffsetLabel);
Slider vOffsetSlider = new Slider(110, 5 + 20 * 1, 80, 10);
shadowWidget.getContainer().add(vOffsetSlider);
vOffsetSlider.setValue(50f);
vOffsetSlider.addSliderChangeValueEventListener((e)-> {shadowWidget.getStyle().getShadow().setvOffset(vOffsetSlider.getValue() - 50f);});
Label vOffsetLabel = new Label(10, 5 + 20 * 1, 90, 10);
vOffsetLabel.getTextState().setText("VOffset: ");
shadowWidget.getContainer().add(vOffsetLabel);
Slider blurSlider = new Slider(110, 5 + 20 * 2, 80, 10);
shadowWidget.getContainer().add(blurSlider);
blurSlider.addSliderChangeValueEventListener((e)-> {shadowWidget.getStyle().getShadow().setBlur(blurSlider.getValue());});
Label blurLabel = new Label(10, 5 + 20 * 2, 90, 10);
blurLabel.getTextState().setText("Blur: ");
shadowWidget.getContainer().add(blurLabel);
Slider spreadSlider = new Slider(110, 5 + 20 * 3, 80, 10);
shadowWidget.getContainer().add(spreadSlider);
spreadSlider.setValue(50f);
spreadSlider.addSliderChangeValueEventListener((e)-> {shadowWidget.getStyle().getShadow().setSpread(spreadSlider.getValue() - 50f);});
Label spreadLabel = new Label(10, 5 + 20 * 3, 90, 10);
spreadLabel.getTextState().setText("Spread: ");
shadowWidget.getContainer().add(spreadLabel);
Slider transparencySlider = new Slider(110, 5 + 20 * 4, 80, 10);
shadowWidget.getContainer().add(transparencySlider);
transparencySlider.addSliderChangeValueEventListener((e)-> {
shadowWidget.getStyle().getBackground().getColor().w = 1- transparencySlider.getValue() / 100f;
shadowWidget.getContainer().getStyle().getBackground().getColor().w =1- transparencySlider.getValue() / 100f;
});
Label transparencyLabel = new Label(10, 5 + 20 * 4, 90, 10);
transparencyLabel.getTextState().setText("W Transparency: ");
shadowWidget.getContainer().add(transparencyLabel);
return shadowWidget;
}
private Animation createColorAnimationOnHover(Component component, Vector4f newColor, Component targetComponent) {
return new Animation() {
private Vector4f initialColor;
private Vector4f colorRange;
private double time;
@Override
protected void beforeAnimation() {
initialColor = new Vector4f(targetComponent.getStyle().getBackground().getColor());
colorRange = newColor.sub(initialColor);
}
@Override
protected boolean animate(double delta) {
time += delta;
targetComponent.getStyle().getBackground().getColor().set(new Vector4f(initialColor)
.add(new Vector4f(colorRange)
.mul((float) Math.abs(Math.sin(time * 2)))));
return !component.isHovered();
}
@Override
protected void afterAnimation() {
targetComponent.getStyle().getBackground().getColor().set(initialColor);
}
};
}
private MouseClickEventListener switchThemeClickListener(Theme[] current, Theme[] list, int[] index, Button switchTheme) {
return event -> {
if (event.getAction().equals(CLICK) && event.getButton().equals(MOUSE_BUTTON_LEFT)) {
Theme curr = current[0];
if(index[0] < list.length && index[0]>-1) {
curr = list[index[0]];
index[0] = (index[0] + 1) % list.length;
} else {
index[0] = 0;
curr = list[0];
}
Themes.setDefaultTheme(curr);
Themes.getDefaultTheme().applyAll(event.getFrame());
}
};
}
private Animation getSlideImageOnClick(ToggleButton toggleButton, Icon bgImageNormal) {
return new Animation() {
private float initialPosition;
private double time;
private double spentTime;
private float endPosition;
@Override
protected void beforeAnimation() {
time = 0.5d;
spentTime = 0;
initialPosition = bgImageNormal.getPosition().x;
if (toggleButton.isToggled()) {
endPosition = 0;
} else {
endPosition = toggleButton.getSize().x - bgImageNormal.getSize().x;
}
}
@Override
protected boolean animate(double delta) {
spentTime += delta;
float percentage = (float) (spentTime / time);
bgImageNormal.getPosition().x = initialPosition + (endPosition - initialPosition) * percentage;
return spentTime >= time;
}
@Override
protected void afterAnimation() {
bgImageNormal.getPosition().x = endPosition;
}
};
}
private Animation getColorAnimation(ToggleButton toggleButton, Vector4f targetColor) {
return new Animation() {
private Vector4f baseColor;
private Vector4f endColor;
private Vector4f colorVector;
private double time;
private double spentTime;
@Override
protected void beforeAnimation() {
time = 1.5d;
spentTime = 0;
baseColor = new Vector4f(toggleButton.getStyle().getBackground().getColor());
endColor = targetColor;
colorVector = new Vector4f(endColor).sub(baseColor);
}
@Override
protected boolean animate(double delta) {
spentTime += delta;
float percentage = (float) (spentTime / time);
Vector4f newColor = new Vector4f(baseColor).add(new Vector4f(colorVector).mul(percentage));
toggleButton.getStyle().getBackground().setColor(newColor);
return spentTime >= time;
}
@Override
protected void afterAnimation() {
toggleButton.getStyle().getBackground().setColor(endColor);
}
};
}
public TextArea getTextArea() {
return textArea;
}
public ImageView getImageView() {
return imageView;
}
public void setImageView(ImageView imageView) {
this.imageView = imageView;
}
public Label getMouseTargetLabel() {
return mouseTargetLabel;
}
public Label getMouseLabel() {
return mouseLabel;
}
public Label getUpsLabel() {
return upsLabel;
}
public Label getFocusedGuiLabel() {
return focusedGuiLabel;
}
public TextInput getTextInput() {
return textInput;
}
public Label getDebugLabel() {
return debugLabel;
}
}
|
package org.mybatis.jpetstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
public class Calculate implements Serializable {
public void hello()
{
System.out.println("Hello World");
System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016");
System.out.println("Fri Dec 2 12:52:58 UTC 2016");
}
}
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
|
package org.mybatis.jpetstore.domain;
import java.io.Serializable;
import java.math.BigDecimal;
public class Calculate implements Serializable {
public void hello()
{
System.out.println("JPET Store Application");
System.out.println("Class name: Calculate.java");
System.out.println("Hello World");
System.out.println("Making a new Entry at Sat Oct 28 11:00:00 UTC 2017");
System.out.println("Sat Oct 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Oct 26 11:00:00 UTC 2017");
System.out.println("Thu Oct 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Oct 24 11:00:00 UTC 2017");
System.out.println("Tue Oct 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Oct 22 11:00:00 UTC 2017");
System.out.println("Sun Oct 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Oct 20 11:00:00 UTC 2017");
System.out.println("Fri Oct 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Oct 18 11:00:00 UTC 2017");
System.out.println("Wed Oct 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Oct 16 11:00:00 UTC 2017");
System.out.println("Mon Oct 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Oct 14 11:00:00 UTC 2017");
System.out.println("Sat Oct 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Oct 12 11:00:00 UTC 2017");
System.out.println("Thu Oct 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Oct 10 11:00:00 UTC 2017");
System.out.println("Tue Oct 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Oct 8 11:00:00 UTC 2017");
System.out.println("Sun Oct 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Oct 6 11:00:00 UTC 2017");
System.out.println("Fri Oct 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Oct 4 11:00:00 UTC 2017");
System.out.println("Wed Oct 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Oct 2 11:00:00 UTC 2017");
System.out.println("Mon Oct 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Sep 30 11:00:00 UTC 2017");
System.out.println("Sat Sep 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Sep 28 11:00:00 UTC 2017");
System.out.println("Thu Sep 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Sep 26 11:00:00 UTC 2017");
System.out.println("Tue Sep 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Sep 24 11:00:00 UTC 2017");
System.out.println("Sun Sep 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Sep 22 11:00:00 UTC 2017");
System.out.println("Fri Sep 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Sep 20 11:00:00 UTC 2017");
System.out.println("Wed Sep 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Sep 18 11:00:00 UTC 2017");
System.out.println("Mon Sep 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Sep 16 11:00:00 UTC 2017");
System.out.println("Sat Sep 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Sep 14 11:00:00 UTC 2017");
System.out.println("Thu Sep 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Sep 12 11:00:00 UTC 2017");
System.out.println("Tue Sep 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Sep 10 11:00:00 UTC 2017");
System.out.println("Sun Sep 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Sep 8 11:00:00 UTC 2017");
System.out.println("Fri Sep 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Sep 6 11:00:00 UTC 2017");
System.out.println("Wed Sep 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Sep 4 11:00:00 UTC 2017");
System.out.println("Mon Sep 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Sep 2 11:00:00 UTC 2017");
System.out.println("Sat Sep 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Aug 30 11:00:00 UTC 2017");
System.out.println("Wed Aug 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Aug 28 11:00:00 UTC 2017");
System.out.println("Mon Aug 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Aug 26 11:00:00 UTC 2017");
System.out.println("Sat Aug 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Aug 24 11:00:00 UTC 2017");
System.out.println("Thu Aug 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Aug 22 11:00:00 UTC 2017");
System.out.println("Tue Aug 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Aug 20 11:00:00 UTC 2017");
System.out.println("Sun Aug 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Aug 18 11:00:00 UTC 2017");
System.out.println("Fri Aug 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Aug 16 11:00:00 UTC 2017");
System.out.println("Wed Aug 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Aug 14 11:00:00 UTC 2017");
System.out.println("Mon Aug 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Aug 12 11:00:00 UTC 2017");
System.out.println("Sat Aug 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Aug 10 11:00:00 UTC 2017");
System.out.println("Thu Aug 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Aug 8 11:00:00 UTC 2017");
System.out.println("Tue Aug 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Aug 6 11:00:00 UTC 2017");
System.out.println("Sun Aug 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Aug 4 11:00:00 UTC 2017");
System.out.println("Fri Aug 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Aug 2 11:00:00 UTC 2017");
System.out.println("Wed Aug 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Jul 30 11:00:00 UTC 2017");
System.out.println("Sun Jul 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Jul 28 11:00:00 UTC 2017");
System.out.println("Fri Jul 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Jul 26 11:00:00 UTC 2017");
System.out.println("Wed Jul 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jul 24 11:00:00 UTC 2017");
System.out.println("Mon Jul 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jul 22 11:00:00 UTC 2017");
System.out.println("Sat Jul 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Jul 20 11:00:00 UTC 2017");
System.out.println("Thu Jul 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Jul 18 11:00:00 UTC 2017");
System.out.println("Tue Jul 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Jul 16 11:00:00 UTC 2017");
System.out.println("Sun Jul 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Jul 14 11:00:00 UTC 2017");
System.out.println("Fri Jul 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Jul 12 11:00:00 UTC 2017");
System.out.println("Wed Jul 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jul 10 11:00:00 UTC 2017");
System.out.println("Mon Jul 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jul 8 11:00:00 UTC 2017");
System.out.println("Sat Jul 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Jul 6 11:00:00 UTC 2017");
System.out.println("Thu Jul 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Jul 4 11:00:00 UTC 2017");
System.out.println("Tue Jul 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Jul 2 11:00:00 UTC 2017");
System.out.println("Sun Jul 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Jun 30 11:00:00 UTC 2017");
System.out.println("Fri Jun 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Jun 28 11:00:00 UTC 2017");
System.out.println("Wed Jun 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jun 26 11:00:00 UTC 2017");
System.out.println("Mon Jun 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jun 24 11:00:00 UTC 2017");
System.out.println("Sat Jun 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Jun 22 11:00:00 UTC 2017");
System.out.println("Thu Jun 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Jun 20 11:00:00 UTC 2017");
System.out.println("Tue Jun 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Jun 18 11:00:00 UTC 2017");
System.out.println("Sun Jun 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Jun 16 11:00:00 UTC 2017");
System.out.println("Fri Jun 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Jun 14 11:00:00 UTC 2017");
System.out.println("Wed Jun 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jun 12 11:00:00 UTC 2017");
System.out.println("Mon Jun 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jun 10 11:00:00 UTC 2017");
System.out.println("Sat Jun 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Jun 8 11:00:00 UTC 2017");
System.out.println("Thu Jun 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Jun 6 11:00:00 UTC 2017");
System.out.println("Tue Jun 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Jun 4 11:00:00 UTC 2017");
System.out.println("Sun Jun 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Jun 2 11:00:00 UTC 2017");
System.out.println("Fri Jun 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue May 30 11:00:00 UTC 2017");
System.out.println("Tue May 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun May 28 11:00:00 UTC 2017");
System.out.println("Sun May 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri May 26 11:00:00 UTC 2017");
System.out.println("Fri May 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed May 24 11:00:00 UTC 2017");
System.out.println("Wed May 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon May 22 11:00:00 UTC 2017");
System.out.println("Mon May 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat May 20 11:00:00 UTC 2017");
System.out.println("Sat May 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu May 18 11:00:00 UTC 2017");
System.out.println("Thu May 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue May 16 11:00:00 UTC 2017");
System.out.println("Tue May 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun May 14 11:00:00 UTC 2017");
System.out.println("Sun May 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri May 12 11:00:00 UTC 2017");
System.out.println("Fri May 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed May 10 11:00:00 UTC 2017");
System.out.println("Wed May 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon May 8 11:00:00 UTC 2017");
System.out.println("Mon May 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat May 6 11:00:00 UTC 2017");
System.out.println("Sat May 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu May 4 11:00:00 UTC 2017");
System.out.println("Thu May 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue May 2 11:00:00 UTC 2017");
System.out.println("Tue May 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Apr 30 11:00:00 UTC 2017");
System.out.println("Sun Apr 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Apr 28 11:00:00 UTC 2017");
System.out.println("Fri Apr 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Apr 26 11:00:00 UTC 2017");
System.out.println("Wed Apr 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Apr 24 11:00:00 UTC 2017");
System.out.println("Mon Apr 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Apr 22 11:00:00 UTC 2017");
System.out.println("Sat Apr 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Apr 20 11:00:00 UTC 2017");
System.out.println("Thu Apr 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Apr 18 11:00:00 UTC 2017");
System.out.println("Tue Apr 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Apr 16 11:00:00 UTC 2017");
System.out.println("Sun Apr 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Apr 14 11:00:00 UTC 2017");
System.out.println("Fri Apr 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Apr 12 11:00:00 UTC 2017");
System.out.println("Wed Apr 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Apr 10 11:00:00 UTC 2017");
System.out.println("Mon Apr 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Apr 8 11:00:00 UTC 2017");
System.out.println("Sat Apr 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Apr 6 11:00:00 UTC 2017");
System.out.println("Thu Apr 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Apr 4 11:00:00 UTC 2017");
System.out.println("Tue Apr 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Apr 2 11:00:00 UTC 2017");
System.out.println("Sun Apr 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Mar 30 11:00:00 UTC 2017");
System.out.println("Thu Mar 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Mar 28 11:00:00 UTC 2017");
System.out.println("Tue Mar 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Mar 26 11:00:00 UTC 2017");
System.out.println("Sun Mar 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Mar 24 11:00:00 UTC 2017");
System.out.println("Fri Mar 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Mar 22 11:00:00 UTC 2017");
System.out.println("Wed Mar 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Mar 20 11:00:00 UTC 2017");
System.out.println("Mon Mar 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Mar 18 11:00:00 UTC 2017");
System.out.println("Sat Mar 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Mar 16 11:00:00 UTC 2017");
System.out.println("Thu Mar 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Mar 14 11:00:00 UTC 2017");
System.out.println("Tue Mar 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Mar 12 11:00:00 UTC 2017");
System.out.println("Sun Mar 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Mar 10 11:00:00 UTC 2017");
System.out.println("Fri Mar 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Mar 8 11:00:00 UTC 2017");
System.out.println("Wed Mar 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Mar 6 11:00:00 UTC 2017");
System.out.println("Mon Mar 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Mar 4 11:00:00 UTC 2017");
System.out.println("Sat Mar 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Mar 2 11:00:00 UTC 2017");
System.out.println("Thu Mar 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Feb 28 11:00:00 UTC 2017");
System.out.println("Tue Feb 28 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Feb 26 11:00:00 UTC 2017");
System.out.println("Sun Feb 26 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Feb 24 11:00:00 UTC 2017");
System.out.println("Fri Feb 24 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Feb 22 11:00:00 UTC 2017");
System.out.println("Wed Feb 22 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Feb 20 11:00:00 UTC 2017");
System.out.println("Mon Feb 20 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Feb 18 11:00:00 UTC 2017");
System.out.println("Sat Feb 18 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Feb 16 11:00:00 UTC 2017");
System.out.println("Thu Feb 16 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Tue Feb 14 11:00:00 UTC 2017");
System.out.println("Tue Feb 14 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sun Feb 12 11:00:00 UTC 2017");
System.out.println("Sun Feb 12 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Fri Feb 10 11:00:00 UTC 2017");
System.out.println("Fri Feb 10 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Wed Feb 8 11:00:00 UTC 2017");
System.out.println("Wed Feb 8 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Feb 6 11:00:00 UTC 2017");
System.out.println("Mon Feb 6 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Feb 4 11:00:00 UTC 2017");
System.out.println("Sat Feb 4 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Thu Feb 2 11:00:00 UTC 2017");
System.out.println("Thu Feb 2 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 30 11:00:00 UTC 2017");
System.out.println("Mon Jan 30 11:00:00 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 28 11:00:15 UTC 2017");
System.out.println("Sat Jan 28 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 26 11:00:15 UTC 2017");
System.out.println("Thu Jan 26 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 24 11:00:15 UTC 2017");
System.out.println("Tue Jan 24 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Sun Jan 22 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Fri Jan 20 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Wed Jan 18 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Mon Jan 16 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Sat Jan 14 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Thu Jan 12 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Tue Jan 10 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Sun Jan 8 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Fri Jan 6 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Wed Jan 4 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Mon Jan 2 11:00:15 UTC 2017");
System.out.println("Making a new Entry at Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Fri Dec 30 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Wed Dec 28 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Mon Dec 26 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Sat Dec 24 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Thu Dec 22 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Tue Dec 20 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Sun Dec 18 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Fri Dec 16 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Wed Dec 14 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Mon Dec 12 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Sat Dec 10 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Thu Dec 8 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Tue Dec 6 11:00:16 UTC 2016");
System.out.println("Making a new Entry at Fri Dec 2 12:52:58 UTC 2016");
System.out.println("Fri Dec 2 12:52:58 UTC 2016");
}
}
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
//Description: Adding coments for documentation
//Project: JpetStore
//Tools used: Jenkins, SonarQube, Rundeck
|
package org.neo4j.driver.projection;
import org.neo4j.driver.exception.Neo4jClientException;
import org.neo4j.driver.v1.Record;
import java.util.function.Function;
/**
* Abstract class for projection.
* A projection is just a function that can be passed to a map.
*/
abstract class Projection<T> implements Function<Record, T> {
/**
* Projection's type.
*/
protected Class type;
/**
* Default constructor.
*
* @param type
*/
public Projection(Class type) {
this.type = type;
}
/**
* Check if the given <code>record</code> has only one column.
* if not, a {@link Neo4jClientException} is throw.
*
* @param record
*/
protected void checkIfRecordHaveSingleValue(Record record) {
if (record.size() > 1) {
throw new Neo4jClientException("Record doesn't have a single column -> can't cast it to primitive object type");
}
}
}
|
package pl.domzal.junit.docker.rule;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Level;
import org.junit.Rule;
import org.junit.rules.ExternalResource;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerCertificateException;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.DockerClient.LogsParam;
import com.spotify.docker.client.DockerException;
import com.spotify.docker.client.LogStream;
import com.spotify.docker.client.messages.ContainerConfig;
import com.spotify.docker.client.messages.ContainerCreation;
import com.spotify.docker.client.messages.ContainerInfo;
import com.spotify.docker.client.messages.ContainerState;
import com.spotify.docker.client.messages.HostConfig;
import com.spotify.docker.client.messages.NetworkSettings;
import com.spotify.docker.client.messages.PortBinding;
import pl.domzal.junit.wait.WaitForUnit;
import pl.domzal.junit.wait.WaitForUnit.WaitForCondition;
public class DockerRule extends ExternalResource {
private static Logger log = LoggerFactory.getLogger(DockerRule.class);
private static final int STOP_TIMEOUT = 5;
private final DockerClient dockerClient;
private ContainerCreation container;
private final DockerRuleBuiler builder;
private Map<String, List<PortBinding>> containerPorts;
public DockerRule(DockerRuleBuiler builder) {
this.builder = builder;
HostConfig hostConfig = HostConfig.builder()
.portBindings(hostPortBindings(builder.getExposedPorts()))
.extraHosts(builder.getExtraHosts())
.build();
ContainerConfig containerConfig = ContainerConfig.builder()
.hostConfig(hostConfig)
.image(builder.getImageName())
.networkDisabled(false)
//.hostname("bleble:127.0.0.1")
.cmd(builder.getCmd()).build();
try {
dockerClient = DefaultDockerClient.fromEnv().build();
//TODO check if image is available (based of flag in builder ?)
//dockerClient.pull(imageName);
container = dockerClient.createContainer(containerConfig);
log.info("container {} started, id {}", builder.getImageName(), container.id());
} catch (DockerException | InterruptedException | DockerCertificateException e) {
throw new IllegalStateException(e);
}
}
public static DockerRuleBuiler builder() {
return new DockerRuleBuiler();
}
private static Map<String, List<PortBinding>> hostPortBindings(String[] exposedContainerPorts) {
final Map<String, List<PortBinding>> hostPortBindings = new HashMap<String, List<PortBinding>>();
for (String port : exposedContainerPorts) {
List<PortBinding> hostPorts = new ArrayList<PortBinding>();
hostPorts.add(PortBinding.of("0.0.0.0", port + "/tcp"));
hostPortBindings.put(port + "/tcp", hostPorts);
}
return hostPortBindings;
}
@Override
public Statement apply(Statement base, Description description) {
return super.apply(base, description);
}
@Override
protected void before() throws Throwable {
super.before();
dockerClient.startContainer(container.id());
log.debug("{} started", container.id());
ContainerInfo inspectContainer = dockerClient.inspectContainer(container.id());
log.debug("{} inspect", container.id());
containerPorts = inspectContainer.networkSettings().ports();
if (builder.getWaitForMessage()!=null) {
waitForMessage();
}
logMappings(dockerClient);
}
private void waitForMessage() throws TimeoutException, InterruptedException {
final String waitForMessage = builder.getWaitForMessage();
log.info("{} waiting for log message '{}'", container.id(), waitForMessage);
new WaitForUnit(TimeUnit.SECONDS, 30, new WaitForCondition(){
@Override
public boolean isConditionMet() {
return fullLogContent().contains(waitForMessage);
}
@Override
public String timeoutMessage() {
return String.format("Timeout waiting for '%s'", waitForMessage);
}
}).startWaiting();
log.debug("{} message '{}' found", container.id(), waitForMessage);
}
@Override
protected void after() {
super.after();
try {
ContainerState state = dockerClient.inspectContainer(container.id()).state();
log.debug("container state: {}", state);
if (state.running()) {
dockerClient.stopContainer(container.id(), STOP_TIMEOUT);
log.info("{} stopped", container.id());
}
if (!builder.getKeepContainer()) {
dockerClient.removeContainer(container.id(), true);
log.info("{} deleted", container.id());
}
} catch (DockerException e) {
throw new IllegalStateException(e);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
public final String getDockerHost() {
return dockerClient.getHost();
}
/**
* Get host port conteiner internal port was mapped to.
*
* @param containerPort Container port. Typically it matches Dockerfile EXPOSE directive.
* @return Host port conteiner port is exposed on.
*/
public final String getExposedContainerPort(String containerPort) {
String key = containerPort + "/tcp";
List<PortBinding> list = containerPorts.get(key);
if (list == null || list.size() == 0) {
throw new IllegalStateException(String.format("%s is not exposed", key));
}
if (list.size() == 0) {
throw new IllegalStateException(String.format("binding list for %s is empty", key));
}
if (list.size() > 1) {
throw new IllegalStateException(String.format("binding list for %s is longer than 1", key));
}
return list.get(0).hostPort();
}
private void logMappings(DockerClient dockerClient) throws DockerException, InterruptedException {
ContainerInfo inspectContainer = dockerClient.inspectContainer(container.id());
NetworkSettings networkSettings = inspectContainer.networkSettings();
log.info("{} exposed ports: {}", container.id(), networkSettings.ports());
}
public void waitFor(final String searchString, int waitTime) throws TimeoutException, InterruptedException {
new WaitForUnit(TimeUnit.SECONDS, waitTime, TimeUnit.SECONDS, 1, new WaitForCondition() {
@Override
public boolean isConditionMet() {
return StringUtils.contains(fullLogContent(), searchString);
}
@Override
public String tickMessage() {
return String.format("wait for '%s' in log", searchString);
}
@Override
public String timeoutMessage() {
return String.format("container log: \n%s", fullLogContent());
}
})
.setLogLevelBeginEnd(Level.DEBUG)
.setLogLevelProgress(Level.TRACE)
.startWaiting();
}
String fullLogContent() {
try (LogStream stream = dockerClient.logs(container.id(), LogsParam.stdout(), LogsParam.stderr());) {
String fullLog = stream.readFully();
if (log.isTraceEnabled()) {
log.trace("{} full log: {}", container.id(), StringUtils.replace(fullLog, "\n", "|"));
}
return fullLog;
} catch (DockerException | InterruptedException e) {
throw new IllegalStateException(e);
}
}
String getContainerId() {
return container.id();
}
DockerClient getDockerClient() {
return dockerClient;
}
}
|
package redis.clients.jedis;
import redis.clients.jedis.commands.BinaryJedisClusterCommands;
import redis.clients.jedis.commands.JedisClusterBinaryScriptingCommands;
import redis.clients.jedis.commands.MultiKeyBinaryJedisClusterCommands;
import redis.clients.jedis.params.geo.GeoRadiusParam;
import redis.clients.jedis.params.set.SetParams;
import redis.clients.jedis.params.sortedset.ZAddParams;
import redis.clients.jedis.params.sortedset.ZIncrByParams;
import redis.clients.util.KeyMergeUtil;
import redis.clients.util.SafeEncoder;
import java.io.Closeable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.util.JedisClusterHashTagUtil;
public class BinaryJedisCluster implements BinaryJedisClusterCommands,
MultiKeyBinaryJedisClusterCommands, JedisClusterBinaryScriptingCommands, Closeable {
public static final int HASHSLOTS = 16384;
protected static final int DEFAULT_TIMEOUT = 2000;
protected static final int DEFAULT_MAX_ATTEMPTS = 5;
protected int maxAttempts;
protected JedisClusterConnectionHandler connectionHandler;
public BinaryJedisCluster(Set<HostAndPort> nodes, int timeout) {
this(nodes, timeout, DEFAULT_MAX_ATTEMPTS, new GenericObjectPoolConfig());
}
public BinaryJedisCluster(Set<HostAndPort> nodes) {
this(nodes, DEFAULT_TIMEOUT);
}
public BinaryJedisCluster(Set<HostAndPort> jedisClusterNode, int timeout, int maxAttempts,
final GenericObjectPoolConfig poolConfig) {
this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig,
timeout);
this.maxAttempts = maxAttempts;
}
public BinaryJedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout,
int soTimeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) {
this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig,
connectionTimeout, soTimeout);
this.maxAttempts = maxAttempts;
}
public BinaryJedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, String password, GenericObjectPoolConfig poolConfig) {
this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig,
connectionTimeout, soTimeout, password);
this.maxAttempts = maxAttempts;
}
public BinaryJedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, String password, String clientName, GenericObjectPoolConfig poolConfig) {
this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig,
connectionTimeout, soTimeout, password, clientName);
this.maxAttempts = maxAttempts;
}
@Override
public void close() {
if (connectionHandler != null) {
connectionHandler.close();
}
}
public Map<String, JedisPool> getClusterNodes() {
return connectionHandler.getNodes();
}
public Jedis getConnectionFromSlot(int slot) {
return this.connectionHandler.getConnectionFromSlot(slot);
}
@Override
public String set(final byte[] key, final byte[] value) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.set(key, value);
}
}.runBinary(key);
}
@Override
public String set(final byte[] key, final byte[] value, final SetParams params) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.set(key, value, params);
}
}.runBinary(key);
}
@Override
public byte[] get(final byte[] key) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.get(key);
}
}.runBinary(key);
}
@Override
public Long exists(final byte[]... keys) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.exists(keys);
}
}.runBinary(keys.length, keys);
}
@Override
public Boolean exists(final byte[] key) {
return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) {
@Override
public Boolean execute(Jedis connection) {
return connection.exists(key);
}
}.runBinary(key);
}
@Override
public Long persist(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.persist(key);
}
}.runBinary(key);
}
@Override
public String type(final byte[] key) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.type(key);
}
}.runBinary(key);
}
@Override
public Long expire(final byte[] key, final int seconds) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.expire(key, seconds);
}
}.runBinary(key);
}
@Override
public Long pexpire(final byte[] key, final long milliseconds) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.pexpire(key, milliseconds);
}
}.runBinary(key);
}
@Override
public Long expireAt(final byte[] key, final long unixTime) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.expireAt(key, unixTime);
}
}.runBinary(key);
}
@Override
public Long pexpireAt(final byte[] key, final long millisecondsTimestamp) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.pexpireAt(key, millisecondsTimestamp);
}
}.runBinary(key);
}
@Override
public Long ttl(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.ttl(key);
}
}.runBinary(key);
}
@Override
public Long pttl(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.pttl(key);
}
}.runBinary(key);
}
@Override
public Long touch(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.touch(key);
}
}.runBinary(key);
}
@Override
public Long touch(final byte[]... keys) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.touch(keys);
}
}.runBinary(keys.length, keys);
}
@Override
public Boolean setbit(final byte[] key, final long offset, final boolean value) {
return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) {
@Override
public Boolean execute(Jedis connection) {
return connection.setbit(key, offset, value);
}
}.runBinary(key);
}
@Override
public Boolean setbit(final byte[] key, final long offset, final byte[] value) {
return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) {
@Override
public Boolean execute(Jedis connection) {
return connection.setbit(key, offset, value);
}
}.runBinary(key);
}
@Override
public Boolean getbit(final byte[] key, final long offset) {
return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) {
@Override
public Boolean execute(Jedis connection) {
return connection.getbit(key, offset);
}
}.runBinary(key);
}
@Override
public Long setrange(final byte[] key, final long offset, final byte[] value) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.setrange(key, offset, value);
}
}.runBinary(key);
}
@Override
public byte[] getrange(final byte[] key, final long startOffset, final long endOffset) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.getrange(key, startOffset, endOffset);
}
}.runBinary(key);
}
@Override
public byte[] getSet(final byte[] key, final byte[] value) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.getSet(key, value);
}
}.runBinary(key);
}
@Override
public Long setnx(final byte[] key, final byte[] value) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.setnx(key, value);
}
}.runBinary(key);
}
@Override
public String psetex(final byte[] key, final long milliseconds, final byte[] value) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.psetex(key, milliseconds, value);
}
}.runBinary(key);
}
@Override
public String setex(final byte[] key, final int seconds, final byte[] value) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.setex(key, seconds, value);
}
}.runBinary(key);
}
@Override
public Long decrBy(final byte[] key, final long integer) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.decrBy(key, integer);
}
}.runBinary(key);
}
@Override
public Long decr(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.decr(key);
}
}.runBinary(key);
}
@Override
public Long incrBy(final byte[] key, final long integer) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.incrBy(key, integer);
}
}.runBinary(key);
}
@Override
public Double incrByFloat(final byte[] key, final double value) {
return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) {
@Override
public Double execute(Jedis connection) {
return connection.incrByFloat(key, value);
}
}.runBinary(key);
}
@Override
public Long incr(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.incr(key);
}
}.runBinary(key);
}
@Override
public Long append(final byte[] key, final byte[] value) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.append(key, value);
}
}.runBinary(key);
}
@Override
public byte[] substr(final byte[] key, final int start, final int end) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.substr(key, start, end);
}
}.runBinary(key);
}
@Override
public Long hset(final byte[] key, final byte[] field, final byte[] value) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.hset(key, field, value);
}
}.runBinary(key);
}
@Override
public byte[] hget(final byte[] key, final byte[] field) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.hget(key, field);
}
}.runBinary(key);
}
@Override
public Long hsetnx(final byte[] key, final byte[] field, final byte[] value) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.hsetnx(key, field, value);
}
}.runBinary(key);
}
@Override
public String hmset(final byte[] key, final Map<byte[], byte[]> hash) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.hmset(key, hash);
}
}.runBinary(key);
}
@Override
public List<byte[]> hmget(final byte[] key, final byte[]... fields) {
return new JedisClusterCommand<List<byte[]>>(connectionHandler, maxAttempts) {
@Override
public List<byte[]> execute(Jedis connection) {
return connection.hmget(key, fields);
}
}.runBinary(key);
}
@Override
public Long hincrBy(final byte[] key, final byte[] field, final long value) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.hincrBy(key, field, value);
}
}.runBinary(key);
}
@Override
public Double hincrByFloat(final byte[] key, final byte[] field, final double value) {
return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) {
@Override
public Double execute(Jedis connection) {
return connection.hincrByFloat(key, field, value);
}
}.runBinary(key);
}
@Override
public Boolean hexists(final byte[] key, final byte[] field) {
return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) {
@Override
public Boolean execute(Jedis connection) {
return connection.hexists(key, field);
}
}.runBinary(key);
}
@Override
public Long hdel(final byte[] key, final byte[]... field) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.hdel(key, field);
}
}.runBinary(key);
}
@Override
public Long hlen(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.hlen(key);
}
}.runBinary(key);
}
@Override
public Set<byte[]> hkeys(final byte[] key) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.hkeys(key);
}
}.runBinary(key);
}
@Override
public Collection<byte[]> hvals(final byte[] key) {
return new JedisClusterCommand<Collection<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Collection<byte[]> execute(Jedis connection) {
return connection.hvals(key);
}
}.runBinary(key);
}
@Override
public Map<byte[], byte[]> hgetAll(final byte[] key) {
return new JedisClusterCommand<Map<byte[], byte[]>>(connectionHandler, maxAttempts) {
@Override
public Map<byte[], byte[]> execute(Jedis connection) {
return connection.hgetAll(key);
}
}.runBinary(key);
}
@Override
public Long rpush(final byte[] key, final byte[]... args) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.rpush(key, args);
}
}.runBinary(key);
}
@Override
public Long lpush(final byte[] key, final byte[]... args) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.lpush(key, args);
}
}.runBinary(key);
}
@Override
public Long llen(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.llen(key);
}
}.runBinary(key);
}
@Override
public List<byte[]> lrange(final byte[] key, final long start, final long end) {
return new JedisClusterCommand<List<byte[]>>(connectionHandler, maxAttempts) {
@Override
public List<byte[]> execute(Jedis connection) {
return connection.lrange(key, start, end);
}
}.runBinary(key);
}
@Override
public String ltrim(final byte[] key, final long start, final long end) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.ltrim(key, start, end);
}
}.runBinary(key);
}
@Override
public byte[] lindex(final byte[] key, final long index) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.lindex(key, index);
}
}.runBinary(key);
}
@Override
public String lset(final byte[] key, final long index, final byte[] value) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.lset(key, index, value);
}
}.runBinary(key);
}
@Override
public Long lrem(final byte[] key, final long count, final byte[] value) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.lrem(key, count, value);
}
}.runBinary(key);
}
@Override
public byte[] lpop(final byte[] key) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.lpop(key);
}
}.runBinary(key);
}
@Override
public byte[] rpop(final byte[] key) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.rpop(key);
}
}.runBinary(key);
}
@Override
public Long sadd(final byte[] key, final byte[]... member) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.sadd(key, member);
}
}.runBinary(key);
}
@Override
public Set<byte[]> smembers(final byte[] key) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.smembers(key);
}
}.runBinary(key);
}
@Override
public Long srem(final byte[] key, final byte[]... member) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.srem(key, member);
}
}.runBinary(key);
}
@Override
public byte[] spop(final byte[] key) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.spop(key);
}
}.runBinary(key);
}
@Override
public Set<byte[]> spop(final byte[] key, final long count) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.spop(key, count);
}
}.runBinary(key);
}
@Override
public Long scard(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.scard(key);
}
}.runBinary(key);
}
@Override
public Boolean sismember(final byte[] key, final byte[] member) {
return new JedisClusterCommand<Boolean>(connectionHandler, maxAttempts) {
@Override
public Boolean execute(Jedis connection) {
return connection.sismember(key, member);
}
}.runBinary(key);
}
@Override
public byte[] srandmember(final byte[] key) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.srandmember(key);
}
}.runBinary(key);
}
@Override
public Long strlen(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.strlen(key);
}
}.runBinary(key);
}
@Override
public Long zadd(final byte[] key, final double score, final byte[] member) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zadd(key, score, member);
}
}.runBinary(key);
}
@Override
public Long zadd(final byte[] key, final double score, final byte[] member,
final ZAddParams params) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zadd(key, score, member, params);
}
}.runBinary(key);
}
@Override
public Long zadd(final byte[] key, final Map<byte[], Double> scoreMembers) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zadd(key, scoreMembers);
}
}.runBinary(key);
}
@Override
public Long zadd(final byte[] key, final Map<byte[], Double> scoreMembers, final ZAddParams params) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zadd(key, scoreMembers, params);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrange(final byte[] key, final long start, final long end) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrange(key, start, end);
}
}.runBinary(key);
}
@Override
public Long zrem(final byte[] key, final byte[]... member) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zrem(key, member);
}
}.runBinary(key);
}
@Override
public Double zincrby(final byte[] key, final double score, final byte[] member) {
return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) {
@Override
public Double execute(Jedis connection) {
return connection.zincrby(key, score, member);
}
}.runBinary(key);
}
@Override
public Double zincrby(final byte[] key, final double score, final byte[] member,
final ZIncrByParams params) {
return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) {
@Override
public Double execute(Jedis connection) {
return connection.zincrby(key, score, member, params);
}
}.runBinary(key);
}
@Override
public Long zrank(final byte[] key, final byte[] member) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zrank(key, member);
}
}.runBinary(key);
}
@Override
public Long zrevrank(final byte[] key, final byte[] member) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zrevrank(key, member);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrevrange(final byte[] key, final long start, final long end) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrevrange(key, start, end);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrangeWithScores(final byte[] key, final long start, final long end) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrangeWithScores(key, start, end);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrevrangeWithScores(final byte[] key, final long start, final long end) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrevrangeWithScores(key, start, end);
}
}.runBinary(key);
}
@Override
public Long zcard(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zcard(key);
}
}.runBinary(key);
}
@Override
public Double zscore(final byte[] key, final byte[] member) {
return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) {
@Override
public Double execute(Jedis connection) {
return connection.zscore(key, member);
}
}.runBinary(key);
}
@Override
public List<byte[]> sort(final byte[] key) {
return new JedisClusterCommand<List<byte[]>>(connectionHandler, maxAttempts) {
@Override
public List<byte[]> execute(Jedis connection) {
return connection.sort(key);
}
}.runBinary(key);
}
@Override
public List<byte[]> sort(final byte[] key, final SortingParams sortingParameters) {
return new JedisClusterCommand<List<byte[]>>(connectionHandler, maxAttempts) {
@Override
public List<byte[]> execute(Jedis connection) {
return connection.sort(key, sortingParameters);
}
}.runBinary(key);
}
@Override
public Long zcount(final byte[] key, final double min, final double max) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zcount(key, min, max);
}
}.runBinary(key);
}
@Override
public Long zcount(final byte[] key, final byte[] min, final byte[] max) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zcount(key, min, max);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrangeByScore(final byte[] key, final double min, final double max) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrangeByScore(key, min, max);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrangeByScore(final byte[] key, final byte[] min, final byte[] max) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrangeByScore(key, min, max);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrevrangeByScore(final byte[] key, final double max, final double min) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrevrangeByScore(key, max, min);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrangeByScore(final byte[] key, final double min, final double max,
final int offset, final int count) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrangeByScore(key, min, max, offset, count);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrevrangeByScore(key, max, min);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrangeByScore(final byte[] key, final byte[] min, final byte[] max,
final int offset, final int count) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrangeByScore(key, min, max, offset, count);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrevrangeByScore(final byte[] key, final double max, final double min,
final int offset, final int count) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrevrangeByScore(key, max, min, offset, count);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final double min, final double max) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrangeByScoreWithScores(key, min, max);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrevrangeByScoreWithScores(key, max, min);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final double min, final double max,
final int offset, final int count) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrangeByScoreWithScores(key, min, max, offset, count);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min,
final int offset, final int count) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrevrangeByScore(key, max, min, offset, count);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrangeByScoreWithScores(key, min, max);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrevrangeByScoreWithScores(key, max, min);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max,
final int offset, final int count) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrangeByScoreWithScores(key, min, max, offset, count);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final double max,
final double min, final int offset, final int count) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrevrangeByScoreWithScores(key, max, min, offset, count);
}
}.runBinary(key);
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final byte[] max,
final byte[] min, final int offset, final int count) {
return new JedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> execute(Jedis connection) {
return connection.zrevrangeByScoreWithScores(key, max, min, offset, count);
}
}.runBinary(key);
}
@Override
public Long zremrangeByRank(final byte[] key, final long start, final long end) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zremrangeByRank(key, start, end);
}
}.runBinary(key);
}
@Override
public Long zremrangeByScore(final byte[] key, final double start, final double end) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zremrangeByScore(key, start, end);
}
}.runBinary(key);
}
@Override
public Long zremrangeByScore(final byte[] key, final byte[] start, final byte[] end) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zremrangeByScore(key, start, end);
}
}.runBinary(key);
}
@Override
public Long linsert(final byte[] key, final Client.LIST_POSITION where, final byte[] pivot,
final byte[] value) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.linsert(key, where, pivot, value);
}
}.runBinary(key);
}
@Override
public Long lpushx(final byte[] key, final byte[]... arg) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.lpushx(key, arg);
}
}.runBinary(key);
}
@Override
public Long rpushx(final byte[] key, final byte[]... arg) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.rpushx(key, arg);
}
}.runBinary(key);
}
@Override
public Long del(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.del(key);
}
}.runBinary(key);
}
@Override
public Long unlink(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.unlink(key);
}
}.runBinary(key);
}
@Override
public Long unlink(final byte[]... keys) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.unlink(keys);
}
}.runBinary(keys.length, keys);
}
@Override
public byte[] echo(final byte[] arg) {
// note that it'll be run from arbitary node
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.echo(arg);
}
}.runBinary(arg);
}
@Override
public Long bitcount(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.bitcount(key);
}
}.runBinary(key);
}
@Override
public Long bitcount(final byte[] key, final long start, final long end) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.bitcount(key, start, end);
}
}.runBinary(key);
}
@Override
public Long pfadd(final byte[] key, final byte[]... elements) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.pfadd(key, elements);
}
}.runBinary(key);
}
@Override
public long pfcount(final byte[] key) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.pfcount(key);
}
}.runBinary(key);
}
@Override
public List<byte[]> srandmember(final byte[] key, final int count) {
return new JedisClusterCommand<List<byte[]>>(connectionHandler, maxAttempts) {
@Override
public List<byte[]> execute(Jedis connection) {
return connection.srandmember(key, count);
}
}.runBinary(key);
}
@Override
public Long zlexcount(final byte[] key, final byte[] min, final byte[] max) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zlexcount(key, min, max);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrangeByLex(key, min, max);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max,
final int offset, final int count) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrangeByLex(key, min, max, offset, count);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrevrangeByLex(key, max, min);
}
}.runBinary(key);
}
@Override
public Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min,
final int offset, final int count) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.zrevrangeByLex(key, max, min, offset, count);
}
}.runBinary(key);
}
@Override
public Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zremrangeByLex(key, min, max);
}
}.runBinary(key);
}
@Override
public Object eval(final byte[] script, final byte[] keyCount, final byte[]... params) {
return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) {
@Override
public Object execute(Jedis connection) {
return connection.eval(script, keyCount, params);
}
}.runBinary(Integer.parseInt(SafeEncoder.encode(keyCount)), params);
}
@Override
public Object eval(final byte[] script, final int keyCount, final byte[]... params) {
return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) {
@Override
public Object execute(Jedis connection) {
return connection.eval(script, keyCount, params);
}
}.runBinary(keyCount, params);
}
@Override
public Object eval(final byte[] script, final List<byte[]> keys, final List<byte[]> args) {
return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) {
@Override
public Object execute(Jedis connection) {
return connection.eval(script, keys, args);
}
}.runBinary(keys.size(), keys.toArray(new byte[keys.size()][]));
}
@Override
public Object eval(final byte[] script, final byte[] key) {
return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) {
@Override
public Object execute(Jedis connection) {
return connection.eval(script);
}
}.runBinary(key);
}
@Override
public Object evalsha(final byte[] sha1, final byte[] key) {
return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) {
@Override
public Object execute(Jedis connection) {
return connection.evalsha(sha1);
}
}.runBinary(key);
}
@Override
public Object evalsha(final byte[] sha1, final List<byte[]> keys, final List<byte[]> args) {
return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) {
@Override
public Object execute(Jedis connection) {
return connection.evalsha(sha1, keys, args);
}
}.runBinary(keys.size(), keys.toArray(new byte[keys.size()][]));
}
@Override
public Object evalsha(final byte[] sha1, final int keyCount, final byte[]... params) {
return new JedisClusterCommand<Object>(connectionHandler, maxAttempts) {
@Override
public Object execute(Jedis connection) {
return connection.evalsha(sha1, keyCount, params);
}
}.runBinary(keyCount, params);
}
@Override
public List<Long> scriptExists(final byte[] key, final byte[][] sha1) {
return new JedisClusterCommand<List<Long>>(connectionHandler, maxAttempts) {
@Override
public List<Long> execute(Jedis connection) {
return connection.scriptExists(sha1);
}
}.runBinary(key);
}
@Override
public byte[] scriptLoad(final byte[] script, final byte[] key) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.scriptLoad(script);
}
}.runBinary(key);
}
@Override
public String scriptFlush(final byte[] key) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.scriptFlush();
}
}.runBinary(key);
}
@Override
public String scriptKill(final byte[] key) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.scriptKill();
}
}.runBinary(key);
}
@Override
public Long del(final byte[]... keys) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.del(keys);
}
}.runBinary(keys.length, keys);
}
@Override
public List<byte[]> blpop(final int timeout, final byte[]... keys) {
return new JedisClusterCommand<List<byte[]>>(connectionHandler, maxAttempts) {
@Override
public List<byte[]> execute(Jedis connection) {
return connection.blpop(timeout, keys);
}
}.runBinary(keys.length, keys);
}
@Override
public List<byte[]> brpop(final int timeout, final byte[]... keys) {
return new JedisClusterCommand<List<byte[]>>(connectionHandler, maxAttempts) {
@Override
public List<byte[]> execute(Jedis connection) {
return connection.brpop(timeout, keys);
}
}.runBinary(keys.length, keys);
}
@Override
public List<byte[]> mget(final byte[]... keys) {
return new JedisClusterCommand<List<byte[]>>(connectionHandler, maxAttempts) {
@Override
public List<byte[]> execute(Jedis connection) {
return connection.mget(keys);
}
}.runBinary(keys.length, keys);
}
@Override
public String mset(final byte[]... keysvalues) {
byte[][] keys = new byte[keysvalues.length / 2][];
for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) {
keys[keyIdx] = keysvalues[keyIdx * 2];
}
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.mset(keysvalues);
}
}.runBinary(keys.length, keys);
}
@Override
public Long msetnx(final byte[]... keysvalues) {
byte[][] keys = new byte[keysvalues.length / 2][];
for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) {
keys[keyIdx] = keysvalues[keyIdx * 2];
}
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.msetnx(keysvalues);
}
}.runBinary(keys.length, keys);
}
@Override
public String rename(final byte[] oldkey, final byte[] newkey) {
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.rename(oldkey, newkey);
}
}.runBinary(2, oldkey, newkey);
}
@Override
public Long renamenx(final byte[] oldkey, final byte[] newkey) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.renamenx(oldkey, newkey);
}
}.runBinary(2, oldkey, newkey);
}
@Override
public byte[] rpoplpush(final byte[] srckey, final byte[] dstkey) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.rpoplpush(srckey, dstkey);
}
}.runBinary(2, srckey, dstkey);
}
@Override
public Set<byte[]> sdiff(final byte[]... keys) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.sdiff(keys);
}
}.runBinary(keys.length, keys);
}
@Override
public Long sdiffstore(final byte[] dstkey, final byte[]... keys) {
byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys);
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.sdiffstore(dstkey, keys);
}
}.runBinary(wholeKeys.length, wholeKeys);
}
@Override
public Set<byte[]> sinter(final byte[]... keys) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.sinter(keys);
}
}.runBinary(keys.length, keys);
}
@Override
public Long sinterstore(final byte[] dstkey, final byte[]... keys) {
byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys);
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.sinterstore(dstkey, keys);
}
}.runBinary(wholeKeys.length, wholeKeys);
}
@Override
public Long smove(final byte[] srckey, final byte[] dstkey, final byte[] member) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.smove(srckey, dstkey, member);
}
}.runBinary(2, srckey, dstkey);
}
@Override
public Long sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.sort(key, sortingParameters, dstkey);
}
}.runBinary(2, key, dstkey);
}
@Override
public Long sort(final byte[] key, final byte[] dstkey) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.sort(key, dstkey);
}
}.runBinary(2, key, dstkey);
}
@Override
public Set<byte[]> sunion(final byte[]... keys) {
return new JedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> execute(Jedis connection) {
return connection.sunion(keys);
}
}.runBinary(keys.length, keys);
}
@Override
public Long sunionstore(final byte[] dstkey, final byte[]... keys) {
byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys);
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.sunionstore(dstkey, keys);
}
}.runBinary(wholeKeys.length, wholeKeys);
}
@Override
public Long zinterstore(final byte[] dstkey, final byte[]... sets) {
byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets);
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zinterstore(dstkey, sets);
}
}.runBinary(wholeKeys.length, wholeKeys);
}
@Override
public Long zinterstore(final byte[] dstkey, final ZParams params, final byte[]... sets) {
byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets);
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zinterstore(dstkey, params, sets);
}
}.runBinary(wholeKeys.length, wholeKeys);
}
@Override
public Long zunionstore(final byte[] dstkey, final byte[]... sets) {
byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets);
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zunionstore(dstkey, sets);
}
}.runBinary(wholeKeys.length, wholeKeys);
}
@Override
public Long zunionstore(final byte[] dstkey, final ZParams params, final byte[]... sets) {
byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets);
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.zunionstore(dstkey, params, sets);
}
}.runBinary(wholeKeys.length, wholeKeys);
}
@Override
public byte[] brpoplpush(final byte[] source, final byte[] destination, final int timeout) {
return new JedisClusterCommand<byte[]>(connectionHandler, maxAttempts) {
@Override
public byte[] execute(Jedis connection) {
return connection.brpoplpush(source, destination, timeout);
}
}.runBinary(2, source, destination);
}
@Override
public Long publish(final byte[] channel, final byte[] message) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.publish(channel, message);
}
}.runWithAnyNode();
}
@Override
public void subscribe(final BinaryJedisPubSub jedisPubSub, final byte[]... channels) {
new JedisClusterCommand<Integer>(connectionHandler, maxAttempts) {
@Override
public Integer execute(Jedis connection) {
connection.subscribe(jedisPubSub, channels);
return 0;
}
}.runWithAnyNode();
}
@Override
public void psubscribe(final BinaryJedisPubSub jedisPubSub, final byte[]... patterns) {
new JedisClusterCommand<Integer>(connectionHandler, maxAttempts) {
@Override
public Integer execute(Jedis connection) {
connection.psubscribe(jedisPubSub, patterns);
return 0;
}
}.runWithAnyNode();
}
@Override
public Long bitop(final BitOP op, final byte[] destKey, final byte[]... srcKeys) {
byte[][] wholeKeys = KeyMergeUtil.merge(destKey, srcKeys);
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.bitop(op, destKey, srcKeys);
}
}.runBinary(wholeKeys.length, wholeKeys);
}
@Override
public String pfmerge(final byte[] destkey, final byte[]... sourcekeys) {
byte[][] wholeKeys = KeyMergeUtil.merge(destkey, sourcekeys);
return new JedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String execute(Jedis connection) {
return connection.pfmerge(destkey, sourcekeys);
}
}.runBinary(wholeKeys.length, wholeKeys);
}
@Override
public Long pfcount(final byte[]... keys) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.pfcount(keys);
}
}.runBinary(keys.length, keys);
}
@Override
public Long geoadd(final byte[] key, final double longitude, final double latitude,
final byte[] member) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.geoadd(key, longitude, latitude, member);
}
}.runBinary(key);
}
@Override
public Long geoadd(final byte[] key, final Map<byte[], GeoCoordinate> memberCoordinateMap) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.geoadd(key, memberCoordinateMap);
}
}.runBinary(key);
}
@Override
public Double geodist(final byte[] key, final byte[] member1, final byte[] member2) {
return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) {
@Override
public Double execute(Jedis connection) {
return connection.geodist(key, member1, member2);
}
}.runBinary(key);
}
@Override
public Double geodist(final byte[] key, final byte[] member1, final byte[] member2,
final GeoUnit unit) {
return new JedisClusterCommand<Double>(connectionHandler, maxAttempts) {
@Override
public Double execute(Jedis connection) {
return connection.geodist(key, member1, member2, unit);
}
}.runBinary(key);
}
@Override
public List<byte[]> geohash(final byte[] key, final byte[]... members) {
return new JedisClusterCommand<List<byte[]>>(connectionHandler, maxAttempts) {
@Override
public List<byte[]> execute(Jedis connection) {
return connection.geohash(key, members);
}
}.runBinary(key);
}
@Override
public List<GeoCoordinate> geopos(final byte[] key, final byte[]... members) {
return new JedisClusterCommand<List<GeoCoordinate>>(connectionHandler, maxAttempts) {
@Override
public List<GeoCoordinate> execute(Jedis connection) {
return connection.geopos(key, members);
}
}.runBinary(key);
}
@Override
public List<GeoRadiusResponse> georadius(final byte[] key, final double longitude,
final double latitude, final double radius, final GeoUnit unit) {
return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) {
@Override
public List<GeoRadiusResponse> execute(Jedis connection) {
return connection.georadius(key, longitude, latitude, radius, unit);
}
}.runBinary(key);
}
@Override
public List<GeoRadiusResponse> georadius(final byte[] key, final double longitude,
final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) {
return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) {
@Override
public List<GeoRadiusResponse> execute(Jedis connection) {
return connection.georadius(key, longitude, latitude, radius, unit, param);
}
}.runBinary(key);
}
@Override
public List<GeoRadiusResponse> georadiusByMember(final byte[] key, final byte[] member,
final double radius, final GeoUnit unit) {
return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) {
@Override
public List<GeoRadiusResponse> execute(Jedis connection) {
return connection.georadiusByMember(key, member, radius, unit);
}
}.runBinary(key);
}
@Override
public List<GeoRadiusResponse> georadiusByMember(final byte[] key, final byte[] member,
final double radius, final GeoUnit unit, final GeoRadiusParam param) {
return new JedisClusterCommand<List<GeoRadiusResponse>>(connectionHandler, maxAttempts) {
@Override
public List<GeoRadiusResponse> execute(Jedis connection) {
return connection.georadiusByMember(key, member, radius, unit, param);
}
}.runBinary(key);
}
@Override
public ScanResult<byte[]> scan(final byte[] cursor, final ScanParams params) {
byte[] matchPattern = null;
if (params == null || (matchPattern = params.binaryMatch()) == null || matchPattern.length == 0) {
throw new IllegalArgumentException(BinaryJedisCluster.class.getSimpleName() + " only supports SCAN commands with non-empty MATCH patterns");
}
if (JedisClusterHashTagUtil.isClusterCompliantMatchPattern(matchPattern)) {
return new JedisClusterCommand< ScanResult<byte[]>>(connectionHandler,
maxAttempts) {
@Override
public ScanResult<byte[]> execute(Jedis connection) {
return connection.scan(cursor, params);
}
}.runBinary(matchPattern);
} else {
throw new IllegalArgumentException(BinaryJedisCluster.class.getSimpleName() + " only supports SCAN commands with MATCH patterns containing hash-tags ( curly-brackets enclosed strings )");
}
}
@Override
public ScanResult<Map.Entry<byte[], byte[]>> hscan(final byte[] key, final byte[] cursor) {
return new JedisClusterCommand<ScanResult<Map.Entry<byte[], byte[]>>>(connectionHandler,
maxAttempts) {
@Override
public ScanResult<Map.Entry<byte[], byte[]>> execute(Jedis connection) {
return connection.hscan(key, cursor);
}
}.runBinary(key);
}
@Override
public ScanResult<Map.Entry<byte[], byte[]>> hscan(final byte[] key, final byte[] cursor,
final ScanParams params) {
return new JedisClusterCommand<ScanResult<Map.Entry<byte[], byte[]>>>(connectionHandler,
maxAttempts) {
@Override
public ScanResult<Map.Entry<byte[], byte[]>> execute(Jedis connection) {
return connection.hscan(key, cursor, params);
}
}.runBinary(key);
}
@Override
public ScanResult<byte[]> sscan(final byte[] key, final byte[] cursor) {
return new JedisClusterCommand<ScanResult<byte[]>>(connectionHandler, maxAttempts) {
@Override
public ScanResult<byte[]> execute(Jedis connection) {
return connection.sscan(key, cursor);
}
}.runBinary(key);
}
@Override
public ScanResult<byte[]> sscan(final byte[] key, final byte[] cursor, final ScanParams params) {
return new JedisClusterCommand<ScanResult<byte[]>>(connectionHandler, maxAttempts) {
@Override
public ScanResult<byte[]> execute(Jedis connection) {
return connection.sscan(key, cursor, params);
}
}.runBinary(key);
}
@Override
public ScanResult<Tuple> zscan(final byte[] key, final byte[] cursor) {
return new JedisClusterCommand<ScanResult<Tuple>>(connectionHandler, maxAttempts) {
@Override
public ScanResult<Tuple> execute(Jedis connection) {
return connection.zscan(key, cursor);
}
}.runBinary(key);
}
@Override
public ScanResult<Tuple> zscan(final byte[] key, final byte[] cursor, final ScanParams params) {
return new JedisClusterCommand<ScanResult<Tuple>>(connectionHandler, maxAttempts) {
@Override
public ScanResult<Tuple> execute(Jedis connection) {
return connection.zscan(key, cursor, params);
}
}.runBinary(key);
}
@Override
public List<Long> bitfield(final byte[] key, final byte[]... arguments) {
return new JedisClusterCommand<List<Long>>(connectionHandler, maxAttempts) {
@Override
public List<Long> execute(Jedis connection) {
return connection.bitfield(key, arguments);
}
}.runBinary(key);
}
@Override
public Long hstrlen(final byte[] key, final byte[] field) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.hstrlen(key, field);
}
}.runBinary(key);
}
}
|
package securbank.services;
import java.util.List;
import java.util.UUID;
import javax.transaction.Transactional;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import securbank.dao.AccountDao;
import securbank.dao.TransactionDao;
import securbank.dao.TransferDao;
import securbank.models.Account;
import securbank.models.Transaction;
import securbank.models.Transfer;
import securbank.models.User;
/**
* @author Mitikaa
*
*/
@Service("transferService")
@Transactional
public class TransferServiceImpl implements TransferService{
@Autowired
private TransferDao transferDao;
@Autowired
private TransactionDao transactionDao;
@Autowired
private AccountDao accountDao;
@Autowired
private AccountService accountService;
@Autowired
private TransactionService transactionService;
@Autowired
private UserService userService;
@Autowired
private EmailService emailService;
@Autowired
OtpService otpService;
@Autowired
private Environment env;
private SimpleMailMessage message;
final static Logger logger = LoggerFactory.getLogger(TransferServiceImpl.class);
/**
* Initiates new transfer
*
* @param transfer
* The transfer to be initiated
* @return transfer
*/
@Override
public Transfer initiateTransfer(Transfer transfer) {
logger.info("Initiating new transfer request");
User currentUser = userService.getCurrentUser();
if(currentUser==null){
logger.info("Current logged in user is null");
return null;
}
//accountTo and accountFrom should not have same email address
if(currentUser.getEmail().equalsIgnoreCase(transfer.getToAccount().getUser().getEmail())){
logger.info("Transfer to and from accounts are same");
return null;
}
//get user's checking account
logger.info("Getting current user's checking account");
for (Account acc: currentUser.getAccounts()){
if (acc.getType().equalsIgnoreCase("checking")){
transfer.setFromAccount(acc);
}
}
//check otp
if(!transfer.getOtp().equals(otpService.getOtpByUser(transfer.getFromAccount().getUser()).getCode())){
logger.info("Otp mismatch");
return null;
}
if(isTransferValid(transfer)==false){
return null;
}
//check if account exists and is active
if(isToAccountValid(transfer)==false){
return null;
}
//get user's checking account
logger.info("Getting ToAccount user's checking account");
User toUser = userService.getUserByEmail(transfer.getToAccount().getUser().getEmail());
for (Account acc: toUser.getAccounts()){
if (acc.getType().equalsIgnoreCase("checking")){
transfer.setToAccount(acc);
}
}
//user types should be external
if((!"ROLE_INDIVIDUAL".equalsIgnoreCase(currentUser.getRole())) && (!"ROLE_MERCHANT".equalsIgnoreCase(currentUser.getRole()))){
logger.info("Current user is not an external user");
return null;
}
if((!"ROLE_INDIVIDUAL".equalsIgnoreCase(transfer.getToAccount().getUser().getRole())) && (!"ROLE_MERCHANT".equalsIgnoreCase(transfer.getToAccount().getUser().getRole()))){
logger.info("To account user is not an external user");
return null;
}
transfer.setStatus("Pending");
transfer.setActive(true);
transfer.setCreatedOn(LocalDateTime.now());
transferDao.save(transfer);
logger.info("After transferDao save");
//send email to sender
User user = transfer.getFromAccount().getUser();
message = new SimpleMailMessage();
message.setText(env.getProperty("external.user.transfer.to.body"));
message.setSubject(env.getProperty("external.user.transfer.subject"));
message.setTo(user.getEmail());
emailService.sendEmail(message);
//send email to sender
user = transfer.getToAccount().getUser();
message = new SimpleMailMessage();
message.setText(env.getProperty("external.user.transfer.from.body"));
message.setSubject(env.getProperty("external.user.transfer.subject"));
message.setTo(user.getEmail());
emailService.sendEmail(message);
return transfer;
}
/**
* Approves new transfer
*
* @param transfer
* The transfer to be initiated
* @return transfer
*/
@Override
public Transfer approveTransfer(Transfer transfer) {
logger.info("Inside approve transfer");
//check if transaction is pending
if(transferDao.findById(transfer.getTransferId())==null){
logger.info("Not a pending transfer");
return null;
}
User currentUser = userService.getCurrentUser();
if(currentUser==null){
logger.info("Current logged in user is null");
return null;
}
transfer.setStatus("Approved");
transfer.setModifiedBy(currentUser);
//call transaction Service to create new approved debit and credit transactions
transactionService.approveTransfer(transfer);
return transfer;
}
/**
* Declines new transfer
*
* @param transfer
* The transfer to be initiated
* @return transfer
*/
@Override
public Transfer declineTransfer(Transfer transfer) {
logger.info("Inside decline transfer");
//check if transaction is pending
if(transferDao.findById(transfer.getTransferId())==null){
logger.info("Not a pending transfer");
return null;
}
User currentUser = userService.getCurrentUser();
if(currentUser==null){
logger.info("Current logged in user is null");
return null;
}
transfer.setStatus("Declined");
return transfer;
}
/**
* Fetches all pending transfers by account number
*
* @param accountNumber
* The list of pending transfer
* @return list of transfer
* */
@Override
public List<Transfer> getPendingTransfersByAccountNumber(Long accountNumber) {
// TODO Auto-generated method stub
return null;
}
/**
* Fetches all pending transfers by account number and account type
*
* @param accountNumber
* @param accountType
* The list of pending transfer
* @return list of transfer
* */
@Override
public List<Transfer> getPendingTransfersByType(Long accountNumber, String accountType) {
// TODO Auto-generated method stub
return null;
}
/**
* Fetches all pending transfers by approval status
*
* @param approvalStatus
* The list of pending transfers
* @return list of transfer
* */
@Override
public List<Transfer> getTransfersByStatus(String approvalStatus) {
logger.info("Getting pending transfers by approval status");
if(approvalStatus==null){
return null;
}
return transferDao.findByApprovalStatus(approvalStatus);
}
/**
* Fetches all pending transfers by approval status
*
* @param approvalStatus
* The list of pending transfers
* @return list of transfer
* */
@Override
public List<Transfer> getTransfersByStatusAndUser(User user, String approvalStatus) {
logger.info("Get waiting transfers by approval status");
if(approvalStatus==null){
return null;
}
return transferDao.findByUserAndApprovalStatus(user, approvalStatus);
}
/**
* Fetches transfer by transactionId
*
* @param transactionId
* pending transfer
* @return transfer
* */
@Override
public Transfer getTransferById(UUID id) {
logger.info("Getting pending transfers by transfer id");
Transfer transfer = transferDao.findById(id);
if (transfer == null || transfer.getActive() == false) {
return null;
}
return transferDao.findById(id);
}
/**
* Fetches transfer by accountNumber
*
* @param accountNumber
* pending transfer
* @return transfer
* */
@Override
public Transfer getPendingTransfernByAccountNumber(Long accountNumber) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isTransferValid(Transfer transfer) {
Account account = transfer.getFromAccount();
Double pendingAmount = 0.0;
//check for pending transfer amounts
for(Transfer transf: transferDao.findPendingTransferByFromAccount(account)){
pendingAmount += transf.getAmount();
}
//check for pending transaction amounts
for(Transaction trans: transactionDao.findPendingByAccountAndType(account, "DEBIT")){
pendingAmount += trans.getAmount();
}
//check if transfer amount is valid
if(pendingAmount+transfer.getAmount() > transfer.getFromAccount().getBalance()){
logger.info("Invalid transfer: amount requested to be debitted is more than permitted");
return false;
}
return true;
}
@Override
public boolean isToAccountValid(Transfer transfer) {
if(userService.getUserByEmail(transfer.getToAccount().getUser().getEmail())!=null){
return true;
}
return false;
}
@Override
public Transfer initiateMerchantPaymentRequest(Transfer transfer) {
logger.info("Initiating new payment request");
User currentUser = userService.getCurrentUser();
if(currentUser==null){
logger.info("Current logged in user is null");
return null;
}
//accountTo and accountFrom should not have same email address
if(currentUser.getEmail().equalsIgnoreCase(transfer.getFromAccount().getUser().getEmail())){
logger.info("Transfer to and from accounts are same");
return null;
}
//get user's checking account
logger.info("Getting current user's checking account");
for (Account acc: currentUser.getAccounts()){
if (acc.getType().equalsIgnoreCase("checking")){
transfer.setToAccount(acc);
}
}
//check otp
if(!transfer.getOtp().equals(otpService.getOtpByUser(transfer.getToAccount().getUser()).getCode())){
logger.info("Otp mismatch");
return null;
}
//get user's checking account
logger.info("Getting fromAccount user's checking account");
User fromUser = userService.getUserByEmail(transfer.getFromAccount().getUser().getEmail());
for (Account acc: fromUser.getAccounts()){
if (acc.getType().equalsIgnoreCase("checking")){
transfer.setFromAccount(acc);
}
}
if(isTransferValid(transfer)==false){
return null;
}
//check if account exists and is active
if(isToAccountValid(transfer)==false){
return null;
}
//user types should be external
if(!"ROLE_MERCHANT".equalsIgnoreCase(currentUser.getRole())){
logger.info("Current user is not a merchant");
return null;
}
if(!"ROLE_INDIVIDUAL".equalsIgnoreCase(transfer.getFromAccount().getUser().getRole())){
logger.info("From account user is not an external user");
return null;
}
transfer.setStatus("Waiting");
transfer.setActive(true);
transfer.setCreatedOn(LocalDateTime.now());
transferDao.save(transfer);
logger.info("After transferDao save");
//send email to sender
User user = transfer.getFromAccount().getUser();
message = new SimpleMailMessage();
message.setText(env.getProperty("external.user.transfer.to.body"));
message.setSubject(env.getProperty("external.user.transfer.subject"));
message.setTo(user.getEmail());
emailService.sendEmail(message);
//send email to sender
user = transfer.getToAccount().getUser();
message = new SimpleMailMessage();
message.setText(env.getProperty("external.user.transfer.from.body"));
message.setSubject(env.getProperty("external.user.transfer.subject"));
message.setTo(user.getEmail());
emailService.sendEmail(message);
return transfer;
}
@Override
public Transfer approveTransferToPending(Transfer transfer) {
transfer.setStatus("Pending");
transfer.setModifiedBy(userService.getCurrentUser());
transfer.setModifiedOn(LocalDateTime.now());
transferDao.update(transfer);
return transfer;
}
}
|
package stexfires.util;
import java.util.Locale;
import java.util.Objects;
import java.util.function.UnaryOperator;
/**
* @author Mathias Kalb
* @since 0.1
*/
public enum StringUnaryOperatorType {
LOWER_CASE,
UPPER_CASE,
TRIM_TO_NULL,
TRIM_TO_EMPTY,
EMPTY_TO_NULL,
NULL_TO_EMPTY,
REMOVE_HORIZONTAL_WHITESPACE,
REMOVE_WHITESPACE,
REMOVE_VERTICAL_WHITESPACE,
REMOVE_LEADING_HORIZONTAL_WHITESPACE,
REMOVE_LEADING_WHITESPACE,
REMOVE_LEADING_VERTICAL_WHITESPACE,
REMOVE_TRAILING_HORIZONTAL_WHITESPACE,
REMOVE_TRAILING_WHITESPACE,
REMOVE_TRAILING_VERTICAL_WHITESPACE,
REVERSE,
TAB_TO_SPACES_2,
TAB_TO_SPACES_4;
private static final String EMPTY = "";
public static UnaryOperator<String> prefix(String prefix) {
Objects.requireNonNull(prefix);
return value -> value == null ? prefix : prefix + value;
}
public static UnaryOperator<String> postfix(String postfix) {
Objects.requireNonNull(postfix);
return value -> value == null ? postfix : value + postfix;
}
public static UnaryOperator<String> stringUnaryOperator(StringUnaryOperatorType stringUnaryOperatorType) {
Objects.requireNonNull(stringUnaryOperatorType);
return value -> operate(stringUnaryOperatorType, value, null);
}
public static UnaryOperator<String> stringUnaryOperator(StringUnaryOperatorType stringUnaryOperatorType, Locale locale) {
Objects.requireNonNull(stringUnaryOperatorType);
Objects.requireNonNull(locale);
return value -> operate(stringUnaryOperatorType, value, locale);
}
private static String operate(StringUnaryOperatorType stringUnaryOperatorType, String value) {
return operate(stringUnaryOperatorType, value, null);
}
private static String operate(StringUnaryOperatorType stringUnaryOperatorType, String value, Locale locale) {
Objects.requireNonNull(stringUnaryOperatorType);
String result = null;
switch (stringUnaryOperatorType) {
case LOWER_CASE:
if (value != null) {
if (locale != null) {
result = value.toLowerCase(locale);
} else {
result = value.toLowerCase();
}
}
break;
case UPPER_CASE:
if (value != null) {
if (locale != null) {
result = value.toUpperCase(locale);
} else {
result = value.toUpperCase();
}
}
break;
case TRIM_TO_NULL:
if (value != null) {
result = value.trim();
if (result.isEmpty()) {
result = null;
}
}
break;
case TRIM_TO_EMPTY:
if (value != null) {
result = value.trim();
} else {
result = EMPTY;
}
break;
case EMPTY_TO_NULL:
if (value != null && !value.isEmpty()) {
result = value;
}
break;
case NULL_TO_EMPTY:
if (value != null) {
result = value;
} else {
result = EMPTY;
}
break;
case REMOVE_HORIZONTAL_WHITESPACE:
if (value != null) {
result = value.replaceAll("\\h", EMPTY);
}
break;
case REMOVE_WHITESPACE:
if (value != null) {
result = value.replaceAll("\\s", EMPTY);
}
break;
case REMOVE_VERTICAL_WHITESPACE:
if (value != null) {
result = value.replaceAll("\\v", EMPTY);
}
break;
case REMOVE_LEADING_HORIZONTAL_WHITESPACE:
if (value != null) {
result = value.replaceFirst("^\\h+", EMPTY);
}
break;
case REMOVE_LEADING_WHITESPACE:
if (value != null) {
result = value.replaceFirst("^\\s+", EMPTY);
}
break;
case REMOVE_LEADING_VERTICAL_WHITESPACE:
if (value != null) {
result = value.replaceFirst("^\\v+", EMPTY);
}
break;
case REMOVE_TRAILING_HORIZONTAL_WHITESPACE:
if (value != null) {
result = value.replaceFirst("\\h+$", EMPTY);
}
break;
case REMOVE_TRAILING_WHITESPACE:
if (value != null) {
result = value.replaceFirst("\\s+$", EMPTY);
}
break;
case REMOVE_TRAILING_VERTICAL_WHITESPACE:
if (value != null) {
result = value.replaceFirst("\\v+$", EMPTY);
}
break;
case REVERSE:
if (value != null) {
result = new StringBuilder(value).reverse().toString();
}
break;
case TAB_TO_SPACES_2:
if (value != null) {
result = value.replaceAll("\\t", " ");
}
break;
case TAB_TO_SPACES_4:
if (value != null) {
result = value.replaceAll("\\t", " ");
}
break;
default:
result = value;
}
return result;
}
public UnaryOperator<String> stringUnaryOperator() {
return value -> operate(this, value, null);
}
public UnaryOperator<String> stringUnaryOperator(Locale locale) {
Objects.requireNonNull(locale);
return value -> operate(this, value, locale);
}
public String operate(String value) {
return operate(this, value);
}
public String operate(String value, Locale locale) {
Objects.requireNonNull(locale);
return operate(this, value, locale);
}
}
|
package tigase.server.xmppsession;
import java.util.Queue;
import java.util.logging.Logger;
import tigase.db.NonAuthUserRepository;
import tigase.server.Packet;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.NotAuthorizedException;
import tigase.xmpp.XMPPResourceConnection;
import tigase.xmpp.StanzaType;
import tigase.util.JIDUtils;
/**
* Describe class PacketFilter here.
*
*
* Created: Fri Feb 2 15:08:58 2007
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class PacketFilter {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log =
Logger.getLogger("tigase.server.xmppsession.PacketFilter");
/**
* Creates a new <code>PacketFilter</code> instance.
*
*/
public PacketFilter() { }
public boolean forward(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results) {
if (session == null) {
return false;
} // end of if (session == null)
try {
// For all messages coming from the owner of this account set
// proper 'from' attribute. This is actually needed for the case
// when the user sends a message to himself.
if (packet.getFrom() != null
&& packet.getFrom().equals(session.getConnectionId())) {
packet.getElement().setAttribute("from", session.getJID());
log.finest("Setting correct from attribute: " + session.getJID());
}
// Apparently all code below breaks all cases when packet addressed to
// the user should be processed in server on user behalf so it is commented
// for now. The correct solution is to handle all unprocessed packets in
// "process" method.
// So here we just set proper from address and that's it.
// I think we should modify all plugins code and remove setting proper
// from address as this has been already done here so no need for
// duplicated code to maintaind and process.
// // This could be earlier at the beginnig of the method, but I want to have
// // from address set properly whenever possible
// if (packet.getElemTo() == null || session.isDummy()
// || packet.getElemName().equals("presence")) {
// return false;
// String id = JIDUtils.getNodeID(packet.getElemTo());
// if (id.equals(session.getUserId())
// && packet.getFrom() != null
// && packet.getFrom().equals(packet.getElemFrom())) {
// // Yes this is message to 'this' client
// log.finest("Yes, this is packet to 'this' client: " + id);
// Element elem = packet.getElement().clone();
// Packet result = new Packet(elem);
// result.setTo(session.getParentSession().
// getResourceConnection(packet.getElemTo()).getConnectionId());
// log.finest("Setting to: " + result.getTo());
// result.setFrom(packet.getTo());
// results.offer(result);
// } else {
// // // This is message to some other client
// // Element result = packet.getElement().clone();
// // results.offer(new Packet(result));
// return false;
// } // end of else
} catch (NotAuthorizedException e) {
return false;
} // end of try-catch
return false;
}
public boolean process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results) {
if (session == null) {
return false;
} // end of if (session == null)
log.finest("Processing packet: " + packet.getStringData());
try {
// Can not forward packet if there is no destination address
if (packet.getElemTo() == null) {
// If this is simple <iq type="result"/> then ignore it
// and consider it OK
if (packet.getElemName().equals("iq")
&& packet.getType() != null
&& packet.getType() == StanzaType.result) {
// Nothing to do....
return true;
}
log.warning("No 'to' address, can't deliver packet: "
+ packet.getStringData());
return false;
}
// Already done in forward method....
// No need to repeat this (performance - everything counts...)
// // For all messages coming from the owner of this account set
// // proper 'from' attribute. This is actually needed for the case
// // when the user sends a message to himself.
// if (packet.getFrom() != null
// && packet.getFrom().equals(session.getConnectionId())) {
// packet.getElement().setAttribute("from", session.getJID());
// log.finest("Setting correct from attribute: " + session.getJID());
// } // end of if (packet.getFrom().equals(session.getConnectionId()))
String id = null;
id = JIDUtils.getNodeID(packet.getElemTo());
if (id.equals(session.getUserId())) {
// Yes this is message to 'this' client
log.finest("Yes, this is packet to 'this' client: " + id);
Element elem = packet.getElement().clone();
Packet result = new Packet(elem);
result.setTo(session.getParentSession().
getResourceConnection(packet.getElemTo()).getConnectionId());
log.finest("Setting to: " + result.getTo());
result.setFrom(packet.getTo());
results.offer(result);
return true;
} // end of else
id = JIDUtils.getNodeID(packet.getElemFrom());
if (id.equals(session.getUserId())) {
Element result = packet.getElement().clone();
results.offer(new Packet(result));
return true;
}
} catch (NotAuthorizedException e) {
log.warning("NotAuthorizedException for packet: " + packet.getStringData());
results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
"You must authorize session first.", true));
} // end of try-catch
return false;
}
}
|
package tk.kirlian.DuckShop.items;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.List;
import java.util.LinkedList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import tk.kirlian.DuckShop.*;
import tk.kirlian.DuckShop.errors.*;
/**
* Represents a tangible item, rather than money.
*/
public class TangibleItem extends Item {
/**
* The format for a tangible item: the amount as an integer, then a
* space, then the item name, then an optional durability value.
*/
private static final Pattern tangibleItemPattern = Pattern.compile("(\\d+)\\s+(\\w+|\\d+)\\s*(\\d*)");
private static final ItemDB itemDB = ItemDB.getInstance();
private int itemId;
private int amount;
private short damage;
/**
* Create a new TangibleItem instance.
* <p>
* The item string is not parsed; it is simply kept so it can be
* later retrieved by {@link #getOriginalString()}.
*/
public TangibleItem(final int itemId, final int amount, final short damage, final String itemString) {
super(itemString);
this.itemId = itemId;
this.amount = amount;
this.damage = damage;
}
/**
* Create a new TangibleItem.
*/
public TangibleItem(final int itemId, final int amount, final short damage) {
super();
this.itemId = itemId;
this.amount = amount;
this.damage = damage;
}
/**
* Parse a TangibleItem from a String.
*/
public static TangibleItem fromString(final String itemString)
throws InvalidSyntaxException {
Matcher matcher = tangibleItemPattern.matcher(itemString);
if(matcher.matches()) {
// Group 1 is definitely an integer, since it was matched with "\d+"
int amount = Integer.parseInt(matcher.group(1));
String itemName = matcher.group(2);
int itemId;
short damage = 0;
// Try parsing it as an item ID first
try {
itemId = Integer.parseInt(itemName);
} catch(NumberFormatException ex) {
// If it isn't an integer, treat it as an item name
ItemDefinition itemDfn = itemDB.getItemByAlias(itemName);
if(itemDfn == null) {
throw new InvalidSyntaxException();
} else {
itemId = itemDfn.getId();
damage = itemDfn.getDamage();
}
}
// If there's another number after that, it's a damage value
try {
damage = Short.parseShort(matcher.group(3));
} catch(NumberFormatException ex) {
// Do nothing -- keep the damage value from the code above
}
// Check if it's actually a real item
if(Material.getMaterial(itemId) == null) {
throw new InvalidSyntaxException();
}
// Create the object!
return new TangibleItem(itemId, amount, damage, itemString);
} else {
throw new InvalidSyntaxException();
}
}
/**
* Get the item ID, or the data value.
*/
public int getItemId() {
return itemId;
}
/**
* Get the number of items.
*/
public int getAmount() {
return amount;
}
/**
* Get the damage value of this object.
*/
public short getDamage() {
return damage;
}
/**
* Create a single ItemStack corresponding to this object.
*/
public ItemStack toItemStack() {
return new ItemStack(itemId, amount, damage);
}
/**
* Create an array of ItemStacks with the same data as this object,
* but grouped into stacks.
*/
public ItemStack[] toItemStackArray() {
int maxStackSize = Material.getMaterial(itemId).getMaxStackSize();
int leftover = amount;
ItemStack[] stacks;
int quotient = amount / maxStackSize;
if(amount % maxStackSize == 0) {
stacks = new ItemStack[quotient];
} else {
// If it cannot be divided evenly, the last cell will
// contain the part left over
stacks = new ItemStack[quotient+1];
stacks[quotient] = new ItemStack(itemId, amount % maxStackSize, damage);
}
for(int i = 0; i < quotient; ++i) {
stacks[i] = new ItemStack(itemId, maxStackSize, damage);
}
return stacks;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof TangibleItem) {
TangibleItem other = (TangibleItem)obj;
return (this.itemId == other.itemId && this.damage == other.damage);
} else if(obj instanceof ItemStack) {
ItemStack other = (ItemStack)obj;
return (this.itemId == other.getTypeId() && this.damage == other.getDurability());
} else {
return false;
}
}
@Override
public int hashCode() {
int hash = itemId - 199;
hash = hash * 887 + damage;
hash = hash * 887 + amount;
return hash;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder(15);
buffer.append(Integer.toString(amount));
buffer.append(" ");
ItemDefinition itemDfn = itemDB.getItemById(itemId, damage);
if(itemDfn != null) {
// If there is a specific name for this, use it
buffer.append(itemDfn.getShortName());
} else {
// Otherwise, use the generic name + damage value
itemDfn = itemDB.getItemById(itemId, (short)0);
if(itemDfn != null) {
buffer.append(itemDfn.getShortName());
buffer.append(Short.toString(damage));
} else {
// If there isn't even a generic name, just use the ID
buffer.append(Integer.toString(itemId));
if(damage != 0) {
buffer.append(" ");
buffer.append(Short.toString(damage));
}
}
}
return buffer.toString();
}
}
|
package uk.nhsbsa.gds.hack.mvc;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import java.util.List;
import java.util.UUID;
import javax.websocket.server.PathParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import uk.nhsbsa.gds.hack.data.IRepository;
import uk.nhsbsa.gds.hack.model.Order;
import uk.nhsbsa.gds.hack.service.IOrderService;
@Controller
public class OrderController {
/** Logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
@Autowired
@Qualifier("orderRepository")
private IRepository<Order, String> orderRepo;
@Autowired
private IOrderService orderService;
@RequestMapping("/orders/{id}")
public String get(Model model, @PathVariable String id) {
Order order = orderRepo.find(id);
orderService.update(order);
return "redirect:orders";
}
@RequestMapping("/orders")
public String list(Model model) {
List<Order> orders = orderRepo.findAll();
model.addAttribute("orders", orders);
return "orderList";
}
@RequestMapping(value="/orders", method=POST)
public String create(Model model, Order order) {
LOGGER.info("Creating new Order: {}", order);
order.setId(UUID.randomUUID().toString());
orderRepo.add(order);
LOGGER.info("Created new Order: {}", order);
return "redirect:/orders";
}
}
|
package yokohama.unit.translator;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import lombok.NonNull;
import lombok.SneakyThrows;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import yokohama.unit.ast.Assertion;
import yokohama.unit.ast.Definition;
import yokohama.unit.ast.EqualToMatcher;
import yokohama.unit.ast.Execution;
import yokohama.unit.ast.FourPhaseTest;
import yokohama.unit.ast.Group;
import yokohama.unit.ast.Ident;
import yokohama.unit.ast.InstanceOfMatcher;
import yokohama.unit.ast.InstanceSuchThatMatcher;
import yokohama.unit.ast.LetBindings;
import yokohama.unit.ast.Matcher;
import yokohama.unit.ast.NullValueMatcher;
import yokohama.unit.ast.Phase;
import yokohama.unit.ast.Position;
import yokohama.unit.ast.Predicate;
import yokohama.unit.ast.Proposition;
import yokohama.unit.ast.Row;
import yokohama.unit.ast.Table;
import yokohama.unit.ast.TableExtractVisitor;
import yokohama.unit.ast.TableRef;
import yokohama.unit.ast.Test;
import yokohama.unit.ast_junit.CatchClause;
import yokohama.unit.ast_junit.ClassDecl;
import yokohama.unit.ast_junit.ClassType;
import yokohama.unit.ast_junit.CompilationUnit;
import yokohama.unit.ast_junit.EqualToMatcherExpr;
import yokohama.unit.ast_junit.InstanceOfMatcherExpr;
import yokohama.unit.ast_junit.InvokeStaticExpr;
import yokohama.unit.ast_junit.IsStatement;
import yokohama.unit.ast_junit.NonArrayType;
import yokohama.unit.ast_junit.NullExpr;
import yokohama.unit.ast_junit.NullValueMatcherExpr;
import yokohama.unit.ast_junit.PrimitiveType;
import yokohama.unit.ast_junit.Span;
import yokohama.unit.ast_junit.TestMethod;
import yokohama.unit.ast_junit.Statement;
import yokohama.unit.ast_junit.TryStatement;
import yokohama.unit.ast_junit.Type;
import yokohama.unit.ast_junit.VarInitStatement;
import yokohama.unit.ast_junit.Var;
import yokohama.unit.ast_junit.VarExpr;
import yokohama.unit.util.GenSym;
import yokohama.unit.util.SUtils;
public class AstToJUnitAst {
private final Optional<Path> docyPath;
private final String className;
private final String packageName;
ExpressionStrategy expressionStrategy;
MockStrategy mockStrategy;
AstToJUnitAst(
Optional<Path> docyPath,
String className,
String packageName,
ExpressionStrategy expressionStrategy,
MockStrategy mockStrategy) {
this.docyPath = docyPath;
this.className = className;
this.packageName = packageName;
this.expressionStrategy = expressionStrategy;
this.mockStrategy = mockStrategy;
}
TableExtractVisitor tableExtractVisitor = new TableExtractVisitor();
Span spanOf(yokohama.unit.ast.Span span) {
return new Span(docyPath, span.getStart(), span.getEnd());
}
public CompilationUnit translate(String name, Group group, @NonNull String packageName) {
List<Definition> definitions = group.getDefinitions();
final List<Table> tables = tableExtractVisitor.extractTables(group);
List<TestMethod> methods =
definitions.stream()
.flatMap(definition -> definition.accept(
test -> translateTest(test, tables).stream(),
fourPhaseTest -> translateFourPhaseTest(fourPhaseTest, tables, new GenSym()).stream(),
table -> Stream.empty()))
.collect(Collectors.toList());
ClassDecl classDecl = new ClassDecl(name, methods);
return new CompilationUnit(packageName, classDecl);
}
List<TestMethod> translateTest(Test test, final List<Table> tables) {
final String name = test.getName();
List<Assertion> assertions = test.getAssertions();
List<TestMethod> testMethods =
IntStream.range(0, assertions.size())
.mapToObj(Integer::new)
.flatMap(i -> translateAssertion(assertions.get(i), i + 1, name, tables).stream())
.collect(Collectors.toList());
return testMethods;
}
List<TestMethod> translateAssertion(Assertion assertion, int index, String testName, List<Table> tables) {
String methodName = SUtils.toIdent(testName) + "_" + index;
List<Proposition> propositions = assertion.getPropositions();
return assertion.getFixture().accept(
() -> {
GenSym genSym = new GenSym();
String env = genSym.generate("env");
return Arrays.asList(
new TestMethod(
methodName,
ListUtils.union(
expressionStrategy.env(env),
propositions.stream()
.flatMap(proposition ->
translateProposition(
proposition,
genSym,
env))
.collect(Collectors.toList()))));
},
tableRef -> {
GenSym genSym = new GenSym();
String env = genSym.generate("env");
List<List<Statement>> table = translateTableRef(tableRef, tables, genSym, env);
return IntStream.range(0, table.size())
.mapToObj(Integer::new)
.map(i -> {
return new TestMethod(
methodName + "_" + (i + 1),
ListUtils.union(
expressionStrategy.env(env),
ListUtils.union(
table.get(i),
propositions
.stream()
.flatMap(proposition ->
translateProposition(
proposition,
genSym,
env))
.collect(Collectors.toList()))));
})
.collect(Collectors.toList());
},
bindings -> {
GenSym genSym = new GenSym();
String env = genSym.generate("env");
return Arrays.asList(
new TestMethod(
methodName,
ListUtils.union(
expressionStrategy.env(env),
Stream.concat(
bindings.getBindings()
.stream()
.flatMap(binding ->
translateBinding(
binding,
genSym,
env)),
propositions.stream()
.flatMap(proposition ->
translateProposition(
proposition,
genSym,
env)))
.collect(Collectors.toList()))));
});
}
Stream<Statement> translateProposition(Proposition proposition, GenSym genSym, String envVarName) {
String actual = genSym.generate("actual");
String expected = genSym.generate("expected");
Predicate predicate = proposition.getPredicate();
Stream<Statement> subjectAndPredicate = predicate.<Stream<Statement>>accept(
isPredicate -> {
return Stream.concat(
expressionStrategy.eval(
actual, envVarName, proposition.getSubject(),
genSym, docyPath, className, packageName).stream(),
translateMatcher(isPredicate.getComplement(), expected, actual, genSym, envVarName));
},
isNotPredicate -> {
// inhibit `is not instance e of Exception such that...`
isNotPredicate.getComplement().accept(
equalTo -> null,
instanceOf -> null,
instanceSuchThat -> {
throw new TranslationException(
spanOf(instanceSuchThat.getSpan()).toString() + ": " +
"`instance _ of _ such that` cannot follow `is not`");
},
nullValue -> null);
String unexpected = genSym.generate("unexpected");
return Stream.concat(
expressionStrategy.eval(
actual, envVarName, proposition.getSubject(),
genSym, docyPath, className, packageName).stream(),
Stream.concat(
translateMatcher(isNotPredicate.getComplement(), unexpected, actual, genSym, envVarName),
Stream.of(new VarInitStatement(
Type.MATCHER,
expected,
new InvokeStaticExpr(
new ClassType("org.hamcrest.CoreMatchers", Span.dummySpan()),
Arrays.asList(),
"not",
Arrays.asList(Type.MATCHER),
Arrays.asList(new Var(unexpected)),
Type.MATCHER),
spanOf(predicate.getSpan())))));
},
throwsPredicate -> {
String __ = genSym.generate("tmp");
return Stream.concat(
bindThrown(
actual,
expressionStrategy.eval(
__, envVarName, proposition.getSubject(),
genSym, docyPath, className, packageName),
genSym,
envVarName),
translateMatcher(throwsPredicate.getThrowee(), expected, actual, genSym, envVarName));
}
);
Matcher matcher = predicate.accept(
isPredicate -> isPredicate.getComplement(),
isNotPredicate -> isNotPredicate.getComplement(),
throwsPredicate -> throwsPredicate.getThrowee());
return Stream.concat(
subjectAndPredicate,
matcher instanceof InstanceSuchThatMatcher
? Stream.empty()
: Stream.of(new IsStatement(new Var(actual), new Var(expected), spanOf(predicate.getSpan()))));
}
Stream<Statement> bindThrown(String actual, List<Statement> statements, GenSym genSym, String envVarName) {
String e = genSym.generate("ex");
/*
Throwable actual;
try {
// statements
actual = null;
} catch (XXXXException e) { // extract the cause if wrapped: inserted by the strategy
actual = e.get...;
} catch (Throwable e) {
actual = e;
}
*/
return Stream.of(
new TryStatement(
ListUtils.union(
statements,
Arrays.asList(new VarInitStatement(
Type.THROWABLE, actual, new NullExpr(), Span.dummySpan()))),
Arrays.asList(expressionStrategy.catchAndAssignCause(actual, genSym),
new CatchClause(
new ClassType("java.lang.Throwable", Span.dummySpan()),
new Var(e),
Arrays.asList(new VarInitStatement(
Type.THROWABLE, actual, new VarExpr(e), Span.dummySpan())))),
Arrays.asList()));
}
Stream<Statement> translateMatcher(
Matcher matcher,
String varName,
String actual,
GenSym genSym,
String envVarName) {
return matcher.<Stream<Statement>>accept(
(EqualToMatcher equalTo) -> {
Var objVar = new Var(genSym.generate("obj"));
return Stream.concat(
expressionStrategy.eval(
objVar.getName(), envVarName, equalTo.getExpr(),
genSym, docyPath, className, packageName).stream(),
Stream.of(new VarInitStatement(
Type.MATCHER,
varName,
new EqualToMatcherExpr(objVar),
Span.dummySpan())));
},
(InstanceOfMatcher instanceOf) -> {
return Stream.of(new VarInitStatement(
Type.MATCHER,
varName,
new InstanceOfMatcherExpr(instanceOf.getClazz().getName()),
spanOf(instanceOf.getSpan())));
},
(InstanceSuchThatMatcher instanceSuchThat) -> {
String bindVarName = instanceSuchThat.getVar().getName();
yokohama.unit.ast.ClassType clazz = instanceSuchThat.getClazz();
List<Proposition> propositions = instanceSuchThat.getPropositions();
Span span = spanOf(instanceSuchThat.getSpan());
String instanceOfVarName = genSym.generate("instanceOfMatcher");
Stream<Statement> instanceOfStatements = Stream.of(
new VarInitStatement(
Type.MATCHER,
instanceOfVarName,
new InstanceOfMatcherExpr(clazz.getName()),
spanOf(clazz.getSpan())),
new IsStatement(
new Var(actual),
new Var(instanceOfVarName),
spanOf(clazz.getSpan())));
Stream<Statement> bindStatements =
expressionStrategy.bind(envVarName, bindVarName, new Var(actual), genSym)
.stream();
Stream<Statement> suchThatStatements =
propositions
.stream()
.flatMap(proposition ->
translateProposition(proposition, genSym, envVarName));
return Stream.concat(
instanceOfStatements,
Stream.concat(
bindStatements,
suchThatStatements));
},
(NullValueMatcher nullValue) -> {
return Stream.of(
new VarInitStatement(
Type.MATCHER,
varName,
new NullValueMatcherExpr(),
spanOf(nullValue.getSpan())));
});
}
Stream<Statement> translateBinding(yokohama.unit.ast.Binding binding, GenSym genSym, String envVarName) {
String name = binding.getName().getName();
String varName = genSym.generate(name);
return Stream.concat(
translateExpr(binding.getValue(), varName, genSym, envVarName),
expressionStrategy.bind(envVarName, name, new Var(varName), genSym).stream());
}
Stream<Statement> translateExpr(yokohama.unit.ast.Expr expr, String varName, GenSym genSym, String envVarName) {
return expr.accept(
quotedExpr ->
expressionStrategy.eval(
varName, envVarName, quotedExpr,
genSym, docyPath, className, packageName)
.stream(),
stubExpr -> {
return mockStrategy.stub(
varName,
stubExpr.getClassToStub(),
stubExpr.getBehavior(),
expressionStrategy,
envVarName,
genSym,
docyPath,
className,
packageName);
});
}
Type translateType(yokohama.unit.ast.Type type) {
return new Type(
translateNonArrayType(type.getNonArrayType()), type.getDims());
}
NonArrayType translateNonArrayType(yokohama.unit.ast.NonArrayType nonArrayType) {
return nonArrayType.accept(
primitiveType -> new PrimitiveType(primitiveType.getKind()),
classType -> new ClassType(
classType.getName(),
new Span(
docyPath,
classType.getSpan().getStart(),
classType.getSpan().getEnd()))
);
}
List<List<Statement>> translateTableRef(TableRef tableRef, List<Table> tables, GenSym genSym, String envVarName) {
String name = tableRef.getName();
List<String> idents = tableRef.getIdents()
.stream()
.map(Ident::getName)
.collect(Collectors.toList());
switch(tableRef.getType()) {
case INLINE:
return translateTable(
tables.stream()
.filter(table -> table.getName().equals(name))
.findFirst()
.get(),
idents,
genSym,
envVarName);
case CSV:
return parseCSV(name, CSVFormat.DEFAULT.withHeader(), idents, genSym, envVarName);
case TSV:
return parseCSV(name, CSVFormat.TDF.withHeader(), idents, genSym, envVarName);
case EXCEL:
return parseExcel(name, idents, genSym, envVarName);
}
throw new IllegalArgumentException("'" + Objects.toString(tableRef) + "' is not a table reference.");
}
List<List<Statement>> translateTable(Table table, List<String> idents, GenSym genSym, String envVarName) {
return table.getRows()
.stream()
.map(row ->
translateRow(
row,
table.getHeader()
.stream()
.map(Ident::getName)
.collect(Collectors.toList()),
idents,
genSym,
envVarName))
.collect(Collectors.toList());
}
List<Statement> translateRow(Row row, List<String> header, List<String> idents, GenSym genSym, String envVarName) {
return IntStream.range(0, header.size())
.filter(i -> idents.contains(header.get(i)))
.mapToObj(Integer::new)
.flatMap(i -> {
String varName = genSym.generate(header.get(i));
return Stream.concat(
translateExpr(row.getExprs().get(i), varName, genSym, envVarName),
expressionStrategy.bind(envVarName, header.get(i), new Var(varName), genSym).stream());
})
.collect(Collectors.toList());
}
@SneakyThrows(IOException.class)
List<List<Statement>> parseCSV(String fileName, CSVFormat format, List<String> idents, GenSym genSym, String envVarName) {
try ( final InputStream in = getClass().getResourceAsStream(fileName);
final Reader reader = new InputStreamReader(in, "UTF-8");
final CSVParser parser = new CSVParser(reader, format)) {
return StreamSupport.stream(parser.spliterator(), false)
.map(record ->
parser.getHeaderMap().keySet()
.stream()
.filter(key -> idents.contains(key))
.flatMap(name -> {
String varName = genSym.generate(name);
return Stream.concat(
expressionStrategy.eval(
varName, envVarName,
new yokohama.unit.ast.QuotedExpr(
record.get(name),
new yokohama.unit.ast.Span(
new Position((int)parser.getCurrentLineNumber(), -1),
new Position(-1, -1))),
genSym,
Optional.of(Paths.get(fileName)),
className, packageName).stream(),
expressionStrategy.bind(envVarName, name, new Var(varName), genSym).stream());
})
.collect(Collectors.toList()))
.collect(Collectors.toList());
}
}
List<List<Statement>> parseExcel(String fileName, List<String> idents, GenSym genSym, String envVarName) {
try (InputStream in = getClass().getResourceAsStream(fileName)) {
final Workbook book = WorkbookFactory.create(in);
final Sheet sheet = book.getSheetAt(0);
final int top = sheet.getFirstRowNum();
final int left = sheet.getRow(top).getFirstCellNum();
List<String> names = StreamSupport.stream(sheet.getRow(top).spliterator(), false)
.map(cell -> cell.getStringCellValue())
.collect(Collectors.toList());
return StreamSupport.stream(sheet.spliterator(), false)
.skip(1)
.map(row ->
IntStream.range(0, names.size())
.filter(i -> idents.contains(names.get(i)))
.mapToObj(Integer::new)
.flatMap(i -> {
String varName = genSym.generate(names.get(i));
return Stream.concat(
expressionStrategy.eval(
varName, envVarName,
new yokohama.unit.ast.QuotedExpr(
row.getCell(left + i).getStringCellValue(),
new yokohama.unit.ast.Span(
new Position(row.getRowNum() + 1, left + i + 1),
new Position(-1, -1))),
genSym,
Optional.of(Paths.get(fileName)),
className, packageName).stream(),
expressionStrategy.bind(envVarName, names.get(i), new Var(varName), genSym).stream());
})
.collect(Collectors.toList()))
.collect(Collectors.toList());
} catch (InvalidFormatException | IOException e) {
throw new TranslationException(e);
}
}
List<TestMethod> translateFourPhaseTest(FourPhaseTest fourPhaseTest, List<Table> tables, GenSym genSym) {
String env = genSym.generate("env");
String testName = SUtils.toIdent(fourPhaseTest.getName());
Stream<Statement> bindings;
if (fourPhaseTest.getSetup().isPresent()) {
Phase setup = fourPhaseTest.getSetup().get();
if (setup.getLetBindings().isPresent()) {
LetBindings letBindings = setup.getLetBindings().get();
bindings = letBindings.getBindings()
.stream()
.flatMap(binding -> {
String varName = genSym.generate(binding.getName());
return Stream.concat(
translateExpr(binding.getValue(), varName, genSym, env),
expressionStrategy.bind(env, binding.getName(), new Var(varName), genSym).stream());
});
} else {
bindings = Stream.empty();
}
} else {
bindings = Stream.empty();
}
Optional<Stream<Statement>> setupActions =
fourPhaseTest.getSetup()
.map(Phase::getExecutions)
.map(execition -> translateExecutions(execition, genSym, env));
Optional<Stream<Statement>> exerciseActions =
fourPhaseTest.getExercise()
.map(Phase::getExecutions)
.map(execution -> translateExecutions(execution, genSym, env));
Stream<Statement> testStatements = fourPhaseTest.getVerify().getAssertions()
.stream()
.flatMap(assertion ->
assertion.getPropositions()
.stream()
.flatMap(proposition -> translateProposition(proposition, genSym, env))
);
List<Statement> statements =
Stream.concat(
bindings,
Stream.concat(
Stream.concat(
setupActions.isPresent() ? setupActions.get() : Stream.empty(),
exerciseActions.isPresent() ? exerciseActions.get() : Stream.empty()),
testStatements)
).collect(Collectors.toList());
List<Statement> actionsAfter;
if (fourPhaseTest.getTeardown().isPresent()) {
Phase teardown = fourPhaseTest.getTeardown().get();
actionsAfter = translateExecutions(teardown.getExecutions(), genSym, env).collect(Collectors.toList());
} else {
actionsAfter = Arrays.asList();
}
return Arrays.asList(
new TestMethod(
testName,
ListUtils.union(
expressionStrategy.env(env),
actionsAfter.size() > 0
? Arrays.asList(
new TryStatement(
statements,
Arrays.asList(),
actionsAfter))
: statements)));
}
Stream<Statement> translateExecutions(List<Execution> executions, GenSym genSym, String envVarName) {
String __ = genSym.generate("__");
return executions.stream()
.flatMap(execution ->
execution.getExpressions()
.stream()
.flatMap(expression ->
expressionStrategy.eval(
__,
envVarName,
expression,
genSym,
docyPath,
className,
packageName).stream()));
}
}
|
package de.factoryfx.javafx.stage;
import java.util.List;
import de.factoryfx.javafx.view.container.ViewsDisplayWidget;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class BorderPaneStage {
public BorderPaneStage(Stage stage, List<Menu> menus, ViewsDisplayWidget instance, int width, int height, StackPane stackPane, List<String> cssResourceUrlExternalForm) {
BorderPane root = new BorderPane();
root.setCenter(instance.createContent());
MenuBar menuBar = new MenuBar();
menuBar.getMenus().addAll(menus);
root.setTop(menuBar);
stackPane.getChildren().add(root);
for (String cssUrl: cssResourceUrlExternalForm){
root.getStylesheets().add(cssUrl);
}
stage.setScene(new Scene(stackPane,width,height));
}
}
|
package org.silverpeas.test;
import com.silverpeas.SilverpeasContent;
import com.silverpeas.admin.components.Parameter;
import com.silverpeas.admin.components.PasteDetail;
import com.silverpeas.admin.components.PasteDetailFromToPK;
import com.silverpeas.admin.components.WAComponent;
import com.silverpeas.admin.spaces.SpaceTemplate;
import com.silverpeas.session.SessionInfo;
import com.silverpeas.ui.DisplayI18NHelper;
import com.stratelia.silverpeas.contentManager.SilverContentInterface;
import com.stratelia.silverpeas.domains.DriverSettings;
import com.stratelia.silverpeas.notificationManager.constant.NotifChannel;
import com.stratelia.silverpeas.peasCore.URLManager;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.webactiv.SilverpeasRole;
import com.stratelia.webactiv.beans.admin.*;
import com.stratelia.webactiv.organization.ScheduledDBReset;
import org.silverpeas.EntityReference;
import org.silverpeas.admin.user.constant.UserAccessLevel;
import org.silverpeas.admin.user.constant.UserState;
import org.silverpeas.attachment.model.SimpleDocumentPK;
import org.silverpeas.contribution.model.Contribution;
import org.silverpeas.core.IdentifiableResource;
import org.silverpeas.core.ResourceIdentifier;
import org.silverpeas.core.admin.OrganizationController;
import org.silverpeas.core.admin.OrganizationControllerProvider;
import org.silverpeas.persistence.Transaction;
import org.silverpeas.persistence.TransactionProvider;
import org.silverpeas.persistence.TransactionRuntimeException;
import org.silverpeas.persistence.model.jpa.AbstractJpaEntity;
import org.silverpeas.profile.UserReference;
import org.silverpeas.quota.QuotaKey;
import org.silverpeas.quota.exception.QuotaException;
import org.silverpeas.quota.exception.QuotaRuntimeException;
import org.silverpeas.quota.service.QuotaService;
import org.silverpeas.util.*;
import org.silverpeas.util.comparator.AbstractComparator;
import org.silverpeas.util.comparator.AbstractComplexComparator;
import org.silverpeas.util.exception.FromModule;
import org.silverpeas.util.exception.RelativeFileAccessException;
import org.silverpeas.util.exception.SilverpeasException;
import org.silverpeas.util.exception.SilverpeasRuntimeException;
import org.silverpeas.util.exception.UtilException;
import org.silverpeas.util.exception.WithNested;
import org.silverpeas.util.fileFolder.FileFolderManager;
import org.silverpeas.util.pool.ConnectionPool;
import org.silverpeas.util.template.SilverpeasTemplate;
/**
* This builder extends the {@link WarBuilder} in order to centralize the definition of common
* archive part definitions.
* @author Yohann Chastagnier
*/
public class WarBuilder4LibCore extends WarBuilder<WarBuilder4LibCore> {
/**
* Constructs a war builder for the specified test class. It will load all the resources in the
* same packages of the specified test class.
* @param test the class of the test for which a war archive will be build.
*/
protected <T> WarBuilder4LibCore(final Class<T> test) {
super(test);
}
/**
* Gets an instance of a war archive builder for the specified test class with the
* following common stuffs:
* <ul>
* <li>the resources located in the same package of the specified test class,</li>
* <li>{@link ServiceProvider} features.</li>
* <li>the SilverTrace subsystem subbed,</li>
* <li>the base i18n bundle loaded.</li>
* </ul>
* @return the instance of the war archive builder.
*/
public static <T> WarBuilder4LibCore onWarForTestClass(Class<T> test) {
WarBuilder4LibCore warBuilder = new WarBuilder4LibCore(test);
warBuilder.addClasses(SilverTrace.class);
warBuilder.addServiceProviderFeatures();
warBuilder.addBundleBaseFeatures();
warBuilder.addClasses(EntityReference.class);
warBuilder.addAsResource("maven.properties");
return warBuilder;
}
/**
* Adds cache features:
* <ul>
* <li>ehcache maven dependencies</li>
* <li>org.silverpeas.cache</li>
* </ul>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addCacheFeatures() {
if (!contains("org.silverpeas.cache")) {
addMavenDependencies("net.sf.ehcache:ehcache-core");
addPackages(true, "org.silverpeas.cache");
addClasses(SessionInfo.class);
}
return this;
}
/**
* Adds common utilities classes:
* <ul>
* <li>{@link ArrayUtil}</li>
* <li>{@link StringUtil}</li>
* <li>{@link CollectionUtil}</li>
* <li>{@link MapUtil}</li>
* <li>{@link DateUtil}</li>
* <li>{@link AssertArgument}</li>
* <li>{@link EncodeHelper}</li>
* <li>{@link ActionType} and classes in {@link org.silverpeas.util.annotation}</li>
* <li>{@link #addSilverpeasContentFeatures()}</li>
* <li>{@link AbstractComplexComparator}</li>
* <li>{@link AbstractComparator}</li>
* <li>{@link ListSlice}</li>
* </ul>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addCommonBasicUtilities() {
if (!contains(ArrayUtil.class)) {
addClasses(ArrayUtil.class);
}
if (!contains(StringUtil.class)) {
addClasses(StringUtil.class);
}
if (!contains(MapUtil.class)) {
addClasses(MapUtil.class);
}
if (!contains(ArrayUtil.class)) {
addClasses(ArrayUtil.class);
}
if (!contains(EncodeHelper.class)) {
addClasses(EncodeHelper.class);
}
if (!contains(DateUtil.class)) {
addClasses(DateUtil.class);
addPackages(true, "com.silverpeas.calendar");
}
if (!contains(Charsets.class)) {
addClasses(Charsets.class);
}
if (!contains(CollectionUtil.class)) {
addClasses(CollectionUtil.class, ExtractionList.class, ExtractionComplexList.class);
}
if (!contains(AssertArgument.class)) {
addClasses(AssertArgument.class);
}
if (!contains(ActionType.class)) {
addSilverpeasContentFeatures();
addClasses(ActionType.class);
addPackages(false, "org.silverpeas.util.annotation");
}
if (!contains(AbstractComplexComparator.class)) {
addClasses(AbstractComplexComparator.class, AbstractComparator.class);
}
if (!contains(ListSlice.class)) {
addClasses(ListSlice.class);
}
return this;
}
/**
* Sets common user beans.
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addCommonUserBeans() {
if (!contains(UserDetail.class)) {
addClasses(UserDetail.class, UserAccessLevel.class, UserState.class);
}
if (!contains(UserFull.class)) {
addClasses(UserFull.class);
}
if (!contains(UserLog.class)) {
addClasses(UserLog.class);
}
if (!contains(Domain.class)) {
addClasses(Domain.class);
}
if (!contains(UserReference.class)) {
addClasses(UserReference.class);
}
return this;
}
/**
* Adds bases of Silverpeas exception classes:
* <ul>
* <li>{@link WithNested}</li>
* <li>{@link FromModule}</li>
* <li>{@link SilverpeasException}</li>
* <li>{@link SilverpeasRuntimeException}</li>
* <li>{@link UtilException}</li>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addSilverpeasExceptionBases() {
if (!contains(SilverpeasException.class)) {
addClasses(WithNested.class);
addClasses(FromModule.class);
addClasses(SilverpeasException.class);
addClasses(SilverpeasRuntimeException.class);
addClasses(UtilException.class);
}
return this;
}
/**
* Adds bundle features.
* @return the instance of the war builder.
*/
private WarBuilder4LibCore addBundleBaseFeatures() {
if (!contains(ResourceLocator.class)) {
addClasses(ResourceLocator.class, DisplayI18NHelper.class, ConfigurationClassLoader.class,
ConfigurationControl.class, VariableResolver.class, PropertiesWrapper.class,
ResourceBundleWrapper.class, FileUtil.class, MimeTypes.class,
RelativeFileAccessException.class, GeneralPropertiesManager.class);
addAsResource("org/silverpeas/general.properties");
addAsResource("org/silverpeas/multilang/generalMultilang.properties");
addAsResource("org/silverpeas/lookAndFeel/generalLook.properties");
addAsResource("org/silverpeas/util/i18n.properties");
addAsResource("org/silverpeas/util/multilang/i18n_fr.properties");
addAsResource("org/silverpeas/util/multilang/i18n_en.properties");
addAsResource("org/silverpeas/util/multilang/util.properties");
addAsResource("org/silverpeas/util/multilang/util_fr.properties");
addAsResource("org/silverpeas/util/multilang/util_en.properties");
}
return this;
}
/**
* Adds URL features.
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addSilverpeasUrlFeatures() {
if (!contains(URLManager.class)) {
addClasses(URLManager.class);
}
return this;
}
/**
* Adds common classes to handle silverpeas content features.
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addSilverpeasContentFeatures() {
if (!contains(Contribution.class)) {
addClasses(Contribution.class, IdentifiableResource.class);
}
if (!contains(SilverpeasContent.class)) {
addClasses(SilverpeasContent.class);
}
if (!contains(SilverContentInterface.class)) {
addClasses(SilverContentInterface.class);
}
if (!contains(WAPrimaryKey.class)) {
addClasses(WAPrimaryKey.class, ForeignPK.class, SimpleDocumentPK.class, PasteDetail.class,
PasteDetailFromToPK.class);
}
return this;
}
/**
* Adds file repository features.
* Calls automatically:
* <ul>
* <li>{@link #addBundleBaseFeatures()}</li>
* <li>{@link #addSilverpeasUrlFeatures()}</li>
* <li>{@link #addCommonBasicUtilities()}</li>
* </ul>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addFileRepositoryFeatures() {
addBundleBaseFeatures();
addSilverpeasUrlFeatures();
addCommonBasicUtilities();
if (!contains(FileRepositoryManager.class)) {
addClasses(FileRepositoryManager.class, FileFolderManager.class);
}
return this;
}
/**
* Sets JDBC persistence features.
* Calls automatically:
* <ul>
* <li>{@link #addCommonBasicUtilities()}</li>
* </ul>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addJdbcPersistenceFeatures() {
addCommonBasicUtilities();
if (!contains(DBUtil.class)) {
addClasses(DBUtil.class, ConnectionPool.class, Transaction.class, TransactionProvider.class,
TransactionRuntimeException.class);
addPackages(false, "org.silverpeas.persistence.jdbc");
}
return this;
}
/**
* Sets JPA persistence features.
* Calls automatically:
* <ul>
* <li>{@link #addJdbcPersistenceFeatures()}</li>
* <li>{@link #addBundleBaseFeatures()}</li>
* <li>{@link #addCacheFeatures()}</li>
* <li>{@link #addCommonUserBeans()}</li>
* </ul>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addJpaPersistenceFeatures() {
addJdbcPersistenceFeatures();
addBundleBaseFeatures();
addCacheFeatures();
addCommonUserBeans();
if (!contains(AbstractJpaEntity.class)) {
addClasses(ResourceIdentifier.class);
addPackages(true, "org.silverpeas.admin.user.constant");
addPackages(true, "org.silverpeas.persistence.model");
addPackages(true, "org.silverpeas.persistence.repository");
addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml");
}
return this;
}
/**
* Sets stubbed administration features.
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addStubbedAdministrationFeatures() {
if (!contains(StubbedAdministration.class)) {
addClasses(StubbedAdministration.class);
addCommonUserBeans();
addClasses(AdministrationServiceProvider.class, Administration.class, Parameter.class,
PasteDetail.class, WAComponent.class, SpaceTemplate.class, ComponentInst.class,
ComponentInstLight.class, SpaceInst.class, SpaceInstLight.class, CompoSpace.class,
QuotaException.class, ProfileInst.class, SpaceAndChildren.class, SpaceProfileInst.class,
Group.class, GroupProfileInst.class, AdminGroupInst.class, SearchCriteria.class,
UserDetailsSearchCriteria.class, GroupsSearchCriteria.class, DomainProperty.class);
addClasses(Recover.class, AdminException.class);
addPackages(true, "org.silverpeas.util.i18n");
// Exclusions
applyManually(war -> war.deleteClass("com.stratelia.webactiv.beans.admin.Admin"));
}
return this;
}
/**
* Adds common administration utilities.
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addAdministrationUtilities() {
if (!contains(SilverpeasRole.class)) {
addClasses(SilverpeasRole.class);
}
if (!contains(AdminException.class)) {
addClasses(AdminException.class);
}
if (!contains(QuotaException.class)) {
addClasses(QuotaException.class, QuotaKey.class, QuotaRuntimeException.class);
}
return this;
}
/**
* Sets string template features.
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addStringTemplateFeatures() {
if (!contains(SilverpeasTemplate.class)) {
addMavenDependencies("org.antlr:stringtemplate");
addPackages(true, "org.silverpeas.util.template");
addAsResource("org/silverpeas/util/stringtemplate.properties");
}
return this;
}
/**
* Sets Quota Bases features.
* Calls automatically:
* <ul>
* <li>{@link #addJpaPersistenceFeatures()}</li>
* </ul>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addQuotaBasesFeatures() {
if (!contains(QuotaService.class)) {
addClasses(QuotaService.class);
addPackages(true, "org.silverpeas.quota");
// Centralized features
addJpaPersistenceFeatures();
}
return this;
}
/**
* Sets notification features.
* Calls automatically:
* <ul>
* <li>{@link #addSilverpeasUrlFeatures()}</li>
* </ul>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addNotificationFeatures() {
if (!contains(NotifChannel.class)) {
addPackages(true, "com.stratelia.silverpeas.notificationManager");
addPackages(true, "com.stratelia.silverpeas.notificationserver");
addAsResource("org/silverpeas/notificationManager");
addClasses(JNDINames.class, AbstractTable.class);
addAsResource("org/silverpeas/util/jndi.properties");
// Centralized features
addSilverpeasUrlFeatures();
}
return this;
}
/**
* Sets administration features.
* Calls automatically:
* <ul>
* <li>{@link #addJpaPersistenceFeatures()}</li>
* <li>{@link #addQuotaBasesFeatures()}</li>
* <li>{@link #addStringTemplateFeatures()}</li>
* <li>{@link #addAdministrationUtilities()}</li>
* <li>{@link #addCommonUserBeans()}</li>
* <li>{@link #addOrganisationFeatures()}</li>
* <li>{@link #addSchedulerFeatures()}</li>
* </ul>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addAdministrationFeatures() {
if (!contains(Administration.class)) {
addClasses(Administration.class, ScheduledDBReset.class);
addClasses(Recover.class);
addClasses(DriverSettings.class);
addPackages(true, "org.silverpeas.util.i18n");
addPackages(true, "com.silverpeas.admin.components");
addPackages(true, "com.silverpeas.admin.spaces");
addPackages(true, "com.silverpeas.domains");
addPackages(true, "com.stratelia.silverpeas.domains.sqldriver");
addPackages(true, "com.stratelia.webactiv.beans.admin");
addPackages(false, "org.silverpeas.notification");
addPackages(true, "org.silverpeas.admin.component.notification");
addPackages(true, "org.silverpeas.admin.space.notification");
addPackages(true, "org.silverpeas.admin.user.constant");
addPackages(true, "org.silverpeas.admin.user.notification");
addPackages(true, "org.silverpeas.util.clipboard");
addAsResource("org/silverpeas/admin/roleMapping.properties");
addAsResource("org/silverpeas/beans/admin/admin.properties");
addAsResource("org/silverpeas/beans/admin/instance/control/instanciator.properties");
// Exclusions
applyManually(war -> war.deleteClass(StubbedAdministration.class));
// Centralized features
addJpaPersistenceFeatures();
addQuotaBasesFeatures();
addStringTemplateFeatures();
addAdministrationUtilities();
addCommonUserBeans();
addOrganisationFeatures();
addSchedulerFeatures();
}
return this;
}
/**
* Sets organisation features.
* Calls automatically:
* <ul>
* <li>{@link #addAdministrationFeatures()}</li>
* </ul>
* @return the instance of the war builder.
*/
public WarBuilder4LibCore addOrganisationFeatures() {
if (!contains(OrganizationController.class)) {
addClasses(OrganizationController.class, OrganizationControllerProvider.class);
addPackages(true, "com.stratelia.webactiv.organization");
addPackages(true, "com.stratelia.webactiv.persistence");
addClasses(Schema.class, SchemaPool.class);
// Centralized features
addAdministrationFeatures();
}
return this;
}
/**
* Sets manual CDI features.
* @return the instance of the war builder.
*/
private WarBuilder4LibCore addServiceProviderFeatures() {
addClasses(CDIContainer.class).addPackages(true, "org.silverpeas.initialization");
return this;
}
/**
* Add scheduler features in web archive (war) with quartz libraries.
* @return the instance of the war builder with scheduler features.
*/
public WarBuilder4LibCore addSchedulerFeatures() {
if (!contains("com.silverpeas.scheduler")) {
addMavenDependencies("org.quartz-scheduler:quartz");
addPackages(true, "com.silverpeas.scheduler");
}
return this;
}
/**
* Add benchmark test features in web archive (war).
* @return the instance of the war builder with benchmark test features.
*/
public WarBuilder4LibCore addBenchmarkTestFeatures() {
addMavenDependencies("com.carrotsearch:junit-benchmarks");
return this;
}
/**
* Add novell jldap libraries in web archive (war)
* @return the instance of the war builder with novell jldap
*/
public WarBuilder4LibCore addLDAPFeatures() {
addMavenDependencies("com.novell.ldap:jldap", "org.forgerock.opendj:opendj-server");
return this;
}
}
|
package gov.va.isaac.gui.mapping.data;
import gov.va.isaac.ExtendedAppContext;
import gov.va.isaac.constants.ISAAC;
import gov.va.isaac.util.OTFUtility;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.ihtsdo.otf.tcc.api.blueprint.IdDirective;
import org.ihtsdo.otf.tcc.api.blueprint.InvalidCAB;
import org.ihtsdo.otf.tcc.api.blueprint.RefexDirective;
import org.ihtsdo.otf.tcc.api.blueprint.RefexDynamicCAB;
import org.ihtsdo.otf.tcc.api.concept.ConceptChronicleBI;
import org.ihtsdo.otf.tcc.api.contradiction.ContradictionException;
import org.ihtsdo.otf.tcc.api.coordinate.Status;
import org.ihtsdo.otf.tcc.api.refexDynamic.RefexDynamicChronicleBI;
import org.ihtsdo.otf.tcc.api.refexDynamic.RefexDynamicVersionBI;
import org.ihtsdo.otf.tcc.api.refexDynamic.data.RefexDynamicDataBI;
import org.ihtsdo.otf.tcc.model.cc.refexDynamic.data.dataTypes.RefexDynamicString;
import org.ihtsdo.otf.tcc.model.index.service.SearchResult;
public class MappingItemCommentDAO extends MappingDAO
{
/**
* Create (and store to the DB) a new comment
* @param pMappingItemUUID - The item the comment is being added to
* @param pCommentText - The text of the comment
* @param commentContext - (optional) field for storing other arbitrary info about the comment. An editor may wish to put certain keywords on
* some comments - this field is indexed, so a search for comments could query this field.
* @throws IOException
*/
public static MappingItemComment createMappingItemComment(UUID pMappingItemUUID, String pCommentText, String commentContext) throws IOException
{
if (pMappingItemUUID == null)
{
throw new IOException("UUID of component to attach the comment to is required");
}
if (StringUtils.isBlank(pCommentText))
{
throw new IOException("The comment is required");
}
try
{
RefexDynamicCAB commentAnnotation = new RefexDynamicCAB(pMappingItemUUID, ISAAC.COMMENT_ATTRIBUTE.getPrimodialUuid());
commentAnnotation.setData(new RefexDynamicDataBI[] {
new RefexDynamicString(pCommentText),
(StringUtils.isBlank(commentContext) ? null : new RefexDynamicString(commentContext))}, null);
commentAnnotation.computeMemberUuid();
if (ExtendedAppContext.getDataStore().hasUuid(commentAnnotation.getComponentUuid()))
{
throw new IOException("A comment of that value already exists on that item.");
}
RefexDynamicChronicleBI<?> rdc = OTFUtility.getBuilder().construct(commentAnnotation);
ConceptChronicleBI cc = ExtendedAppContext.getDataStore().getConcept(rdc.getConceptNid());
ExtendedAppContext.getDataStore().addUncommitted(cc);
ExtendedAppContext.getDataStore().commit(cc);
return new MappingItemComment((RefexDynamicVersionBI<?>) ExtendedAppContext.getDataStore().getComponentVersion(OTFUtility.getViewCoordinate(), rdc.getPrimordialUuid()));
}
catch (InvalidCAB | ContradictionException | PropertyVetoException e)
{
throw new IOException("Unexpected error", e);
}
}
/**
* Read all comments for a particular mapping item (which could be a mapping set, or a mapping item)
* @param mappingUUID - The UUID of a MappingSet or a MappingItem
* @param activeOnly - when true, only return active comments
* @return
* @throws IOException
*/
public static List<MappingItemComment> getComments(UUID mappingUUID, boolean activeOnly) throws IOException {
List<MappingItemComment> comments = new ArrayList<MappingItemComment>();
try
{
int mappingNid = ExtendedAppContext.getDataStore().getNidForUuids(mappingUUID);
for (SearchResult sr : search(ISAAC.COMMENT_ATTRIBUTE.getPrimodialUuid()))
{
RefexDynamicVersionBI<?> rc = (RefexDynamicVersionBI<?>) ExtendedAppContext.getDataStore().
getComponentVersion(OTFUtility.getViewCoordinate(), sr.getNid());
if (rc != null)
{
if (activeOnly && !rc.isActive())
{
continue;
}
if (rc.getReferencedComponentNid() == mappingNid)
{
comments.add(new MappingItemComment(rc));
}
}
}
}
catch (ContradictionException e)
{
LOG.error("Unexpected error reading comments", e);
throw new IOException("internal error reading comments");
}
return comments;
}
/**
* @param commentPrimordialUUID - The ID of the comment to be re-activated
* @throws IOException
*/
public void unRetireComment(UUID commentPrimordialUUID) throws IOException
{
setRefexStatus(commentPrimordialUUID, Status.ACTIVE);
}
/**
* @param commentPrimordialUUID - The ID of the comment to be retired
* @throws IOException
*/
public void retireComment(UUID commentPrimordialUUID) throws IOException
{
setRefexStatus(commentPrimordialUUID, Status.INACTIVE);
}
/**
* Store the values passed in as a new revision of a comment (the old revision remains in the DB)
* @param comment - The MappingItemComment with revisions (contains fields where the setters have been called)
* @throws IOException
*/
public void updateComment(MappingItemComment comment) throws IOException
{
try
{
RefexDynamicVersionBI<?> rdv = readCurrentRefex(comment.getPrimordialUUID());
RefexDynamicCAB commentCab = rdv.makeBlueprint(OTFUtility.getViewCoordinate(), IdDirective.PRESERVE, RefexDirective.EXCLUDE);
commentCab.getData()[0] = new RefexDynamicString(comment.getCommentText());
commentCab.getData()[1] = (StringUtils.isNotBlank(comment.getCommentContext()) ? new RefexDynamicString(comment.getCommentContext()) : null);
RefexDynamicChronicleBI<?> rdc = OTFUtility.getBuilder().construct(commentCab);
ConceptChronicleBI cc = ExtendedAppContext.getDataStore().getConcept(rdc.getConceptNid());
ExtendedAppContext.getDataStore().addUncommitted(cc);
ExtendedAppContext.getDataStore().commit(cc);
}
catch (InvalidCAB | ContradictionException | PropertyVetoException e)
{
LOG.error("Unexpected!", e);
throw new IOException("Internal error");
}
}
}
|
package com.haulmont.cuba.core.sys.persistence;
import org.apache.openjpa.jdbc.sql.*;
import org.apache.openjpa.jdbc.schema.ForeignKey;
import org.apache.openjpa.jdbc.schema.Column;
import org.apache.openjpa.jdbc.schema.Table;
import com.haulmont.cuba.core.PersistenceProvider;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
public class DBDictionaryUtils
{
private static final String DELETE_TS_COL = "DELETE_TS";
public static SQLBuffer toTraditionalJoin(DBDictionary dbDictionary, Join join) {
ForeignKey fk = join.getForeignKey();
if (fk == null)
return null;
boolean inverse = join.isForeignKeyInversed();
Column[] from = (inverse) ? fk.getPrimaryKeyColumns()
: fk.getColumns();
Column[] to = (inverse) ? fk.getColumns()
: fk.getPrimaryKeyColumns();
// do column joins
SQLBuffer buf = new SQLBuffer(dbDictionary);
int count = 0;
for (int i = 0; i < from.length; i++, count++) {
if (count > 0)
buf.append(" AND ");
buf.append(join.getAlias1()).append(".").append(from[i]);
buf.append(" = ");
buf.append(join.getAlias2()).append(".").append(to[i]);
// KK: support deferred delete for collections
if (inverse
&& to[i].getTable().containsColumn(DELETE_TS_COL)
&& PersistenceProvider.getEntityManager().isDeleteDeferred())
{
buf.append(" AND ");
buf.append(join.getAlias2()).append(".").append(DELETE_TS_COL).append(" IS NULL");
}
}
// do constant joins
Column[] constCols = fk.getConstantColumns();
for (int i = 0; i < constCols.length; i++, count++) {
if (count > 0)
buf.append(" AND ");
if (inverse)
buf.appendValue(fk.getConstant(constCols[i]), constCols[i]);
else
buf.append(join.getAlias1()).append(".").
append(constCols[i]);
buf.append(" = ");
if (inverse)
buf.append(join.getAlias2()).append(".").
append(constCols[i]);
else
buf.appendValue(fk.getConstant(constCols[i]), constCols[i]);
}
Column[] constColsPK = fk.getConstantPrimaryKeyColumns();
for (int i = 0; i < constColsPK.length; i++, count++) {
if (count > 0)
buf.append(" AND ");
if (inverse)
buf.append(join.getAlias1()).append(".").
append(constColsPK[i]);
else
buf.appendValue(fk.getPrimaryKeyConstant(constColsPK[i]),
constColsPK[i]);
buf.append(" = ");
if (inverse)
buf.appendValue(fk.getPrimaryKeyConstant(constColsPK[i]),
constColsPK[i]);
else
buf.append(join.getAlias2()).append(".").
append(constColsPK[i]);
}
return buf;
}
public static SQLBuffer getWhere(DBDictionary dbDictionary, Select sel, boolean forUpdate) {
Joins joins = sel.getJoins();
if (sel.getJoinSyntax() == JoinSyntaxes.SYNTAX_SQL92
|| joins == null || joins.isEmpty())
{
SQLBuffer buf = sel.getWhere();
if (!PersistenceProvider.getEntityManager().isDeleteDeferred())
return buf;
Map<Table, String> tables = new HashMap<Table, String>();
Collection columns;
if (buf != null) {
columns = buf.getColumns();
}
else {
columns = sel.getSelects();
}
if (columns != null) {
for (Object item : columns) {
if (item instanceof Column) {
Column col = (Column) item;
for (String s : (Collection<String>) sel.getTableAliases()) {
int i = s.indexOf(' ');
String tableName = s.substring(0, i);
if (col.getTable().getName().equals(tableName)) {
if (col.getTable().containsColumn(DELETE_TS_COL))
tables.put(col.getTable(), s.substring(i + 1));
break;
}
}
}
}
}
StringBuilder sb = new StringBuilder();
for (String alias : tables.values()) {
if (sb.length() > 0)
sb.append(" AND ");
sb.append(alias).append(".").append(DELETE_TS_COL).append(" IS NULL");
}
sel.where(sb.toString());
return sel.getWhere();
}
SQLBuffer where = new SQLBuffer(dbDictionary);
if (sel.getWhere() != null)
where.append(sel.getWhere());
if (joins != null)
sel.append(where, joins);
return where;
}
}
|
package sk.henrichg.phoneprofilesplus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.telephony.PhoneNumberUtils;
import android.text.format.DateFormat;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TimeZone;
public class DataWrapper {
public Context context = null;
private boolean forGUI = false;
private boolean monochrome = false;
private int monochromeValue = 0xFF;
private Handler toastHandler;
private DatabaseHandler databaseHandler = null;
private ActivateProfileHelper activateProfileHelper = null;
private List<Profile> profileList = null;
private List<Event> eventList = null;
DataWrapper(Context c,
boolean fgui,
boolean mono,
int monoVal)
{
context = c;
setParameters(fgui, mono, monoVal);
databaseHandler = getDatabaseHandler();
}
public void setParameters(
boolean fgui,
boolean mono,
int monoVal)
{
forGUI = fgui;
monochrome = mono;
monochromeValue = monoVal;
}
public void setToastHandler(Handler handler)
{
toastHandler = handler;
}
public DatabaseHandler getDatabaseHandler()
{
if (databaseHandler == null)
// parameter must by application context
databaseHandler = DatabaseHandler.getInstance(context);
return databaseHandler;
}
public ActivateProfileHelper getActivateProfileHelper()
{
if (activateProfileHelper == null)
activateProfileHelper = new ActivateProfileHelper();
return activateProfileHelper;
}
public List<Profile> getProfileList()
{
if (profileList == null)
{
profileList = getDatabaseHandler().getAllProfiles();
if (forGUI)
{
for (Profile profile : profileList)
{
profile.generateIconBitmap(context, monochrome, monochromeValue);
//if (generateIndicators)
profile.generatePreferencesIndicator(context, monochrome, monochromeValue);
}
}
}
return profileList;
}
public void setProfileList(List<Profile> profileList, boolean recycleBitmaps)
{
if (recycleBitmaps)
invalidateProfileList();
else
if (this.profileList != null)
this.profileList.clear();
this.profileList = profileList;
}
public Profile getNoinitializedProfile(String name, String icon, int order)
{
return new Profile(
name,
icon + "|1",
false,
order,
0,
"-1|1|0",
"-1|1|0",
"-1|1|0",
"-1|1|0",
"-1|1|0",
"-1|1|0",
0,
Settings.System.DEFAULT_RINGTONE_URI.toString(),
0,
Settings.System.DEFAULT_NOTIFICATION_URI.toString(),
0,
Settings.System.DEFAULT_ALARM_ALERT_URI.toString(),
0,
0,
0,
0,
Profile.BRIGHTNESS_ADAPTIVE_BRIGHTNESS_NOT_SET+"|1|1|0",
0,
"-|0",
0,
0,
0,
0,
"-",
0,
false,
0,
0,
0,
0,
0,
Profile.AFTERDURATIONDO_NOTHING,
0,
0,
0
);
}
private String getVolumeLevelString(int percentage, int maxValue)
{
Double dValue = maxValue / 100.0 * percentage;
return String.valueOf(dValue.intValue());
}
public List<Profile> getDefaultProfileList()
{
invalidateProfileList();
getDatabaseHandler().deleteAllProfiles();
AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
int maximumValueRing = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
int maximumValueNotification = audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
int maximumValueMusic = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int maximumValueAlarm = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
//int maximumValueSystem = audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
//int maximumValueVoicecall = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
Profile profile;
profile = getNoinitializedProfile(context.getString(R.string.default_profile_name_home), "ic_profile_home_2", 1);
profile._showInActivator = true;
profile._volumeRingerMode = 1;
profile._volumeRingtone = getVolumeLevelString(71, maximumValueRing)+"|0|0";
profile._volumeNotification = getVolumeLevelString(86, maximumValueNotification)+"|0|0";
profile._volumeAlarm = getVolumeLevelString(100, maximumValueAlarm)+"|0|0";
profile._volumeMedia = getVolumeLevelString(80, maximumValueMusic)+"|0|0";
profile._deviceWiFi = 1;
//profile._deviceBrightness = "60|0|0|0";
getDatabaseHandler().addProfile(profile, false);
profile = getNoinitializedProfile(context.getString(R.string.default_profile_name_outdoor), "ic_profile_outdoors_1", 2);
profile._showInActivator = true;
profile._volumeRingerMode = 2;
profile._volumeRingtone = getVolumeLevelString(100, maximumValueRing)+"|0|0";
profile._volumeNotification = getVolumeLevelString(100, maximumValueNotification)+"|0|0";
profile._volumeAlarm = getVolumeLevelString(100, maximumValueAlarm)+"|0|0";
profile._volumeMedia = getVolumeLevelString(93, maximumValueMusic)+"|0|0";
profile._deviceWiFi = 2;
//profile._deviceBrightness = "255|0|0|0";
getDatabaseHandler().addProfile(profile, false);
profile = getNoinitializedProfile(context.getString(R.string.default_profile_name_work), "ic_profile_work_5", 3);
profile._showInActivator = true;
profile._volumeRingerMode = 1;
profile._volumeRingtone = getVolumeLevelString(57, maximumValueRing)+"|0|0";
profile._volumeNotification = getVolumeLevelString(71, maximumValueNotification)+"|0|0";
profile._volumeAlarm = getVolumeLevelString(57, maximumValueAlarm)+"|0|0";
profile._volumeMedia = getVolumeLevelString(80, maximumValueMusic)+"|0|0";
profile._deviceWiFi = 2;
//profile._deviceBrightness = "60|0|0|0";
getDatabaseHandler().addProfile(profile, false);
profile = getNoinitializedProfile(context.getString(R.string.default_profile_name_meeting), "ic_profile_meeting_2", 4);
profile._showInActivator = true;
profile._volumeRingerMode = 4;
profile._volumeRingtone = getVolumeLevelString(0, maximumValueRing)+"|0|0";
profile._volumeNotification = getVolumeLevelString(0, maximumValueNotification)+"|0|0";
profile._volumeAlarm = getVolumeLevelString(0, maximumValueAlarm)+"|0|0";
profile._volumeMedia = getVolumeLevelString(0, maximumValueMusic)+"|0|0";
profile._deviceWiFi = 0;
//profile._deviceBrightness = Profile.BRIGHTNESS_ADAPTIVE_BRIGHTNESS_NOT_SET+"|1|1|0";
getDatabaseHandler().addProfile(profile, false);
profile = getNoinitializedProfile(context.getString(R.string.default_profile_name_sleep), "ic_profile_sleep", 5);
profile._showInActivator = true;
profile._volumeRingerMode = 4;
profile._volumeRingtone = getVolumeLevelString(0, maximumValueRing)+"|0|0";
profile._volumeNotification = getVolumeLevelString(0, maximumValueNotification)+"|0|0";
profile._volumeAlarm = getVolumeLevelString(100, maximumValueAlarm)+"|0|0";
profile._volumeMedia = getVolumeLevelString(0, maximumValueMusic)+"|0|0";
profile._deviceWiFi = 0;
//profile._deviceBrightness = "10|0|0|0";
getDatabaseHandler().addProfile(profile, false);
profile = getNoinitializedProfile(context.getString(R.string.default_profile_name_battery_low), "ic_profile_battery_1", 6);
profile._showInActivator = false;
profile._deviceAutosync = 2;
profile._deviceMobileData = 2;
profile._deviceWiFi = 2;
profile._deviceBluetooth = 2;
profile._deviceGPS = 2;
getDatabaseHandler().addProfile(profile, false);
return getProfileList();
}
public void invalidateProfileList()
{
if (profileList != null)
{
for (Profile profile : profileList)
{
profile.releaseIconBitmap();
profile.releasePreferencesIndicator();
}
profileList.clear();
}
profileList = null;
}
public Profile getActivatedProfileFromDB()
{
Profile profile = getDatabaseHandler().getActivatedProfile();
if (forGUI && (profile != null))
{
profile.generateIconBitmap(context, monochrome, monochromeValue);
profile.generatePreferencesIndicator(context, monochrome, monochromeValue);
}
return profile;
}
public Profile getActivatedProfile()
{
if (profileList == null)
{
return getActivatedProfileFromDB();
}
else
{
Profile profile;
for (int i = 0; i < profileList.size(); i++)
{
profile = profileList.get(i);
if (profile._checked)
return profile;
}
// when filter is set and profile not found, get profile from db
return getActivatedProfileFromDB();
}
}
/*
public Profile getFirstProfile()
{
if (profileList == null)
{
Profile profile = getDatabaseHandler().getFirstProfile();
if (forGUI && (profile != null))
{
profile.generateIconBitmap(context, monochrome, monochromeValue);
profile.generatePreferencesIndicator(context, monochrome, monochromeValue);
}
return profile;
}
else
{
Profile profile;
if (profileList.size() > 0)
profile = profileList.get(0);
else
profile = null;
return profile;
}
}
*/
/*
public int getProfileItemPosition(Profile profile)
{
if (profile == null)
return -1;
if (profileList == null)
return getDatabaseHandler().getProfilePosition(profile);
else
{
for (int i = 0; i < profileList.size(); i++)
{
if (profileList.get(i)._id == profile._id)
return i;
}
return -1;
}
}
*/
public void setProfileActive(Profile profile)
{
if ((profileList == null) || (profile == null))
return;
for (Profile p : profileList)
{
p._checked = false;
}
profile._checked = true;
/* // teraz musime najst profile v profileList
int position = getProfileItemPosition(profile);
if (position != -1)
{
// najdenemu objektu nastavime _checked
Profile _profile = profileList.get(position);
if (_profile != null)
_profile._checked = true;
} */
}
public void activateProfileFromEvent(long profile_id, boolean interactive, boolean manual,
boolean merged, String eventNotificationSound, boolean log)
{
int startupSource = GlobalData.STARTUP_SOURCE_SERVICE;
if (manual)
startupSource = GlobalData.STARTUP_SOURCE_SERVICE_MANUAL;
getActivateProfileHelper().initialize(this, null, context);
_activateProfile(getProfileById(profile_id, merged), merged, startupSource, interactive, null, eventNotificationSound, log);
}
public void updateNotificationAndWidgets(Profile profile, String eventNotificationSound)
{
getActivateProfileHelper().initialize(this, null, context);
getActivateProfileHelper().showNotification(profile, eventNotificationSound);
getActivateProfileHelper().updateWidget();
}
public void deactivateProfile()
{
if (profileList == null)
return;
for (Profile p : profileList)
{
p._checked = false;
}
}
private Profile getProfileByIdFromDB(long id, boolean merged)
{
Profile profile = getDatabaseHandler().getProfile(id, merged);
if (forGUI && (profile != null))
{
profile.generateIconBitmap(context, monochrome, monochromeValue);
profile.generatePreferencesIndicator(context, monochrome, monochromeValue);
}
return profile;
}
public Profile getProfileById(long id, boolean merged)
{
if ((profileList == null) || merged)
{
return getProfileByIdFromDB(id, merged);
}
else
{
Profile profile;
for (int i = 0; i < profileList.size(); i++)
{
profile = profileList.get(i);
if (profile._id == id)
return profile;
}
// when filter is set and profile not found, get profile from db
return getProfileByIdFromDB(id, false);
}
}
public void updateProfile(Profile profile)
{
if (profile != null)
{
Profile origProfile = getProfileById(profile._id, false);
if (origProfile != null)
origProfile.copyProfile(profile);
}
}
public void reloadProfilesData()
{
invalidateProfileList();
getProfileList();
}
public void deleteProfile(Profile profile)
{
if (profile == null)
return;
profileList.remove(profile);
if (eventList == null)
eventList = getEventList();
// unlink profile from events
for (Event event : eventList)
{
if (event._fkProfileStart == profile._id)
event._fkProfileStart = 0;
if (event._fkProfileEnd == profile._id)
event._fkProfileEnd = GlobalData.PROFILE_NO_ACTIVATE;
}
// unlink profile from Background profile
if (Long.valueOf(GlobalData.applicationBackgroundProfile) == profile._id)
{
SharedPreferences preferences = context.getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString(GlobalData.PREF_APPLICATION_BACKGROUND_PROFILE, String.valueOf(GlobalData.PROFILE_NO_ACTIVATE));
editor.commit();
}
}
public void deleteAllProfiles()
{
profileList.clear();
if (eventList == null)
eventList = getEventList();
// unlink profiles from events
for (Event event : eventList)
{
event._fkProfileStart = 0;
event._fkProfileEnd = GlobalData.PROFILE_NO_ACTIVATE;
}
// unlink profiles from Background profile
SharedPreferences preferences = context.getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString(GlobalData.PREF_APPLICATION_BACKGROUND_PROFILE, String.valueOf(GlobalData.PROFILE_NO_ACTIVATE));
editor.commit();
}
public List<Event> getEventList()
{
if (eventList == null)
{
eventList = getDatabaseHandler().getAllEvents();
}
return eventList;
}
public void setEventList(List<Event> eventList)
{
if (this.eventList != null)
this.eventList.clear();
this.eventList = eventList;
}
public void invalidateEventList()
{
if (eventList != null)
eventList.clear();
eventList = null;
}
/*
public Event getFirstEvent(int filterType)
{
if (eventList == null)
{
Event event = getDatabaseHandler().getFirstEvent();
return event;
}
else
{
Event event;
if (eventList.size() > 0)
event = eventList.get(0);
else
event = null;
return event;
}
}
*/
/*
public int getEventItemPosition(Event event)
{
if (event == null)
return - 1;
if (eventList == null)
return getDatabaseHandler().getEventPosition(event);
else
{
for (int i = 0; i < eventList.size(); i++)
{
if (eventList.get(i)._id == event._id)
return i;
}
return -1;
}
}
*/
public void sortEventsByPriorityAsc()
{
class PriorityComparator implements Comparator<Event> {
public int compare(Event lhs, Event rhs) {
int res = 0;
if ((lhs != null) && (rhs != null))
res = lhs._priority - rhs._priority;
return res;
}
}
getEventList();
if (eventList != null)
{
Collections.sort(eventList, new PriorityComparator());
}
}
public void sortEventsByPriorityDesc()
{
class PriorityComparator implements Comparator<Event> {
public int compare(Event lhs, Event rhs) {
int res = 0;
if ((lhs != null) && (rhs != null))
res = rhs._priority - lhs._priority;
return res;
}
}
getEventList();
if (eventList != null)
{
Collections.sort(eventList, new PriorityComparator());
}
}
public Event getEventById(long id)
{
if (eventList == null)
{
Event event = getDatabaseHandler().getEvent(id);
return event;
}
else
{
Event event;
for (int i = 0; i < eventList.size(); i++)
{
event = eventList.get(i);
if (event._id == id)
return event;
}
// when filter is set and profile not found, get profile from db
return getDatabaseHandler().getEvent(id);
}
}
public void updateEvent(Event event)
{
if (event != null)
{
Event origEvent = getEventById(event._id);
origEvent.copyEvent(event);
}
}
public void reloadEventsData()
{
invalidateEventList();
getEventList();
}
// stops all events associated with profile
public void stopEventsForProfile(Profile profile, boolean saveEventStatus)
{
List<EventTimeline> eventTimelineList = getEventTimelineList();
for (Event event : getEventList())
{
//if ((event.getStatusFromDB(this) == Event.ESTATUS_RUNNING) &&
// (event._fkProfileStart == profile._id))
if (event._fkProfileStart == profile._id)
event.stopEvent(this, eventTimelineList, false, true, saveEventStatus, false);
}
restartEvents(false, false, true);
}
// pauses all events
public void pauseAllEvents(boolean noSetSystemEvent, boolean blockEvents/*, boolean activateReturnProfile*/)
{
List<EventTimeline> eventTimelineList = getEventTimelineList();
for (Event event : getEventList())
{
if (event != null)
{
int status = event.getStatusFromDB(this);
if (status == Event.ESTATUS_RUNNING)
event.pauseEvent(this, eventTimelineList, false, true,
noSetSystemEvent, false, null);
setEventBlocked(event, false);
if (blockEvents && (status == Event.ESTATUS_RUNNING) && event._forceRun)
{
// block only running forcerun events
setEventBlocked(event, true);
}
}
}
// blockEvents == true -> manual profile activation is set
GlobalData.setEventsBlocked(context, blockEvents);
}
// stops all events
public void stopAllEvents(boolean saveEventStatus, boolean activateRetirnProfile)
{
List<EventTimeline> eventTimelineList = getEventTimelineList();
//for (Event event : getEventList())
for (int i = eventTimelineList.size()-1; i >= 0; i
{
EventTimeline eventTimeline = eventTimelineList.get(i);
if (eventTimeline != null)
{
long eventId = eventTimeline._fkEvent;
Event event = getEventById(eventId);
if (event != null)
{
//if (event.getStatusFromDB(this) != Event.ESTATUS_STOP)
event.stopEvent(this, eventTimelineList, activateRetirnProfile, true, saveEventStatus, false);
}
}
}
}
public void unlinkEventsFromProfile(Profile profile)
{
for (Event event : getEventList())
{
if (event._fkProfileStart == profile._id)
event._fkProfileStart = 0;
if (event._fkProfileEnd == profile._id)
event._fkProfileEnd = GlobalData.PROFILE_NO_ACTIVATE;
}
}
public void unlinkAllEvents()
{
for (Event event : getEventList())
{
event._fkProfileStart = 0;
event._fkProfileEnd = GlobalData.PROFILE_NO_ACTIVATE;
}
}
public void activateProfileOnBoot()
{
if (GlobalData.applicationActivate)
{
Profile profile = getDatabaseHandler().getActivatedProfile();
long profileId = 0;
if (profile != null)
profileId = profile._id;
else
{
profileId = Long.valueOf(GlobalData.applicationBackgroundProfile);
if (profileId == GlobalData.PROFILE_NO_ACTIVATE)
profileId = 0;
}
activateProfile(profileId, GlobalData.STARTUP_SOURCE_BOOT, null, "");
}
else
activateProfile(0, GlobalData.STARTUP_SOURCE_BOOT, null, "");
}
// this is called in boot or first start application
public void firstStartEvents(boolean startedFromService)
{
if (startedFromService)
invalidateEventList(); // force load form db
if (!startedFromService) {
GlobalData.setEventsBlocked(context, false);
getDatabaseHandler().unblockAllEvents();
GlobalData.setForceRunEventRunning(context, false);
}
/*
if (startedFromService) {
// deactivate profile, profile will by activated in call of RestartEventsBroadcastReceiver
getDatabaseHandler().deactivateProfile();
}
*/
removeAllEventDelays(true);
WifiScanAlarmBroadcastReceiver.setAlarm(context, false);
BluetoothScanAlarmBroadcastReceiver.setAlarm(context, false);
SearchCalendarEventsBroadcastReceiver.setAlarm(context);
if (!getIsManualProfileActivation()) {
Intent intent = new Intent();
intent.setAction(RestartEventsBroadcastReceiver.INTENT_RESTART_EVENTS);
context.sendBroadcast(intent);
}
else
{
GlobalData.setApplicationStarted(context, true);
activateProfileOnBoot();
}
}
public Event getNoinitializedEvent(String name)
{
return new Event(name,
0,
GlobalData.PROFILE_NO_ACTIVATE,
Event.ESTATUS_STOP,
"",
false,
false,
Event.EPRIORITY_MEDIUM,
0,
false,
Event.EATENDDO_UNDONE_PROFILE,
false
);
}
private long getProfileIdByName(String name)
{
if (profileList == null)
{
return 0;
}
else
{
Profile profile;
for (int i = 0; i < profileList.size(); i++)
{
profile = profileList.get(i);
if (profile._name.equals(name))
return profile._id;
}
return 0;
}
}
public void generateDefaultEventList()
{
invalidateEventList();
getDatabaseHandler().deleteAllEvents();
Calendar calendar = Calendar.getInstance();
calendar.clear();
int gmtOffset = TimeZone.getDefault().getRawOffset();
Event event;
event = getNoinitializedEvent(context.getString(R.string.default_event_name_during_the_week));
event._fkProfileStart = getProfileIdByName(context.getString(R.string.default_profile_name_home));
//event._undoneProfile = false;
event._atEndDo = Event.EATENDDO_NONE;
event._eventPreferencesTime._enabled = true;
event._eventPreferencesTime._monday = true;
event._eventPreferencesTime._tuesday = true;
event._eventPreferencesTime._wendesday = true;
event._eventPreferencesTime._thursday = true;
event._eventPreferencesTime._friday = true;
//calendar.clear(Calendar.DATE);
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
//calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.MILLISECOND, 0);
event._eventPreferencesTime._startTime = calendar.getTimeInMillis() + gmtOffset;
///calendar.clear(Calendar.DATE);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 0);
//calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.MILLISECOND, 0);
event._eventPreferencesTime._endTime = calendar.getTimeInMillis() + gmtOffset;
//event._eventPreferencesTime._useEndTime = true;
getDatabaseHandler().addEvent(event);
event = getNoinitializedEvent(context.getString(R.string.default_event_name_weekend));
event._fkProfileStart = getProfileIdByName(context.getString(R.string.default_profile_name_home));
//event._undoneProfile = false;
event._atEndDo = Event.EATENDDO_NONE;
event._eventPreferencesTime._enabled = true;
event._eventPreferencesTime._saturday = true;
event._eventPreferencesTime._sunday = true;
//calendar.clear(Calendar.DATE);
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
//calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.MILLISECOND, 0);
event._eventPreferencesTime._startTime = calendar.getTimeInMillis() + gmtOffset;
//calendar.clear(Calendar.DATE);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 0);
//calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.MILLISECOND, 0);
event._eventPreferencesTime._endTime = calendar.getTimeInMillis() + gmtOffset;
//event._eventPreferencesTime._useEndTime = true;
getDatabaseHandler().addEvent(event);
event = getNoinitializedEvent(context.getString(R.string.default_event_name_during_the_work));
event._fkProfileStart = getProfileIdByName(context.getString(R.string.default_profile_name_work));
//event._undoneProfile = true;
event._atEndDo = Event.EATENDDO_NONE;
event._priority = Event.EPRIORITY_HIGHER;
event._eventPreferencesTime._enabled = true;
event._eventPreferencesTime._monday = true;
event._eventPreferencesTime._tuesday = true;
event._eventPreferencesTime._wendesday = true;
event._eventPreferencesTime._thursday = true;
event._eventPreferencesTime._friday = true;
//calendar.clear(Calendar.DATE);
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 30);
//calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.MILLISECOND, 0);
event._eventPreferencesTime._startTime = calendar.getTimeInMillis() + gmtOffset;
//calendar.clear(Calendar.DATE);
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 30);
//calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.MILLISECOND, 0);
event._eventPreferencesTime._endTime = calendar.getTimeInMillis() + gmtOffset;
//event._eventPreferencesTime._useEndTime = true;
getDatabaseHandler().addEvent(event);
event = getNoinitializedEvent(context.getString(R.string.default_event_name_overnight));
event._fkProfileStart = getProfileIdByName(context.getString(R.string.default_profile_name_sleep));
//event._undoneProfile = false;
event._atEndDo = Event.EATENDDO_NONE;
event._eventPreferencesTime._enabled = true;
event._eventPreferencesTime._monday = true;
event._eventPreferencesTime._tuesday = true;
event._eventPreferencesTime._wendesday = true;
event._eventPreferencesTime._thursday = true;
event._eventPreferencesTime._friday = true;
event._eventPreferencesTime._saturday = true;
event._eventPreferencesTime._sunday = true;
//calendar.clear(Calendar.DATE);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 0);
//calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.MILLISECOND, 0);
event._eventPreferencesTime._startTime = calendar.getTimeInMillis() + gmtOffset;
//calendar.clear(Calendar.DATE);
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
//calendar.set(Calendar.SECOND, 0);
//calendar.set(Calendar.MILLISECOND, 0);
event._eventPreferencesTime._endTime = calendar.getTimeInMillis() + gmtOffset;
//event._eventPreferencesTime._useEndTime = true;
getDatabaseHandler().addEvent(event);
event = getNoinitializedEvent(context.getString(R.string.default_event_name_low_battery));
event._fkProfileStart = getProfileIdByName(context.getString(R.string.default_profile_name_battery_low));
//event._undoneProfile = false;
event._atEndDo = Event.EATENDDO_NONE;
event._priority = Event.EPRIORITY_HIGHEST;
event._forceRun = true;
event._eventPreferencesBattery._enabled = true;
event._eventPreferencesBattery._levelLow = 0;
event._eventPreferencesBattery._levelHight = 10;
event._eventPreferencesBattery._charging = false;
getDatabaseHandler().addEvent(event);
}
public List<EventTimeline> getEventTimelineList()
{
return getDatabaseHandler().getAllEventTimelines();
}
public void invalidateDataWrapper()
{
invalidateProfileList();
invalidateEventList();
databaseHandler = null;
if (activateProfileHelper != null)
activateProfileHelper.deinitialize();
activateProfileHelper = null;
}
private void _activateProfile(Profile _profile, boolean merged, int startupSource,
boolean _interactive, Activity _activity,
String eventNotificationSound, boolean log)
{
Profile profile = GlobalData.getMappedProfile(_profile, context);
//profile = filterProfileWithBatteryEvents(profile);
if (profile != null)
GlobalData.logE("$$$ DataWrapper._activateProfile","profileName="+profile._name);
else
GlobalData.logE("$$$ DataWrapper._activateProfile","profile=null");
boolean interactive = _interactive;
final Activity activity = _activity;
// get currently activated profile
Profile activatedProfile = getActivatedProfile();
if ((startupSource != GlobalData.STARTUP_SOURCE_SERVICE) &&
//(startupSource != GlobalData.STARTUP_SOURCE_BOOT) && // on boot must set as manual activation
(startupSource != GlobalData.STARTUP_SOURCE_LAUNCHER_START))
{
// manual profile activation
ActivateProfileHelper.lockRefresh = true;
// pause all events
// for forcerRun events set system events and block all events
pauseAllEvents(false, true/*, true*/);
ActivateProfileHelper.lockRefresh = false;
}
databaseHandler.activateProfile(profile);
setProfileActive(profile);
String profileIcon = "";
int profileDuration = 0;
if (profile != null)
{
profileIcon = profile._icon;
if ((profile._afterDurationDo != Profile.AFTERDURATIONDO_NOTHING) &&
(profile._duration > 0))
profileDuration = profile._duration;
activateProfileHelper.execute(profile, merged, interactive, eventNotificationSound);
if ((startupSource != GlobalData.STARTUP_SOURCE_SERVICE) &&
(startupSource != GlobalData.STARTUP_SOURCE_BOOT) &&
(startupSource != GlobalData.STARTUP_SOURCE_LAUNCHER_START))
{
// manual profile activation
//// set profile duration alarm
// save before activated profile
long profileId = 0;
if (activatedProfile != null)
profileId = activatedProfile._id;
GlobalData.setActivatedProfileForDuration(context, profileId);
ProfileDurationAlarmBroadcastReceiver.setAlarm(profile, context);
}
else
ProfileDurationAlarmBroadcastReceiver.removeAlarm(context);
}
else
ProfileDurationAlarmBroadcastReceiver.removeAlarm(context);
activatedProfile = getActivatedProfile();
activateProfileHelper.showNotification(activatedProfile, eventNotificationSound);
activateProfileHelper.updateWidget();
if (log && (profile != null))
getDatabaseHandler().addActivityLog(DatabaseHandler.ALTYPE_PROFILEACTIVATION, null,
getProfileNameWithManualIndicator(profile, true),
profileIcon, profileDuration);
if (profile != null)
{
if (GlobalData.notificationsToast && (!ActivateProfileHelper.lockRefresh))
{
// toast notification
//Context _context = activity;
//if (_context == null)
// _context = context.getApplicationContext();
// create a handler to post messages to the main thread
if (toastHandler != null)
{
final Profile __profile = profile;
toastHandler.post(new Runnable() {
public void run() {
showToastAfterActivation(__profile);
}
});
}
else
showToastAfterActivation(profile);
}
}
// for startActivityForResult
if (activity != null)
{
Intent returnIntent = new Intent();
returnIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile._id);
returnIntent.getIntExtra(GlobalData.EXTRA_START_APP_SOURCE, startupSource);
activity.setResult(Activity.RESULT_OK,returnIntent);
}
finishActivity(startupSource, true, activity);
}
private void showToastAfterActivation(Profile profile)
{
Toast msg = Toast.makeText(context,
context.getResources().getString(R.string.toast_profile_activated_0) + ": " + profile._name + " " +
context.getResources().getString(R.string.toast_profile_activated_1),
Toast.LENGTH_SHORT);
msg.show();
}
private void activateProfileWithAlert(Profile profile, int startupSource, boolean interactive,
Activity activity, String eventNotificationSound)
{
boolean isforceRunEvent = false;
/*
if (interactive)
{
// search for forceRun events
getEventList();
for (Event event : eventList)
{
if (event != null)
{
if ((event.getStatus() == Event.ESTATUS_RUNNING) && (event._forceRun))
{
isforceRunEvent = true;
break;
}
}
}
}
*/
if ((interactive) && (GlobalData.applicationActivateWithAlert ||
(startupSource == GlobalData.STARTUP_SOURCE_EDITOR) ||
(isforceRunEvent)))
{
// set theme and language for dialog alert ;-)
// not working on Android 2.3.x
GUIData.setTheme(activity, true, false);
GUIData.setLanguage(activity.getBaseContext());
final Profile _profile = profile;
final boolean _interactive = interactive;
final int _startupSource = startupSource;
final Activity _activity = activity;
final String _eventNotificationSound = eventNotificationSound;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
dialogBuilder.setTitle(activity.getResources().getString(R.string.profile_string_0) + ": " + profile._name);
if (isforceRunEvent)
dialogBuilder.setMessage(R.string.manual_profile_activation_forceRun_message);
else
dialogBuilder.setMessage(activity.getResources().getString(R.string.activate_profile_alert_message));
//dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
_activateProfile(_profile, false, _startupSource, _interactive, _activity,
_eventNotificationSound, true);
}
});
dialogBuilder.setNegativeButton(R.string.alert_button_no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// for startActivityForResult
Intent returnIntent = new Intent();
_activity.setResult(Activity.RESULT_CANCELED, returnIntent);
finishActivity(_startupSource, false, _activity);
}
});
dialogBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
// for startActivityForResult
Intent returnIntent = new Intent();
_activity.setResult(Activity.RESULT_CANCELED,returnIntent);
finishActivity(_startupSource, false, _activity);
}
});
dialogBuilder.show();
}
else
{
_activateProfile(profile, false, startupSource, interactive, activity, eventNotificationSound, true);
}
}
private void finishActivity(int startupSource, boolean afterActivation, Activity _activity)
{
final Activity activity = _activity;
boolean finish = true;
if (startupSource == GlobalData.STARTUP_SOURCE_ACTIVATOR)
{
finish = false;
if (GlobalData.applicationClose)
{
// ma sa zatvarat aktivita po aktivacii
if (GlobalData.getApplicationStarted(context))
// aplikacia je uz spustena, mozeme aktivitu zavriet
// tymto je vyriesene, ze pri spusteni aplikacie z launchera
// sa hned nezavrie
finish = afterActivation;
}
}
else
if (startupSource == GlobalData.STARTUP_SOURCE_EDITOR)
{
finish = false;
}
if (finish)
{
if (activity != null)
activity.finish();
}
}
public void activateProfile(long profile_id, int startupSource, Activity activity, String eventNotificationSound)
{
Profile profile;
// pre profil, ktory je prave aktivny, treba aktualizovat aktivitu
profile = getActivatedProfile();
boolean actProfile = false;
boolean interactive = false;
if ((startupSource == GlobalData.STARTUP_SOURCE_SHORTCUT) ||
(startupSource == GlobalData.STARTUP_SOURCE_WIDGET) ||
(startupSource == GlobalData.STARTUP_SOURCE_ACTIVATOR) ||
(startupSource == GlobalData.STARTUP_SOURCE_EDITOR) ||
(startupSource == GlobalData.STARTUP_SOURCE_SERVICE) ||
(startupSource == GlobalData.STARTUP_SOURCE_LAUNCHER))
{
// aktivacia spustena z shortcutu, widgetu, aktivatora, editora, zo service, profil aktivujeme
actProfile = true;
interactive = ((startupSource != GlobalData.STARTUP_SOURCE_SERVICE));
}
else
if (startupSource == GlobalData.STARTUP_SOURCE_BOOT)
{
// aktivacia bola spustena po boote telefonu
ProfileDurationAlarmBroadcastReceiver.removeAlarm(context);
if (GlobalData.applicationActivate)
{
// je nastavene, ze pri starte sa ma aktivita aktivovat
actProfile = true;
}
/*else
{
// nema sa aktivovat profil pri starte, ale musim pozriet, ci daky event bezi
// a ak ano, aktivovat profil posledneho eventu v timeline
boolean eventRunning = false;
List<EventTimeline> eventTimelineList = getEventTimelineList();
if (eventTimelineList.size() > 0)
{
eventRunning = true;
EventTimeline eventTimeline = eventTimelineList.get(eventTimelineList.size()-1);
Event _event = getEventById(eventTimeline._fkEvent);
profile = getProfileById(_event._fkProfileStart);
actProfile = true;
}
if ((profile != null) && (!eventRunning))
{
getDatabaseHandler().deactivateProfile();
//profile._checked = false;
profile = null;
}
}*/
}
else
if (startupSource == GlobalData.STARTUP_SOURCE_LAUNCHER_START)
{
// aktivacia bola spustena z lauchera
ProfileDurationAlarmBroadcastReceiver.removeAlarm(context);
if (GlobalData.applicationActivate)
{
// je nastavene, ze pri starte sa ma aktivita aktivovat
actProfile = true;
}
/*else
{
if (profile != null)
{
getDatabaseHandler().deactivateProfile();
//profile._checked = false;
profile = null;
}
}*/
}
if ((startupSource == GlobalData.STARTUP_SOURCE_SHORTCUT) ||
(startupSource == GlobalData.STARTUP_SOURCE_WIDGET) ||
(startupSource == GlobalData.STARTUP_SOURCE_ACTIVATOR) ||
(startupSource == GlobalData.STARTUP_SOURCE_EDITOR) ||
(startupSource == GlobalData.STARTUP_SOURCE_SERVICE) ||
(startupSource == GlobalData.STARTUP_SOURCE_LAUNCHER_START) ||
(startupSource == GlobalData.STARTUP_SOURCE_LAUNCHER))
{
if (profile_id == 0)
profile = null;
else
profile = getProfileById(profile_id, false);
}
if (actProfile && (profile != null))
{
// aktivacia profilu
activateProfileWithAlert(profile, startupSource, interactive, activity, eventNotificationSound);
}
else
{
activateProfileHelper.showNotification(profile, eventNotificationSound);
activateProfileHelper.updateWidget();
// for startActivityForResult
if (activity != null)
{
Intent returnIntent = new Intent();
returnIntent.putExtra(GlobalData.EXTRA_PROFILE_ID, profile_id);
returnIntent.getIntExtra(GlobalData.EXTRA_START_APP_SOURCE, startupSource);
activity.setResult(Activity.RESULT_OK,returnIntent);
}
finishActivity(startupSource, true, activity);
}
}
@SuppressWarnings("deprecation")
@SuppressLint({ "NewApi", "SimpleDateFormat" })
public boolean doEventService(Event event, boolean statePause,
boolean restartEvent, boolean interactive,
boolean forDelayAlarm, boolean reactivate,
Profile mergedProfile)
{
int newEventStatus = Event.ESTATUS_NONE;
boolean eventStart = true;
boolean timePassed = true;
boolean batteryPassed = true;
boolean callPassed = true;
boolean peripheralPassed = true;
boolean calendarPassed = true;
boolean wifiPassed = true;
boolean screenPassed = true;
boolean bluetoothPassed = true;
boolean smsPassed = true;
boolean isCharging = false;
float batteryPct = 100.0f;
GlobalData.logE("DataWrapper.doEventService","
GlobalData.logE("DataWrapper.doEventService","
GlobalData.logE("DataWrapper.doEventService","
if (event._eventPreferencesTime._enabled)
{
// compute start datetime
long startAlarmTime;
long endAlarmTime;
startAlarmTime = event._eventPreferencesTime.computeAlarm(true);
String alarmTimeS = DateFormat.getDateFormat(context).format(startAlarmTime) +
" " + DateFormat.getTimeFormat(context).format(startAlarmTime);
GlobalData.logE("DataWrapper.doEventService","startAlarmTime="+alarmTimeS);
//startAlarmTime -= (1000 * 30); // decrease 30 seconds
endAlarmTime = event._eventPreferencesTime.computeAlarm(false);
alarmTimeS = DateFormat.getDateFormat(context).format(endAlarmTime) +
" " + DateFormat.getTimeFormat(context).format(endAlarmTime);
GlobalData.logE("DataWrapper.doEventService","endAlarmTime="+alarmTimeS);
//endAlarmTime -= (1000 * 30); // decrease 30 seconds
Calendar now = Calendar.getInstance();
// round time
if (now.get(Calendar.SECOND) > 0)
{
now.add(Calendar.MINUTE, 1);
now.set(Calendar.SECOND, 0);
}
long nowAlarmTime = now.getTimeInMillis();
alarmTimeS = DateFormat.getDateFormat(context).format(nowAlarmTime) +
" " + DateFormat.getTimeFormat(context).format(nowAlarmTime);
GlobalData.logE("DataWrapper.doEventService","nowAlarmTime="+alarmTimeS);
timePassed = ((nowAlarmTime >= startAlarmTime) && (nowAlarmTime <= endAlarmTime));
eventStart = eventStart && timePassed;
}
if (event._eventPreferencesBattery._enabled)
{
// get battery status
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
if (batteryStatus != null)
{
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
GlobalData.logE("DataWrapper.doEventService","status="+status);
isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
GlobalData.logE("DataWrapper.doEventService","isCharging="+isCharging);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
batteryPct = level / (float)scale;
GlobalData.logE("DataWrapper.doEventService","batteryPct="+batteryPct);
batteryPassed = (isCharging == event._eventPreferencesBattery._charging);
if (batteryPassed)
{
if ((batteryPct >= (event._eventPreferencesBattery._levelLow / (float)100)) &&
(batteryPct <= (event._eventPreferencesBattery._levelHight / (float)100)))
{
eventStart = eventStart && true;
}
else
{
batteryPassed = false;
eventStart = eventStart && false;
}
}
}
else
{
batteryPassed = false;
isCharging = false;
batteryPct = -1.0f;
}
}
if (event._eventPreferencesCall._enabled)
{
SharedPreferences preferences = context.getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE);
int callEventType = preferences.getInt(GlobalData.PREF_EVENT_CALL_EVENT_TYPE, PhoneCallBroadcastReceiver.CALL_EVENT_UNDEFINED);
String phoneNumber = preferences.getString(GlobalData.PREF_EVENT_CALL_PHONE_NUMBER, "");
boolean phoneNumberFinded = false;
if (callEventType != PhoneCallBroadcastReceiver.CALL_EVENT_UNDEFINED)
{
if (event._eventPreferencesCall._contactListType != EventPreferencesCall.CONTACT_LIST_TYPE_NOT_USE)
{
// find phone number in groups
String[] splits = event._eventPreferencesCall._contactGroups.split("\\|");
for (int i = 0; i < splits.length; i++) {
String[] projection = new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID};
String selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=? AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
String[] selectionArgs = new String[]{splits[i]};
Cursor mCursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, selection, selectionArgs, null);
while (mCursor.moveToNext()) {
String contactId = mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
String[] projection2 = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER};
String selection2 = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?" + " and " +
ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "=1";
String[] selection2Args = new String[]{contactId};
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection2, selection2, selection2Args, null);
while (phones.moveToNext()) {
String _phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (PhoneNumberUtils.compare(_phoneNumber, phoneNumber)) {
phoneNumberFinded = true;
break;
}
}
phones.close();
if (phoneNumberFinded)
break;
}
mCursor.close();
if (phoneNumberFinded)
break;
}
if (!phoneNumberFinded) {
// find phone number in contacts
splits = event._eventPreferencesCall._contacts.split("\\|");
for (int i = 0; i < splits.length; i++) {
String[] splits2 = splits[i].split("
// get phone number from contacts
String[] projection = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.HAS_PHONE_NUMBER};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1' and " + ContactsContract.Contacts._ID + "=?";
String[] selectionArgs = new String[]{splits2[0]};
Cursor mCursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, projection, selection, selectionArgs, null);
while (mCursor.moveToNext()) {
String[] projection2 = new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER};
String selection2 = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?" + " and " + ContactsContract.CommonDataKinds.Phone._ID + "=?";
String[] selection2Args = new String[]{splits2[0], splits2[1]};
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection2, selection2, selection2Args, null);
while (phones.moveToNext()) {
String _phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (PhoneNumberUtils.compare(_phoneNumber, phoneNumber)) {
phoneNumberFinded = true;
break;
}
}
phones.close();
if (phoneNumberFinded)
break;
}
mCursor.close();
if (phoneNumberFinded)
break;
}
}
if (event._eventPreferencesCall._contactListType == EventPreferencesCall.CONTACT_LIST_TYPE_BLACK_LIST)
phoneNumberFinded = !phoneNumberFinded;
}
else
phoneNumberFinded = true;
if (phoneNumberFinded)
{
if (event._eventPreferencesCall._callEvent == EventPreferencesCall.CALL_EVENT_RINGING)
{
if ((callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_INCOMING_CALL_RINGING) ||
((callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_INCOMING_CALL_ANSWERED)))
eventStart = eventStart && true;
else
callPassed = false;
}
else
if (event._eventPreferencesCall._callEvent == EventPreferencesCall.CALL_EVENT_INCOMING_CALL_ANSWERED)
{
if (callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_INCOMING_CALL_ANSWERED)
eventStart = eventStart && true;
else
callPassed = false;
}
else
if (event._eventPreferencesCall._callEvent == EventPreferencesCall.CALL_EVENT_OUTGOING_CALL_STARTED)
{
if (callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_OUTGOING_CALL_ANSWERED)
eventStart = eventStart && true;
else
callPassed = false;
}
if ((callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_INCOMING_CALL_ENDED) ||
(callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_OUTGOING_CALL_ENDED))
{
callPassed = true;
eventStart = eventStart && false;
Editor editor = preferences.edit();
editor.putInt(GlobalData.PREF_EVENT_CALL_EVENT_TYPE, PhoneCallBroadcastReceiver.CALL_EVENT_UNDEFINED);
editor.putString(GlobalData.PREF_EVENT_CALL_PHONE_NUMBER, "");
editor.commit();
}
}
else
callPassed = false;
}
else
callPassed = false;
}
if (event._eventPreferencesPeripherals._enabled)
{
if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_DESK_DOCK) ||
(event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_CAR_DOCK))
{
// get dock status
IntentFilter ifilter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
Intent dockStatus = context.registerReceiver(null, ifilter);
boolean isDocked = false;
boolean isCar = false;
boolean isDesk = false;
if (dockStatus != null)
{
int dockState = dockStatus.getIntExtra(Intent.EXTRA_DOCK_STATE, -1);
isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
isCar = dockState == Intent.EXTRA_DOCK_STATE_CAR;
isDesk = dockState == Intent.EXTRA_DOCK_STATE_DESK ||
dockState == Intent.EXTRA_DOCK_STATE_LE_DESK ||
dockState == Intent.EXTRA_DOCK_STATE_HE_DESK;
}
if (isDocked)
{
if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_DESK_DOCK)
&& isDesk)
peripheralPassed = true;
else
if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_CAR_DOCK)
&& isCar)
peripheralPassed = true;
else
peripheralPassed = false;
}
else
peripheralPassed = false;
eventStart = eventStart && peripheralPassed;
}
else
if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_WIRED_HEADSET) ||
(event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_BLUETOOTH_HEADSET) ||
(event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_HEADPHONES))
{
SharedPreferences preferences = context.getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE);
boolean headsetConnected = preferences.getBoolean(GlobalData.PREF_EVENT_HEADSET_CONNECTED, false);
boolean headsetMicrophone = preferences.getBoolean(GlobalData.PREF_EVENT_HEADSET_MICROPHONE, false);
boolean bluetoothHeadset = preferences.getBoolean(GlobalData.PREF_EVENT_HEADSET_BLUETOOTH, false);
if (headsetConnected)
{
if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_WIRED_HEADSET)
&& headsetMicrophone && (!bluetoothHeadset))
peripheralPassed = true;
else
if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_BLUETOOTH_HEADSET)
&& headsetMicrophone && bluetoothHeadset)
peripheralPassed = true;
else
if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_HEADPHONES)
&& (!headsetMicrophone) && (!bluetoothHeadset))
peripheralPassed = true;
else
peripheralPassed = false;
}
else
peripheralPassed = false;
eventStart = eventStart && peripheralPassed;
}
}
if (event._eventPreferencesCalendar._enabled)
{
// compute start datetime
long startAlarmTime;
long endAlarmTime;
if (event._eventPreferencesCalendar._eventFound)
{
startAlarmTime = event._eventPreferencesCalendar.computeAlarm(true);
String alarmTimeS = DateFormat.getDateFormat(context).format(startAlarmTime) +
" " + DateFormat.getTimeFormat(context).format(startAlarmTime);
GlobalData.logE("DataWrapper.doEventService","startAlarmTime="+alarmTimeS);
//startAlarmTime -= (1000 * 30); // decrease 30 seconds
endAlarmTime = event._eventPreferencesCalendar.computeAlarm(false);
alarmTimeS = DateFormat.getDateFormat(context).format(endAlarmTime) +
" " + DateFormat.getTimeFormat(context).format(endAlarmTime);
GlobalData.logE("DataWrapper.doEventService","endAlarmTime="+alarmTimeS);
//endAlarmTime -= (1000 * 30); // decrease 30 seconds
Calendar now = Calendar.getInstance();
// round time
if (now.get(Calendar.SECOND) > 0)
{
now.add(Calendar.MINUTE, 1);
now.set(Calendar.SECOND, 0);
}
long nowAlarmTime = now.getTimeInMillis();
alarmTimeS = DateFormat.getDateFormat(context).format(nowAlarmTime) +
" " + DateFormat.getTimeFormat(context).format(nowAlarmTime);
GlobalData.logE("DataWrapper.doEventService","nowAlarmTime="+alarmTimeS);
calendarPassed = ((nowAlarmTime >= startAlarmTime) && (nowAlarmTime <= endAlarmTime));
}
else
calendarPassed = false;
eventStart = eventStart && calendarPassed;
}
if (event._eventPreferencesWifi._enabled)
{
wifiPassed = false;
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
boolean isWifiEnabled = wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED;
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (isWifiEnabled)
{
GlobalData.logE("DataWrapper.doEventService","wifiStateEnabled=true");
GlobalData.logE("@@@ DataWrapper.doEventService","-- eventSSID="+event._eventPreferencesWifi._SSID);
if (networkInfo.isConnected())
{
GlobalData.logE("@@@ DataWrapper.doEventService","wifi connected");
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
GlobalData.logE("@@@ DataWrapper.doEventService","wifiSSID="+getSSID(wifiInfo));
GlobalData.logE("@@@ DataWrapper.doEventService","wifiBSSID="+wifiInfo.getBSSID());
wifiPassed = compareSSID(wifiInfo, event._eventPreferencesWifi._SSID);
if (wifiPassed)
{
// event SSID is connected
if (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTCONNECTED)
// for this connectionTypes, wifi must not be connected to event SSID
wifiPassed = false;
}
}
else
{
GlobalData.logE("@@@ DataWrapper.doEventService", "wifi not connected");
if (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTCONNECTED)
// for this connectionTypes, wifi must not be connected to event SSID
wifiPassed = true;
}
}
else
GlobalData.logE("DataWrapper.doEventService","wifiStateEnabled=false");
if ((event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_INFRONT) ||
(event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTINFRONT))
{
if (!wifiPassed)
{
if (WifiScanAlarmBroadcastReceiver.scanResults != null)
{
//GlobalData.logE("@@@x DataWrapper.doEventService","scanResults != null");
//GlobalData.logE("@@@x DataWrapper.doEventService","-- eventSSID="+event._eventPreferencesWifi._SSID);
for (WifiSSIDData result : WifiScanAlarmBroadcastReceiver.scanResults)
{
//GlobalData.logE("@@@x DataWrapper.doEventService","wifiSSID="+getSSID(result));
//GlobalData.logE("@@@x DataWrapper.doEventService","wifiBSSID="+result.BSSID);
if (compareSSID(result, event._eventPreferencesWifi._SSID))
{
GlobalData.logE("@@@x DataWrapper.doEventService","wifi found");
wifiPassed = true;
break;
}
}
if (!wifiPassed)
GlobalData.logE("@@@x DataWrapper.doEventService","wifi not found");
if (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTINFRONT)
// if wifi is not in front of event SSID, then passed
wifiPassed = !wifiPassed;
}
else
GlobalData.logE("$$$x DataWrapper.doEventService","scanResults == null");
}
}
eventStart = eventStart && wifiPassed;
}
if (event._eventPreferencesScreen._enabled)
{
boolean isScreenOn;
//if (android.os.Build.VERSION.SDK_INT >= 20)
// Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// isScreenOn = display.getState() != Display.STATE_OFF;
//else
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
isScreenOn = pm.isScreenOn();
boolean keyguardShowing = false;
if (event._eventPreferencesScreen._whenUnlocked)
{
KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 16)
keyguardShowing = kgMgr.isKeyguardLocked();
else
keyguardShowing = kgMgr.inKeyguardRestrictedInputMode();
}
if (event._eventPreferencesScreen._eventType == EventPreferencesScreen.ETYPE_SCREENON)
{
if (event._eventPreferencesScreen._whenUnlocked)
screenPassed = isScreenOn && (!keyguardShowing);
else
screenPassed = isScreenOn;
}
else
{
if (event._eventPreferencesScreen._whenUnlocked)
screenPassed = (!isScreenOn) || keyguardShowing;
else
screenPassed = !isScreenOn;
}
eventStart = eventStart && screenPassed;
}
if (event._eventPreferencesBluetooth._enabled)
{
bluetoothPassed = false;
BluetoothAdapter bluetooth = (BluetoothAdapter) BluetoothAdapter.getDefaultAdapter();
boolean isBluetoothEnabled = bluetooth.isEnabled();
if (isBluetoothEnabled)
{
GlobalData.logE("DataWrapper.doEventService","bluetoothEnabled=true");
GlobalData.logE("@@@ DataWrapper.doEventService","-- eventAdapterName="+event._eventPreferencesBluetooth._adapterName);
if (BluetoothConnectionBroadcastReceiver.isBluetoothConnected(context, "")) {
GlobalData.logE("@@@ DataWrapper.doEventService", "bluetooth connected");
if (BluetoothConnectionBroadcastReceiver.isBluetoothConnected(context, event._eventPreferencesBluetooth._adapterName)) {
// event BT adapter is connected
bluetoothPassed = true;
if (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTCONNECTED)
// for this connectionTypes, BT must not be connected to event BT adapter
bluetoothPassed = false;
}
}
else
{
GlobalData.logE("@@@ DataWrapper.doEventService", "bluetooth not connected");
if (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTCONNECTED)
// for this connectionTypes, BT must not be connected to event BT adapter
bluetoothPassed = true;
}
}
else
GlobalData.logE("DataWrapper.doEventService","bluetoothEnabled=true");
if ((event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_INFRONT) ||
(event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTINFRONT))
{
if (!bluetoothPassed)
{
if (BluetoothScanAlarmBroadcastReceiver.scanResults != null)
{
//GlobalData.logE("@@@ DataWrapper.doEventService","-- eventAdapterName="+event._eventPreferencesBluetooth._adapterName);
for (BluetoothDeviceData device : BluetoothScanAlarmBroadcastReceiver.scanResults)
{
if (device.getName().equals(event._eventPreferencesBluetooth._adapterName))
{
GlobalData.logE("@@@ DataWrapper.doEventService","bluetooth found");
//GlobalData.logE("@@@ DataWrapper.doEventService","bluetoothAdapterName="+device.getName());
//GlobalData.logE("@@@ DataWrapper.doEventService","bluetoothAddress="+device.getAddress());
bluetoothPassed = true;
break;
}
}
if (!bluetoothPassed)
GlobalData.logE("@@@ DataWrapper.doEventService","bluetooth not found");
if (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTINFRONT)
// if bluetooth is not in front of event BT adapter name, then passed
bluetoothPassed = !bluetoothPassed;
}
else
GlobalData.logE("@@@x DataWrapper.doEventService","scanResults == null");
}
}
eventStart = eventStart && bluetoothPassed;
}
if (event._eventPreferencesSMS._enabled)
{
SharedPreferences preferences = context.getSharedPreferences(GlobalData.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE);
//int smsEventType = preferences.getInt(GlobalData.PREF_EVENT_SMS_EVENT_TYPE, EventPreferencesSMS.SMS_EVENT_UNDEFINED);
String phoneNumber = preferences.getString(GlobalData.PREF_EVENT_SMS_PHONE_NUMBER, "");
long startTime = preferences.getLong(GlobalData.PREF_EVENT_SMS_DATE, 0);
boolean phoneNumberFinded = false;
//GlobalData.logE("DataWrapper.doEventService","smsEventType="+smsEventType);
//if (smsEventType != EventPreferencesSMS.SMS_EVENT_UNDEFINED)
GlobalData.logE("DataWrapper.doEventService","phoneNumber="+phoneNumber);
// save sms date into event
if (event.getStatus() != Event.ESTATUS_RUNNING)
{
event._eventPreferencesSMS._startTime = startTime;
getDatabaseHandler().updateSMSStartTimes(event);
}
// comute start time
int gmtOffset = TimeZone.getDefault().getRawOffset();
startTime = startTime - gmtOffset;
SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
String alarmTimeS = sdf.format(startTime);
GlobalData.logE("DataWrapper.doEventService","startTime="+alarmTimeS);
// compute end datetime
long endAlarmTime = event._eventPreferencesSMS.computeAlarm();
alarmTimeS = sdf.format(endAlarmTime);
GlobalData.logE("DataWrapper.doEventService","endAlarmTime="+alarmTimeS);
Calendar now = Calendar.getInstance();
long nowAlarmTime = now.getTimeInMillis();
alarmTimeS = sdf.format(nowAlarmTime);
GlobalData.logE("DataWrapper.doEventService","nowAlarmTime="+alarmTimeS);
smsPassed = ((nowAlarmTime >= startTime) && (nowAlarmTime <= endAlarmTime));
if (smsPassed)
{
GlobalData.logE("DataWrapper.doEventService","start time passed");
if (event._eventPreferencesSMS._contactListType != EventPreferencesCall.CONTACT_LIST_TYPE_NOT_USE)
{
// find phone number in groups
String[] splits = event._eventPreferencesSMS._contactGroups.split("\\|");
for (int i = 0; i < splits.length; i++) {
String[] projection = new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID};
String selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=? AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
String[] selectionArgs = new String[]{splits[i]};
Cursor mCursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, selection, selectionArgs, null);
while (mCursor.moveToNext()) {
String contactId = mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
String[] projection2 = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER};
String selection2 = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?" + " and " +
ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "=1";
String[] selection2Args = new String[]{contactId};
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection2, selection2, selection2Args, null);
while (phones.moveToNext()) {
String _phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (PhoneNumberUtils.compare(_phoneNumber, phoneNumber)) {
phoneNumberFinded = true;
break;
}
}
phones.close();
if (phoneNumberFinded)
break;
}
mCursor.close();
if (phoneNumberFinded)
break;
}
if (!phoneNumberFinded) {
// find phone number in contacts
splits = event._eventPreferencesSMS._contacts.split("\\|");
for (int i = 0; i < splits.length; i++) {
String[] splits2 = splits[i].split("
// get phone number from contacts
String[] projection = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.HAS_PHONE_NUMBER};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1' and " + ContactsContract.Contacts._ID + "=?";
String[] selectionArgs = new String[]{splits2[0]};
Cursor mCursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, projection, selection, selectionArgs, null);
while (mCursor.moveToNext()) {
String[] projection2 = new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER};
String selection2 = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?" + " and " + ContactsContract.CommonDataKinds.Phone._ID + "=?";
String[] selection2Args = new String[]{splits2[0], splits2[1]};
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection2, selection2, selection2Args, null);
while (phones.moveToNext()) {
String _phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (PhoneNumberUtils.compare(_phoneNumber, phoneNumber)) {
phoneNumberFinded = true;
break;
}
}
phones.close();
if (phoneNumberFinded)
break;
}
mCursor.close();
if (phoneNumberFinded)
break;
}
}
if (event._eventPreferencesSMS._contactListType == EventPreferencesCall.CONTACT_LIST_TYPE_BLACK_LIST)
phoneNumberFinded = !phoneNumberFinded;
}
else
phoneNumberFinded = true;
if (phoneNumberFinded)
{
//if (event._eventPreferencesSMS._smsEvent == smsEventType)
eventStart = eventStart && true;
smsPassed = true;
}
else
smsPassed = false;
}
//else
// smsPassed = false;
}
GlobalData.logE("DataWrapper.doEventService","timePassed="+timePassed);
GlobalData.logE("DataWrapper.doEventService","batteryPassed="+batteryPassed);
GlobalData.logE("DataWrapper.doEventService","callPassed="+callPassed);
GlobalData.logE("DataWrapper.doEventService","peripheralPassed="+peripheralPassed);
GlobalData.logE("DataWrapper.doEventService","calendarPassed="+calendarPassed);
GlobalData.logE("DataWrapper.doEventService","wifiPassed="+wifiPassed);
GlobalData.logE("DataWrapper.doEventService","screenPassed="+screenPassed);
GlobalData.logE("DataWrapper.doEventService","bluetoothPassed="+bluetoothPassed);
GlobalData.logE("DataWrapper.doEventService","smsPassed="+smsPassed);
GlobalData.logE("DataWrapper.doEventService","eventStart="+eventStart);
GlobalData.logE("DataWrapper.doEventService","restartEvent="+restartEvent);
GlobalData.logE("DataWrapper.doEventService","statePause="+statePause);
List<EventTimeline> eventTimelineList = getEventTimelineList();
if (timePassed &&
batteryPassed &&
callPassed &&
peripheralPassed &&
calendarPassed &&
wifiPassed &&
screenPassed &&
bluetoothPassed &&
smsPassed)
{
// podmienky sedia, vykoname, co treba
if (eventStart)
newEventStatus = Event.ESTATUS_RUNNING;
else
newEventStatus = Event.ESTATUS_PAUSE;
}
else
newEventStatus = Event.ESTATUS_PAUSE;
GlobalData.logE("DataWrapper.doEventService","event.getStatus()="+event.getStatus());
GlobalData.logE("DataWrapper.doEventService","newEventStatus="+newEventStatus);
//GlobalData.logE("@@@ DataWrapper.doEventService","restartEvent="+restartEvent);
if ((event.getStatus() != newEventStatus) || restartEvent || event._isInDelay)
{
GlobalData.logE("DataWrapper.doEventService"," do new event status");
if ((newEventStatus == Event.ESTATUS_RUNNING) && (!statePause))
{
GlobalData.logE("$$$ DataWrapper.doEventService","start event");
if (!forDelayAlarm)
{
// called not for delay alarm
if (!event._isInDelay) {
// if not delay alarm is set, set it
event.setDelayAlarm(this, true, false, true); // for start delay
}
if (!event._isInDelay)
{
// no delay alarm is set
// start event
event.startEvent(this, eventTimelineList, false, interactive, reactivate, true, mergedProfile);
}
}
if (forDelayAlarm && event._isInDelay)
{
// called for delay alarm
// start event
event.startEvent(this, eventTimelineList, false, interactive, reactivate, true, mergedProfile);
}
}
else
if (((newEventStatus == Event.ESTATUS_PAUSE) || restartEvent) && statePause)
{
// when pausing and it is for restart events, force pause
GlobalData.logE("DataWrapper.doEventService","pause event");
event.pauseEvent(this, eventTimelineList, true, false, false, true, mergedProfile);
}
}
GlobalData.logE("DataWrapper.doEventService","
return (timePassed &&
batteryPassed &&
callPassed &&
peripheralPassed &&
calendarPassed &&
wifiPassed &&
screenPassed &&
bluetoothPassed &&
smsPassed);
}
public void restartEvents(boolean ignoreEventsBlocking, boolean unblockEventsRun, boolean keepActivatedProfile)
{
GlobalData.logE("DataWrapper.restartEvents","xxx");
if (!GlobalData.getGlobalEventsRuning(context))
// events are globally stopped
return;
GlobalData.logE("DataWrapper.restartEvents","events are not globbaly stopped");
if (GlobalData.getEventsBlocked(context) && (!ignoreEventsBlocking))
return;
GlobalData.logE("DataWrapper.restartEvents","events are not blocked");
//Profile activatedProfile = getActivatedProfile();
if (unblockEventsRun)
{
GlobalData.setEventsBlocked(context, false);
getDatabaseHandler().unblockAllEvents();
GlobalData.setForceRunEventRunning(context, false);
}
if (!keepActivatedProfile)
getDatabaseHandler().deactivateProfile();
Intent intent = new Intent();
intent.setAction(RestartEventsBroadcastReceiver.INTENT_RESTART_EVENTS);
context.sendBroadcast(intent);
}
public void restartEventsWithRescan(boolean showToast)
{
// remove all event delay alarms
removeAllEventDelays(false);
// ignoruj manualnu aktivaciu profilu
// a odblokuj forceRun eventy
restartEvents(true, true, false);
if (GlobalData.applicationEventWifiRescan.equals(GlobalData.RESCAN_TYPE_RESTART_EVENTS) ||
GlobalData.applicationEventWifiRescan.equals(GlobalData.RESCAN_TYPE_SCREEN_ON_RESTART_EVENTS))
{
// rescan wifi
WifiScanAlarmBroadcastReceiver.setAlarm(context, true);
//sendBroadcast(context);
//setAlarm(context, true);
}
if (GlobalData.applicationEventBluetoothRescan.equals(GlobalData.RESCAN_TYPE_RESTART_EVENTS) ||
GlobalData.applicationEventBluetoothRescan.equals(GlobalData.RESCAN_TYPE_SCREEN_ON_RESTART_EVENTS))
{
// rescan bluetooth
BluetoothScanAlarmBroadcastReceiver.setAlarm(context, true);
}
if (showToast)
{
Toast msg = Toast.makeText(context,
context.getResources().getString(R.string.toast_events_restarted),
Toast.LENGTH_SHORT);
msg.show();
}
}
public void restartEventsWithAlert(Activity activity)
{
if (!GlobalData.getGlobalEventsRuning(context))
// events are globally stopped
return;
/*
if (!GlobalData.getEventsBlocked(context))
return;
*/
if (GlobalData.applicationActivateWithAlert || (activity instanceof EditorProfilesActivity))
{
final Activity _activity = activity;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity);
dialogBuilder.setTitle(R.string.restart_events_alert_title);
dialogBuilder.setMessage(R.string.restart_events_alert_message);
//dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
dialogBuilder.setPositiveButton(R.string.alert_button_yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
restartEventsWithRescan(true);
if (GlobalData.applicationClose && (!(_activity instanceof EditorProfilesActivity)))
_activity.finish();
}
});
dialogBuilder.setNegativeButton(R.string.alert_button_no, null);
dialogBuilder.show();
}
else
{
restartEventsWithRescan(true);
if (GlobalData.applicationClose)
activity.finish();
}
}
public void restartEventsWithDelay(int delay)
{
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, RestartEventsBroadcastReceiver.class);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, delay);
long alarmTime = calendar.getTimeInMillis();
//SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
//GlobalData.logE("@@@ WifiScanAlarmBroadcastReceiver.setAlarm","oneshot="+oneshot+"; alarmTime="+sdf.format(alarmTime));
PendingIntent alarmIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmTime, alarmIntent);
}
public void setEventBlocked(Event event, boolean blocked)
{
event._blocked = blocked;
getDatabaseHandler().updateEventBlocked(event);
}
public boolean getIsManualProfileActivation()
{
if (!GlobalData.getEventsBlocked(context))
return false;
else
if (GlobalData.getForceRunEventRunning(context))
return false;
else
return true;
}
public String getProfileNameWithManualIndicator(Profile profile, boolean addIndicators)
{
if (profile == null)
return "";
String name = profile._name;
if (GlobalData.getEventsBlocked(context))
{
if (addIndicators)
{
if (GlobalData.getForceRunEventRunning(context))
{
name = "[\u00BB] " + name;
}
else
{
name = "[M] " + name;
}
}
}
if (addIndicators)
{
String eventName = getLastStartedEventName();
if (!eventName.isEmpty())
name = name + " [" + eventName + "]";
}
return name;
}
public String getLastStartedEventName()
{
List<EventTimeline> eventTimelineList = getEventTimelineList();
if (GlobalData.getGlobalEventsRuning(context) && GlobalData.getApplicationStarted(context))
{
if (eventTimelineList.size() > 0)
{
EventTimeline eventTimeLine = eventTimelineList.get(eventTimelineList.size()-1);
long event_id = eventTimeLine._fkEvent;
Event event = getEventById(event_id);
if (event != null)
{
if ((!GlobalData.getEventsBlocked(context)) || (event._forceRun))
{
Profile profile = getActivatedProfile();
if ((profile != null) && (event._fkProfileStart == profile._id))
// last started event activatees activated profile
return event._name;
else
return "";
}
else
return "";
}
else
return "";
}
else
{
long profileId = Long.valueOf(GlobalData.applicationBackgroundProfile);
if ((!GlobalData.getEventsBlocked(context)) && (profileId != GlobalData.PROFILE_NO_ACTIVATE))
{
Profile profile = getActivatedProfile();
if ((profile != null) && (profile._id == profileId))
return context.getString(R.string.event_name_background_profile);
else
return "";
}
else
return "";
}
}
else
return "";
}
public static String getSSID(WifiInfo wifiInfo)
{
String SSID = wifiInfo.getSSID();
if (SSID == null)
SSID = "";
SSID = SSID.replace("\"", "");
if (SSID.isEmpty())
{
if (WifiScanAlarmBroadcastReceiver.wifiConfigurationList != null)
{
for (WifiSSIDData wifiConfiguration : WifiScanAlarmBroadcastReceiver.wifiConfigurationList)
{
if (wifiConfiguration.bssid.equals(wifiInfo.getBSSID()))
return wifiConfiguration.ssid.replace("\"", "");
}
}
}
return SSID;
}
public static boolean compareSSID(WifiInfo wifiInfo, String SSID)
{
String ssid2 = "\"" + SSID + "\"";
return (getSSID(wifiInfo).equals(SSID) || getSSID(wifiInfo).equals(ssid2));
}
public static String getSSID(WifiSSIDData result)
{
String SSID;
if (result.ssid == null)
SSID = "";
else
SSID = result.ssid.replace("\"", "");
if (SSID.isEmpty())
{
if (WifiScanAlarmBroadcastReceiver.wifiConfigurationList != null)
{
for (WifiSSIDData wifiConfiguration : WifiScanAlarmBroadcastReceiver.wifiConfigurationList)
{
if ((wifiConfiguration.bssid != null) &&
(wifiConfiguration.bssid.equals(result.bssid)))
return wifiConfiguration.ssid.replace("\"", "");
}
}
}
return SSID;
}
public static boolean compareSSID(WifiSSIDData result, String SSID)
{
String ssid2 = "\"" + SSID + "\"";
return (getSSID(result).equals(SSID) || getSSID(result).equals(ssid2));
}
public void removeAllEventDelays(boolean onlyFromDb)
{
if (!onlyFromDb) {
for (Event event : getEventList()) {
event.removeDelayAlarm(this, true);
event.removeDelayAlarm(this, false);
}
}
getDatabaseHandler().removeAllEventsInDelay();
}
}
|
package com.intellij.ide.actions;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.ui.LafManager;
import com.intellij.ide.ui.laf.darcula.DarculaLookAndFeelInfo;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.actionSystem.ShortcutSet;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.fileEditor.impl.IdeDocumentHistoryImpl;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.JBPopupListener;
import com.intellij.openapi.ui.popup.LightweightWindowEvent;
import com.intellij.openapi.util.DimensionService;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfoRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.FocusManagerImpl;
import com.intellij.ui.CaptionPanel;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.ScrollingUtil;
import com.intellij.ui.WindowMoveListener;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import com.intellij.ui.speedSearch.ListWithFilter;
import com.intellij.ui.speedSearch.NameFilteringListModel;
import com.intellij.ui.speedSearch.SpeedSearch;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import static com.intellij.ui.speedSearch.SpeedSearchSupply.ENTERED_PREFIX_PROPERTY_NAME;
public class RecentLocationsAction extends DumbAwareAction {
private static final String RECENT_LOCATIONS_ACTION_ID = "RecentLocations";
private static final String LOCATION_SETTINGS_KEY = "recent.locations.popup";
private static final String SHOW_RECENT_CHANGED_LOCATIONS = "SHOW_RECENT_CHANGED_LOCATIONS";
private static final int DEFAULT_WIDTH = JBUI.scale(700);
private static final int DEFAULT_HEIGHT = JBUI.scale(530);
private static final int MINIMUM_WIDTH = JBUI.scale(600);
private static final int MINIMUM_HEIGHT = JBUI.scale(450);
private static final Color SHORTCUT_FOREGROUND_COLOR = UIUtil.getContextHelpForeground();
public static final String SHORTCUT_HEX_COLOR = String.format("#%02x%02x%02x",
SHORTCUT_FOREGROUND_COLOR.getRed(),
SHORTCUT_FOREGROUND_COLOR.getGreen(),
SHORTCUT_FOREGROUND_COLOR.getBlue());
static final String EMPTY_FILE_TEXT = IdeBundle.message("recent.locations.popup.empty.file.text");
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(RECENT_LOCATIONS_ACTION_ID);
Project project = getEventProject(e);
if (project == null) {
return;
}
RecentLocationsDataModel model = new RecentLocationsDataModel(project, ContainerUtil.newArrayList());
JBList<RecentLocationItem> list = new JBList<>(JBList.createDefaultListModel(model.getPlaces(showChanged(project))));
final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(list,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
ListWithFilter<RecentLocationItem> listWithFilter = (ListWithFilter<RecentLocationItem>)ListWithFilter
.wrap(list, scrollPane, getNamer(project, model), true);
listWithFilter.setAutoPackHeight(false);
listWithFilter.setBorder(BorderFactory.createEmptyBorder());
final SpeedSearch speedSearch = listWithFilter.getSpeedSearch();
speedSearch.addChangeListener(
evt -> {
if (evt.getPropertyName().equals(ENTERED_PREFIX_PROPERTY_NAME)) {
if (StringUtil.isEmpty(speedSearch.getFilter())) {
model.getEditorsToRelease().forEach(editor -> clearSelectionInEditor(editor));
}
}
});
list.setCellRenderer(new RecentLocationsRenderer(project, speedSearch, model));
list.setEmptyText(IdeBundle.message("recent.locations.popup.empty.text"));
list.setBackground(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground());
ScrollingUtil.installActions(list);
ScrollingUtil.ensureSelectionExists(list);
JLabel title = createTitle(showChanged(project));
ShortcutSet showChangedOnlyShortcutSet = KeymapUtil.getActiveKeymapShortcuts(RECENT_LOCATIONS_ACTION_ID);
JBCheckBox checkBox = createCheckbox(project, showChangedOnlyShortcutSet);
JPanel topPanel = createHeaderPanel(title, checkBox);
JPanel mainPanel = createMainPanel(listWithFilter, topPanel);
Color borderColor = SystemInfoRt.isMac && LafManager.getInstance().getCurrentLookAndFeel() instanceof DarculaLookAndFeelInfo
? topPanel.getBackground()
: null;
Ref<Boolean> navigationRef = Ref.create(false);
JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(mainPanel, list)
.setProject(project)
.setCancelOnClickOutside(true)
.setRequestFocus(true)
.setCancelCallback(() -> {
if (speedSearch.isHoldingFilter() && !navigationRef.get()) {
speedSearch.reset();
return false;
}
return true;
})
.setResizable(true)
.setMovable(true)
.setBorderColor(borderColor)
.setDimensionServiceKey(project, LOCATION_SETTINGS_KEY, true)
.setMinSize(new Dimension(MINIMUM_WIDTH, MINIMUM_HEIGHT))
.setLocateWithinScreenBounds(false)
.createPopup();
DumbAwareAction.create(event -> {
checkBox.setSelected(!checkBox.isSelected());
updateItems(project, model, listWithFilter, title, checkBox, popup);
}).registerCustomShortcutSet(showChangedOnlyShortcutSet, list, popup);
checkBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateItems(project, model, listWithFilter, title, checkBox, popup);
}
});
if (DimensionService.getInstance().getSize(LOCATION_SETTINGS_KEY, project) == null) {
popup.setSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
}
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
int clickCount = event.getClickCount();
if (clickCount > 1 && clickCount % 2 == 0) {
event.consume();
final int i = list.locationToIndex(event.getPoint());
if (i != -1) {
list.setSelectedIndex(i);
navigateToSelected(project, list, popup, navigationRef);
}
}
}
});
popup.addListener(new JBPopupListener() {
@Override
public void onClosed(@NotNull LightweightWindowEvent event) {
model.getEditorsToRelease().forEach(editor -> EditorFactory.getInstance().releaseEditor(editor));
model.getProjectConnection().disconnect();
}
});
initSearchActions(project, model, listWithFilter, list, popup, navigationRef);
IdeEventQueue.getInstance().getPopupManager().closeAllPopups(false);
list.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (!(e.getOppositeComponent() instanceof JCheckBox)) {
popup.cancel();
}
}
});
showPopup(project, popup);
}
private static void updateItems(@NotNull Project project,
@NotNull RecentLocationsDataModel data,
@NotNull ListWithFilter<RecentLocationItem> listWithFilter,
@NotNull JLabel title,
@NotNull JBCheckBox checkBox,
@NotNull JBPopup popup) {
boolean state = checkBox.isSelected();
PropertiesComponent.getInstance(project).setValue(SHOW_RECENT_CHANGED_LOCATIONS, state);
updateModel(listWithFilter, data, state);
updateTitleText(title, state);
FocusManagerImpl.getInstance().requestFocus(listWithFilter, false);
popup.pack(false, false);
}
@NotNull
public JBCheckBox createCheckbox(@NotNull Project project, @NotNull ShortcutSet checkboxShortcutSet) {
String text = "<html>"
+ IdeBundle.message("recent.locations.title.text")
+ " <font color=\"" + SHORTCUT_HEX_COLOR + "\">"
+ KeymapUtil.getShortcutsText(checkboxShortcutSet.getShortcuts()) + "</font>"
+ "</html>";
JBCheckBox checkBox = new JBCheckBox(text);
checkBox.setSelected(showChanged(project));
checkBox.setBorder(JBUI.Borders.empty());
checkBox.setOpaque(false);
return checkBox;
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(getEventProject(e) != null);
}
static void clearSelectionInEditor(@NotNull Editor editor) {
editor.getSelectionModel().removeSelection(true);
}
private static void showPopup(@NotNull Project project, @NotNull JBPopup popup) {
Point savedLocation = DimensionService.getInstance().getLocation(LOCATION_SETTINGS_KEY, project);
Window recentFocusedWindow = WindowManagerEx.getInstanceEx().getMostRecentFocusedWindow();
if (savedLocation != null && recentFocusedWindow != null) {
popup.showInScreenCoordinates(recentFocusedWindow, savedLocation);
}
else {
popup.showCenteredInCurrentWindow(project);
}
}
private static void updateModel(@NotNull ListWithFilter<RecentLocationItem> listWithFilter,
@NotNull RecentLocationsDataModel data,
boolean changed) {
NameFilteringListModel<RecentLocationItem> model = (NameFilteringListModel<RecentLocationItem>)listWithFilter.getList().getModel();
DefaultListModel<RecentLocationItem> originalModel = (DefaultListModel<RecentLocationItem>)model.getOriginalModel();
originalModel.removeAllElements();
data.getPlaces(changed).forEach(item -> originalModel.addElement(item));
listWithFilter.getSpeedSearch().reset();
}
@NotNull
private static JPanel createMainPanel(@NotNull ListWithFilter listWithFilter, @NotNull JPanel topPanel) {
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(listWithFilter, BorderLayout.CENTER);
return mainPanel;
}
@NotNull
private static JPanel createHeaderPanel(@NotNull JLabel title, @NotNull JComponent checkbox) {
JPanel topPanel = new CaptionPanel();
topPanel.add(title, BorderLayout.WEST);
topPanel.add(checkbox, BorderLayout.EAST);
Dimension size = topPanel.getPreferredSize();
size.height = JBUI.scale(29);
topPanel.setPreferredSize(size);
topPanel.setBorder(JBUI.Borders.empty(5, 8));
WindowMoveListener moveListener = new WindowMoveListener(topPanel);
topPanel.addMouseListener(moveListener);
topPanel.addMouseMotionListener(moveListener);
return topPanel;
}
@NotNull
private static JLabel createTitle(boolean showChanged) {
JBLabel title = new JBLabel();
title.setFont(title.getFont().deriveFont(Font.BOLD));
updateTitleText(title, showChanged);
return title;
}
private static void updateTitleText(@NotNull JLabel title, boolean showChanged) {
title.setText(showChanged
? IdeBundle.message("recent.locations.changed.locations")
: IdeBundle.message("recent.locations.popup.title"));
}
@NotNull
private static Function<RecentLocationItem, String> getNamer(@NotNull Project project, @NotNull RecentLocationsDataModel data) {
return value -> {
String breadcrumb = data.getBreadcrumbsMap(showChanged(project)).get(value.getInfo());
EditorEx editor = value.getEditor();
return breadcrumb + " " + value.getInfo().getFile().getName() + " " + editor.getDocument().getText();
};
}
private static void initSearchActions(@NotNull Project project,
@NotNull RecentLocationsDataModel data,
@NotNull ListWithFilter<RecentLocationItem> listWithFilter,
@NotNull JBList<RecentLocationItem> list,
@NotNull JBPopup popup,
@NotNull Ref<Boolean> navigationRef) {
listWithFilter.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
int clickCount = event.getClickCount();
if (clickCount > 1 && clickCount % 2 == 0) {
event.consume();
navigateToSelected(project, list, popup, navigationRef);
}
}
});
DumbAwareAction.create(e -> navigateToSelected(project, list, popup, navigationRef))
.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), listWithFilter, popup);
DumbAwareAction.create(e -> removePlaces(project, listWithFilter, list, data))
.registerCustomShortcutSet(CustomShortcutSet.fromString("DELETE", "BACK_SPACE"), listWithFilter, popup);
}
private static void removePlaces(@NotNull Project project,
@NotNull ListWithFilter<RecentLocationItem> listWithFilter,
@NotNull JBList<RecentLocationItem> list,
@NotNull RecentLocationsDataModel data) {
List<RecentLocationItem> selectedValue = list.getSelectedValuesList();
if (selectedValue.isEmpty()) {
return;
}
int index = list.getSelectedIndex();
boolean changed = showChanged(project);
IdeDocumentHistory ideDocumentHistory = IdeDocumentHistory.getInstance(project);
for (RecentLocationItem item : selectedValue) {
if (changed) {
ContainerUtil.filter(ideDocumentHistory.getChangePlaces(), info -> IdeDocumentHistoryImpl.isSame(info, item.getInfo()))
.forEach(info -> ideDocumentHistory.removeChangePlace(info));
}
else {
ContainerUtil.filter(ideDocumentHistory.getBackPlaces(), info -> IdeDocumentHistoryImpl.isSame(info, item.getInfo()))
.forEach(info -> ideDocumentHistory.removeBackPlace(info));
}
}
updateModel(listWithFilter, data, showChanged(project));
if (list.getModel().getSize() > 0) ScrollingUtil.selectItem(list, index < list.getModel().getSize() ? index : index - 1);
}
private static void navigateToSelected(@NotNull Project project,
@NotNull JBList<RecentLocationItem> list,
@NotNull JBPopup popup,
@NotNull Ref<Boolean> navigationRef) {
RecentLocationItem selectedValue = list.getSelectedValue();
if (selectedValue != null) {
IdeDocumentHistory.getInstance(project).gotoPlaceInfo(selectedValue.getInfo());
}
navigationRef.set(true);
popup.closeOk(null);
}
static boolean showChanged(@NotNull Project project) {
return PropertiesComponent.getInstance(project).getBoolean(SHOW_RECENT_CHANGED_LOCATIONS, false);
}
}
|
package com.intellij.keymap;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NonNls;
import java.util.Map;
import java.util.Set;
public abstract class KeymapsTestCase extends KeymapsTestCaseBase {
// @formatter:off
@NonNls @SuppressWarnings({"HardCodedStringLiteral"})
protected static final Map<String, String[][]> DEFAULT_DUPLICATES = new THashMap<String, String[][]>(){{
put("$default", new String[][] {
{ "ADD", "ExpandTreeNode", "Graph.ZoomIn"},
{ "BACK_SPACE", "EditorBackSpace", "Images.Thumbnails.UpFolder"},
{ "ENTER", "Console.Execute", "Console.TableResult.EditValue", "DirDiffMenu.SynchronizeDiff", "EditorChooseLookupItem",
"EditorEnter", "Images.Thumbnails.EnterAction", "NextTemplateVariable", "PropertyInspectorActions.EditValue",
"SearchEverywhere.SelectItem"},
{ "F2", "GotoNextError", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "Console.TableResult.EditValue", "XDebugger.SetValue", "Arrangement.Rule.Edit", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"},
{ "alt ENTER", "ShowIntentionActions", "Console.TableResult.EditValue"},
{ "F5", "Graph.ApplyCurrentLayout", "CopyElement"},
{ "F7", "NextDiff", "StepInto"},
{ "INSERT", "EditorToggleInsertState", "UsageView.Include", "DomElementsTreeView.AddElement", "DomCollectionControl.Add", "XDebugger.NewWatch"},
{ "SUBTRACT", "CollapseTreeNode", "Graph.ZoomOut"},
{ "TAB", "EditorChooseLookupItemReplace", "NextTemplateVariable", "NextParameter", "EditorIndentSelection",
"EditorTab", "NextTemplateParameter", "ExpandLiveTemplateByTab", "BraceOrQuoteOut",
"SearchEverywhere.CompleteCommand", "SearchEverywhere.NextTab"},
{ "LEFT", "EditorLeft", "Vcs.Log.GoToChild"},
{ "RIGHT", "EditorRight", "Vcs.Log.GoToParent"},
{ "alt DOWN", "ShowContent", "MethodDown", "Arrangement.Rule.Match.Condition.Move.Down", "ShowSearchHistory"},
{ "alt UP", "MethodUp", "Arrangement.Rule.Match.Condition.Move.Up"},
{ "alt F1", "SelectIn", "ProjectViewChangeView"},
{ "alt INSERT", "FileChooser.NewFolder", "Generate", "NewElement"},
{ "alt LEFT", "Diff.PrevChange", "PreviousTab"},
{ "alt RIGHT", "Diff.NextChange", "NextTab"},
{ "control F10", "Android.HotswapChanges", "UpdateRunningApplication"},
{ "control 1", "FileChooser.GotoHome", "GotoBookmark1", "DuplicatesForm.SendToLeft"},
{ "control 2", "FileChooser.GotoProject", "GotoBookmark2", "DuplicatesForm.SendToRight"},
{ "control 3", "GotoBookmark3", "FileChooser.GotoModule"},
{ "control ADD", "ExpandAll", "ExpandExpandableComponent", "ExpandRegion"},
{ "control DIVIDE", "CommentByLineComment", "Images.Editor.ActualSize", "Graph.ActualSize"},
{ "control DOWN", "EditorScrollDown", "EditorLookupDown", "MethodOverloadSwitchDown", "SearchEverywhere.NavigateToNextGroup"},
{ "control ENTER", "Console.Execute.Multiline", "DirDiffMenu.SynchronizeDiff.All", "EditorSplitLine", "ViewSource", "PyExecuteCellAction"},
{ "control EQUALS", "ExpandAll", "ExpandExpandableComponent", "ExpandRegion"},
{ "control F5", "Refresh", "Rerun"},
{ "control D", "EditorDuplicate", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"},
{ "control L", "FindNext", "Vcs.Log.FocusTextFilter"},
{ "control M", "EditorScrollToCenter", "Vcs.ShowMessageHistory", "TodoViewGroupByShowModules"},
{ "control F", "TodoViewGroupByFlattenPackage", "Find"},
{ "control N", "FileChooser.NewFolder", "GotoClass", "GotoChangedFile"},
{ "control P", "ChangesView.GroupBy.Directory", "FileChooser.TogglePathShowing", "ParameterInfo", "TodoViewGroupByShowPackages"},
{ "control R", "Replace", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"},
{ "control SLASH", "CommentByLineComment", "Images.Editor.ActualSize", "Graph.ActualSize"},
{ "control SPACE", "CodeCompletion", "ChangesView.SetDefault"},
{ "control U", "GotoSuperMethod", "CommanderSwapPanels"},
{ "control UP", "EditorScrollUp", "EditorLookupUp", "MethodOverloadSwitchUp", "SearchEverywhere.NavigateToPrevGroup"},
{ "control SUBTRACT", "CollapseAll", "CollapseExpandableComponent", "CollapseRegion"},
{ "control alt A", "ChangesView.AddUnversioned", "Diagram.DeselectAll"},
{ "control alt K", "Git.Commit.And.Push.Executor", "Hg.Commit.And.Push.Executor"},
{ "control alt E", "PerforceDirect.Edit", "Console.History.Browse"},
{ "control alt DOWN", "NextOccurence", "Console.TableResult.NextPage"},
{ "control alt G", "DatabaseView.SqlGenerator", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction", "Mvc.RunTarget"},
{ "control alt R", "org.jetbrains.plugins.ruby.tasks.rake.actions.RakeTasksPopupAction", "Django.RunManageTaskAction"},
{ "control alt UP", "PreviousOccurence", "Console.TableResult.PreviousPage"},
{ "control alt N", "Inline", "Console.TableResult.SetNull"},
{ "ctrl alt H", "CallHierarchy", "ChangesView.ShelveSilently"},
{ "ctrl alt U", "ShowUmlDiagramPopup", "ChangesView.UnshelveSilently"},
{ "control MINUS", "CollapseAll", "CollapseExpandableComponent", "CollapseRegion"},
{ "control PERIOD", "EditorChooseLookupItemDot", "CollapseSelection"},
{ "shift DELETE", "$Cut", "Maven.Uml.Exclude"},
{ "shift ENTER", "CollapseExpandableComponent", "Console.TableResult.EditValueMaximized", "DatabaseView.PropertiesAction", "EditorStartNewLine", "ExpandExpandableComponent", "OpenElementInNewWindow"},
{ "shift F4", "Debugger.EditTypeSource", "EditSourceInNewWindow"},
{ "shift F6", "RenameElement", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"},
{ "shift F7", "PreviousDiff", "SmartStepInto"},
{ "shift TAB", "PreviousTemplateVariable", "PrevParameter", "EditorUnindentSelection", "PrevTemplateParameter", "SearchEverywhere.PrevTab"},
{ "shift alt L", "org.jetbrains.plugins.ruby.console.LoadInIrbConsoleAction", "context.load"},
{ "shift alt M", "ChangesView.Move", "Vcs.MoveChangedLinesToChangelist"},
{ "shift control D", "TagDocumentationNavigation", "Diff.ShowSettingsPopup", "Uml.ShowDiff", "Console.TableResult.CompareCells"},
{ "shift control DOWN", "ResizeToolWindowDown", "MoveStatementDown"},
{ "shift control ENTER", "EditorCompleteStatement", "Console.Jpa.GenerateSql"},
{ "shift control F10", "Console.Open", "RunClass", "RunTargetAction"},
{ "shift control F8", "ViewBreakpoints", "EditBreakpoint"},
{ "shift control G", "ClassTemplateNavigation", "GoToClass"},
{ "shift control LEFT", "EditorPreviousWordWithSelection", "ResizeToolWindowLeft", },
{ "shift control RIGHT", "EditorNextWordWithSelection", "ResizeToolWindowRight", },
{ "shift control T", "GotoTest", "Images.ShowThumbnails", "RunDashboard.ShowConfigurations"},
{ "shift control UP", "ResizeToolWindowUp", "MoveStatementUp"},
{ "shift control alt D", "UML.ShowChanges", "Console.TableResult.CloneColumn"},
{ "shift control U", "ShelveChanges.UnshelveWithDialog", "EditorToggleCase"},
{ "shift control alt ENTER", "Console.Jpa.GenerateDDL", "Console.Transaction.Commit"},
{ "control E", "RecentFiles", "Vcs.ShowMessageHistory"},
{ "control alt Z", "Vcs.RollbackChangedLines", "ChangesView.Revert"},
{ "control TAB", "Switcher", "Diff.FocusOppositePane"},
{ "shift control TAB", "Switcher", "Diff.FocusOppositePaneAndScroll"},
{ "ctrl alt ENTER", "EditorStartNewLineBefore", "QuickActionPopup"},
{ "alt button1", "EditorCreateRectangularSelectionOnMouseDrag", "QuickEvaluateExpression"},
{ "button2", "EditorPasteFromX11", "GotoDeclaration", "EditorCreateRectangularSelectionOnMouseDrag"},
{ "ctrl alt F", "IntroduceField", "ShowFilterPopup"},
{ "PAGE_DOWN", "EditorPageDown", "SearchEverywhere.NavigateToNextGroup"},
{ "PAGE_UP", "EditorPageUp", "SearchEverywhere.NavigateToPrevGroup"},
});
put("Mac OS X 10.5+", new String[][] {
{ "BACK_SPACE", "$Delete", "EditorBackSpace", "Images.Thumbnails.UpFolder"},
{ "shift BACK_SPACE", "EditorBackSpace", "UsageView.Include"},
{ "meta BACK_SPACE", "EditorDeleteLine", "$Delete"},
{ "control LEFT", "Diff.PrevChange", "PreviousTab"},
{ "control RIGHT", "Diff.NextChange", "NextTab"},
{ "control DOWN", "ShowContent", "EditorLookupDown", "MethodDown"},
{ "control UP", "EditorLookupUp", "MethodUp"},
{ "control TAB", "Switcher", "Diff.FocusOppositePane"},
{ "shift control TAB", "Switcher", "Diff.FocusOppositePaneAndScroll"},
{ "meta L", "Vcs.Log.FocusTextFilter", "GotoLine"},
{ "meta R", "Refresh", "Rerun", "Replace", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"},
{ "control O", "ExportToTextFile", "OverrideMethods", },
{ "control ENTER", "Generate", "NewElement", "PyExecuteCellAction"},
{ "control SPACE", "CodeCompletion", "ChangesView.SetDefault"},
{ "ctrl meta R", "Android.HotswapChanges", "RerunTests"},
{ "meta 1", "ActivateProjectToolWindow", "FileChooser.GotoHome", "DuplicatesForm.SendToLeft"},
{ "meta 2", "ActivateFavoritesToolWindow", "FileChooser.GotoProject", "DuplicatesForm.SendToRight"},
{ "meta 3", "ActivateFindToolWindow", "FileChooser.GotoModule"},
{ "meta M", "MinimizeCurrentWindow", "TodoViewGroupByShowModules"},
{ "meta N", "FileChooser.NewFolder", "Generate", "NewElement"},
{ "meta O", "GotoClass", "GotoChangedFile"},
{ "shift meta G", "ClassTemplateNavigation", "GoToClass", "FindPrevious"},
{ "shift meta M", "ChangesView.Move", "Vcs.MoveChangedLinesToChangelist"},
{ "shift meta LEFT", "EditorLineStartWithSelection", "ResizeToolWindowLeft", },
{ "shift meta RIGHT", "EditorLineEndWithSelection", "ResizeToolWindowRight", },
{ "shift meta CLOSE_BRACKET", "Diff.NextChange", "NextTab"},
{ "shift meta OPEN_BRACKET", "Diff.PrevChange", "PreviousTab"},
{ "alt R", "Django.RunManageTaskAction", "org.jetbrains.plugins.ruby.tasks.rake.actions.RakeTasksPopupAction"},
{ "alt DOWN", "EditorUnSelectWord", "Arrangement.Rule.Match.Condition.Move.Down", "MethodOverloadSwitchDown", "ShowSearchHistory"},
{ "alt UP", "EditorSelectWord", "Arrangement.Rule.Match.Condition.Move.Up", "MethodOverloadSwitchUp"},
{ "ctrl m", "EditorMatchBrace", "Vcs.ShowMessageHistory"},
{ "meta UP", "ShowNavBar", "SearchEverywhere.NavigateToPrevGroup"},
{ "meta DOWN", "EditSource", "SearchEverywhere.NavigateToNextGroup"},
});
put("Mac OS X", new String[][] {
{ "BACK_SPACE", "$Delete", "EditorBackSpace", "Images.Thumbnails.UpFolder"},
{ "control LEFT", "Diff.PrevChange", "PreviousTab"},
{ "control RIGHT", "Diff.NextChange", "NextTab"},
{ "control DOWN", "EditorLookupDown", "ShowContent", "MethodDown"},
{ "control UP", "EditorLookupUp", "MethodUp"},
{ "control ENTER", "Generate", "NewElement", "PyExecuteCellAction"},
{ "control F5", "Refresh", "Rerun"},
{ "control TAB", "Switcher", "Diff.FocusOppositePane"},
{ "control N", "Generate", "NewElement"},
{ "shift control TAB", "Switcher", "Diff.FocusOppositePaneAndScroll"},
{ "meta M", "MinimizeCurrentWindow", "TodoViewGroupByShowModules"},
{ "meta 1", "ActivateProjectToolWindow", "FileChooser.GotoHome", "DuplicatesForm.SendToLeft"},
{ "meta 2", "ActivateFavoritesToolWindow", "FileChooser.GotoProject", "DuplicatesForm.SendToRight"},
{ "meta 3", "ActivateFindToolWindow", "FileChooser.GotoModule"},
{ "shift meta LEFT", "EditorLineStartWithSelection", "ResizeToolWindowLeft", },
{ "shift meta RIGHT", "EditorLineEndWithSelection", "ResizeToolWindowRight", },
{ "alt R", "Django.RunManageTaskAction", "org.jetbrains.plugins.ruby.tasks.rake.actions.RakeTasksPopupAction"},
});
put("Emacs", new String[][] {
{ "TAB", "EditorChooseLookupItemReplace", "NextTemplateVariable", "NextParameter", "EditorIndentSelection",
"EmacsStyleIndent", "NextTemplateParameter", "ExpandLiveTemplateByTab", "BraceOrQuoteOut",
"SearchEverywhere.CompleteCommand", "SearchEverywhere.NextTab"},
{ "alt SLASH", "CodeCompletion", "HippieCompletion"},
{ "control D", "$Delete", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"},
{ "control K", "EditorCutLineEnd", "CheckinProject"},
{ "control L", "EditorScrollToCenter", "Vcs.Log.FocusTextFilter"},
{ "control M", "EditorEnter", "EditorChooseLookupItem", "NextTemplateVariable", "Console.Execute", "TodoViewGroupByShowModules"},
{ "control N", "EditorDown", "FileChooser.NewFolder"},
{ "control F", "EditorRight", "TodoViewGroupByFlattenPackage"},
{ "control P", "ChangesView.GroupBy.Directory", "EditorUp", "FileChooser.TogglePathShowing","TodoViewGroupByShowPackages"},
{ "control R", "org.jetbrains.plugins.ruby.rails.console.ReloadSources", "FindPrevious"},
{ "control SLASH", "$Undo", "Images.Editor.ActualSize", "Graph.ActualSize"},
{ "control SPACE", "EditorToggleStickySelection", "ChangesView.SetDefault"},
{ "control X,N", "Diff.NextChange", "NextTab"},
{ "control X,P", "Diff.PrevChange", "PreviousTab"},
{ "control UP", "EditorBackwardParagraph", "EditorLookupUp", "MethodOverloadSwitchUp", "SearchEverywhere.NavigateToPrevGroup"},
{ "control DOWN", "EditorForwardParagraph", "EditorLookupDown", "MethodOverloadSwitchDown", "SearchEverywhere.NavigateToNextGroup"},
{ "control alt A", "MethodUp", "ChangesView.AddUnversioned", "Diagram.DeselectAll"},
{ "control alt E", "MethodDown", "PerforceDirect.Edit", "Console.History.Browse"},
{ "control alt G", "GotoDeclaration", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction", "Mvc.RunTarget"},
{ "control alt S", "ShowSettings", "Find"},
{ "shift alt S", "FindUsages", "context.save"},
{ "shift alt G", "GotoChangedFile", "GotoClass", "hg4idea.QGotoFromPatches"},
{ "shift alt P", "ParameterInfo", "hg4idea.QPushAction"},
{ "shift control X", SECOND_STROKE, "com.jetbrains.php.framework.FrameworkRunConsoleAction"},
{ "shift ctrl DOWN", "EditorForwardParagraphWithSelection", "ResizeToolWindowDown"},
{ "shift ctrl UP", "EditorBackwardParagraphWithSelection", "ResizeToolWindowUp"},
});
put("Visual Studio", new String[][] {
{ "F5", "Resume", "Graph.ApplyCurrentLayout"},
{ "F7", "NextDiff", "CompileDirty"},
{ "alt F2", "ShowBookmarks", "WebOpenInAction"},
{ "alt F8", "ReformatCode", "ForceStepInto", "EvaluateExpression"},
{ "control COMMA", "GotoClass", "GotoChangedFile"},
{ "control F1", "ExternalJavaDoc", "ShowErrorDescription"},
{ "control F10", "Android.HotswapChanges", "RunToCursor", "UpdateRunningApplication"},
{ "control N", "FileChooser.NewFolder", "Generate", },
{ "control P", "ChangesView.GroupBy.Directory", "FileChooser.TogglePathShowing", "Print", "TodoViewGroupByShowPackages"},
{ "control alt F", "ReformatCode", "IntroduceField", "ShowFilterPopup"},
{ "shift F12", "RestoreDefaultLayout", "FindUsagesInFile"},
{ "shift F2", "GotoPreviousError", "GotoDeclaration"},
{ "shift control F7", "FindUsagesInFile", "HighlightUsagesInFile"},
{ "shift control I", "ImplementMethods", "QuickImplementations"},
{ "alt F9", "ViewBreakpoints", "EditBreakpoint"},
{ "alt MULTIPLY", "ShowExecutionPoint", "Images.Thumbnails.ToggleRecursive"},
{ "shift alt U", "GotoPrevElementUnderCaretUsage", "ToggleCamelSnakeCase"},
{ "shift alt D", "GotoNextElementUnderCaretUsage", "hg4idea.QFold"}
});
put("Default for XWin", new String[][] {
{ "shift ctrl alt button1", "EditorAddRectangularSelectionOnMouseDrag", "QuickEvaluateExpression"},
});
put("Default for GNOME", new String[][] {
{ "shift alt 1", "SelectIn", "ProjectViewChangeView"},
{ "shift alt 7", "IDEtalk.SearchUserHistory", "FindUsages"},
{ "shift alt LEFT", "PreviousEditorTab", "Back"},
{ "shift alt RIGHT", "NextEditorTab", "Forward"},
});
put("Default for KDE", new String[][] {
{ "control 1", "FileChooser.GotoHome", "ShowErrorDescription", "DuplicatesForm.SendToLeft"},
{ "control 2", "FileChooser.GotoProject", "Stop", "DuplicatesForm.SendToRight"},
{ "control 3", "FindWordAtCaret", "FileChooser.GotoModule"},
{ "control 5", "Refresh", "Rerun"},
{ "shift alt 1", "SelectIn", "ProjectViewChangeView"},
{ "shift alt 7", "IDEtalk.SearchUserHistory", "FindUsages"},
{ "shift alt L", "ReformatCode", "org.jetbrains.plugins.ruby.console.LoadInIrbConsoleAction", "context.load"},
});
put("Eclipse", new String[][] {
{ "F2", "Console.TableResult.EditValue", "QuickJavaDoc", "XDebugger.SetValue", "Arrangement.Rule.Edit"},
{ "F5", "Graph.ApplyCurrentLayout", "StepInto"},
{ "alt DOWN", "ShowContent", "MoveStatementDown", "Arrangement.Rule.Match.Condition.Move.Down", "ShowSearchHistory"},
{ "alt UP", "MoveStatementUp", "Arrangement.Rule.Match.Condition.Move.Up"},
{ "alt HOME", "ViewNavigationBar", "ShowNavBar"},
{ "control F10", "Android.HotswapChanges", "ShowPopupMenu", "UpdateRunningApplication"},
{ "control D", "EditorDeleteLine", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"},
{ "control L", "Vcs.Log.FocusTextFilter", "GotoLine"},
{ "control N", "ShowPopupMenu", "FileChooser.NewFolder"},
{ "control P", "ChangesView.GroupBy.Directory", "FileChooser.TogglePathShowing", "Print", "TodoViewGroupByShowPackages"},
{ "control R", "RunToCursor", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"},
{ "control U", "EvaluateExpression", "CommanderSwapPanels"},
{ "control F", "Replace", "TodoViewGroupByFlattenPackage"},
{ "control PAGE_DOWN", "Diff.NextChange", "NextTab"},
{ "control PAGE_UP", "Diff.PrevChange", "PreviousTab"},
{ "control F6", "Diff.NextChange", "NextTab"},
{ "control alt DOWN", "Console.TableResult.NextPage", "EditorDuplicateLines"},
{ "control alt E", "Console.History.Browse", "ExecuteInPyConsoleAction", "PerforceDirect.Edit"},
{ "control alt LEFT", "Diff.NextChange", "NextTab"},
{ "control alt RIGHT", "Diff.PrevChange", "PreviousTab"},
{ "shift alt D", "hg4idea.QFold", "Debug"},
{ "shift alt G", "RerunTests", "hg4idea.QGotoFromPatches"},
{ "shift alt L", "IntroduceVariable", "org.jetbrains.plugins.ruby.console.LoadInIrbConsoleAction", "context.load"},
{ "shift alt P", "hg4idea.QPushAction", "ImplementMethods"},
{ "shift alt R", "RenameElement", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"},
{ "shift alt S", "ShowPopupMenu", "context.save"},
{ "shift alt T", "ShowPopupMenu", "tasks.switch"},
{ "shift control DOWN", "ResizeToolWindowDown", "MethodDown"},
{ "shift control E", "EditSource", "RecentChangedFiles"},
{ "shift control F6", "ChangeTypeSignature", "Diff.PrevChange", "PreviousTab"},
{ "shift control F11", "ToggleBookmark", "FocusTracer"},
{ "shift control G", "FindUsagesInFile", "ClassTemplateNavigation", "GoToClass"},
{ "shift control I", "QuickImplementations", "XDebugger.Inspect"},
{ "shift control UP", "ResizeToolWindowUp", "MethodUp"},
{ "shift control K", "Vcs.Push", "FindPrevious"},
{ "shift control X", "EditorToggleCase", "com.jetbrains.php.framework.FrameworkRunConsoleAction"},
{ "shift control T", "GotoClass", "GotoChangedFile"},
});
put("NetBeans 6.5", new String[][] {
{ "F4", "RunToCursor", "EditSource"},
{ "F5", "Debugger.ResumeThread", "Resume", "Graph.ApplyCurrentLayout"},
{ "alt DOWN", "GotoNextElementUnderCaretUsage", "ShowContent", "Arrangement.Rule.Match.Condition.Move.Down", "ShowSearchHistory"},
{ "alt UP", "GotoPrevElementUnderCaretUsage", "Arrangement.Rule.Match.Condition.Move.Up"},
{ "control 1", "ActivateProjectToolWindow", "DuplicatesForm.SendToLeft"},
{ "control 2", "ActivateProjectToolWindow", "FileChooser.GotoProject", "DuplicatesForm.SendToRight"},
{ "control 3", "ActivateProjectToolWindow", "FileChooser.GotoModule"},
{ "control BACK_SPACE", "EditorDeleteToWordStart", "ToggleDockMode"},
{ "control DIVIDE", "CollapseRegionRecursively", "Images.Editor.ActualSize", "Graph.ActualSize"},
{ "control M", "Vcs.ShowMessageHistory", "Move", "TodoViewGroupByShowModules"},
{ "control N", "NewElement", "FileChooser.NewFolder"},
{ "control R", "RenameElement", "org.jetbrains.plugins.ruby.rails.console.ReloadSources", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"},
{ "control U", SECOND_STROKE, "CommanderSwapPanels"},
{ "control O", "GotoClass", "GotoChangedFile"},
{ "control PERIOD", "GotoNextError", "EditorChooseLookupItemDot"},
{ "control PAGE_DOWN", "Diff.NextChange", "NextTab"},
{ "control PAGE_UP", "Diff.PrevChange", "PreviousTab"},
{ "control alt DOWN", "MethodDown", "NextOccurence", "Console.TableResult.NextPage"},
{ "control alt UP", "MethodUp", "PreviousOccurence", "Console.TableResult.PreviousPage"},
{ "shift F4", "RecentFiles", "Debugger.EditTypeSource", "Vcs.ShowMessageHistory", "EditSourceInNewWindow"},
{ "shift alt F9", "ChooseDebugConfiguration", "ValidateXml", "ValidateJsp"},
{ "shift alt D", "ToggleFloatingMode", "hg4idea.QFold"},
{ "shift control DOWN", "EditorDuplicate", "ResizeToolWindowDown", },
{ "shift control F7", "HighlightUsagesInFile", "XDebugger.NewWatch"},
{ "shift control UP", "EditorDuplicate", "ResizeToolWindowUp", },
{ "shift control K", "HippieCompletion", "Vcs.Push"},
{ "control alt E", "Console.History.Browse", "ExecuteInPyConsoleAction", "PerforceDirect.Edit"},
});
put("JBuilder", new String[][] {
{ "F2", "EditorTab", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "Console.TableResult.EditValue", "XDebugger.SetValue", "Arrangement.Rule.Edit", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"},
{ "F5", "ToggleBreakpointEnabled", "Graph.ApplyCurrentLayout"},
{ "TAB", "EditorChooseLookupItemReplace", "NextTemplateVariable", "NextParameter", "EditorIndentSelection",
"EmacsStyleIndent", "NextTemplateParameter", "ExpandLiveTemplateByTab", "BraceOrQuoteOut",
"SearchEverywhere.CompleteCommand", "SearchEverywhere.NextTab"},
{ "control F6", "PreviousEditorTab", "PreviousTab", },
{ "control L", "Vcs.Log.FocusTextFilter", "EditorSelectLine"},
{ "control M", "Vcs.ShowMessageHistory", "OverrideMethods", "TodoViewGroupByShowModules"},
{ "control P", "ChangesView.GroupBy.Directory", "FileChooser.TogglePathShowing", "FindInPath", "TodoViewGroupByShowPackages"},
{ "shift control A", "SaveAll", "GotoAction"},
{ "shift control E", "RecentChangedFiles", "ExtractMethod"},
{ "shift control ENTER", "FindUsages", "Console.Jpa.GenerateSql"},
{ "shift control F6", "NextTab", "ChangeTypeSignature"},
{ "shift control G", "GotoSymbol", "ClassTemplateNavigation", "GoToClass"},
{ "shift control X", "EditorToggleShowWhitespaces", "com.jetbrains.php.framework.FrameworkRunConsoleAction"},
});
put("Eclipse (Mac OS X)", new String[][] {
{ "meta BACK_SPACE", "EditorDeleteToWordStart", "$Delete"},
{ "F2", "Console.TableResult.EditValue", "QuickJavaDoc", "XDebugger.SetValue", "Arrangement.Rule.Edit", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"},
{ "F3", "GotoDeclaration", "EditSource"},
{ "F5", "StepInto", "Graph.ApplyCurrentLayout"},
{ "alt DOWN", "MoveStatementDown", "Arrangement.Rule.Match.Condition.Move.Down", "MethodOverloadSwitchDown", "ShowSearchHistory"},
{ "alt UP", "MoveStatementUp", "Arrangement.Rule.Match.Condition.Move.Up", "MethodOverloadSwitchUp"},
{ "control PERIOD", "EditorChooseLookupItemDot", "HippieCompletion"},
{ "meta 1", "FileChooser.GotoHome", "ShowIntentionActions", "DuplicatesForm.SendToLeft"},
{ "meta 3", "FileChooser.GotoModule", "GotoAction"},
{ "meta D", "EditorDeleteLine", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"},
{ "meta I", "DatabaseView.PropertiesAction", "AutoIndentLines"},
{ "meta P", "ChangesView.GroupBy.Directory", "FileChooser.TogglePathShowing", "Print", "TodoViewGroupByShowPackages"},
{ "meta R", "org.jetbrains.plugins.ruby.rails.console.ReloadSources", "RunToCursor"},
{ "meta U", "CommanderSwapPanels", "EvaluateExpression"},
{ "meta W", "CloseContent", "CloseActiveTab"},
{ "meta F6", "Diff.NextChange", "NextTab"},
{ "shift meta T", "GotoClass", "GotoChangedFile"},
{ "meta alt LEFT", "Diff.PrevChange", "PreviousTab"},
{ "meta alt RIGHT", "Diff.NextChange", "NextTab"},
{ "meta alt DOWN", "Console.TableResult.NextPage", "EditorDuplicateLines"},
{ "shift meta F11", "Run", "FocusTracer"},
{ "shift meta G", "ClassTemplateNavigation", "GoToClass", "FindUsages"},
{ "shift meta K", "Vcs.Push", "FindPrevious"},
{ "shift meta X", "EditorToggleCase", "com.jetbrains.php.framework.FrameworkRunConsoleAction"},
{ "shift meta U", "FindUsagesInFile", "ShelveChanges.UnshelveWithDialog"},
{ "shift meta F6", "Diff.PrevChange", "PreviousTab"},
{ "control shift alt Z", "Vcs.RollbackChangedLines", "ChangesView.Revert"},
{ "meta alt H", "ChangesView.ShelveSilently", "RunDashboard.ShowConfigurations"}
});
put("Sublime Text", new String[][] {
{ "F2", "Arrangement.Rule.Edit", "ChangesView.Rename", "Console.TableResult.EditValue", "Git.Reword.Commit", "GotoNextBookmark", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "ShelvedChanges.Rename", "XDebugger.SetValue"},
{ "ctrl ADD", "EditorIncreaseFontSize", "ExpandAll", "ExpandExpandableComponent"},
{ "ctrl D", "CompareTwoFiles", "Diff.ShowDiff", "FileChooser.GotoDesktop", "SelectNextOccurrence", "SendEOF"},
{ "ctrl ENTER", "Console.Execute.Multiline", "DirDiffMenu.SynchronizeDiff.All", "EditorStartNewLine", "PyExecuteCellAction", "ViewSource"},
{ "ctrl EQUALS", "EditorIncreaseFontSize", "ExpandAll", "ExpandExpandableComponent"},
{ "ctrl L", "EditorSelectWord", "Vcs.Log.FocusTextFilter"},
{ "ctrl M", "EditorMatchBrace", "TodoViewGroupByShowModules", "Vcs.ShowMessageHistory"},
{ "ctrl MINUS", "CollapseAll", "CollapseExpandableComponent", "EditorDecreaseFontSize"},
{ "ctrl N", "FileChooser.NewFolder", "NewElement"},
{ "ctrl P", "ChangesView.GroupBy.Directory", "FileChooser.TogglePathShowing", "GotoFile"},
{ "ctrl R", "FileStructurePopup", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"},
{ "ctrl SUBTRACT", "CollapseAll", "CollapseExpandableComponent", "EditorDecreaseFontSize"},
{ "ctrl alt DOWN", "Console.TableResult.NextPage", "EditorCloneCaretBelow"},
{ "ctrl alt UP", "Console.TableResult.PreviousPage", "EditorCloneCaretAbove"},
{ "shift ENTER", "CollapseExpandableComponent", "Console.TableResult.EditValueMaximized", "DatabaseView.PropertiesAction", "EditorSplitLine", "ExpandExpandableComponent", "OpenElementInNewWindow"},
{ "shift ctrl D", "Console.TableResult.CompareCells", "EditorDuplicate", "Uml.ShowDiff"},
{ "shift ctrl DOWN", "MoveLineDown", "ResizeToolWindowDown"},
{ "shift ctrl ENTER", "Console.Jpa.GenerateSql", "EditorStartNewLineBefore"},
{ "shift ctrl T", "Images.ShowThumbnails", "ReopenClosedTab", "RunDashboard.ShowConfigurations"},
{ "shift ctrl UP", "MoveLineUp", "ResizeToolWindowUp"}
});
put("Sublime Text OSX", new String[][] {
{ "F2", "Arrangement.Rule.Edit", "ChangesView.Rename", "Console.TableResult.EditValue", "Git.Reword.Commit", "GotoNextBookmark", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "ShelvedChanges.Rename", "XDebugger.SetValue"},
{ "meta ADD", "EditorIncreaseFontSize", "ExpandAll", "ExpandExpandableComponent"},
{ "meta D", "CompareTwoFiles", "Diff.ShowDiff", "FileChooser.GotoDesktop", "SelectNextOccurrence", "SendEOF"},
{ "meta DOWN", "EditorTextEnd", "SearchEverywhere.NavigateToNextGroup"},
{ "meta ENTER", "Console.Execute.Multiline", "DirDiffMenu.SynchronizeDiff.All", "EditorStartNewLine", "ViewSource"},
{ "meta EQUALS", "EditorIncreaseFontSize", "ExpandAll", "ExpandExpandableComponent"},
{ "meta I", "DatabaseView.PropertiesAction", "IncrementalSearch"},
{ "meta L", "EditorSelectWord", "Vcs.Log.FocusTextFilter"},
{ "meta MINUS", "CollapseAll", "CollapseExpandableComponent", "EditorDecreaseFontSize"},
{ "meta P", "ChangesView.GroupBy.Directory", "FileChooser.TogglePathShowing", "GotoFile"},
{ "meta R", "FileStructurePopup", "Refresh", "Rerun", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"},
{ "meta SUBTRACT", "CollapseAll", "CollapseExpandableComponent", "EditorDecreaseFontSize"},
{ "meta UP", "EditorTextStart", "SearchEverywhere.NavigateToPrevGroup"},
{ "meta alt DOWN", "Console.TableResult.NextPage", "GotoDeclaration"},
{ "meta alt G", "DatabaseView.SqlGenerator", "FindWordAtCaret", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction"},
{ "shift ENTER", "CollapseExpandableComponent", "Console.TableResult.EditValueMaximized", "EditorSplitLine", "ExpandExpandableComponent", "OpenElementInNewWindow"},
{ "shift meta D", "Console.TableResult.CompareCells", "EditorDuplicate", "Uml.ShowDiff"},
{ "shift meta ENTER", "Console.Jpa.GenerateSql", "EditorStartNewLineBefore"},
{ "shift meta T", "Images.ShowThumbnails", "ReopenClosedTab", "RunDashboard.ShowConfigurations"}
});
}};
// @formatter:on
@NonNls protected static final Set<String> DEFAULT_UNKNOWN_ACTION_IDS = ContainerUtil.set(
"ActivateVersionControlToolWindow", "ActivateFavoritesToolWindow", "ActivateCommanderToolWindow", "ActivateDebugToolWindow",
"ActivateFindToolWindow",
"ActivateHierarchyToolWindow", "ActivateMessagesToolWindow", "ActivateProjectToolWindow", "ActivateRunToolWindow",
"ActivateStructureToolWindow", "ActivateTODOToolWindow", "ActivateWebToolWindow", "ActivatePaletteToolWindow",
"ActivateTerminalToolWindow",
"IDEtalk.SearchUserHistory", "IDEtalk.SearchUserHistory", "IDEtalk.Rename",
""
);
@NonNls protected static final Set<String> DEFAULT_BOUND_ACTIONS = ContainerUtil.set(
"EditorDelete"
);
}
|
package com.intellij.coverage;
import com.intellij.coverage.view.CoverageViewManager;
import com.intellij.coverage.view.CoverageViewSuiteListener;
import com.intellij.execution.RunManager;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunConfigurationBase;
import com.intellij.execution.configurations.RunnerSettings;
import com.intellij.execution.configurations.coverage.CoverageEnabledConfiguration;
import com.intellij.execution.impl.RunManagerImpl;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.colors.EditorColorsListener;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.editor.event.EditorFactoryListener;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vfs.*;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.rt.coverage.data.ClassData;
import com.intellij.rt.coverage.data.LineCoverage;
import com.intellij.rt.coverage.data.LineData;
import com.intellij.rt.coverage.data.ProjectData;
import com.intellij.ui.UIBundle;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.UIUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
/**
* @author ven
*/
public class CoverageDataManagerImpl extends CoverageDataManager implements Disposable{
private final List<CoverageSuiteListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private static final Logger LOG = Logger.getInstance(CoverageDataManagerImpl.class);
@NonNls
private static final String SUITE = "SUITE";
private final Project myProject;
private final Set<CoverageSuite> myCoverageSuites = new HashSet<>();
private boolean myIsProjectClosing = false;
private final Object myLock = new Object();
private boolean mySubCoverageIsActive;
private final VirtualFileContentsChangedAdapter myContentListener = new VirtualFileContentsChangedAdapter() {
@Override
protected void onFileChange(@NotNull VirtualFile fileOrDirectory) {
if (myCurrentSuiteRoots != null && VfsUtilCore.isUnder(fileOrDirectory.getPath(), myCurrentSuiteRoots)) {
myCurrentSuitesBundle.restoreCoverageData();
updateCoverageData(myCurrentSuitesBundle);
}
}
@Override
protected void onBeforeFileChange(@NotNull VirtualFile fileOrDirectory) { }
};
private Set<LocalFileSystem.WatchRequest> myWatchRequests;
private List<String> myCurrentSuiteRoots;
@Override
public CoverageSuitesBundle getCurrentSuitesBundle() {
return myCurrentSuitesBundle;
}
private CoverageSuitesBundle myCurrentSuitesBundle;
private final Object ANNOTATORS_LOCK = new Object();
private final Map<Editor, SrcFileAnnotator> myAnnotators = new HashMap<>();
public CoverageDataManagerImpl(@NotNull Project project) {
myProject = project;
MessageBusConnection connection = project.getMessageBus().connect();
connection.subscribe(EditorColorsManager.TOPIC, new EditorColorsListener() {
@Override
public void globalSchemeChange(EditorColorsScheme scheme) {
chooseSuitesBundle(myCurrentSuitesBundle);
}
});
connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
@Override
public void projectOpened(@NotNull Project project) {
if (project == myProject) {
EditorFactory.getInstance().addEditorFactoryListener(new CoverageEditorFactoryListener(), CoverageDataManagerImpl.this);
}
}
@Override
public void projectClosing(@NotNull Project project) {
if (project != myProject) {
return;
}
synchronized (myLock) {
myIsProjectClosing = true;
}
}
});
final CoverageViewSuiteListener coverageViewListener = createCoverageViewListener();
if (coverageViewListener != null) {
addSuiteListener(coverageViewListener, this);
}
CoverageRunner.EP_NAME.addExtensionPointListener(new ExtensionPointListener<CoverageRunner>() {
@Override
public void extensionRemoved(@NotNull CoverageRunner coverageRunner, @NotNull PluginDescriptor pluginDescriptor) {
CoverageSuitesBundle suitesBundle = getCurrentSuitesBundle();
if (suitesBundle != null &&
Arrays.stream(suitesBundle.getSuites()).anyMatch(suite -> coverageRunner == suite.getRunner())) {
chooseSuitesBundle(null);
}
RunManager runManager = RunManager.getInstance(project);
List<RunConfiguration> configurations = runManager.getAllConfigurationsList();
for (RunConfiguration configuration : configurations) {
if (configuration instanceof RunConfigurationBase) {
CoverageEnabledConfiguration coverageEnabledConfiguration =
((RunConfigurationBase)configuration).getCopyableUserData(CoverageEnabledConfiguration.COVERAGE_KEY);
if (coverageEnabledConfiguration != null && Objects.equals(coverageRunner.getId(), coverageEnabledConfiguration.getRunnerId())) {
coverageEnabledConfiguration.coverageRunnerExtensionRemoved(coverageRunner);
((RunConfigurationBase)configuration).putCopyableUserData(CoverageEnabledConfiguration.COVERAGE_KEY, null);
}
}
}
//cleanup created templates
((RunManagerImpl)runManager).reloadSchemes();
for (CoverageSuite suite : getSuites()) {
if (suite instanceof BaseCoverageSuite) {
CoverageRunner runner = suite.getRunner();
if (runner == coverageRunner) {
((BaseCoverageSuite)suite).setRunner(null);
}
}
}
ActionToolbarImpl.updateAllToolbarsImmediately();
}
}, this);
CoverageEngine.EP_NAME.addExtensionPointListener(new ExtensionPointListener<CoverageEngine>() {
@Override
public void extensionRemoved(@NotNull CoverageEngine coverageEngine, @NotNull PluginDescriptor pluginDescriptor) {
CoverageSuitesBundle suitesBundle = getCurrentSuitesBundle();
if (suitesBundle != null && suitesBundle.getCoverageEngine() == coverageEngine) {
chooseSuitesBundle(null);
}
myCoverageSuites.removeIf(suite -> suite.getCoverageEngine() == coverageEngine);
}
}, this);
}
@Nullable
protected CoverageViewSuiteListener createCoverageViewListener() {
return new CoverageViewSuiteListener(this, myProject);
}
@Override
public void readExternal(Element element) throws InvalidDataException {
for (Element suiteElement : element.getChildren(SUITE)) {
final CoverageRunner coverageRunner = BaseCoverageSuite.readRunnerAttribute(suiteElement);
// skip unknown runners
if (coverageRunner == null) {
// collect gc
final CoverageFileProvider fileProvider = BaseCoverageSuite.readDataFileProviderAttribute(suiteElement);
if (fileProvider.isValid()) {
//deleteCachedCoverage(fileProvider.getCoverageDataFilePath());
}
continue;
}
CoverageSuite suite = null;
for (CoverageEngine engine : CoverageEngine.EP_NAME.getExtensions()) {
if (coverageRunner.acceptsCoverageEngine(engine)) {
suite = engine.createEmptyCoverageSuite(coverageRunner);
if (suite != null) {
if (suite instanceof BaseCoverageSuite) {
((BaseCoverageSuite)suite).setProject(myProject);
}
break;
}
}
}
if (suite != null) {
try {
suite.readExternal(suiteElement);
myCoverageSuites.add(suite);
}
catch (NumberFormatException e) {
//try next suite
}
}
}
}
@Override
public void writeExternal(final Element element) throws WriteExternalException {
for (CoverageSuite coverageSuite : myCoverageSuites) {
final Element suiteElement = new Element(SUITE);
element.addContent(suiteElement);
coverageSuite.writeExternal(suiteElement);
}
}
@Override
public CoverageSuite addCoverageSuite(final String name, final CoverageFileProvider fileProvider, final String[] filters, final long lastCoverageTimeStamp,
@Nullable final String suiteToMergeWith,
final CoverageRunner coverageRunner,
final boolean collectLineInfo,
final boolean tracingEnabled) {
final CoverageSuite suite = createCoverageSuite(coverageRunner, name, fileProvider, filters, lastCoverageTimeStamp, suiteToMergeWith, collectLineInfo, tracingEnabled);
if (suiteToMergeWith == null || !name.equals(suiteToMergeWith)) {
removeCoverageSuite(suite);
}
myCoverageSuites.remove(suite); // remove previous instance
myCoverageSuites.add(suite); // add new instance
return suite;
}
@Override
public CoverageSuite addExternalCoverageSuite(String selectedFileName,
long timeStamp,
CoverageRunner coverageRunner,
CoverageFileProvider fileProvider) {
final CoverageSuite suite = createCoverageSuite(coverageRunner, selectedFileName, fileProvider, ArrayUtilRt.EMPTY_STRING_ARRAY, timeStamp, null, false, false);
myCoverageSuites.add(suite);
return suite;
}
@Override
public CoverageSuite addCoverageSuite(final CoverageEnabledConfiguration config) {
final String name = config.getName() + " Coverage Results";
final String covFilePath = config.getCoverageFilePath();
assert covFilePath != null; // Shouldn't be null here!
final CoverageRunner coverageRunner = config.getCoverageRunner();
LOG.assertTrue(coverageRunner != null, "Coverage runner id = " + config.getRunnerId());
final DefaultCoverageFileProvider fileProvider = new DefaultCoverageFileProvider(new File(covFilePath));
final CoverageSuite suite = createCoverageSuite(config, name, coverageRunner, fileProvider);
// remove previous instance
removeCoverageSuite(suite);
// add new instance
myCoverageSuites.add(suite);
return suite;
}
@Override
public void removeCoverageSuite(final CoverageSuite suite) {
suite.deleteCachedCoverageData();
myCoverageSuites.remove(suite);
if (myCurrentSuitesBundle != null && myCurrentSuitesBundle.contains(suite)) {
CoverageSuite[] suites = myCurrentSuitesBundle.getSuites();
suites = ArrayUtil.remove(suites, suite);
chooseSuitesBundle(suites.length > 0 ? new CoverageSuitesBundle(suites) : null);
}
}
@Override
public CoverageSuite @NotNull [] getSuites() {
return myCoverageSuites.toArray(new CoverageSuite[0]);
}
@Override
public void chooseSuitesBundle(final CoverageSuitesBundle suite) {
if (myCurrentSuitesBundle == suite && suite == null) {
return;
}
if (myWatchRequests != null) {
LocalFileSystem.getInstance().removeWatchedRoots(myWatchRequests);
VirtualFileManager.getInstance().removeVirtualFileListener(myContentListener);
myWatchRequests = null;
myCurrentSuiteRoots = null;
}
updateCoverageData(suite);
}
private void updateCoverageData(CoverageSuitesBundle suite) {
LOG.assertTrue(!myProject.isDefault());
fireBeforeSuiteChosen();
mySubCoverageIsActive = false;
if (myCurrentSuitesBundle != null) {
myCurrentSuitesBundle.getCoverageEngine().getCoverageAnnotator(myProject).onSuiteChosen(suite);
}
myCurrentSuitesBundle = suite;
disposeAnnotators();
if (suite == null) {
triggerPresentationUpdate();
return;
}
for (CoverageSuite coverageSuite : myCurrentSuitesBundle.getSuites()) {
final boolean suiteFileExists = coverageSuite.getCoverageDataFileProvider().ensureFileExists();
if (!suiteFileExists) {
chooseSuitesBundle(null);
return;
}
}
renewCoverageData(suite);
fireAfterSuiteChosen();
}
@Override
public void coverageGathered(@NotNull final CoverageSuite suite) {
ApplicationManager.getApplication().invokeLater(() -> {
if (myProject.isDisposed()) return;
if (myCurrentSuitesBundle != null) {
final String message = CoverageBundle.message("display.coverage.prompt", suite.getPresentableName());
final CoverageOptionsProvider coverageOptionsProvider = CoverageOptionsProvider.getInstance(myProject);
final DialogWrapper.DoNotAskOption doNotAskOption = new DialogWrapper.DoNotAskOption() {
@Override
public boolean isToBeShown() {
return coverageOptionsProvider.getOptionToReplace() == 3;
}
@Override
public void setToBeShown(boolean value, int exitCode) {
coverageOptionsProvider.setOptionsToReplace(value ? 3 : exitCode);
}
@Override
public boolean canBeHidden() {
return true;
}
@Override
public boolean shouldSaveOptionsOnCancel() {
return true;
}
@NotNull
@Override
public String getDoNotShowMessage() {
return UIBundle.message("dialog.options.do.not.show");
}
};
final String[] options = myCurrentSuitesBundle.getCoverageEngine() == suite.getCoverageEngine() ?
new String[] {
CoverageBundle.message("coverage.replace.active.suites"),
CoverageBundle.message("coverage.add.to.active.suites"),
CoverageBundle.message("coverage.do.not.apply.collected.coverage")} :
new String[] {
CoverageBundle.message("coverage.replace.active.suites"),
CoverageBundle.message("coverage.do.not.apply.collected.coverage")};
final int answer = doNotAskOption.isToBeShown() ? Messages.showDialog(message, CoverageBundle.message("code.coverage"),
options, 1, Messages.getQuestionIcon(),
doNotAskOption) : coverageOptionsProvider.getOptionToReplace();
if (answer == DialogWrapper.OK_EXIT_CODE) {
chooseSuitesBundle(new CoverageSuitesBundle(suite));
}
else if (answer == 1) {
chooseSuitesBundle(new CoverageSuitesBundle(ArrayUtil.append(myCurrentSuitesBundle.getSuites(), suite)));
}
}
else {
chooseSuitesBundle(new CoverageSuitesBundle(suite));
}
});
}
@Override
public void triggerPresentationUpdate() {
renewInformationInEditors();
UIUtil.invokeLaterIfNeeded(() -> {
if (myProject.isDisposed()) return;
ProjectView.getInstance(myProject).refresh();
CoverageViewManager.getInstance(myProject).setReady(true);
});
}
@Override
public void attachToProcess(@NotNull final ProcessHandler handler,
@NotNull final RunConfigurationBase configuration,
final RunnerSettings runnerSettings) {
handler.addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(@NotNull final ProcessEvent event) {
processGatheredCoverage(configuration, runnerSettings);
}
});
}
@Override
public void processGatheredCoverage(@NotNull RunConfigurationBase configuration, RunnerSettings runnerSettings) {
if (runnerSettings instanceof CoverageRunnerData) {
processGatheredCoverage(configuration);
}
}
/**
* Called from EDT, on external coverage suite choosing
*/
public void addRootsToWatch(List<? extends CoverageSuite> suites) {
myCurrentSuiteRoots = ContainerUtil.map(suites, suite -> suite.getCoverageDataFileName());
LocalFileSystem fileSystem = LocalFileSystem.getInstance();
myCurrentSuiteRoots.forEach(path -> fileSystem.refreshAndFindFileByPath(path));
myWatchRequests = fileSystem.addRootsToWatch(myCurrentSuiteRoots, true);
VirtualFileManager.getInstance().addVirtualFileListener(myContentListener);
}
@Override
public void dispose() { }
public static void processGatheredCoverage(RunConfigurationBase configuration) {
final Project project = configuration.getProject();
if (project.isDisposed()) return;
final CoverageDataManager coverageDataManager = CoverageDataManager.getInstance(project);
final CoverageEnabledConfiguration coverageEnabledConfiguration = CoverageEnabledConfiguration.getOrCreate(configuration);
final CoverageSuite coverageSuite = coverageEnabledConfiguration.getCurrentCoverageSuite();
if (coverageSuite != null) {
((BaseCoverageSuite)coverageSuite).setConfiguration(configuration);
coverageDataManager.coverageGathered(coverageSuite);
}
}
protected void renewCoverageData(@NotNull final CoverageSuitesBundle suite) {
if (myCurrentSuitesBundle != null) {
myCurrentSuitesBundle.getCoverageEngine().getCoverageAnnotator(myProject).renewCoverageData(suite, this);
}
}
private void renewInformationInEditors() {
final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
final VirtualFile[] openFiles = fileEditorManager.getOpenFiles();
for (VirtualFile openFile : openFiles) {
final FileEditor[] allEditors = fileEditorManager.getAllEditors(openFile);
applyInformationToEditor(allEditors, openFile);
}
}
private void applyInformationToEditor(FileEditor[] editors, final VirtualFile file) {
final PsiFile psiFile = doInReadActionIfProjectOpen(() -> PsiManager.getInstance(myProject).findFile(file));
if (psiFile != null && myCurrentSuitesBundle != null && psiFile.isPhysical()) {
final CoverageEngine engine = myCurrentSuitesBundle.getCoverageEngine();
if (!engine.coverageEditorHighlightingApplicableTo(psiFile)) {
return;
}
for (FileEditor editor : editors) {
if (editor instanceof TextEditor) {
final Editor textEditor = ((TextEditor)editor).getEditor();
SrcFileAnnotator annotator;
synchronized (ANNOTATORS_LOCK) {
annotator = myAnnotators.remove(textEditor);
}
if (annotator != null) {
Disposer.dispose(annotator);
}
break;
}
}
for (FileEditor editor : editors) {
if (editor instanceof TextEditor) {
final Editor textEditor = ((TextEditor)editor).getEditor();
SrcFileAnnotator annotator = getAnnotator(textEditor);
if (annotator == null) {
annotator = new SrcFileAnnotator(psiFile, textEditor);
synchronized (ANNOTATORS_LOCK) {
myAnnotators.put(textEditor, annotator);
}
}
if (myCurrentSuitesBundle != null && engine.acceptedByFilters(psiFile, myCurrentSuitesBundle)) {
annotator.showCoverageInformation(myCurrentSuitesBundle);
}
}
}
}
}
@Override
public <T> T doInReadActionIfProjectOpen(Computable<T> computation) {
synchronized(myLock) {
if (myIsProjectClosing) return null;
}
return ApplicationManager.getApplication().runReadAction(computation);
}
@Override
public void selectSubCoverage(@NotNull final CoverageSuitesBundle suite, final List<String> testNames) {
suite.restoreCoverageData();
final ProjectData data = suite.getCoverageData();
if (data == null) return;
mySubCoverageIsActive = true;
final Map<String, Set<Integer>> executionTrace = new HashMap<>();
for (CoverageSuite coverageSuite : suite.getSuites()) {
suite.getCoverageEngine().collectTestLines(testNames, coverageSuite, executionTrace);
}
final ProjectData projectData = new ProjectData();
for (String className : executionTrace.keySet()) {
ClassData loadedClassData = projectData.getClassData(className);
if (loadedClassData == null) {
loadedClassData = projectData.getOrCreateClassData(className);
}
final Set<Integer> lineNumbers = executionTrace.get(className);
final ClassData oldData = data.getClassData(className);
LOG.assertTrue(oldData != null, "missed className: \"" + className + "\"");
final Object[] oldLines = oldData.getLines();
LOG.assertTrue(oldLines != null);
int maxNumber = oldLines.length;
for (Integer lineNumber : lineNumbers) {
if (lineNumber >= maxNumber) {
maxNumber = lineNumber + 1;
}
}
final LineData[] lines = new LineData[maxNumber];
for (Integer line : lineNumbers) {
final int lineIdx = line.intValue() - 1;
String methodSig = null;
if (lineIdx < oldData.getLines().length) {
final LineData oldLineData = oldData.getLineData(lineIdx);
if (oldLineData != null) {
methodSig = oldLineData.getMethodSignature();
}
}
final LineData lineData = new LineData(lineIdx, methodSig);
if (methodSig != null) {
loadedClassData.registerMethodSignature(lineData);
}
lineData.setStatus(LineCoverage.FULL);
lines[lineIdx] = lineData;
}
loadedClassData.setLines(lines);
}
suite.setCoverageData(projectData);
renewCoverageData(suite);
}
@Override
public void restoreMergedCoverage(@NotNull final CoverageSuitesBundle suite) {
mySubCoverageIsActive = false;
suite.restoreCoverageData();
renewCoverageData(suite);
}
@Override
public void addSuiteListener(final CoverageSuiteListener listener, Disposable parentDisposable) {
myListeners.add(listener);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
myListeners.remove(listener);
}
});
}
public void fireBeforeSuiteChosen() {
for (CoverageSuiteListener listener : myListeners) {
listener.beforeSuiteChosen();
}
}
public void fireAfterSuiteChosen() {
for (CoverageSuiteListener listener : myListeners) {
listener.afterSuiteChosen();
}
}
@Override
public boolean isSubCoverageActive() {
return mySubCoverageIsActive;
}
@Nullable
public SrcFileAnnotator getAnnotator(Editor editor) {
synchronized (ANNOTATORS_LOCK) {
return myAnnotators.get(editor);
}
}
public void disposeAnnotators() {
synchronized (ANNOTATORS_LOCK) {
for (SrcFileAnnotator annotator : myAnnotators.values()) {
if (annotator != null) {
Disposer.dispose(annotator);
}
}
myAnnotators.clear();
}
}
@NotNull
private static CoverageSuite createCoverageSuite(final CoverageEnabledConfiguration config,
final String name,
final CoverageRunner coverageRunner,
final DefaultCoverageFileProvider fileProvider) {
CoverageSuite suite = null;
for (CoverageEngine engine : CoverageEngine.EP_NAME.getExtensions()) {
if (coverageRunner.acceptsCoverageEngine(engine) && engine.isApplicableTo(config.getConfiguration())) {
suite = engine.createCoverageSuite(coverageRunner, name, fileProvider, config);
if (suite != null) {
break;
}
}
}
LOG.assertTrue(suite != null, "Cannot create coverage suite for runner: " + coverageRunner.getPresentableName());
return suite;
}
@NotNull
private CoverageSuite createCoverageSuite(final CoverageRunner coverageRunner,
final String name,
final CoverageFileProvider fileProvider,
final String[] filters,
final long lastCoverageTimeStamp,
final String suiteToMergeWith,
final boolean collectLineInfo,
final boolean tracingEnabled) {
CoverageSuite suite = null;
for (CoverageEngine engine : CoverageEngine.EP_NAME.getExtensions()) {
if (coverageRunner.acceptsCoverageEngine(engine)) {
suite = engine.createCoverageSuite(coverageRunner, name, fileProvider, filters, lastCoverageTimeStamp,
suiteToMergeWith, collectLineInfo, tracingEnabled, false, myProject);
if (suite != null) {
break;
}
}
}
LOG.assertTrue(suite != null, "Cannot create coverage suite for runner: " + coverageRunner.getPresentableName());
return suite;
}
private class CoverageEditorFactoryListener implements EditorFactoryListener {
private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, CoverageDataManagerImpl.this);
private final Map<Editor, Runnable> myCurrentEditors = new HashMap<>();
@Override
public void editorCreated(@NotNull EditorFactoryEvent event) {
synchronized (myLock) {
if (myIsProjectClosing) return;
}
final Editor editor = event.getEditor();
if (editor.getProject() != myProject) return;
final PsiFile psiFile = ReadAction.compute(() -> {
if (myProject.isDisposed()) return null;
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
final Document document = editor.getDocument();
return documentManager.getPsiFile(document);
});
if (psiFile != null && myCurrentSuitesBundle != null && psiFile.isPhysical()) {
final CoverageEngine engine = myCurrentSuitesBundle.getCoverageEngine();
if (!engine.coverageEditorHighlightingApplicableTo(psiFile)) {
return;
}
SrcFileAnnotator annotator = getAnnotator(editor);
if (annotator == null) {
annotator = new SrcFileAnnotator(psiFile, editor);
}
final SrcFileAnnotator finalAnnotator = annotator;
synchronized (ANNOTATORS_LOCK) {
myAnnotators.put(editor, finalAnnotator);
}
final Runnable request = () -> {
if (myProject.isDisposed()) return;
if (myCurrentSuitesBundle != null) {
if (engine.acceptedByFilters(psiFile, myCurrentSuitesBundle)) {
finalAnnotator.showCoverageInformation(myCurrentSuitesBundle);
}
}
};
myCurrentEditors.put(editor, request);
myAlarm.addRequest(request, 100);
}
}
@Override
public void editorReleased(@NotNull EditorFactoryEvent event) {
final Editor editor = event.getEditor();
if (editor.getProject() != myProject) return;
try {
final SrcFileAnnotator fileAnnotator;
synchronized (ANNOTATORS_LOCK) {
fileAnnotator = myAnnotators.remove(editor);
}
if (fileAnnotator != null) {
Disposer.dispose(fileAnnotator);
}
}
finally {
final Runnable request = myCurrentEditors.remove(editor);
if (request != null) {
myAlarm.cancelRequest(request);
}
}
}
}
}
|
package org.batfish.grammar.flatjuniper;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.batfish.grammar.flatjuniper.FlatJuniperCombinedParser;
import org.batfish.grammar.flatjuniper.FlatJuniperParser.*;
import org.batfish.common.BatfishException;
import org.batfish.main.Warnings;
import org.batfish.representation.AsPath;
import org.batfish.representation.AsSet;
import org.batfish.representation.ExtendedCommunity;
import org.batfish.representation.Ip;
import org.batfish.representation.IpProtocol;
import org.batfish.representation.IsoAddress;
import org.batfish.representation.NamedPort;
import org.batfish.representation.Prefix;
import org.batfish.representation.RoutingProtocol;
import org.batfish.representation.juniper.AggregateRoute;
import org.batfish.representation.juniper.BgpGroup;
import org.batfish.representation.juniper.CommunityList;
import org.batfish.representation.juniper.CommunityListLine;
import org.batfish.representation.juniper.Family;
import org.batfish.representation.juniper.FirewallFilter;
import org.batfish.representation.juniper.FwFrom;
import org.batfish.representation.juniper.FwFromDestinationAddress;
import org.batfish.representation.juniper.FwFromDestinationPort;
import org.batfish.representation.juniper.FwFromProtocol;
import org.batfish.representation.juniper.FwFromSourceAddress;
import org.batfish.representation.juniper.FwFromSourcePort;
import org.batfish.representation.juniper.FwTerm;
import org.batfish.representation.juniper.FwThenAccept;
import org.batfish.representation.juniper.FwThenDiscard;
import org.batfish.representation.juniper.FwThenNextTerm;
import org.batfish.representation.juniper.FwThenNop;
import org.batfish.representation.juniper.GeneratedRoute;
import org.batfish.representation.juniper.Interface;
import org.batfish.representation.juniper.IpBgpGroup;
import org.batfish.representation.juniper.IsisInterfaceLevelSettings;
import org.batfish.representation.juniper.IsisLevelSettings;
import org.batfish.representation.juniper.IsisSettings;
import org.batfish.representation.juniper.JuniperVendorConfiguration;
import org.batfish.representation.juniper.NamedBgpGroup;
import org.batfish.representation.juniper.OspfArea;
import org.batfish.representation.juniper.PolicyStatement;
import org.batfish.representation.juniper.PrefixList;
import org.batfish.representation.juniper.PsFrom;
import org.batfish.representation.juniper.PsFromAsPath;
import org.batfish.representation.juniper.PsFromColor;
import org.batfish.representation.juniper.PsFromCommunity;
import org.batfish.representation.juniper.PsFromInterface;
import org.batfish.representation.juniper.PsFromPrefixList;
import org.batfish.representation.juniper.PsFromProtocol;
import org.batfish.representation.juniper.PsFromRouteFilter;
import org.batfish.representation.juniper.PsTerm;
import org.batfish.representation.juniper.PsThen;
import org.batfish.representation.juniper.PsThenAccept;
import org.batfish.representation.juniper.PsThenCommunityAdd;
import org.batfish.representation.juniper.PsThenCommunityDelete;
import org.batfish.representation.juniper.PsThenCommunitySet;
import org.batfish.representation.juniper.PsThenLocalPreference;
import org.batfish.representation.juniper.PsThenMetric;
import org.batfish.representation.juniper.PsThenNextHopIp;
import org.batfish.representation.juniper.PsThenReject;
import org.batfish.representation.juniper.RouteFilter;
import org.batfish.representation.juniper.RouteFilterLine;
import org.batfish.representation.juniper.RouteFilterLineExact;
import org.batfish.representation.juniper.RouteFilterLineLengthRange;
import org.batfish.representation.juniper.RouteFilterLineLonger;
import org.batfish.representation.juniper.RouteFilterLineOrLonger;
import org.batfish.representation.juniper.RouteFilterLineThrough;
import org.batfish.representation.juniper.RouteFilterLineUpTo;
import org.batfish.representation.juniper.RoutingInformationBase;
import org.batfish.representation.juniper.RoutingInstance;
import org.batfish.representation.juniper.StaticRoute;
import org.batfish.representation.juniper.BgpGroup.BgpGroupType;
import org.batfish.util.SubRange;
import org.batfish.util.Util;
public class ConfigurationBuilder extends FlatJuniperParserBaseListener {
private static final AggregateRoute DUMMY_AGGREGATE_ROUTE = new AggregateRoute(
Prefix.ZERO);
private static final BgpGroup DUMMY_BGP_GROUP = new BgpGroup();
private static final StaticRoute DUMMY_STATIC_ROUTE = new StaticRoute(
Prefix.ZERO);
private static final String F_BGP_LOCAL_AS_LOOPS = "protocols - bgp - group? - local-as - loops";
private static final String F_BGP_LOCAL_AS_PRIVATE = "protocols - bgp - group? - local-as - private";
private static final String F_COMPLEX_POLICY = "boolean combination of policy-statements";
private static final String F_FIREWALL_TERM_THEN_ROUTING_INSTANCE = "firewall - filter - term - then - routing-instance";
private static final String F_IPV6 = "ipv6 - other";
private static final String F_POLICY_TERM_THEN_NEXT_HOP = "policy-statement - term - then - next-hop";
public static NamedPort getNamedPort(PortContext ctx) {
if (ctx.AFS() != null) {
return NamedPort.AFS;
}
else if (ctx.BGP() != null) {
return NamedPort.BGP;
}
else if (ctx.BIFF() != null) {
return NamedPort.BIFFudp_OR_EXECtcp;
}
else if (ctx.BOOTPC() != null) {
return NamedPort.BOOTPC;
}
else if (ctx.BOOTPS() != null) {
return NamedPort.BOOTPS_OR_DHCP;
}
else if (ctx.CMD() != null) {
return NamedPort.CMDtcp_OR_SYSLOGudp;
}
else if (ctx.CVSPSERVER() != null) {
return NamedPort.CVSPSERVER;
}
else if (ctx.DHCP() != null) {
return NamedPort.BOOTPS_OR_DHCP;
}
else if (ctx.DOMAIN() != null) {
return NamedPort.DOMAIN;
}
else if (ctx.EKLOGIN() != null) {
return NamedPort.EKLOGIN;
}
else if (ctx.EKSHELL() != null) {
return NamedPort.EKSHELL;
}
else if (ctx.EXEC() != null) {
return NamedPort.BIFFudp_OR_EXECtcp;
}
else if (ctx.FINGER() != null) {
return NamedPort.FINGER;
}
else if (ctx.FTP() != null) {
return NamedPort.FTP;
}
else if (ctx.FTP_DATA() != null) {
return NamedPort.FTP_DATA;
}
else if (ctx.HTTP() != null) {
return NamedPort.HTTP;
}
else if (ctx.HTTPS() != null) {
return NamedPort.HTTPS;
}
else if (ctx.IDENT() != null) {
return NamedPort.IDENT;
}
else if (ctx.IMAP() != null) {
return NamedPort.IMAP;
}
else if (ctx.KERBEROS_SEC() != null) {
return NamedPort.KERBEROS_SEC;
}
else if (ctx.KLOGIN() != null) {
return NamedPort.KLOGIN;
}
else if (ctx.KPASSWD() != null) {
return NamedPort.KPASSWD;
}
else if (ctx.KRB_PROP() != null) {
return NamedPort.KRB_PROP;
}
else if (ctx.KRBUPDATE() != null) {
return NamedPort.KRBUPDATE;
}
else if (ctx.KSHELL() != null) {
return NamedPort.KSHELL;
}
else if (ctx.LDAP() != null) {
return NamedPort.LDAP;
}
else if (ctx.LDP() != null) {
return NamedPort.LDP;
}
else if (ctx.LOGIN() != null) {
return NamedPort.LOGINtcp_OR_WHOudp;
}
else if (ctx.MOBILEIP_AGENT() != null) {
return NamedPort.MOBILE_IP_AGENT;
}
else if (ctx.MOBILIP_MN() != null) {
return NamedPort.MOBILE_IP_MN;
}
else if (ctx.MSDP() != null) {
return NamedPort.MSDP;
}
else if (ctx.NETBIOS_DGM() != null) {
return NamedPort.NETBIOS_DGM;
}
else if (ctx.NETBIOS_NS() != null) {
return NamedPort.NETBIOS_NS;
}
else if (ctx.NETBIOS_SSN() != null) {
return NamedPort.NETBIOS_SSN;
}
else if (ctx.NFSD() != null) {
return NamedPort.NFSD;
}
else if (ctx.NNTP() != null) {
return NamedPort.NNTP;
}
else if (ctx.NTALK() != null) {
return NamedPort.NTALK;
}
else if (ctx.NTP() != null) {
return NamedPort.NTP;
}
else if (ctx.POP3() != null) {
return NamedPort.POP3;
}
else if (ctx.PPTP() != null) {
return NamedPort.PPTP;
}
else if (ctx.PRINTER() != null) {
return NamedPort.LDP;
}
else if (ctx.RADACCT() != null) {
return NamedPort.RADIUS_JUNIPER;
}
else if (ctx.RADIUS() != null) {
return NamedPort.RADIUS_JUNIPER;
}
else if (ctx.RIP() != null) {
return NamedPort.RIP;
}
else if (ctx.RKINIT() != null) {
return NamedPort.RKINIT;
}
else if (ctx.SMTP() != null) {
return NamedPort.SMTP;
}
else if (ctx.SNMP() != null) {
return NamedPort.SNMP;
}
else if (ctx.SNMPTRAP() != null) {
return NamedPort.SNMPTRAP;
}
else if (ctx.SNPP() != null) {
return NamedPort.SNPP;
}
else if (ctx.SOCKS() != null) {
return NamedPort.SOCKS;
}
else if (ctx.SSH() != null) {
return NamedPort.SSH;
}
else if (ctx.SUNRPC() != null) {
return NamedPort.SUNRPC;
}
else if (ctx.SYSLOG() != null) {
return NamedPort.CMDtcp_OR_SYSLOGudp;
}
else if (ctx.TACACS() != null) {
return NamedPort.TACACS;
}
else if (ctx.TACACS_DS() != null) {
return NamedPort.TACACS_DS;
}
else if (ctx.TALK() != null) {
return NamedPort.TALK;
}
else if (ctx.TELNET() != null) {
return NamedPort.TELNET;
}
else if (ctx.TFTP() != null) {
return NamedPort.TFTP;
}
else if (ctx.TIMED() != null) {
return NamedPort.TIMED;
}
else if (ctx.WHO() != null) {
return NamedPort.LOGINtcp_OR_WHOudp;
}
else if (ctx.XDMCP() != null) {
return NamedPort.XDMCP;
}
else {
throw new BatfishException("missing port-number mapping for port: \""
+ ctx.getText() + "\"");
}
}
public static int getPortNumber(PortContext ctx) {
if (ctx.DEC() != null) {
int port = toInt(ctx.DEC());
return port;
}
else {
NamedPort namedPort = getNamedPort(ctx);
return namedPort.number();
}
}
private static long toCommunityLong(Sc_literalContext sc_literal) {
String text = sc_literal.COMMUNITY_LITERAL().getText();
return Util.communityStringToLong(text);
}
private static long toCommunityLong(Sc_namedContext ctx) {
if (ctx.NO_ADVERTISE() != null) {
return 0xFFFFFF02l;
}
if (ctx.NO_EXPORT() != null) {
return 0xFFFFFF01l;
}
else {
throw new BatfishException(
"missing named-community-to-long mapping for: \""
+ ctx.getText() + "\"");
}
}
private static long toCommunityLong(Standard_communityContext ctx) {
if (ctx.sc_literal() != null) {
return toCommunityLong(ctx.sc_literal());
}
else if (ctx.sc_named() != null) {
return toCommunityLong(ctx.sc_named());
}
else {
throw new BatfishException("Cannot convert to community long");
}
}
private static Integer toInt(TerminalNode node) {
return toInt(node.getSymbol());
}
private static int toInt(Token token) {
return Integer.parseInt(token.getText());
}
private static IpProtocol toIpProtocol(Ip_protocolContext ctx) {
if (ctx.DEC() != null) {
int protocolNum = toInt(ctx.DEC());
return IpProtocol.fromNumber(protocolNum);
}
else if (ctx.AH() != null) {
return IpProtocol.AHP;
}
else if (ctx.DSTOPTS() != null) {
return IpProtocol.IPv6_Opts;
}
else if (ctx.EGP() != null) {
return IpProtocol.EGP;
}
else if (ctx.ESP() != null) {
return IpProtocol.ESP;
}
else if (ctx.FRAGMENT() != null) {
return IpProtocol.IPv6_Frag;
}
else if (ctx.GRE() != null) {
return IpProtocol.GRE;
}
else if (ctx.HOP_BY_HOP() != null) {
return IpProtocol.HOPOPT;
}
else if (ctx.ICMP() != null) {
return IpProtocol.ICMP;
}
else if (ctx.ICMP6() != null) {
return IpProtocol.IPv6_ICMP;
}
else if (ctx.ICMPV6() != null) {
return IpProtocol.IPv6_ICMP;
}
else if (ctx.IGMP() != null) {
return IpProtocol.IGMP;
}
else if (ctx.IPIP() != null) {
return IpProtocol.IPINIP;
}
else if (ctx.IPV6() != null) {
return IpProtocol.IPv6;
}
else if (ctx.OSPF() != null) {
return IpProtocol.OSPF;
}
else if (ctx.PIM() != null) {
return IpProtocol.PIM;
}
else if (ctx.RSVP() != null) {
return IpProtocol.RSVP;
}
else if (ctx.SCTP() != null) {
return IpProtocol.SCTP;
}
else if (ctx.TCP() != null) {
return IpProtocol.TCP;
}
else if (ctx.UDP() != null) {
return IpProtocol.UDP;
}
else if (ctx.VRRP() != null) {
return IpProtocol.VRRP;
}
else {
throw new BatfishException(
"missing protocol-enum mapping for protocol: \"" + ctx.getText()
+ "\"");
}
}
private static RoutingProtocol toRoutingProtocol(Routing_protocolContext ctx) {
if (ctx.AGGREGATE() != null) {
return RoutingProtocol.AGGREGATE;
}
else if (ctx.BGP() != null) {
return RoutingProtocol.BGP;
}
else if (ctx.DIRECT() != null) {
return RoutingProtocol.CONNECTED;
}
else if (ctx.ISIS() != null) {
return RoutingProtocol.ISIS;
}
else if (ctx.LDP() != null) {
return RoutingProtocol.LDP;
}
else if (ctx.LOCAL() != null) {
return RoutingProtocol.LOCAL;
}
else if (ctx.OSPF() != null) {
return RoutingProtocol.OSPF;
}
else if (ctx.RSVP() != null) {
return RoutingProtocol.RSVP;
}
else if (ctx.STATIC() != null) {
return RoutingProtocol.STATIC;
}
else {
throw new BatfishException("missing routing protocol-enum mapping");
}
}
private JuniperVendorConfiguration _configuration;
private AggregateRoute _currentAggregateRoute;
private OspfArea _currentArea;
private BgpGroup _currentBgpGroup;
private CommunityList _currentCommunityList;
private FirewallFilter _currentFilter;
private Family _currentFirewallFamily;
private FwTerm _currentFwTerm;
private GeneratedRoute _currentGeneratedRoute;
private Interface _currentInterface;
private Prefix _currentInterfacePrefix;
private Interface _currentIsisInterface;
private IsisInterfaceLevelSettings _currentIsisInterfaceLevelSettings;
private IsisLevelSettings _currentIsisLevelSettings;
private Interface _currentMasterInterface;
private Interface _currentOspfInterface;
private PolicyStatement _currentPolicyStatement;
private PrefixList _currentPrefixList;
private PsTerm _currentPsTerm;
private Set<PsThen> _currentPsThens;
private RoutingInformationBase _currentRib;
private RouteFilter _currentRouteFilter;
private RouteFilterLine _currentRouteFilterLine;
private Prefix _currentRouteFilterPrefix;
private RoutingInstance _currentRoutingInstance;
private StaticRoute _currentStaticRoute;
private FlatJuniperCombinedParser _parser;
private final Map<PsTerm, RouteFilter> _termRouteFilters;
private final String _text;
private final Set<String> _unimplementedFeatures;
private final Warnings _w;
public ConfigurationBuilder(FlatJuniperCombinedParser parser, String text,
Warnings warnings, Set<String> unimplementedFeatures) {
_parser = parser;
_text = text;
_configuration = new JuniperVendorConfiguration(unimplementedFeatures);
_currentRoutingInstance = _configuration.getDefaultRoutingInstance();
_termRouteFilters = new HashMap<PsTerm, RouteFilter>();
_unimplementedFeatures = unimplementedFeatures;
_w = warnings;
}
@Override
public void enterAt_interface(At_interfaceContext ctx) {
Map<String, Interface> interfaces = _currentRoutingInstance
.getInterfaces();
String unitFullName = null;
if (ctx.ip != null) {
Ip ip = new Ip(ctx.ip.getText());
for (Interface iface : interfaces.values()) {
for (Interface unit : iface.getUnits().values()) {
if (unit.getAllPrefixIps().contains(ip)) {
_currentOspfInterface = unit;
unitFullName = unit.getName();
}
}
}
if (_currentOspfInterface == null) {
throw new BatfishException(
"Could not find interface with ip address: " + ip.toString());
}
}
else {
String name = ctx.id.name.getText();
String unit = null;
if (ctx.id.unit != null) {
unit = ctx.id.unit.getText();
}
unitFullName = name + "." + unit;
_currentOspfInterface = interfaces.get(name);
if (_currentOspfInterface == null) {
_currentOspfInterface = new Interface(name);
interfaces.put(name, _currentOspfInterface);
}
if (unit != null) {
Map<String, Interface> units = _currentOspfInterface.getUnits();
_currentOspfInterface = units.get(unitFullName);
if (_currentOspfInterface == null) {
_currentOspfInterface = new Interface(unitFullName);
units.put(unitFullName, _currentOspfInterface);
}
}
}
Ip currentArea = _currentArea.getAreaIp();
if (ctx.at_interface_tail() != null
&& ctx.at_interface_tail().ait_passive() != null) {
_currentOspfInterface.getOspfPassiveAreas().add(currentArea);
}
else {
Ip interfaceActiveArea = _currentOspfInterface.getOspfActiveArea();
if (interfaceActiveArea != null
&& !currentArea.equals(interfaceActiveArea)) {
throw new BatfishException("Interface: \""
+ unitFullName.toString()
+ "\" assigned to multiple active areas");
}
_currentOspfInterface.setOspfActiveArea(currentArea);
}
}
@Override
public void enterBt_group(Bt_groupContext ctx) {
String name = ctx.name.getText();
Map<String, NamedBgpGroup> namedBgpGroups = _currentRoutingInstance
.getNamedBgpGroups();
NamedBgpGroup namedBgpGroup = namedBgpGroups.get(name);
if (namedBgpGroup == null) {
namedBgpGroup = new NamedBgpGroup(name);
namedBgpGroup.setParent(_currentBgpGroup);
namedBgpGroups.put(name, namedBgpGroup);
}
_currentBgpGroup = namedBgpGroup;
}
@Override
public void enterBt_neighbor(Bt_neighborContext ctx) {
if (ctx.IP_ADDRESS() != null) {
Ip remoteAddress = new Ip(ctx.IP_ADDRESS().getText());
Map<Ip, IpBgpGroup> ipBgpGroups = _currentRoutingInstance
.getIpBgpGroups();
IpBgpGroup ipBgpGroup = ipBgpGroups.get(remoteAddress);
if (ipBgpGroup == null) {
ipBgpGroup = new IpBgpGroup(remoteAddress);
ipBgpGroup.setParent(_currentBgpGroup);
ipBgpGroups.put(remoteAddress, ipBgpGroup);
}
_currentBgpGroup = ipBgpGroup;
}
else if (ctx.IPV6_ADDRESS() != null) {
_currentBgpGroup = DUMMY_BGP_GROUP;
}
}
@Override
public void enterFromt_route_filter(Fromt_route_filterContext ctx) {
if (ctx.IP_PREFIX() != null) {
_currentRouteFilterPrefix = new Prefix(ctx.IP_PREFIX().getText());
_currentRouteFilter = _termRouteFilters.get(_currentPsTerm);
if (_currentRouteFilter == null) {
String rfName = _currentPolicyStatement.getName() + ":"
+ _currentPsTerm.getName();
_currentRouteFilter = new RouteFilter(rfName);
_termRouteFilters.put(_currentPsTerm, _currentRouteFilter);
_configuration.getRouteFilters().put(rfName, _currentRouteFilter);
PsFromRouteFilter from = new PsFromRouteFilter(rfName);
_currentPsTerm.getFroms().add(from);
}
}
}
@Override
public void enterFromt_route_filter_then(Fromt_route_filter_thenContext ctx) {
if (_currentRouteFilterPrefix != null) { // not ipv6
RouteFilterLine line = _currentRouteFilterLine;
_currentPsThens = line.getThens();
}
}
@Override
public void enterFwft_term(Fwft_termContext ctx) {
String name = ctx.name.getText();
Map<String, FwTerm> terms = _currentFilter.getTerms();
_currentFwTerm = terms.get(name);
if (_currentFwTerm == null) {
_currentFwTerm = new FwTerm(name);
terms.put(name, _currentFwTerm);
}
}
@Override
public void enterFwt_family(Fwt_familyContext ctx) {
if (ctx.INET() != null) {
_currentFirewallFamily = Family.INET;
}
else if (ctx.INET6() != null) {
_currentFirewallFamily = Family.INET6;
}
else if (ctx.MPLS() != null) {
_currentFirewallFamily = Family.MPLS;
}
}
@Override
public void enterFwt_filter(Fwt_filterContext ctx) {
String name = ctx.name.getText();
Map<String, FirewallFilter> filters = _configuration.getFirewallFilters();
_currentFilter = filters.get(name);
if (_currentFilter == null) {
_currentFilter = new FirewallFilter(name, _currentFirewallFamily);
filters.put(name, _currentFilter);
}
}
@Override
public void enterIfamt_address(Ifamt_addressContext ctx) {
Set<Prefix> allPrefixes = _currentInterface.getAllPrefixes();
Prefix prefix = new Prefix(ctx.IP_PREFIX().getText());
_currentInterfacePrefix = prefix;
if (_currentInterface.getPrimaryPrefix() == null) {
_currentInterface.setPrimaryPrefix(prefix);
}
if (_currentInterface.getPreferredPrefix() == null) {
_currentInterface.setPreferredPrefix(prefix);
}
allPrefixes.add(prefix);
Ip ip = prefix.getAddress();
_currentInterface.getAllPrefixIps().add(ip);
}
@Override
public void enterIntt_named(Intt_namedContext ctx) {
if (ctx.name == null) {
_currentInterface = _currentRoutingInstance.getGlobalMasterInterface();
}
else {
String ifaceName = ctx.name.getText();
Map<String, Interface> interfaces = _currentRoutingInstance
.getInterfaces();
_currentInterface = interfaces.get(ifaceName);
if (_currentInterface == null) {
_currentInterface = new Interface(ifaceName);
interfaces.put(ifaceName, _currentInterface);
}
}
_currentMasterInterface = _currentInterface;
}
@Override
public void enterIsisit_level(Isisit_levelContext ctx) {
int level = toInt(ctx.DEC());
switch (level) {
case 1:
_currentIsisInterfaceLevelSettings = _currentIsisInterface
.getIsisSettings().getLevel1Settings();
break;
case 2:
_currentIsisInterfaceLevelSettings = _currentIsisInterface
.getIsisSettings().getLevel2Settings();
break;
default:
throw new BatfishException("invalid IS-IS level: " + level);
}
_currentIsisInterfaceLevelSettings.setEnabled(true);
}
@Override
public void enterIsist_interface(Isist_interfaceContext ctx) {
Map<String, Interface> interfaces = _currentRoutingInstance
.getInterfaces();
String unitFullName = null;
String name = ctx.id.name.getText();
String unit = null;
if (ctx.id.unit != null) {
unit = ctx.id.unit.getText();
}
unitFullName = name + "." + unit;
_currentIsisInterface = interfaces.get(name);
if (_currentIsisInterface == null) {
_currentIsisInterface = new Interface(name);
interfaces.put(name, _currentIsisInterface);
}
if (unit != null) {
Map<String, Interface> units = _currentIsisInterface.getUnits();
_currentIsisInterface = units.get(unitFullName);
if (_currentIsisInterface == null) {
_currentIsisInterface = new Interface(unitFullName);
units.put(unitFullName, _currentIsisInterface);
}
}
_currentIsisInterface.getIsisSettings().setEnabled(true);
}
@Override
public void enterIsist_level(Isist_levelContext ctx) {
IsisSettings isisSettings = _currentRoutingInstance.getIsisSettings();
int level = toInt(ctx.DEC());
switch (level) {
case 1:
_currentIsisLevelSettings = isisSettings.getLevel1Settings();
break;
case 2:
_currentIsisLevelSettings = isisSettings.getLevel2Settings();
break;
default:
throw new BatfishException("invalid level: " + level);
}
_currentIsisLevelSettings.setEnabled(true);
}
@Override
public void enterIt_unit(It_unitContext ctx) {
String unit = ctx.num.getText();
String unitFullName = _currentMasterInterface.getName() + "." + unit;
Map<String, Interface> units = _currentMasterInterface.getUnits();
_currentInterface = units.get(unitFullName);
if (_currentInterface == null) {
_currentInterface = new Interface(unitFullName);
units.put(unitFullName, _currentInterface);
}
}
@Override
public void enterOt_area(Ot_areaContext ctx) {
Ip areaIp = new Ip(ctx.area.getText());
Map<Ip, OspfArea> areas = _currentRoutingInstance.getOspfAreas();
_currentArea = areas.get(areaIp);
if (_currentArea == null) {
_currentArea = new OspfArea(areaIp);
areas.put(areaIp, _currentArea);
}
}
@Override
public void enterPot_community(Pot_communityContext ctx) {
String name = ctx.name.getText();
Map<String, CommunityList> communityLists = _configuration
.getCommunityLists();
_currentCommunityList = communityLists.get(name);
if (_currentCommunityList == null) {
_currentCommunityList = new CommunityList(name);
communityLists.put(name, _currentCommunityList);
}
}
@Override
public void enterPot_policy_statement(Pot_policy_statementContext ctx) {
String name = ctx.name.getText();
Map<String, PolicyStatement> policyStatements = _configuration
.getPolicyStatements();
_currentPolicyStatement = policyStatements.get(name);
if (_currentPolicyStatement == null) {
_currentPolicyStatement = new PolicyStatement(name);
policyStatements.put(name, _currentPolicyStatement);
}
_currentPsTerm = _currentPolicyStatement.getSingletonTerm();
_currentPsThens = _currentPsTerm.getThens();
}
@Override
public void enterPot_prefix_list(Pot_prefix_listContext ctx) {
String name = ctx.name.getText();
Map<String, PrefixList> prefixLists = _configuration.getPrefixLists();
_currentPrefixList = prefixLists.get(name);
if (_currentPrefixList == null) {
_currentPrefixList = new PrefixList(name);
prefixLists.put(name, _currentPrefixList);
}
}
@Override
public void enterPst_term(Pst_termContext ctx) {
String name = ctx.name.getText();
Map<String, PsTerm> terms = _currentPolicyStatement.getTerms();
_currentPsTerm = terms.get(name);
if (_currentPsTerm == null) {
_currentPsTerm = new PsTerm(name);
terms.put(name, _currentPsTerm);
}
_currentPsThens = _currentPsTerm.getThens();
}
@Override
public void enterRft_exact(Rft_exactContext ctx) {
if (_currentRouteFilterPrefix != null) { // not ipv6
RouteFilterLineExact fromRouteFilterExact = new RouteFilterLineExact(
_currentRouteFilterPrefix);
_currentRouteFilterLine = _currentRouteFilter
.insertLine(fromRouteFilterExact);
}
}
@Override
public void enterRft_longer(Rft_longerContext ctx) {
if (_currentRouteFilterPrefix != null) { // not ipv6
RouteFilterLineLonger fromRouteFilterOrLonger = new RouteFilterLineLonger(
_currentRouteFilterPrefix);
_currentRouteFilterLine = _currentRouteFilter
.insertLine(fromRouteFilterOrLonger);
}
}
@Override
public void enterRft_orlonger(Rft_orlongerContext ctx) {
if (_currentRouteFilterPrefix != null) { // not ipv6
RouteFilterLineOrLonger fromRouteFilterOrLonger = new RouteFilterLineOrLonger(
_currentRouteFilterPrefix);
_currentRouteFilterLine = _currentRouteFilter
.insertLine(fromRouteFilterOrLonger);
}
}
@Override
public void enterRft_prefix_length_range(Rft_prefix_length_rangeContext ctx) {
int minPrefixLength = toInt(ctx.low);
int maxPrefixLength = toInt(ctx.high);
if (_currentRouteFilterPrefix != null) { // not ipv6
RouteFilterLineLengthRange fromRouteFilterLengthRange = new RouteFilterLineLengthRange(
_currentRouteFilterPrefix, minPrefixLength, maxPrefixLength);
_currentRouteFilterLine = _currentRouteFilter
.insertLine(fromRouteFilterLengthRange);
}
}
@Override
public void enterRft_through(Rft_throughContext ctx) {
if (_currentRouteFilterPrefix != null) { // not ipv6
Prefix throughPrefix = new Prefix(ctx.IP_PREFIX().getText());
RouteFilterLineThrough fromRouteFilterThrough = new RouteFilterLineThrough(
_currentRouteFilterPrefix, throughPrefix);
_currentRouteFilterLine = _currentRouteFilter
.insertLine(fromRouteFilterThrough);
}
}
@Override
public void enterRft_upto(Rft_uptoContext ctx) {
int maxPrefixLength = toInt(ctx.high);
if (_currentRouteFilterPrefix != null) { // not ipv6
RouteFilterLineUpTo fromRouteFilterUpTo = new RouteFilterLineUpTo(
_currentRouteFilterPrefix, maxPrefixLength);
_currentRouteFilterLine = _currentRouteFilter
.insertLine(fromRouteFilterUpTo);
}
}
@Override
public void enterRibt_aggregate(Ribt_aggregateContext ctx) {
if (ctx.IP_PREFIX() != null) {
Prefix prefix = new Prefix(ctx.IP_PREFIX().getText());
Map<Prefix, AggregateRoute> aggregateRoutes = _currentRib
.getAggregateRoutes();
_currentAggregateRoute = aggregateRoutes.get(prefix);
if (_currentAggregateRoute == null) {
_currentAggregateRoute = new AggregateRoute(prefix);
aggregateRoutes.put(prefix, _currentAggregateRoute);
}
}
else {
_currentAggregateRoute = DUMMY_AGGREGATE_ROUTE;
}
}
@Override
public void enterRit_named_routing_instance(
Rit_named_routing_instanceContext ctx) {
String name;
name = ctx.name.getText();
_currentRoutingInstance = _configuration.getRoutingInstances().get(name);
if (_currentRoutingInstance == null) {
_currentRoutingInstance = new RoutingInstance(name);
_configuration.getRoutingInstances()
.put(name, _currentRoutingInstance);
}
}
@Override
public void enterRot_generate(Rot_generateContext ctx) {
if (ctx.IP_PREFIX() != null) {
Prefix prefix = new Prefix(ctx.IP_PREFIX().getText());
Map<Prefix, GeneratedRoute> generatedRoutes = _currentRib
.getGeneratedRoutes();
_currentGeneratedRoute = generatedRoutes.get(prefix);
if (_currentGeneratedRoute == null) {
_currentGeneratedRoute = new GeneratedRoute(prefix);
generatedRoutes.put(prefix, _currentGeneratedRoute);
}
}
else if (ctx.IPV6_PREFIX() != null) {
todo(ctx, F_IPV6);
}
}
@Override
public void enterRot_rib(Rot_ribContext ctx) {
String name = ctx.name.getText();
Map<String, RoutingInformationBase> ribs = _currentRoutingInstance
.getRibs();
_currentRib = ribs.get(name);
if (_currentRib == null) {
_currentRib = new RoutingInformationBase(name);
ribs.put(name, _currentRib);
}
}
@Override
public void enterRst_route(Rst_routeContext ctx) {
if (ctx.IP_PREFIX() != null) {
Prefix prefix = new Prefix(ctx.IP_PREFIX().getText());
Map<Prefix, StaticRoute> staticRoutes = _currentRib.getStaticRoutes();
_currentStaticRoute = staticRoutes.get(prefix);
if (_currentStaticRoute == null) {
_currentStaticRoute = new StaticRoute(prefix);
staticRoutes.put(prefix, _currentStaticRoute);
}
}
else if (ctx.IPV6_PREFIX() != null) {
_currentStaticRoute = DUMMY_STATIC_ROUTE;
}
}
@Override
public void enterS_firewall(S_firewallContext ctx) {
_currentFirewallFamily = Family.INET;
}
@Override
public void enterS_protocols_bgp(S_protocols_bgpContext ctx) {
_currentBgpGroup = _currentRoutingInstance.getMasterBgpGroup();
}
@Override
public void enterS_routing_options(S_routing_optionsContext ctx) {
_currentRib = _currentRoutingInstance.getRibs().get(
RoutingInformationBase.RIB_IPV4_UNICAST);
}
@Override
public void exitAgt_as_path(Agt_as_pathContext ctx) {
AsPath asPath = toAsPath(ctx.path);
_currentAggregateRoute.setAsPath(asPath);
}
@Override
public void exitAgt_preference(Agt_preferenceContext ctx) {
int preference = toInt(ctx.preference);
_currentAggregateRoute.setPreference(preference);
}
@Override
public void exitAt_interface(At_interfaceContext ctx) {
_currentOspfInterface = null;
}
@Override
public void exitBpast_as(Bpast_asContext ctx) {
int peerAs = toInt(ctx.as);
_currentBgpGroup.setPeerAs(peerAs);
}
@Override
public void exitBt_description(Bt_descriptionContext ctx) {
String description = ctx.s_description().description.getText();
_currentBgpGroup.setDescription(description);
}
@Override
public void exitBt_export(Bt_exportContext ctx) {
Policy_expressionContext expr = ctx.expr;
if (expr.variable() != null) {
String name = expr.variable().getText();
_currentBgpGroup.getExportPolicies().add(name);
}
else {
todo(ctx, F_COMPLEX_POLICY);
}
}
@Override
public void exitBt_import(Bt_importContext ctx) {
Policy_expressionContext expr = ctx.expr;
if (expr.variable() != null) {
String name = expr.variable().getText();
_currentBgpGroup.getImportPolicies().add(name);
}
else {
todo(ctx, F_COMPLEX_POLICY);
}
}
@Override
public void exitBt_local_address(Bt_local_addressContext ctx) {
if (ctx.IP_ADDRESS() != null) {
Ip localAddress = new Ip(ctx.IP_ADDRESS().getText());
_currentBgpGroup.setLocalAddress(localAddress);
}
}
@Override
public void exitBt_remove_private(Bt_remove_privateContext ctx) {
_currentBgpGroup.setRemovePrivate(true);
}
@Override
public void exitBt_type(Bt_typeContext ctx) {
if (ctx.INTERNAL() != null) {
_currentBgpGroup.setType(BgpGroupType.INTERNAL);
}
else if (ctx.EXTERNAL() != null) {
_currentBgpGroup.setType(BgpGroupType.EXTERNAL);
}
}
@Override
public void exitCt_members(Ct_membersContext ctx) {
if (ctx.community_regex() != null) {
_currentCommunityList.getLines().add(
new CommunityListLine(ctx.community_regex().getText()));
}
else if (ctx.extended_community_regex() != null) {
_currentCommunityList.getLines().add(
new CommunityListLine(ctx.extended_community_regex().getText()));
}
else if (ctx.standard_community() != null) {
long communityVal = toCommunityLong(ctx.standard_community());
String communityStr = org.batfish.util.Util
.longToCommunity(communityVal);
_currentCommunityList.getLines().add(
new CommunityListLine(communityStr));
}
else if (ctx.extended_community() != null) {
long communityVal = toCommunityLong(ctx.extended_community());
String communityStr = org.batfish.util.Util
.longToCommunity(communityVal);
_currentCommunityList.getLines().add(
new CommunityListLine(communityStr));
}
}
@Override
public void exitFromt_as_path(Fromt_as_pathContext ctx) {
String name = ctx.name.getText();
PsFromAsPath fromAsPath = new PsFromAsPath(name);
_currentPsTerm.getFroms().add(fromAsPath);
}
@Override
public void exitFromt_color(Fromt_colorContext ctx) {
int color = toInt(ctx.color);
PsFromColor fromColor = new PsFromColor(color);
_currentPsTerm.getFroms().add(fromColor);
}
@Override
public void exitFromt_community(Fromt_communityContext ctx) {
String name = ctx.name.getText();
PsFromCommunity fromCommunity = new PsFromCommunity(name);
_currentPsTerm.getFroms().add(fromCommunity);
}
@Override
public void exitFromt_interface(Fromt_interfaceContext ctx) {
String name = ctx.id.name.getText();
String unit = null;
if (ctx.id.unit != null) {
unit = ctx.id.unit.getText();
}
String unitFullName = name + "." + unit;
Map<String, Interface> interfaces = _currentRoutingInstance
.getInterfaces();
Interface iface = interfaces.get(name);
if (iface == null) {
iface = new Interface(name);
interfaces.put(name, iface);
}
PsFrom from;
if (unit != null) {
Map<String, Interface> units = iface.getUnits();
iface = units.get(unitFullName);
if (iface == null) {
iface = new Interface(unitFullName);
units.put(unitFullName, iface);
}
from = new PsFromInterface(unitFullName);
}
else {
from = new PsFromInterface(name);
}
_currentPsTerm.getFroms().add(from);
}
@Override
public void exitFromt_prefix_list(Fromt_prefix_listContext ctx) {
String name = ctx.name.getText();
PsFrom from = new PsFromPrefixList(name);
_currentPsTerm.getFroms().add(from);
}
@Override
public void exitFromt_protocol(Fromt_protocolContext ctx) {
RoutingProtocol protocol = toRoutingProtocol(ctx.protocol);
PsFromProtocol fromProtocol = new PsFromProtocol(protocol);
_currentPsTerm.getFroms().add(fromProtocol);
}
@Override
public void exitFromt_route_filter(Fromt_route_filterContext ctx) {
_currentRouteFilterPrefix = null;
_currentRouteFilter = null;
_currentRouteFilterLine = null;
}
@Override
public void exitFromt_route_filter_then(Fromt_route_filter_thenContext ctx) {
_currentPsThens = _currentPsTerm.getThens();
}
@Override
public void exitFwfromt_destination_address(
Fwfromt_destination_addressContext ctx) {
if (ctx.IP_PREFIX() != null) {
Prefix prefix = new Prefix(ctx.IP_PREFIX().getText());
FwFrom from = new FwFromDestinationAddress(prefix);
_currentFwTerm.getFroms().add(from);
}
}
@Override
public void exitFwfromt_destination_port(Fwfromt_destination_portContext ctx) {
if (ctx.port() != null) {
int port = getPortNumber(ctx.port());
SubRange subrange = new SubRange(port, port);
FwFrom from = new FwFromDestinationPort(subrange);
_currentFwTerm.getFroms().add(from);
}
else if (ctx.range() != null) {
for (SubrangeContext subrangeContext : ctx.range().range_list) {
int low = toInt(subrangeContext.low);
int high = toInt(subrangeContext.high);
SubRange subrange = new SubRange(low, high);
FwFrom from = new FwFromDestinationPort(subrange);
_currentFwTerm.getFroms().add(from);
}
}
}
@Override
public void exitFwfromt_protocol(Fwfromt_protocolContext ctx) {
IpProtocol protocol = toIpProtocol(ctx.ip_protocol());
FwFrom from = new FwFromProtocol(protocol);
_currentFwTerm.getFroms().add(from);
}
@Override
public void exitFwfromt_source_address(Fwfromt_source_addressContext ctx) {
if (ctx.IP_PREFIX() != null) {
Prefix prefix = new Prefix(ctx.IP_PREFIX().getText());
FwFrom from = new FwFromSourceAddress(prefix);
_currentFwTerm.getFroms().add(from);
}
}
@Override
public void exitFwfromt_source_port(Fwfromt_source_portContext ctx) {
if (ctx.port() != null) {
int port = getPortNumber(ctx.port());
SubRange subrange = new SubRange(port, port);
FwFrom from = new FwFromSourcePort(subrange);
_currentFwTerm.getFroms().add(from);
}
else if (ctx.range() != null) {
for (SubrangeContext subrangeContext : ctx.range().range_list) {
int low = toInt(subrangeContext.low);
int high = toInt(subrangeContext.high);
SubRange subrange = new SubRange(low, high);
FwFrom from = new FwFromSourcePort(subrange);
_currentFwTerm.getFroms().add(from);
}
}
}
@Override
public void exitFwft_term(Fwft_termContext ctx) {
_currentFwTerm = null;
}
@Override
public void exitFwt_filter(Fwt_filterContext ctx) {
_currentFilter = null;
}
@Override
public void exitFwthent_accept(Fwthent_acceptContext ctx) {
_currentFwTerm.getThens().add(FwThenAccept.INSTANCE);
}
@Override
public void exitFwthent_discard(Fwthent_discardContext ctx) {
_currentFwTerm.getThens().add(FwThenDiscard.INSTANCE);
}
@Override
public void exitFwthent_next_term(Fwthent_next_termContext ctx) {
_currentFwTerm.getThens().add(FwThenNextTerm.INSTANCE);
}
@Override
public void exitFwthent_nop(Fwthent_nopContext ctx) {
_currentFwTerm.getThens().add(FwThenNop.INSTANCE);
}
@Override
public void exitFwthent_reject(Fwthent_rejectContext ctx) {
_currentFwTerm.getThens().add(FwThenDiscard.INSTANCE);
}
@Override
public void exitFwthent_routing_instance(Fwthent_routing_instanceContext ctx) {
// TODO: implement
_w.unimplemented(ConfigurationBuilder.F_FIREWALL_TERM_THEN_ROUTING_INSTANCE);
_currentFwTerm.getThens().add(FwThenDiscard.INSTANCE);
}
@Override
public void exitGt_metric(Gt_metricContext ctx) {
int metric = toInt(ctx.metric);
_currentGeneratedRoute.setMetric(metric);
}
@Override
public void exitGt_policy(Gt_policyContext ctx) {
if (_currentGeneratedRoute != null) { // not ipv6
String policy = ctx.policy.getText();
_currentGeneratedRoute.getPolicies().add(policy);
}
}
@Override
public void exitIfamat_preferred(Ifamat_preferredContext ctx) {
_currentInterface.setPreferredPrefix(_currentInterfacePrefix);
}
@Override
public void exitIfamat_primary(Ifamat_primaryContext ctx) {
_currentInterface.setPrimaryPrefix(_currentInterfacePrefix);
}
@Override
public void exitIfamt_address(Ifamt_addressContext ctx) {
_currentInterfacePrefix = null;
}
@Override
public void exitIfamt_filter(Ifamt_filterContext ctx) {
FilterContext filter = ctx.filter();
if (filter.filter_tail() != null) {
if (filter.filter_tail().ft_direction() != null) {
Ft_directionContext ftd = filter.filter_tail().ft_direction();
String name = ftd.name.getText();
DirectionContext direction = ftd.direction();
if (direction.INPUT() != null) {
_currentInterface.setIncomingFilter(name);
}
else if (direction.OUTPUT() != null) {
_currentInterface.setOutgoingFilter(name);
}
}
}
}
@Override
public void exitIntt_named(Intt_namedContext ctx) {
_currentInterface = null;
_currentMasterInterface = null;
}
@Override
public void exitIsisilt_enable(Isisilt_enableContext ctx) {
_currentIsisInterfaceLevelSettings.setEnabled(true);
}
@Override
public void exitIsisilt_metric(Isisilt_metricContext ctx) {
int metric = toInt(ctx.DEC());
_currentIsisInterfaceLevelSettings.setMetric(metric);
}
@Override
public void exitIsisilt_te_metric(Isisilt_te_metricContext ctx) {
int teMetric = toInt(ctx.DEC());
_currentIsisInterfaceLevelSettings.setTeMetric(teMetric);
}
@Override
public void exitIsisit_level(Isisit_levelContext ctx) {
_currentIsisInterfaceLevelSettings = null;
}
@Override
public void exitIsisit_passive(Isisit_passiveContext ctx) {
_currentIsisInterface.getIsisSettings().setPassive(true);
}
@Override
public void exitIsisit_point_to_point(Isisit_point_to_pointContext ctx) {
_currentIsisInterface.getIsisSettings().setPointToPoint(true);
}
@Override
public void exitIsislt_disable(Isislt_disableContext ctx) {
_currentIsisLevelSettings.setEnabled(false);
}
@Override
public void exitIsislt_wide_metrics_only(Isislt_wide_metrics_onlyContext ctx) {
_currentIsisLevelSettings.setWideMetricsOnly(true);
}
@Override
public void exitIsist_export(Isist_exportContext ctx) {
Set<String> policies = new LinkedHashSet<String>();
for (VariableContext policy : ctx.policies) {
policies.add(policy.getText());
}
_currentRoutingInstance.getIsisSettings().getExportPolicies()
.addAll(policies);
}
@Override
public void exitIsist_interface(Isist_interfaceContext ctx) {
_currentIsisInterface = null;
}
@Override
public void exitIsist_level(Isist_levelContext ctx) {
_currentIsisLevelSettings = null;
}
@Override
public void exitIsist_no_ipv4_routing(Isist_no_ipv4_routingContext ctx) {
_currentRoutingInstance.getIsisSettings().setNoIpv4Routing(true);
}
@Override
public void exitIsistet_credibility_protocol_preference(
Isistet_credibility_protocol_preferenceContext ctx) {
_currentRoutingInstance.getIsisSettings()
.setTrafficEngineeringCredibilityProtocolPreference(true);
}
@Override
public void exitIsistet_family_shortcuts(Isistet_family_shortcutsContext ctx) {
if (ctx.INET6() != null) {
todo(ctx, F_IPV6);
}
else { // ipv4
_currentRoutingInstance.getIsisSettings()
.setTrafficEngineeringShortcuts(true);
}
}
@Override
public void exitIsofamt_address(Isofamt_addressContext ctx) {
IsoAddress address = new IsoAddress(ctx.ISO_ADDRESS().getText());
_currentInterface.setIsoAddress(address);
}
@Override
public void exitIt_disable(It_disableContext ctx) {
_currentInterface.setActive(false);
}
@Override
public void exitIt_enable(It_enableContext ctx) {
_currentInterface.setActive(true);
}
@Override
public void exitIt_unit(It_unitContext ctx) {
_currentInterface = _currentMasterInterface;
}
@Override
public void exitLast_loops(Last_loopsContext ctx) {
todo(ctx, F_BGP_LOCAL_AS_LOOPS);
}
@Override
public void exitLast_number(Last_numberContext ctx) {
int localAs = toInt(ctx.as);
_currentBgpGroup.setLocalAs(localAs);
}
@Override
public void exitLast_private(Last_privateContext ctx) {
todo(ctx, F_BGP_LOCAL_AS_PRIVATE);
}
@Override
public void exitOt_area(Ot_areaContext ctx) {
_currentArea = null;
}
@Override
public void exitOt_export(Ot_exportContext ctx) {
String name = ctx.name.getText();
_currentRoutingInstance.getOspfExportPolicies().add(name);
}
@Override
public void exitPlt_network(Plt_networkContext ctx) {
Prefix prefix = new Prefix(ctx.network.getText());
_currentPrefixList.getPrefixes().add(prefix);
}
@Override
public void exitPot_community(Pot_communityContext ctx) {
_currentCommunityList = null;
}
@Override
public void exitPot_policy_statement(Pot_policy_statementContext ctx) {
_currentPolicyStatement = null;
}
public void exitPot_prefix_list(Pot_prefix_listContext ctx) {
_currentPrefixList = null;
}
@Override
public void exitPst_term_tail(Pst_term_tailContext ctx) {
_currentPsTerm = null;
_currentPsThens = null;
}
@Override
public void exitRibt_aggregate(Ribt_aggregateContext ctx) {
_currentAggregateRoute = null;
}
@Override
public void exitRot_autonomous_system(Rot_autonomous_systemContext ctx) {
int as = toInt(ctx.as);
_currentRoutingInstance.setAs(as);
}
@Override
public void exitRot_generate(Rot_generateContext ctx) {
_currentGeneratedRoute = null;
}
@Override
public void exitRot_router_id(Rot_router_idContext ctx) {
Ip id = new Ip(ctx.id.getText());
_currentRoutingInstance.setRouterId(id);
}
@Override
public void exitRot_static(Rot_staticContext ctx) {
_currentStaticRoute = null;
}
@Override
public void exitS_firewall(S_firewallContext ctx) {
_currentFirewallFamily = null;
}
@Override
public void exitS_protocols_bgp(S_protocols_bgpContext ctx) {
_currentBgpGroup = null;
}
@Override
public void exitS_routing_options(S_routing_optionsContext ctx) {
_currentRib = null;
}
@Override
public void exitSrt_discard(Srt_discardContext ctx) {
_currentStaticRoute.setDrop(true);
}
@Override
public void exitSrt_reject(Srt_rejectContext ctx) {
_currentStaticRoute.setDrop(true);
}
@Override
public void exitSrt_tag(Srt_tagContext ctx) {
int tag = toInt(ctx.tag);
_currentStaticRoute.setTag(tag);
}
@Override
public void exitSt_default_address_selection(
St_default_address_selectionContext ctx) {
_configuration.setDefaultAddressSelection(true);
}
@Override
public void exitSt_host_name(St_host_nameContext ctx) {
String hostname = ctx.variable().getText();
_currentRoutingInstance.setHostname(hostname);
}
@Override
public void exitTht_accept(Tht_acceptContext ctx) {
_currentPsThens.add(PsThenAccept.INSTANCE);
}
@Override
public void exitTht_community_add(Tht_community_addContext ctx) {
String name = ctx.name.getText();
PsThenCommunityAdd then = new PsThenCommunityAdd(name, _configuration);
_currentPsThens.add(then);
}
@Override
public void exitTht_community_delete(Tht_community_deleteContext ctx) {
String name = ctx.name.getText();
PsThenCommunityDelete then = new PsThenCommunityDelete(name);
_currentPsThens.add(then);
}
@Override
public void exitTht_community_set(Tht_community_setContext ctx) {
String name = ctx.name.getText();
PsThenCommunitySet then = new PsThenCommunitySet(name);
_currentPsThens.add(then);
}
@Override
public void exitTht_local_preference(Tht_local_preferenceContext ctx) {
int localPreference = toInt(ctx.localpref);
PsThenLocalPreference then = new PsThenLocalPreference(localPreference);
_currentPsThens.add(then);
}
@Override
public void exitTht_metric(Tht_metricContext ctx) {
int metric = toInt(ctx.metric);
PsThenMetric then = new PsThenMetric(metric);
_currentPsThens.add(then);
}
@Override
public void exitTht_next_hop(Tht_next_hopContext ctx) {
PsThen then;
if (ctx.IP_ADDRESS() != null) {
Ip nextHopIp = new Ip(ctx.IP_ADDRESS().getText());
then = new PsThenNextHopIp(nextHopIp);
}
else {
todo(ctx, F_POLICY_TERM_THEN_NEXT_HOP);
return;
}
_currentPsThens.add(then);
}
@Override
public void exitTht_reject(Tht_rejectContext ctx) {
_currentPsThens.add(PsThenReject.INSTANCE);
}
public JuniperVendorConfiguration getConfiguration() {
return _configuration;
}
private AsPath toAsPath(As_path_exprContext path) {
AsPath asPath = new AsPath();
for (As_unitContext ctx : path.items) {
AsSet asSet = new AsSet();
if (ctx.DEC() != null) {
asSet.add(toInt(ctx.DEC()));
}
else {
for (Token token : ctx.as_set().items) {
asSet.add(toInt(token));
}
}
asPath.add(asSet);
}
return asPath;
}
private long toCommunityLong(Ec_namedContext ctx) {
ExtendedCommunity ec = new ExtendedCommunity(ctx.getText());
return ec.asLong();
}
private long toCommunityLong(Extended_communityContext ctx) {
if (ctx.ec_literal() != null) {
throw new BatfishException(
"literal extended communities not supported");
}
else if (ctx.ec_named() != null) {
return toCommunityLong(ctx.ec_named());
}
else {
throw new BatfishException("invalid extended community");
}
}
private void todo(ParserRuleContext ctx, String feature) {
_w.todo(ctx, feature, _parser, _text);
_unimplementedFeatures.add("Juniper: " + feature);
}
}
|
package nl.idgis.publisher.dataset;
import static nl.idgis.publisher.database.QCategory.category;
import static nl.idgis.publisher.database.QDataSource.dataSource;
import static nl.idgis.publisher.database.QSourceDataset.sourceDataset;
import static nl.idgis.publisher.database.QSourceDatasetVersion.sourceDatasetVersion;
import static nl.idgis.publisher.database.QSourceDatasetVersionColumn.sourceDatasetVersionColumn;
import java.sql.Timestamp;
import java.util.ArrayList;
import com.mysema.query.Tuple;
import com.mysema.query.sql.SQLSubQuery;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.dispatch.Futures;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.Function;
import akka.pattern.Patterns;
import akka.util.Timeout;
import scala.concurrent.Future;
import scala.runtime.AbstractFunction1;
import scala.runtime.AbstractFunction2;
import nl.idgis.publisher.database.AsyncDatabaseHelper;
import nl.idgis.publisher.database.AsyncHelper;
import nl.idgis.publisher.database.messages.AlreadyRegistered;
import nl.idgis.publisher.database.messages.RegisterSourceDataset;
import nl.idgis.publisher.database.messages.Registered;
import nl.idgis.publisher.database.messages.Updated;
import nl.idgis.publisher.database.projections.QColumn;
import nl.idgis.publisher.domain.service.Column;
import nl.idgis.publisher.domain.service.Table;
import nl.idgis.publisher.domain.service.VectorDataset;
import nl.idgis.publisher.utils.FutureUtils;
import nl.idgis.publisher.utils.TypedList;
public class DatasetManager extends UntypedActor {
private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
private final ActorRef database;
private AsyncDatabaseHelper db;
private FutureUtils f;
public DatasetManager(ActorRef database) {
this.database = database;
}
public static Props props(ActorRef database) {
return Props.create(DatasetManager.class, database);
}
@Override
public void preStart() throws Exception {
Timeout timeout = Timeout.apply(15000);
db = new AsyncDatabaseHelper(database, timeout, getContext()
.dispatcher(), log);
f = new FutureUtils(getContext().dispatcher(), timeout);
}
private <T> void returnToSender(Future<T> future) {
Patterns.pipe(future, getContext().dispatcher()).pipeTo(getSender(),
getSelf());
}
@Override
public void onReceive(Object msg) throws Exception {
if (msg instanceof RegisterSourceDataset) {
returnToSender(handleRegisterSourceDataset((RegisterSourceDataset) msg));
} else {
unhandled(msg);
}
}
private Future<Integer> getCategoryId(final AsyncHelper tx, final String identification) {
return f.flatMap(
tx.query().from(category)
.where(category.identification.eq(identification))
.singleResult(category.id),
new AbstractFunction1<Integer, Future<Integer>>() {
@Override
public Future<Integer> apply(Integer id) {
if (id == null) {
return tx
.insert(category)
.set(category.identification, identification)
.set(category.name, identification)
.executeWithKey(category.id);
} else {
return Futures.successful(id);
}
}
});
}
private Future<Object> handleRegisterSourceDataset(final RegisterSourceDataset rsd) {
final VectorDataset dataset = rsd.getDataset();
final Timestamp revision = new Timestamp(dataset.getRevisionDate().getTime());
final Table table = dataset.getTable();
return db.transactional(new Function<AsyncHelper, Future<Object>>() {
@Override
public Future<Object> apply(final AsyncHelper tx) throws Exception {
return f.flatMap(
tx.query()
.from(sourceDatasetVersion)
.join(sourceDataset).on(sourceDataset.id.eq(sourceDatasetVersion.sourceDatasetId))
.join(dataSource).on(dataSource.id.eq(sourceDataset.dataSourceId))
.where(dataSource.identification.eq(rsd.getDataSource())
.and(sourceDataset.identification.eq(dataset.getId())))
.singleResult(sourceDatasetVersion.id.max()),
new AbstractFunction1<Integer, Future<Object>>() {
private Future<Void> insertSourceDatasetVersion(Future<Integer> sourceDatasetId) {
return f
.collect(sourceDatasetId)
.collect(getCategoryId(tx, dataset.getCategoryId()))
.flatMap(
new AbstractFunction2<Integer, Integer, Future<Void>>() {
@Override
public Future<Void> apply(Integer sourceDatasetId, Integer categoryId) {
return f.flatMap(
tx
.insert(sourceDatasetVersion)
.set(sourceDatasetVersion.sourceDatasetId, sourceDatasetId)
.set(sourceDatasetVersion.name, table.getName())
.set(sourceDatasetVersion.categoryId, categoryId)
.set(sourceDatasetVersion.revision, new Timestamp(dataset.getRevisionDate().getTime()))
.executeWithKey(sourceDatasetVersion.id),
new AbstractFunction1<Integer, Future<Void>>() {
@Override
public Future<Void> apply(
Integer versionId) {
int i = 0;
ArrayList<Future<Long>> columns = new ArrayList<>();
for (Column column : table.getColumns()) {
columns.add(
tx
.insert(sourceDatasetVersionColumn)
.set(sourceDatasetVersionColumn.sourceDatasetVersionId, versionId)
.set(sourceDatasetVersionColumn.index, i++)
.set(sourceDatasetVersionColumn.name, column.getName())
.set(sourceDatasetVersionColumn.dataType, column.getDataType().toString())
.execute());
}
return f.mapValue(f.sequence(columns), null);
}
});
}
});
}
@Override
public Future<Object> apply(final Integer maxVersionId) {
if (maxVersionId == null) { // new dataset
return f.<Void, Object> mapValue(
insertSourceDatasetVersion(
tx
.insert(sourceDataset)
.columns(sourceDataset.dataSourceId, sourceDataset.identification)
.select(new SQLSubQuery()
.from(dataSource)
.list(dataSource.id, dataset.getId()))
.executeWithKey(sourceDataset.id)),
new Registered());
} else { // existing dataset
return f.flatMap(
tx.query()
.from(sourceDataset)
.join(dataSource).on(dataSource.id.eq(sourceDataset.dataSourceId))
.join(sourceDatasetVersion).on(sourceDatasetVersion.id.eq(maxVersionId))
.join(category).on(category.id.eq(sourceDatasetVersion.categoryId))
.where(dataSource.identification.eq(rsd.getDataSource())
.and(sourceDataset.identification.eq(dataset.getId())))
.singleResult(
sourceDataset.id,
sourceDatasetVersion.name,
category.identification,
sourceDatasetVersion.revision,
sourceDataset.deleteTime),
new AbstractFunction1<Tuple, Future<Object>>() {
@Override
public Future<Object> apply(Tuple existing) {
final Integer sourceDatasetId = existing.get(sourceDataset.id);
final String existingName = existing.get(sourceDatasetVersion.name);
final String existingCategoryIdentification = existing.get(category.identification);
final Timestamp existingRevision = existing.get(sourceDatasetVersion.revision);
final Timestamp existingDeleteTime = existing.get(sourceDataset.deleteTime);
return f.flatMap(
tx.query()
.from(sourceDatasetVersionColumn)
.where(sourceDatasetVersionColumn.sourceDatasetVersionId.eq(maxVersionId))
.orderBy(sourceDatasetVersionColumn.index.asc())
.list(new QColumn(
sourceDatasetVersionColumn.name,
sourceDatasetVersionColumn.dataType)),
new AbstractFunction1<TypedList<Column>, Future<Object>>() {
@Override
public Future<Object> apply(final TypedList<Column> existingColumns) {
if (existingName.equals(table.getName()) // still identical
&& existingCategoryIdentification.equals(dataset.getCategoryId())
&& existingRevision.equals(revision)
&& existingDeleteTime == null
&& existingColumns.equals(new TypedList<Column>(Column.class, table.getColumns()))) {
return Futures.<Object>successful(new AlreadyRegistered());
} else {
if (existingDeleteTime != null) { // reviving dataset
return f.flatMap(
tx
.update(sourceDataset)
.setNull(sourceDataset.deleteTime)
.execute(),
new AbstractFunction1<Long, Future<Object>>() {
@Override
public Future<Object> apply(Long l) {
return f.<Void, Object> mapValue(
insertSourceDatasetVersion(Futures.successful(sourceDatasetId)),
new Updated());
}
});
} else {
return f.<Void, Object> mapValue(
insertSourceDatasetVersion(Futures.successful(sourceDatasetId)),
new Updated());
}
}
}
});
}
});
}
}
});
}
});
}
}
|
package com.jetbrains.python.documentation;
import com.google.common.collect.Lists;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.HashSet;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.ParamHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Set;
/**
* @author yole
*/
public class DocStringParameterReference extends PsiReferenceBase<PsiElement> {
String myType;
public DocStringParameterReference(PsiElement element,
TextRange range,
String refType) {
super(element, range);
myType = refType;
}
@Override
public PsiElement resolve() {
PyDocStringOwner owner = PsiTreeUtil.getParentOfType(getElement(), PyDocStringOwner.class);
if (owner instanceof PyFunction) {
return resolveParameter((PyFunction)owner);
}
if (owner instanceof PyClass) {
final PyFunction init = ((PyClass)owner).findMethodByName(PyNames.INIT, false);
if (init != null) {
return resolveParameter(init);
}
}
return null;
}
@Nullable
private PsiElement resolveParameter(PyFunction owner) {
return owner.getParameterList().findParameterByName(getCanonicalText());
}
@NotNull
@Override
public Object[] getVariants() {
PyDocStringOwner owner = PsiTreeUtil.getParentOfType(getElement(), PyDocStringOwner.class);
if (owner instanceof PyFunction) {
List <PyNamedParameter> result = Lists.newArrayList();
final List<PyNamedParameter> namedParameters = ParamHelper.collectNamedParameters(((PyFunction)owner).getParameterList());
Set<String> usedParameters = new HashSet<String>();
PyStringLiteralExpression expression = PsiTreeUtil.getParentOfType(getElement(), PyStringLiteralExpression.class, false);
if (expression != null) {
PsiReference[] references = expression.getReferences();
for (PsiReference ref : references) {
if (ref instanceof DocStringParameterReference && ((DocStringParameterReference)ref).getType().equals(myType))
usedParameters.add(ref.getCanonicalText());
}
}
for (PyNamedParameter param : namedParameters) {
if (!usedParameters.contains(param.getName()))
result.add(param);
}
return ArrayUtil.toObjectArray(result);
}
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
public String getType() {
return myType;
}
}
|
package com.github.database.rider.cdi;
import com.github.database.rider.cdi.api.RiderPUAnnotation;
import com.github.database.rider.core.dataset.DataSetExecutorImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.spi.CDI;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
@ApplicationScoped
public class JTAConnectionHolder {
private static final Logger log = LoggerFactory.getLogger(JTAConnectionHolder.class.getName());
protected Map<String, Connection> connections = new HashMap<>();
@Inject
@Any
protected Instance<DataSource> datasources;
public void init(String dataSourceName) {
try {
DataSource dataSource = resolveDataSource(dataSourceName);
if (!connections.containsKey(dataSourceName) || !isCachedConnection()) {
connections.put(dataSourceName, dataSource.getConnection());
}
} catch (Exception e) {
throw new RuntimeException("Could not acquire sql connection", e);
}
}
private DataSource resolveDataSource(String dataSourceName) {
if ("".equals(dataSourceName)) { //default datasource
return CDI.current().select(DataSource.class).get();
} else {
return datasources.select(DataSource.class, new RiderPUAnnotation(dataSourceName)).get();
}
}
public Connection getConnection(String datasourceBeanName) throws SQLException {
if (!isCachedConnection()) {
this.init(datasourceBeanName);
}
return connections.get(datasourceBeanName).unwrap(Connection.class);
}
public void tearDown(String dataSource) {
if (!isCachedConnection()) {
try {
connections.get(dataSource).close();
} catch (SQLException e) {
log.error("Could not close sql connection", e);
}
}
}
private boolean isCachedConnection() {
DataSetExecutorImpl cdiDataSetExecutor = DataSetExecutorImpl.getExecutorById(DataSetProcessor.CDI_DBUNIT_EXECUTOR);
return cdiDataSetExecutor != null && cdiDataSetExecutor.getDBUnitConfig().isCacheConnection();
}
}
|
package com.github.database.rider.core;
import com.github.database.rider.core.api.configuration.DBUnit;
import com.github.database.rider.core.api.dataset.DataSet;
import com.github.database.rider.core.api.dataset.ExpectedDataSet;
import com.github.database.rider.core.api.dataset.SeedStrategy;
import com.github.database.rider.core.model.Follower;
import com.github.database.rider.core.model.Tweet;
import com.github.database.rider.core.util.EntityManagerProvider;
import com.github.database.rider.core.model.User;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static com.github.database.rider.core.util.EntityManagerProvider.em;
import static com.github.database.rider.core.util.EntityManagerProvider.tx;
// tag::expectedDeclaration[]
@RunWith(JUnit4.class)
@DBUnit(cacheConnection = true)
public class ExpectedDataSetIt {
@Rule
public EntityManagerProvider emProvider = EntityManagerProvider.instance("rules-it");
@Rule
public DBUnitRule dbUnitRule = DBUnitRule.instance(emProvider.connection());
// end::expectedDeclaration[]
// tag::expected[]
@Test
@DataSet(cleanBefore = true)
@ExpectedDataSet(value = "yml/expectedUsers.yml",ignoreCols = "id")
public void shouldMatchExpectedDataSet() {
EntityManagerProvider instance = EntityManagerProvider.newInstance("rules-it");
User u = new User();
u.setName("expected user1");
User u2 = new User();
u2.setName("expected user2");
instance.tx().begin();
instance.em().persist(u);
instance.em().persist(u2);
instance.tx().commit();
}
// end::expected[]
@Test
@DataSet(cleanBefore = true)
@ExpectedDataSet(value = "yml/expectedUsers.yml",ignoreCols = "id")
public void shouldMatchExpectedDataSetClearingDataBaseBefore() {
EntityManagerProvider instance = EntityManagerProvider.newInstance("rules-it");
User u = new User();
u.setName("expected user1");
User u2 = new User();
u2.setName("expected user2");
instance.tx().begin();
instance.em().persist(u);
instance.em().persist(u2);
instance.tx().commit();
}
@Ignore(value = "How to test failled comparisons?")
// tag::faillingExpected[]
@Test
@ExpectedDataSet(value = "yml/expectedUsers.yml",ignoreCols = "id")
public void shouldNotMatchExpectedDataSet() {
User u = new User();
u.setName("non expected user1");
User u2 = new User();
u2.setName("non expected user2");
EntityManagerProvider.tx().begin();
EntityManagerProvider.em().persist(u);
EntityManagerProvider.em().persist(u2);
EntityManagerProvider.tx().commit();
}
// end::faillingExpected[]
// tag::expectedRegex[]
@Test
@DataSet(cleanBefore = true)
@ExpectedDataSet(value = "yml/expectedUsersRegex.yml")
public void shouldMatchExpectedDataSetUsingRegex() {
User u = new User();
u.setName("expected user1");
User u2 = new User();
u2.setName("expected user2");
EntityManagerProvider.tx().begin();
EntityManagerProvider.em().persist(u);
EntityManagerProvider.em().persist(u2);
EntityManagerProvider.tx().commit();
}
// end::expectedRegex[]
// tag::expectedWithSeeding[]
@Test
@DataSet(value = "yml/user.yml", disableConstraints = true)
@ExpectedDataSet(value = "yml/expectedUser.yml", ignoreCols = "id")
public void shouldMatchExpectedDataSetAfterSeedingDataBase() {
tx().begin();
em().remove(EntityManagerProvider.em().find(User.class,1L));
tx().commit();
}
// end::expectedWithSeeding[]
@Test
@DataSet(value = "yml/user.yml", disableConstraints = true, cleanBefore = true)
@ExpectedDataSet(value = "yml/empty.yml")
public void shouldMatchEmptyYmlDataSet() {
EntityManagerProvider.tx().begin();
EntityManagerProvider.em().remove(EntityManagerProvider.em().find(User.class,1L));
EntityManagerProvider.em().remove(EntityManagerProvider.em().find(User.class,2L));
EntityManagerProvider.tx().commit();
}
@Test
@DataSet(value = "yml/user.yml", disableConstraints = true, transactional = true)
@ExpectedDataSet(value = "yml/empty.yml")
public void shouldMatchEmptyYmlDataSetWithTransaction() {
EntityManagerProvider.em().remove(EntityManagerProvider.em().find(User.class,1L));
EntityManagerProvider.em().remove(EntityManagerProvider.em().find(User.class,2L));
}
@Test
@DataSet(cleanBefore = true,transactional = true)
@ExpectedDataSet(value = {"yml/user.yml","yml/tweet.yml"}, ignoreCols = {"id","user_id"})
public void shouldMatchMultipleDataSets(){
User u = new User();
u.setName("@realpestano");
User u2 = new User();
u2.setName("@dbunit");
em().persist(u);
em().persist(u2);
Tweet t = new Tweet();
t.setContent("dbunit rules again!");
em().persist(t);
}
}
|
package com.redhat.ceylon.compiler.java.runtime.metamodel;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import ceylon.language.Sequential;
import ceylon.language.metamodel.DeclarationType$impl;
import ceylon.language.metamodel.Function$impl;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Ignore;
import com.redhat.ceylon.compiler.java.metadata.TypeInfo;
import com.redhat.ceylon.compiler.java.metadata.TypeParameter;
import com.redhat.ceylon.compiler.java.metadata.TypeParameters;
import com.redhat.ceylon.compiler.java.metadata.Variance;
import com.redhat.ceylon.compiler.java.runtime.model.ReifiedType;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ProducedReference;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
@Ceylon(major = 5)
@com.redhat.ceylon.compiler.java.metadata.Class
@TypeParameters({
@TypeParameter(value = "Type", variance = Variance.OUT),
@TypeParameter(value = "Arguments", variance = Variance.IN, satisfies = "ceylon.language::Sequential<ceylon.language::Anything>"),
})
public class AppliedFunction<Type, Arguments extends Sequential<? extends Object>>
implements ceylon.language.metamodel.Function<Type, Arguments>, ReifiedType {
@Ignore
private final TypeDescriptor $reifiedType;
@Ignore
private final TypeDescriptor $reifiedArguments;
private ceylon.language.metamodel.Type type;
protected FreeFunction declaration;
private MethodHandle method;
private MethodHandle[] dispatch;
private int firstDefaulted = -1;
public AppliedFunction(@Ignore TypeDescriptor $reifiedType,
@Ignore TypeDescriptor $reifiedArguments,
ProducedReference appliedFunction, FreeFunction function, Object instance) {
ProducedType appliedType = appliedFunction.getType();
// FIXME: check that this returns a Callable if we have multiple parameter lists
this.$reifiedType = Metamodel.getTypeDescriptorForProducedType(appliedType);
com.redhat.ceylon.compiler.typechecker.model.Method decl = (com.redhat.ceylon.compiler.typechecker.model.Method) function.declaration;
List<Parameter> parameters = decl.getParameterLists().get(0).getParameters();
com.redhat.ceylon.compiler.typechecker.model.ProducedType tupleType
= com.redhat.ceylon.compiler.typechecker.analyzer.Util.getParameterTypesAsTupleType(decl.getUnit(), parameters, appliedFunction);
this.firstDefaulted = Metamodel.getFirstDefaultedParameter(parameters);
Method[] defaultedMethods = null;
if(firstDefaulted != -1){
// if we have 2 params and first is defaulted we need 2 + 1 - 0 = 3 methods:
// f(), f(a) and f(a, b)
this.dispatch = new MethodHandle[parameters.size() + 1 - firstDefaulted];
defaultedMethods = new Method[dispatch.length];
}
this.$reifiedArguments = Metamodel.getTypeDescriptorForProducedType(tupleType);
this.type = Metamodel.getAppliedMetamodel(appliedType);
this.declaration = function;
// FIXME: delay method setup for when we actually use it?
java.lang.Class<?> javaClass = Metamodel.getJavaClass(function.declaration);
// FIXME: deal with Java classes and overloading
// FIXME: faster lookup with types? but then we have to deal with erasure and stuff
Method found = Metamodel.getJavaMethod((com.redhat.ceylon.compiler.typechecker.model.Method) function.declaration);;
String name = Metamodel.getJavaMethodName((com.redhat.ceylon.compiler.typechecker.model.Method) function.declaration);
for(Method method : javaClass.getDeclaredMethods()){
if(!method.getName().equals(name))
continue;
if(method.isAnnotationPresent(Ignore.class)){
// save method for later
// FIXME: proper checks
if(firstDefaulted != -1){
int params = method.getParameterTypes().length;
defaultedMethods[params - firstDefaulted] = method;
}
continue;
}
// FIXME: deal with private stuff?
}
if(found != null){
boolean variadic = found.isVarArgs();
method = reflectionToMethodHandle(found, javaClass, instance, appliedFunction, parameters, variadic, false);
if(defaultedMethods != null){
// this won't find the last one, but it's method
int i=0;
for(;i<defaultedMethods.length-1;i++){
// FIXME: proper checks
dispatch[i] = reflectionToMethodHandle(defaultedMethods[i], javaClass, instance, appliedFunction, parameters, variadic, false);
}
dispatch[i] = method;
}else if(variadic){
// variadic methods don't have defaulted parameters, but we will simulate one because our calling convention is that
// we treat variadic methods as if the last parameter is optional
firstDefaulted = parameters.size() - 1;
dispatch = new MethodHandle[2];
dispatch[0] = reflectionToMethodHandle(found, javaClass, instance, appliedFunction, parameters, variadic, true);
dispatch[1] = method;
}
}
}
private MethodHandle reflectionToMethodHandle(Method found, java.lang.Class<?> javaClass, Object instance,
ProducedReference appliedFunction, List<Parameter> parameters,
boolean variadic, boolean bindVariadicParameterToEmptyArray) {
MethodHandle method;
try {
if(!Modifier.isPublic(found.getModifiers()));
found.setAccessible(true);
method = MethodHandles.lookup().unreflect(found);
} catch (IllegalAccessException e) {
throw new RuntimeException("Problem getting a MH for constructor for: "+javaClass, e);
}
// box the return type
method = MethodHandleUtil.boxReturnValue(method, found.getReturnType(), appliedFunction.getType());
// we need to cast to Object because this is what comes out when calling it in $call
java.lang.Class<?>[] parameterTypes = found.getParameterTypes();
if(instance != null)
method = method.bindTo(instance);
method = method.asType(MethodType.methodType(Object.class, parameterTypes));
int typeParametersCount = found.getTypeParameters().length;
int skipParameters = 0;
// insert any required type descriptors
if(typeParametersCount != 0 && MethodHandleUtil.isReifiedTypeSupported(found, false)){
List<ProducedType> typeArguments = new ArrayList<ProducedType>();
Map<com.redhat.ceylon.compiler.typechecker.model.TypeParameter, ProducedType> typeArgumentMap = appliedFunction.getTypeArguments();
for (com.redhat.ceylon.compiler.typechecker.model.TypeParameter tp : ((com.redhat.ceylon.compiler.typechecker.model.Method)appliedFunction.getDeclaration()).getTypeParameters()) {
typeArguments.add(typeArgumentMap.get(tp));
}
method = MethodHandleUtil.insertReifiedTypeArguments(method, 0, typeArguments);
skipParameters = typeParametersCount;
}
// get a list of produced parameter types
List<ProducedType> parameterProducedTypes = Metamodel.getParameterProducedTypes(parameters, appliedFunction);
// now convert all arguments (we may need to unbox)
method = MethodHandleUtil.unboxArguments(method, skipParameters, 0, parameterTypes,
parameterProducedTypes, variadic, bindVariadicParameterToEmptyArray);
return method;
}
@Override
public FreeFunction getDeclaration(){
return declaration;
}
@Override
@Ignore
public DeclarationType$impl $ceylon$language$metamodel$DeclarationType$impl() {
// TODO Auto-generated method stub
return null;
}
@Override
@Ignore
public Function$impl<Type, Arguments> $ceylon$language$metamodel$Function$impl() {
// TODO Auto-generated method stub
return null;
}
@Override
public Type $call() {
if(method == null)
throw new RuntimeException("No method found for: "+declaration.getName());
try {
if(firstDefaulted == -1)
return (Type)method.invokeExact();
// FIXME: proper checks
return (Type)dispatch[0].invokeExact();
} catch (Throwable e) {
throw new RuntimeException("Failed to invoke method for "+declaration.getName(), e);
}
}
@Override
public Type $call(Object arg0) {
if(method == null)
throw new RuntimeException("No method found for: "+declaration.getName());
try {
if(firstDefaulted == -1)
return (Type)method.invokeExact(arg0);
// FIXME: proper checks
return (Type)dispatch[1-firstDefaulted].invokeExact(arg0);
} catch (Throwable e) {
throw new RuntimeException("Failed to invoke method for "+declaration.getName(), e);
}
}
@Override
public Type $call(Object arg0, Object arg1) {
if(method == null)
throw new RuntimeException("No method found for: "+declaration.getName());
try {
if(firstDefaulted == -1)
return (Type)method.invokeExact(arg0, arg1);
// FIXME: proper checks
return (Type)dispatch[2-firstDefaulted].invokeExact(arg0, arg1);
} catch (Throwable e) {
throw new RuntimeException("Failed to invoke method for "+declaration.getName(), e);
}
}
@Override
public Type $call(Object arg0, Object arg1, Object arg2) {
if(method == null)
throw new RuntimeException("No method found for: "+declaration.getName());
try {
if(firstDefaulted == -1)
return (Type)method.invokeExact(arg0, arg1, arg2);
// FIXME: proper checks
return (Type)dispatch[3-firstDefaulted].invokeExact(arg0, arg1, arg2);
} catch (Throwable e) {
throw new RuntimeException("Failed to invoke method for "+declaration.getName(), e);
}
}
@Override
public Type $call(Object... args) {
if(method == null)
throw new RuntimeException("No method found for: "+declaration.getName());
try {
// FIXME: this does not do invokeExact and does boxing/widening
if(firstDefaulted == -1)
return (Type)method.invokeWithArguments(args);
// FIXME: proper checks
return (Type)dispatch[args.length-firstDefaulted].invokeWithArguments(args);
} catch (Throwable e) {
throw new RuntimeException("Failed to invoke method for "+declaration.getName(), e);
}
}
@Override
public short $getVariadicParameterIndex() {
// TODO Auto-generated method stub
return -1;
}
@Override
@TypeInfo("ceylon.language.metamodel::Type")
public ceylon.language.metamodel.Type getType() {
return type;
}
@Override
public TypeDescriptor $getType() {
return TypeDescriptor.klass(AppliedFunction.class, $reifiedType, $reifiedArguments);
}
}
|
package functionaltests;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.ProActiveTimeoutException;
import org.objectweb.proactive.core.config.CentralPAPropertyRepository;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.util.ProActiveInet;
import org.objectweb.proactive.utils.OperatingSystem;
import org.ow2.proactive.authentication.crypto.CredData;
import org.ow2.proactive.authentication.crypto.Credentials;
import org.ow2.proactive.process_tree_killer.ProcessTree;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.frontend.ResourceManager;
import org.ow2.proactive.rm.util.process.EnvironmentCookieBasedChildProcessKiller;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.SchedulerAuthenticationInterface;
import org.ow2.proactive.scheduler.common.SchedulerConnection;
import org.ow2.proactive.scheduler.common.SchedulerConstants;
import org.ow2.proactive.scheduler.common.SchedulerEvent;
import org.ow2.proactive.scheduler.common.SchedulerState;
import org.ow2.proactive.scheduler.common.exception.SchedulerException;
import org.ow2.proactive.scheduler.common.exception.UnknownJobException;
import org.ow2.proactive.scheduler.common.job.Job;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobInfo;
import org.ow2.proactive.scheduler.common.job.JobResult;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.JobStatus;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.job.factories.JobFactory;
import org.ow2.proactive.scheduler.common.task.ForkEnvironment;
import org.ow2.proactive.scheduler.common.task.JavaTask;
import org.ow2.proactive.scheduler.common.task.NativeTask;
import org.ow2.proactive.scheduler.common.task.Task;
import org.ow2.proactive.scheduler.common.task.TaskInfo;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties;
import org.ow2.proactive.utils.FileUtils;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import functionaltests.common.CommonTUtils;
import functionaltests.common.InputStreamReaderThread;
import functionaltests.monitor.MonitorEventReceiver;
import functionaltests.monitor.SchedulerMonitorsHandler;
/**
*
* Static helpers that provide main operations for Scheduler functional test.
*
* - helpers for launching a scheduler and a RM in a forked JVM, and deploys 5 local ProActive nodes :
* Scheduler can be stated with default configuration file, configuration is also
* defined in $PA_SCHEDULER/config/PAschedulerProperties.ini. If database exists in
* $PA_SCHEDULER/SCHEDULER_DB/, it recovers it and keeps its state.
*
* Scheduler can be started with specific configuration file for tests, in that case :
* - database database is recovered without jobs, in $PA_SCHEDULER/SCHEDULER_DB/
* - removejobdelay property is set to 1.
* - numberofexecutiononfailure property is set to 2
* - initialwaitingtime is set to 10
*
* scheduler can also be started with other specific scheduler property file, and GCM deployment file,
*
* - helpers to acquire user and administrator interfaces
* - helper for job submission
* - helpers for events waiting. Creates if needed an event receiver that receives
* all Scheduler events, store them until waitForEvent**()methods check theses event.
*
* For waitForEvent**() methods, it acts as Producer-consumer mechanism ;
* a Scheduler produce events that are memorized,
* and waiting methods waitForEvent**() are consumers of these events.
* It means that an event asked to be waited for by a call to waitForEvent**() methods, is removed
* after its occurrence. On the contrary, an event is kept till a waitForEvent**() for this event
* has been called.
*
* waitForTerminatedJob() method dosen't act as other waitForEvent**() Methods.
* This method deduce a job finished from current Scheduler's job states and received event.
* This method can also be used for testing for job submission with killing and restarting
* Scheduler.
*
* WARNING, you cannot get Scheduler user interface and Administrator interface twice ;
* //TODO solve this, one connection per body allowed
*
*
* @author ProActive team
* @since ProActive Scheduling 1.0
*
*/
public class SchedulerTHelper {
private static EnvironmentCookieBasedChildProcessKiller childProcessKiller = new EnvironmentCookieBasedChildProcessKiller(
"TEST");
protected static URL functionalTestRMProperties = SchedulerTHelper.class
.getResource("config/functionalTRMProperties.ini");
protected static URL functionalTestSchedulerProperties = SchedulerTHelper.class
.getResource("config/functionalTSchedulerProperties.ini");
public static final int RMI_PORT = 1199;
public static String schedulerUrl = "rmi://" + ProActiveInet.getInstance().getHostname() + ":" +
RMI_PORT + "/" + SchedulerConstants.SCHEDULER_DEFAULT_NAME;
private static Process schedulerProcess;
protected static SchedulerAuthenticationInterface schedulerAuth;
protected static Scheduler adminSchedInterface;
protected static SchedulerMonitorsHandler monitorsHandler;
protected static MonitorEventReceiver eventReceiver;
public static String admin_username = "demo";
public static String admin_password = "demo";
public static String user_username = "user";
public static String user_password = "pwd";
/**
* Start the scheduler using a forked JVM and
* deploys, with its associated Resource manager, 5 local ProActive nodes.
*
* @throws Exception if an error occurs.
*/
public static void startScheduler() throws Exception {
startScheduler(true, null);
}
/**
* Start the scheduler using a forked JVM and
* deploys, with its associated Resource manager, 5 local ProActive nodes.
*
* @param configuration the Scheduler configuration file to use (default is functionalTSchedulerProperties.ini)
* null to use the default one.
* @throws Exception if an error occurs.
*/
public static void startScheduler(String configuration) throws Exception {
startScheduler(true, configuration);
}
/**
* Start the scheduler using a forked JVM and
* deploys, with its associated empty Resource manager.
*
* @throws Exception if an error occurs.
*/
public static void startSchedulerWithEmptyResourceManager() throws Exception {
startScheduler(false, null);
}
/**
* Same as startSchedulerWithEmptyResourceManager but allows to specify a rm property file path
* @param rmPropertyFilePath the file holding rm properties.
* @throws Exception if an error occurs.
*/
public static void startSchedulerWithEmptyResourceManager(String rmPropertyFilePath) throws Exception {
startScheduler(false, null, rmPropertyFilePath, null);
}
/**
* Starts Scheduler with scheduler properties file,
* @param localnodes true if the RM has to start some nodes
* @param schedPropertiesFilePath the Scheduler configuration file to use (default is functionalTSchedulerProperties.ini)
* null to use the default one.
* @throws Exception
*/
public static void startScheduler(boolean localnodes, String schedPropertiesFilePath) throws Exception {
startScheduler(localnodes, schedPropertiesFilePath, null, null);
}
/**
* Same as startScheduler but allows to specify a file holding rm properties
*
* @throws Exception
*/
public static void startScheduler(boolean localnodes, String schedPropertiesFilePath,
String rmPropertiesFilePath, String rmUrl) throws Exception {
if (schedPropertiesFilePath == null) {
schedPropertiesFilePath = new File(functionalTestSchedulerProperties.toURI()).getAbsolutePath();
}
if (rmPropertiesFilePath == null) {
rmPropertiesFilePath = new File(functionalTestRMProperties.toURI()).getAbsolutePath();
}
cleanTMP();
List<String> commandLine = new ArrayList<String>();
commandLine.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
commandLine.add("-Djava.security.manager");
//commandLine.add("-agentlib:jdwp=transport=dt_socket,server=y,address=9009,suspend=y");
String proactiveHome = CentralPAPropertyRepository.PA_HOME.getValue();
if (!CentralPAPropertyRepository.PA_HOME.isSet()) {
proactiveHome = PAResourceManagerProperties.RM_HOME.getValueAsString();
CentralPAPropertyRepository.PA_HOME.setValue(PAResourceManagerProperties.RM_HOME
.getValueAsString());
}
commandLine.add(CentralPAPropertyRepository.PA_HOME.getCmdLine() + proactiveHome);
commandLine.add(CentralPAPropertyRepository.PA_RMI_PORT.getCmdLine() + RMI_PORT);
String securityPolicy = CentralPAPropertyRepository.JAVA_SECURITY_POLICY.getValue();
if (!CentralPAPropertyRepository.JAVA_SECURITY_POLICY.isSet()) {
securityPolicy = PASchedulerProperties.SCHEDULER_HOME.getValueAsString() +
"/config/security.java.policy-server";
}
commandLine.add(CentralPAPropertyRepository.JAVA_SECURITY_POLICY.getCmdLine() + securityPolicy);
String log4jConfiguration = CentralPAPropertyRepository.LOG4J.getValue();
if (!CentralPAPropertyRepository.LOG4J.isSet()) {
log4jConfiguration = SchedulerTHelper.class.getResource("/log4j-junit").toString();
}
commandLine.add(CentralPAPropertyRepository.LOG4J.getCmdLine() + log4jConfiguration);
commandLine.add(PASchedulerProperties.SCHEDULER_HOME.getCmdLine() +
PASchedulerProperties.SCHEDULER_HOME.getValueAsString());
commandLine.add(PAResourceManagerProperties.RM_HOME.getCmdLine() +
PAResourceManagerProperties.RM_HOME.getValueAsString());
if (System.getProperty("pas.launcher.forkas.method") != null) {
commandLine.add("-Dpas.launcher.forkas.method=" +
System.getProperty("pas.launcher.forkas.method"));
}
if (System.getProperty("proactive.test.runAsMe") != null) {
commandLine.add("-Dproactive.test.runAsMe=true");
}
//commandLine.add("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8765");
commandLine.add("-cp");
commandLine.add(testClasspath());
commandLine.add(CentralPAPropertyRepository.PA_TEST.getCmdLine() + "true");
commandLine.add(SchedulerTStarter.class.getName());
commandLine.add(String.valueOf(localnodes));
commandLine.add(schedPropertiesFilePath);
commandLine.add(rmPropertiesFilePath);
if (rmUrl != null) {
commandLine.add(rmUrl);
}
System.out.println("Starting Scheduler process: " + commandLine);
ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
processBuilder.redirectErrorStream(true);
processBuilder.environment().put(childProcessKiller.getCookieName(), childProcessKiller.getCookieValue());
schedulerProcess = processBuilder.start();
InputStreamReaderThread outputReader = new InputStreamReaderThread(schedulerProcess.getInputStream(),
"[Scheduler VM output]: ");
outputReader.start();
System.out.println("Waiting for the Scheduler using URL: " + schedulerUrl);
schedulerAuth = SchedulerConnection.waitAndJoin(schedulerUrl);
System.out.println("The Scheduler is up and running");
if (localnodes) {
// Waiting while all the nodes will be registered in the RM.
// Without waiting test can finish earlier than nodes are added.
// It leads to test execution hang up on windows due to running processes.
RMTHelper rmHelper = RMTHelper.getDefaultInstance();
ResourceManager rm = rmHelper.getResourceManager();
while (rm.getState().getTotalAliveNodesNumber() < SchedulerTStarter.RM_NODE_NUMBER) {
System.out.println("Waiting for nodes deployment");
Thread.sleep(1000);
}
System.out.println("Nodes are deployed");
}
}
public static String testClasspath() {
// String home = PASchedulerProperties.SCHEDULER_HOME.getValueAsString();
// String classpathToLibFolderWithWildcard = home + File.separator + "dist" + File.separator + "lib" +
// File.separator + "*";
// if (OperatingSystem.getOperatingSystem().equals(OperatingSystem.windows)) {
// // required by windows otherwise wildcard is expanded
// classpathToLibFolderWithWildcard = "\"" + classpathToLibFolderWithWildcard + "\"";
// return classpathToLibFolderWithWildcard;
return System.getProperty("java.class.path");
}
/* convenience method to clean TMP from dataspace when executing test */
private static void cleanTMP() {
File tmp = new File(System.getProperty("java.io.tmpdir"));
for (File f : tmp.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("PA_JVM");
}
})) {
FileUtils.removeDir(f);
}
}
/**
* Kill the forked Scheduler if exists.
*/
public static void killScheduler() throws Exception {
if (schedulerProcess != null) {
schedulerProcess.destroy();
schedulerProcess.waitFor();
schedulerProcess = null;
// sometimes RM_NODE object isn't removed from the RMI registry after JVM with RM is killed (SCHEDULING-1498)
CommonTUtils.cleanupRMActiveObjectRegistry();
for (int nodeNumber = 0; nodeNumber < SchedulerTStarter.RM_NODE_NUMBER; nodeNumber++) {
CommonTUtils.cleanupActiveObjectRegistry(SchedulerTStarter.RM_NODE_NAME + "-" + nodeNumber); // clean nodes
}
CommonTUtils.cleanupActiveObjectRegistry(SchedulerConstants.SCHEDULER_DEFAULT_NAME);
}
schedulerAuth = null;
adminSchedInterface = null;
RMTHelper.getDefaultInstance().reset();
}
/**
* Kill the forked Scheduler and all nodes.
*/
public static void killSchedulerAndNodes() throws Exception {
org.apache.log4j.Logger.getLogger(ProcessTree.class).setLevel(Level.DEBUG);
childProcessKiller.killChildProcesses();
killScheduler();
}
/**
* Restart the scheduler using a forked JVM and all children Nodes.
* User or administrator interface is not reconnected automatically.
*
* @param configuration the Scheduler configuration file to use (default is functionalTSchedulerProperties.ini)
* null to use the default one.
* @throws Exception
*/
public static void killSchedulerAndNodesAndRestart(String configuration) throws Exception {
killSchedulerAndNodes();
startScheduler(configuration);
}
/**
* Log a String on console.
*/
public static void log(String s) {
System.out.println("
}
public static void log(Exception e) {
e.printStackTrace();
}
/**
* Return Scheduler authentication interface. Start Scheduler with test
* configuration file, if scheduler is not yet started.
* @throws Exception
*/
public static SchedulerAuthenticationInterface getSchedulerAuth() throws Exception {
if (schedulerAuth == null) {
try {
// trying to connect to the existing Scheduler
schedulerAuth = SchedulerConnection.join(schedulerUrl);
} catch (Exception e) {
// creating a new Scheduler
startScheduler(null);
}
}
return schedulerAuth;
}
/**
* Starts the scheduler or connected to existing one if in consecutive mode
*
* @throws Exception
*/
public static void init() throws Exception {
getSchedulerAuth();
}
/**
* Return Scheduler's interface. Start Scheduler if needed,
* connect as administrator if needed (if not yet connected as user).
*
* WARNING : if there was a previous connection as User, this connection is shut down.
* And so some event can be missed by event receiver, between disconnection and reconnection
* (only one connection to Scheduler per body is possible).
*
* @return scheduler interface
* @throws Exception if an error occurs.
*/
public static Scheduler getSchedulerInterface() throws Exception {
return getSchedulerInterface(UserType.USER);
}
/**
* Return Scheduler's interface. Start Scheduler if needed,
* connect as administrator if needed (if not yet connected as user).
*
* WARNING : if there was a previous connection as User, this connection is shut down.
* And so some event can be missed by event receiver, between disconnection and reconnection
* (only one connection to Scheduler per body is possible).
*
* @param user Type of user
* @return scheduler interface
* @throws Exception if an error occurs.
*/
public static Scheduler getSchedulerInterface(UserType user) throws Exception {
if (adminSchedInterface == null) {
if (System.getProperty("proactive.test.runAsMe") != null) {
connect(user);
} else {
connect();
}
}
return adminSchedInterface;
}
/**
* Creates a job from an XML job descriptor, submit it, and return immediately.
* connect as user if needed (if not yet connected as user).
* @return JobId the job's identifier corresponding to submission.
* @throws Exception if an error occurs at job creation/submission.
*/
public static JobId submitJob(String jobDescPath) throws Exception {
return submitJob(jobDescPath, UserType.USER);
}
/**
* Creates a job from an XML job descriptor, submit it, and return immediately.
* connect as user if needed (if not yet connected as user).
* @param user Type of user
* @return JobId the job's identifier corresponding to submission.
* @throws Exception if an error occurs at job creation/submission.
*/
public static JobId submitJob(String jobDescPath, UserType user) throws Exception {
Job jobToSubmit = JobFactory.getFactory().createJob(jobDescPath);
return submitJob(jobToSubmit, user);
}
/**
* Creates a job from an XML job descriptor, submit it, and return immediately.
* connect as user if needed (if not yet connected as user).
* @param mode true if forked mode
* @return JobId the job's identifier corresponding to submission.
* @throws Exception if an error occurs at job creation/submission.
*/
public static JobId submitJob(String jobDescPath, ExecutionMode mode) throws Exception {
return submitJob(jobDescPath, mode, UserType.USER);
}
/**
* Creates a job from an XML job descriptor, submit it, and return immediately.
* connect as user if needed (if not yet connected as user).
* @param mode true if forked mode
* @param user Type of user
* @return JobId the job's identifier corresponding to submission.
* @throws Exception if an error occurs at job creation/submission.
*/
public static JobId submitJob(String jobDescPath, ExecutionMode mode, UserType user) throws Exception {
Job jobToSubmit = JobFactory.getFactory().createJob(jobDescPath);
return submitJob(jobToSubmit, mode, user);
}
/**
* Submit a job, and return immediately.
* Connect as user if needed (if not yet connected as user).
* @param jobToSubmit job object to schedule.
* @return JobId the job's identifier corresponding to submission.
* @throws Exception if an error occurs at job submission.
*/
public static JobId submitJob(Job jobToSubmit) throws Exception {
return submitJob(jobToSubmit, UserType.USER);
}
/**
* Submit a job, and return immediately.
* Connect as user if needed (if not yet connected as user).
* @param jobToSubmit job object to schedule.
* @param user Type of user
* @return JobId the job's identifier corresponding to submission.
* @throws Exception if an error occurs at job submission.
*/
public static JobId submitJob(Job jobToSubmit, UserType user) throws Exception {
ExecutionMode mode = checkModeSet();
return submitJob(jobToSubmit, mode, user);
}
/**
* Submit a job, and return immediately.
* Connect as user if needed (if not yet connected as user).
* @param jobToSubmit job object to schedule.
* @param mode true if the mode is forked, false if normal mode
* @return JobId the job's identifier corresponding to submission.
* @throws Exception if an error occurs at job submission.
*/
public static JobId submitJob(Job jobToSubmit, ExecutionMode mode) throws Exception {
return submitJob(jobToSubmit, mode, UserType.USER);
}
/**
* Submit a job, and return immediately.
* Connect as user if needed (if not yet connected as user).
* @param jobToSubmit job object to schedule.
* @param mode true if the mode is forked, false if normal mode
* @param user Type of user
* @return JobId the job's identifier corresponding to submission.
* @throws Exception if an error occurs at job submission.
*/
public static JobId submitJob(Job jobToSubmit, ExecutionMode mode, UserType user) throws Exception {
Scheduler userInt = getSchedulerInterface(user);
if (mode == ExecutionMode.fork) {
setForked(jobToSubmit);
} else if (mode == ExecutionMode.runAsMe) {
setRunAsMe(jobToSubmit);
}
return userInt.submit(jobToSubmit);
}
/**
* Kills a job
* @param jobId
* @return success or failure at killing the job
* @throws Exception
*/
public static boolean killJob(String jobId) throws Exception {
Scheduler userInt = getSchedulerInterface();
return userInt.killJob(jobId);
}
/**
* Remove a job from Scheduler database.
* connect as user if needed (if not yet connected as user).
* @param id of the job to remove from database.
* @throws Exception if an error occurs at job removal.
*/
public static void removeJob(JobId id) throws Exception {
Scheduler userInt = getSchedulerInterface();
userInt.removeJob(id);
}
public static void testJobSubmissionAndVerifyAllResults(String jobDescPath) throws Throwable {
Job testJob = JobFactory.getFactory().createJob(jobDescPath);
testJobSubmissionAndVerifyAllResults(testJob, jobDescPath);
}
public static void testJobSubmissionAndVerifyAllResults(Job testJob, String jobDesc) throws Throwable {
JobId id = testJobSubmission(testJob, UserType.USER);
// check result are not null
JobResult res = SchedulerTHelper.getJobResult(id);
Assert.assertFalse("Had Exception : " + jobDesc, SchedulerTHelper.getJobResult(id).hadException());
for (Map.Entry<String, TaskResult> entry : res.getAllResults().entrySet()) {
Assert.assertFalse("Had Exception (" + jobDesc + ") : " + entry.getKey(), entry.getValue()
.hadException());
Assert.assertNotNull("Result not null (" + jobDesc + ") : " + entry.getKey(), entry.getValue()
.value());
}
SchedulerTHelper.removeJob(id);
SchedulerTHelper.waitForEventJobRemoved(id);
}
/**
* Creates and submit a job from an XML job descriptor, and check
* event related to this job submission :
* 1/ job submitted event
* 2/ job passing from pending to running (with state set to running).
* 3/ every task passing from pending to running (with state set to running).
* 4/ every task passing from running to finished (with state set to finished).
* 5/ and finally job passing from running to finished (with state set to finished).
* Then returns.
*
* This is the simplest events sequence of a job submission. If you need to test
* specific event or task states (failure, rescheduling etc, you must not use this
* helper and check events sequence with waitForEvent**() functions.
*
* @param jobDescPath path to an XML job descriptor to submit
* @return JobId, the job's identifier.
* @throws Exception if an error occurs at job creation/submission, or during
* verification of events sequence.
*/
public static JobId testJobSubmission(String jobDescPath) throws Exception {
return testJobSubmission(jobDescPath, UserType.USER);
}
/**
* Creates and submit a job from an XML job descriptor, and check
* event related to this job submission :
* 1/ job submitted event
* 2/ job passing from pending to running (with state set to running).
* 3/ every task passing from pending to running (with state set to running).
* 4/ every task passing from running to finished (with state set to finished).
* 5/ and finally job passing from running to finished (with state set to finished).
* Then returns.
*
* This is the simplest events sequence of a job submission. If you need to test
* specific event or task states (failure, rescheduling etc, you must not use this
* helper and check events sequence with waitForEvent**() functions.
*
* @param jobDescPath path to an XML job descriptor to submit
* @param user Type of user
* @return JobId, the job's identifier.
* @throws Exception if an error occurs at job creation/submission, or during
* verification of events sequence.
*/
public static JobId testJobSubmission(String jobDescPath, UserType user) throws Exception {
Job jobToTest = JobFactory.getFactory().createJob(jobDescPath);
return testJobSubmission(jobToTest, user);
}
/**
* Creates and submit a job from an XML job descriptor, and check
* event related to this job submission :
* 1/ job submitted event
* 2/ job passing from pending to running (with state set to running).
* 3/ every task passing from pending to running (with state set to running).
* 4/ every task passing from running to finished (with state set to finished).
* 5/ and finally job passing from running to finished (with state set to finished).
* Then returns.
*
* This is the simplest events sequence of a job submission. If you need to test
* specific event or task states (failure, rescheduling etc, you must not use this
* helper and check events sequence with waitForEvent**() functions.
*
* @param jobDescPath path to an XML job descriptor to submit
* @param mode true if forked mode
* @return JobId, the job's identifier.
* @throws Exception if an error occurs at job creation/submission, or during
* verification of events sequence.
*/
public static JobId testJobSubmission(String jobDescPath, ExecutionMode mode) throws Exception {
return testJobSubmission(jobDescPath, mode, UserType.USER);
}
/**
* Creates and submit a job from an XML job descriptor, and check
* event related to this job submission :
* 1/ job submitted event
* 2/ job passing from pending to running (with state set to running).
* 3/ every task passing from pending to running (with state set to running).
* 4/ every task passing from running to finished (with state set to finished).
* 5/ and finally job passing from running to finished (with state set to finished).
* Then returns.
*
* This is the simplest events sequence of a job submission. If you need to test
* specific event or task states (failure, rescheduling etc, you must not use this
* helper and check events sequence with waitForEvent**() functions.
*
* @param jobDescPath path to an XML job descriptor to submit
* @param mode true if forked mode
* @param user Type of user
* @return JobId, the job's identifier.
* @throws Exception if an error occurs at job creation/submission, or during
* verification of events sequence.
*/
public static JobId testJobSubmission(String jobDescPath, ExecutionMode mode, UserType user)
throws Exception {
Job jobToTest = JobFactory.getFactory().createJob(jobDescPath);
return testJobSubmission(jobToTest, mode, user);
}
/**
* Creates and submit a job from an XML job descriptor, and check, with assertions,
* event related to this job submission :
* 1/ job submitted event
* 2/ job passing from pending to running (with state set to running).
* 3/ every task passing from pending to running (with state set to running).
* 4/ every task finish without error ; passing from running to finished (with state set to finished).
* 5/ and finally job passing from running to finished (with state set to finished).
* Then returns.
*
* This is the simplest events sequence of a job submission. If you need to test
* specific events or task states (failures, rescheduling etc, you must not use this
* helper and check events sequence with waitForEvent**() functions.
*
* @param jobToSubmit job object to schedule.
* @return JobId, the job's identifier.
* @throws Exception if an error occurs at job submission, or during
* verification of events sequence.
*/
public static JobId testJobSubmission(Job jobToSubmit) throws Exception {
return testJobSubmission(jobToSubmit, UserType.USER);
}
/**
* Creates and submit a job from an XML job descriptor, and check, with assertions,
* event related to this job submission :
* 1/ job submitted event
* 2/ job passing from pending to running (with state set to running).
* 3/ every task passing from pending to running (with state set to running).
* 4/ every task finish without error ; passing from running to finished (with state set to finished).
* 5/ and finally job passing from running to finished (with state set to finished).
* Then returns.
*
* This is the simplest events sequence of a job submission. If you need to test
* specific events or task states (failures, rescheduling etc, you must not use this
* helper and check events sequence with waitForEvent**() functions.
*
* @param jobToSubmit job object to schedule.
* @param user Type of user
* @return JobId, the job's identifier.
* @throws Exception if an error occurs at job submission, or during
* verification of events sequence.
*/
public static JobId testJobSubmission(Job jobToSubmit, UserType user) throws Exception {
ExecutionMode mode = checkModeSet();
return testJobSubmission(jobToSubmit, mode, user);
}
/**
* Creates and submit a job from an XML job descriptor, and check, with assertions,
* event related to this job submission :
* 1/ job submitted event
* 2/ job passing from pending to running (with state set to running).
* 3/ every task passing from pending to running (with state set to running).
* 4/ every task finish without error ; passing from running to finished (with state set to finished).
* 5/ and finally job passing from running to finished (with state set to finished).
* Then returns.
*
* This is the simplest events sequence of a job submission. If you need to test
* specific events or task states (failures, rescheduling etc, you must not use this
* helper and check events sequence with waitForEvent**() functions.
*
* @param jobToSubmit job object to schedule.
* @param mode true if the mode is forked, false if normal mode
* @return JobId, the job's identifier.
* @throws Exception if an error occurs at job submission, or during
* verification of events sequence.
*/
public static JobId testJobSubmission(Job jobToSubmit, ExecutionMode mode) throws Exception {
return testJobSubmission(jobToSubmit, mode, UserType.USER);
}
/**
* Creates and submit a job from an XML job descriptor, and check, with assertions,
* event related to this job submission :
* 1/ job submitted event
* 2/ job passing from pending to running (with state set to running).
* 3/ every task passing from pending to running (with state set to running).
* 4/ every task finish without error ; passing from running to finished (with state set to finished).
* 5/ and finally job passing from running to finished (with state set to finished).
* Then returns.
*
* This is the simplest events sequence of a job submission. If you need to test
* specific events or task states (failures, rescheduling etc, you must not use this
* helper and check events sequence with waitForEvent**() functions.
*
* @param jobToSubmit job object to schedule.
* @param mode true if the mode is forked, false if normal mode
* @return JobId, the job's identifier.
* @throws Exception if an error occurs at job submission, or during
* verification of events sequence.
*/
public static JobId testJobSubmission(Job jobToSubmit, ExecutionMode mode, UserType user)
throws Exception {
Scheduler userInt = getSchedulerInterface(user);
if (mode == ExecutionMode.fork) {
setForked(jobToSubmit);
} else if (mode == ExecutionMode.runAsMe) {
setRunAsMe(jobToSubmit);
}
JobId id = userInt.submit(jobToSubmit);
log("Job submitted, id " + id.toString());
log("Waiting for jobSubmitted");
JobState receivedstate = SchedulerTHelper.waitForEventJobSubmitted(id);
Assert.assertEquals(id, receivedstate.getId());
log("Waiting for job running");
JobInfo jInfo = SchedulerTHelper.waitForEventJobRunning(id);
Assert.assertEquals(jInfo.getJobId(), id);
Assert.assertEquals("Job " + jInfo.getJobId(), JobStatus.RUNNING, jInfo.getStatus());
if (jobToSubmit instanceof TaskFlowJob) {
for (Task t : ((TaskFlowJob) jobToSubmit).getTasks()) {
log("Waiting for task running : " + t.getName());
TaskInfo ti = waitForEventTaskRunning(id, t.getName());
Assert.assertEquals(t.getName(), ti.getTaskId().getReadableName());
Assert.assertEquals("Task " + t.getName(), TaskStatus.RUNNING, ti.getStatus());
}
for (Task t : ((TaskFlowJob) jobToSubmit).getTasks()) {
log("Waiting for task finished : " + t.getName());
TaskInfo ti = waitForEventTaskFinished(id, t.getName());
Assert.assertEquals(t.getName(), ti.getTaskId().getReadableName());
if (ti.getStatus() == TaskStatus.FAULTY) {
TaskResult tres = userInt.getTaskResult(jInfo.getJobId(), t.getName());
Assert.assertNotNull("Task result of " + t.getName(), tres);
if (tres.getOutput() != null) {
System.err.println("Output of failing task (" + t.getName() + ") :");
System.err.println(tres.getOutput().getAllLogs(true));
}
if (tres.hadException()) {
System.err.println("Exception occurred in task (" + t.getName() + ") :");
tres.getException().printStackTrace(System.err);
}
}
Assert.assertEquals("Task " + t.getName(), TaskStatus.FINISHED, ti.getStatus());
}
}
log("Waiting for job finished");
jInfo = SchedulerTHelper.waitForEventJobFinished(id);
Assert.assertEquals("Job " + jInfo.getJobId(), JobStatus.FINISHED, jInfo.getStatus());
log("Job finished");
return id;
}
/**
* Get job result form a job Id.
* Connect as user if needed (if not yet connected as user).
* @param id job identifier, representing job result.
* @return JobResult storing results.
* @throws Exception if an exception occurs in result retrieval
*/
public static JobResult getJobResult(JobId id) throws Exception {
return getSchedulerInterface().getJobResult(id);
}
public static TaskResult getTaskResult(JobId jobId, String taskName) throws Exception {
return getSchedulerInterface().getTaskResult(jobId, taskName);
}
// events waiting methods
/**
* Wait for a job submission event for a specific job id.
* If event has been already thrown by scheduler, returns immediately
* with job object associated to event, otherwise wait for event reception.
*
* @param id job identifier, for which submission event is waited for.
* @return JobState object corresponding to job submitted event.
*/
public static JobState waitForEventJobSubmitted(JobId id) {
try {
return waitForEventJobSubmitted(id, 0);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout, no timeoutExcpetion
//log sthing ?
return null;
}
}
/**
* Wait for a job submission event for a specific job id.
* If event has been already thrown by scheduler, returns immediately
* with job object associated to event, otherwise wait for event reception.
* @param id job identifier, for which submission event is waited for.
* @param timeout max waiting time in milliseconds.
* @return Jobstate object corresponding to job submitted event.
* @throws ProActiveTimeoutException if timeout is reached.
*/
public static JobState waitForEventJobSubmitted(JobId id, long timeout) throws ProActiveTimeoutException {
return getMonitorsHandler().waitForEventJobSubmitted(id, timeout);
}
/**
* Wait for a specific job passing from pending state to running state.
* If corresponding event has been already thrown by scheduler, returns immediately
* with jobInfo object associated to event, otherwise wait for reception
* of the corresponding event.
*
* @param id job identifier, for which event is waited for.
* @return JobInfo event's associated object.
*/
public static JobInfo waitForEventJobRunning(JobId id) {
try {
return waitForEventJobRunning(id, 0);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout
//log sthing ?
return null;
}
}
/**
* Wait for a job passing from pending to running state.
* If corresponding event has been already thrown by scheduler, returns immediately
* with jobInfo object associated to event, otherwise wait for reception
* of the corresponding event.
* @param id job identifier, for which event is waited for.
* @param timeout max waiting time in milliseconds.
* @return JobInfo event's associated object.
* @throws ProActiveTimeoutException if timeout is reached.
*/
public static JobInfo waitForEventJobRunning(JobId id, long timeout) throws ProActiveTimeoutException {
return getMonitorsHandler().waitForEventJob(SchedulerEvent.JOB_PENDING_TO_RUNNING, id, timeout);
}
/**
* Wait for a job passing from running to finished state.
* If corresponding event has been already thrown by scheduler, returns immediately
* with jobInfo object associated to event, otherwise wait for reception
* of the corresponding event.
* If job is already finished, return immediately.
* @param id job identifier, for which event is waited for.
* @return JobInfo event's associated object.
*/
public static JobInfo waitForEventJobFinished(JobId id) throws Exception {
try {
return waitForJobEvent(id, 0, JobStatus.FINISHED, SchedulerEvent.JOB_RUNNING_TO_FINISHED);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout
//log sthing ?
return null;
}
}
/**
* Wait for a job passing from running to finished state.
* If corresponding event has been already thrown by scheduler, returns immediately
* with JobInfo object associated to event, otherwise wait for event reception.
* This method corresponds to the running to finished transition
*
* @param id job identifier, for which event is waited for.
* @param timeout max waiting time in milliseconds.
* @return JobInfo event's associated object.
* @throws ProActiveTimeoutException if timeout is reached.
*/
public static JobInfo waitForEventJobFinished(JobId id, long timeout) throws Exception {
return waitForJobEvent(id, timeout, JobStatus.FINISHED, SchedulerEvent.JOB_RUNNING_TO_FINISHED);
}
private static JobInfo waitForJobEvent(JobId id, long timeout, JobStatus jobStatusAfterEvent,
SchedulerEvent jobEvent) throws Exception {
JobState jobState = null;
try {
jobState = getSchedulerInterface().getJobState(id);
} catch (UnknownJobException ignored) {
}
if (jobState != null && jobState.getStatus().equals(jobStatusAfterEvent)) {
System.err.println("Job is already finished - do not wait for the 'job finished' event");
return jobState.getJobInfo();
} else {
try {
System.err.println("Waiting for the job finished event");
return getMonitorsHandler().waitForEventJob(jobEvent, id, timeout);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout
//log something ?
return null;
}
}
}
public static JobInfo waitForEventPendingJobFinished(JobId id, long timeout)
throws ProActiveTimeoutException {
return getMonitorsHandler().waitForEventJob(SchedulerEvent.JOB_PENDING_TO_FINISHED, id, timeout);
}
/**
* Wait for a job removed from Scheduler's database.
* If corresponding event has been already thrown by scheduler, returns immediately
* with JobInfo object associated to event, otherwise wait for event reception.
*
* @param id job identifier, for which event is waited for.
* @return JobInfo event's associated object.
*/
public static JobInfo waitForEventJobRemoved(JobId id) {
try {
return waitForEventJobRemoved(id, 0);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout
//log sthing ?
return null;
}
}
/**
* Wait for a event job removed from Scheduler's database.
* If corresponding event has been already thrown by scheduler, returns immediately
* with JobInfo object associated to event, otherwise wait for reception
* of the corresponding event.
*
* @param id job identifier, for which event is waited for.
* @param timeout max waiting time in milliseconds.
* @return JobInfo event's associated object.
* @throws ProActiveTimeoutException if timeout is reached.
*/
public static JobInfo waitForEventJobRemoved(JobId id, long timeout) throws ProActiveTimeoutException {
return getMonitorsHandler().waitForEventJob(SchedulerEvent.JOB_REMOVE_FINISHED, id, timeout);
}
/**
* Wait for a task passing from pending to running.
* If corresponding event has been already thrown by scheduler, returns immediately
* with TaskInfo object associated to event, otherwise wait for reception
* of the corresponding event.
*
* @param jobId job identifier, for which task belongs.
* @param taskName for which event is waited for.
* @return TaskInfo event's associated object.
*/
public static TaskInfo waitForEventTaskRunning(JobId jobId, String taskName) {
try {
return waitForEventTaskRunning(jobId, taskName, 0);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout
//log sthing ?
return null;
}
}
/**
* Wait for a task passing from pending to running.
* If corresponding event has been already thrown by scheduler, returns immediately
* with TaskInfo object associated to event, otherwise wait for reception
* of the corresponding event.
*
* @param jobId job identifier, for which task belongs.
* @param taskName for which event is waited for.
* @param timeout max waiting time in milliseconds.
* @return TaskInfo event's associated object.
* @throws ProActiveTimeoutException if timeout is reached.
*/
public static TaskInfo waitForEventTaskRunning(JobId jobId, String taskName, long timeout)
throws ProActiveTimeoutException {
return getMonitorsHandler().waitForEventTask(SchedulerEvent.TASK_PENDING_TO_RUNNING, jobId, taskName,
timeout);
}
/**
* Wait for a task failed that waits for restart.
* If corresponding event has been already thrown by scheduler, returns immediately
* with TaskInfo object associated to event, otherwise wait for reception
* of the corresponding event.
*
* @param jobId job identifier, for which task belongs.
* @param taskName for which event is waited for.
* @return TaskInfo event's associated object.
*/
public static TaskInfo waitForEventTaskWaitingForRestart(JobId jobId, String taskName) {
try {
return waitForEventTaskWaitingForRestart(jobId, taskName, 0);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout
//log sthing ?
return null;
}
}
/**
* Wait for a task failed that waits for restart.
* If corresponding event has been already thrown by scheduler, returns immediately
* with TaskInfo object associated to event, otherwise wait for reception
* of the corresponding event.
*
* @param jobId job identifier, for which task belongs.
* @param taskName for which event is waited for.
* @param timeout max waiting time in milliseconds.
* @return TaskInfo event's associated object.
* @throws ProActiveTimeoutException if timeout is reached.
*/
public static TaskInfo waitForEventTaskWaitingForRestart(JobId jobId, String taskName, long timeout)
throws ProActiveTimeoutException {
return getMonitorsHandler().waitForEventTask(SchedulerEvent.TASK_WAITING_FOR_RESTART, jobId,
taskName, timeout);
}
/**
* Wait for a task passing from running to finished.
* If corresponding event has been already thrown by scheduler, returns immediately
* with TaskInfo object associated to event, otherwise wait for reception
* of the corresponding event.
*
* @param jobId job identifier, for which task belongs.
* @param taskName for which event is waited for.
* @return TaskEvent, associated event's object.
*/
public static TaskInfo waitForEventTaskFinished(JobId jobId, String taskName) {
try {
return waitForEventTaskFinished(jobId, taskName, 0);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout
//log sthing ?
return null;
}
}
/**
* Wait for a task passing from running to finished.
* If corresponding event has been already thrown by scheduler, returns immediately
* with TaskInfo object associated to event, otherwise wait for reception
* of the corresponding event.
*
* @param jobId job identifier, for which task belongs.
* @param taskName for which event is waited for.
* @param timeout max waiting time in milliseconds.
* @return TaskInfo, associated event's object.
* @throws ProActiveTimeoutException if timeout is reached.
*/
public static TaskInfo waitForEventTaskFinished(JobId jobId, String taskName, long timeout)
throws ProActiveTimeoutException {
return getMonitorsHandler().waitForEventTask(SchedulerEvent.TASK_RUNNING_TO_FINISHED, jobId,
taskName, timeout);
}
/**
* Wait for an event regarding Scheduler state : started, resumed, stopped...
* If a corresponding event has been already thrown by scheduler, returns immediately,
* otherwise wait for reception of the corresponding event.
* @param event awaited event.
*/
public static void waitForEventSchedulerState(SchedulerEvent event) {
try {
waitForEventSchedulerState(event, 0);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout
//log sthing ?
}
}
/**
* Wait for an event regarding Scheduler state : started, resumed, stopped...
* If a corresponding event has been already thrown by scheduler, returns immediately,
* otherwise wait for reception of the corresponding event.
* @param event awaited event.
* @param timeout in milliseconds
* @throws ProActiveTimeoutException if timeout is reached
*/
public static void waitForEventSchedulerState(SchedulerEvent event, long timeout)
throws ProActiveTimeoutException {
getMonitorsHandler().waitForEventSchedulerState(event, timeout);
}
// Job finished waiting methods
/**
* Wait for a finished job. If Job is already finished, methods return.
* This method doesn't wait strictly 'job finished event', it looks
* first if the job is already finished, if yes, returns immediately.
* Otherwise method performs a wait for job finished event.
*
* @param id JobId representing the job awaited to be finished.
*/
public static void waitForFinishedJob(JobId id) {
try {
waitForFinishedJob(id, 0);
} catch (ProActiveTimeoutException e) {
//unreachable block, 0 means infinite, no timeout
//log sthing ?
}
}
/**
* Wait for a finished job. If Job is already finished, methods return.
* This method doesn't wait strictly 'job finished event', it looks
* first if the job is already finished, if yes, returns immediately.
* Otherwise method performs a wait for job finished event.
*
* @param id JobId representing the job awaited to be finished.
* @param timeout in milliseconds
* @throws ProActiveTimeoutException if timeout is reached
*/
public static void waitForFinishedJob(JobId id, long timeout) throws ProActiveTimeoutException {
monitorsHandler.waitForFinishedJob(id, timeout);
}
//private methods
private static void initEventReceiver(Scheduler schedInt) throws NodeException, SchedulerException,
ActiveObjectCreationException {
SchedulerMonitorsHandler mHandler = getMonitorsHandler();
if (eventReceiver == null) {
/** create event receiver then turnActive to avoid deepCopy of MonitorsHandler object
* (shared instance between event receiver and static helpers).
*/
MonitorEventReceiver passiveEventReceiver = new MonitorEventReceiver(mHandler);
eventReceiver = PAActiveObject.turnActive(passiveEventReceiver);
}
SchedulerState state = schedInt.addEventListener(eventReceiver, true, true);
mHandler.init(state);
}
/**
* Init connection as user
* @throws Exception
*/
private static void connect() throws Exception {
SchedulerAuthenticationInterface authInt = getSchedulerAuth();
Credentials cred = Credentials.createCredentials(new CredData(admin_username, admin_password),
authInt.getPublicKey());
adminSchedInterface = authInt.login(cred);
initEventReceiver(adminSchedInterface);
}
/**
* Init connection as user
* @throws Exception
*/
private static void connect(UserType user) throws Exception {
if ((System.getProperty("proactive.test.login." + user) == null) ||
(System.getProperty("proactive.test.password." + user) == null)) {
throw new IllegalStateException(
"Property proactive.test.login or proactive.test.password are not correctly set");
}
String login = System.getProperty("proactive.test.login." + user);
String pwd = System.getProperty("proactive.test.password." + user);
SchedulerAuthenticationInterface authInt = getSchedulerAuth();
Credentials cred = Credentials.createCredentials(new CredData(login, pwd), authInt.getPublicKey());
adminSchedInterface = authInt.login(cred);
initEventReceiver(adminSchedInterface);
}
private static SchedulerMonitorsHandler getMonitorsHandler() {
if (monitorsHandler == null) {
monitorsHandler = new SchedulerMonitorsHandler();
}
return monitorsHandler;
}
public static void setExecutable(String filesList) throws IOException {
Runtime.getRuntime().exec("chmod u+x " + filesList);
}
public static void setForked(Job job) {
if (TaskFlowJob.class.isAssignableFrom(job.getClass())) {
for (Task task : ((TaskFlowJob) job).getTasks()) {
if (JavaTask.class.isAssignableFrom(task.getClass())) {
if (!((JavaTask) task).isFork()) {
ForkEnvironment forkedEnv = new ForkEnvironment();
forkedEnv.addJVMArgument("-Dproactive.test=true");
((JavaTask) task).setForkEnvironment(forkedEnv);
}
}
}
}
}
public static void setRunAsMe(Job job) {
if (TaskFlowJob.class.isAssignableFrom(job.getClass())) {
for (Task task : ((TaskFlowJob) job).getTasks()) {
if (JavaTask.class.isAssignableFrom(task.getClass())) {
if (!task.isRunAsMe()) {
task.setRunAsMe(true);
}
} else if (NativeTask.class.isAssignableFrom(task.getClass())) {
if (!task.isRunAsMe()) {
task.setRunAsMe(true);
}
}
}
}
}
private static ExecutionMode checkModeSet() {
if (System.getProperty("proactive.test.runAsMe") != null) {
return ExecutionMode.runAsMe;
} else if (System.getProperty("proactive.test.fork") != null) {
return ExecutionMode.fork;
} else {
return ExecutionMode.normal;
}
}
}
|
package com.altamiracorp.securegraph.query;
import com.altamiracorp.securegraph.DateOnly;
import com.altamiracorp.securegraph.Property;
import com.altamiracorp.securegraph.Text;
import com.altamiracorp.securegraph.TextIndexHint;
import java.util.Date;
public enum Compare implements Predicate {
EQUAL, NOT_EQUAL, GREATER_THAN, GREATER_THAN_EQUAL, LESS_THAN, LESS_THAN_EQUAL, IN;
@Override
public boolean evaluate(final Iterable<Property> properties, final Object second) {
for (Property property : properties) {
if (evaluate(property, second)) {
return true;
}
}
return false;
}
private boolean evaluate(Property property, Object second) {
Object first = property.getValue();
if (first instanceof DateOnly) {
first = ((DateOnly) first).getDate();
if (second instanceof Date) {
second = new DateOnly((Date) second).getDate();
}
}
if (second instanceof DateOnly) {
second = ((DateOnly) second).getDate();
if (first instanceof Date) {
first = new DateOnly((Date) first).getDate();
}
}
switch (this) {
case EQUAL:
if (null == first) {
return second == null;
}
if (first instanceof Text) {
Text firstText = (Text) first;
if (!firstText.getIndexHint().contains(TextIndexHint.EXACT_MATCH)) {
return false;
}
first = firstText.getText();
}
if (second instanceof Text) {
Text secondText = (Text) second;
if (!secondText.getIndexHint().contains(TextIndexHint.EXACT_MATCH)) {
return false;
}
second = secondText.getText();
}
return first.equals(second);
case NOT_EQUAL:
if (null == first) {
return second != null;
}
return !first.equals(second);
case GREATER_THAN:
if (null == first || second == null) {
return false;
}
return ((Comparable) first).compareTo(second) >= 1;
case LESS_THAN:
if (null == first || second == null) {
return false;
}
return ((Comparable) first).compareTo(second) <= -1;
case GREATER_THAN_EQUAL:
if (null == first || second == null) {
return false;
}
return ((Comparable) first).compareTo(second) >= 0;
case LESS_THAN_EQUAL:
if (null == first || second == null) {
return false;
}
return ((Comparable) first).compareTo(second) <= 0;
case IN:
if (first instanceof Text) {
first = first.toString();
}
return evaluateIn(first, (Object[]) second);
default:
throw new IllegalArgumentException("Invalid compare: " + this);
}
}
private boolean evaluateIn(Object first, Object[] second) {
for (Object o : second) {
if (first.equals(o)) {
return true;
}
}
return false;
}
}
|
package com.braintreepayments.api.internal;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import com.braintreepayments.api.core.BuildConfig;
import com.braintreepayments.api.exceptions.AuthenticationException;
import com.braintreepayments.api.exceptions.AuthorizationException;
import com.braintreepayments.api.exceptions.DownForMaintenanceException;
import com.braintreepayments.api.exceptions.RateLimitException;
import com.braintreepayments.api.exceptions.ServerException;
import com.braintreepayments.api.exceptions.UnexpectedException;
import com.braintreepayments.api.exceptions.UnprocessableEntityException;
import com.braintreepayments.api.exceptions.UpgradeRequiredException;
import com.braintreepayments.api.interfaces.HttpResponseCallback;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocketFactory;
import static java.net.HttpURLConnection.HTTP_ACCEPTED;
import static java.net.HttpURLConnection.HTTP_CREATED;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static java.net.HttpURLConnection.HTTP_UNAVAILABLE;
public class HttpClient<T extends HttpClient> {
private static final String METHOD_GET = "GET";
private static final String METHOD_POST = "POST";
private static final String UTF_8 = "UTF-8";
private final Handler mMainThreadHandler;
@VisibleForTesting
protected final ExecutorService mThreadPool;
private String mUserAgent;
private SSLSocketFactory mSSLSocketFactory;
private int mConnectTimeout;
private int mReadTimeout;
protected String mBaseUrl;
public HttpClient() {
mThreadPool = Executors.newCachedThreadPool();
mMainThreadHandler = new Handler(Looper.getMainLooper());
mUserAgent = "braintree/core/" + BuildConfig.VERSION_NAME;
mConnectTimeout = (int) TimeUnit.SECONDS.toMillis(30);
mReadTimeout = (int) TimeUnit.SECONDS.toMillis(30);
try {
mSSLSocketFactory = new TLSSocketFactory();
} catch (SSLException e) {
mSSLSocketFactory = null;
}
}
/**
* @param userAgent the user agent to be sent with all http requests.
* @return {@link HttpClient} for method chaining.
*/
@SuppressWarnings("unchecked")
public T setUserAgent(String userAgent) {
mUserAgent = userAgent;
return (T) this;
}
/**
* @param sslSocketFactory the {@link SSLSocketFactory} to use for all https requests.
* @return {@link HttpClient} for method chaining.
*/
@SuppressWarnings("unchecked")
public T setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
mSSLSocketFactory = sslSocketFactory;
return (T) this;
}
/**
* @param baseUrl the base url to use when only a path is supplied to
* {@link #get(String, HttpResponseCallback)} or {@link #post(String, String, HttpResponseCallback)}
* @return {@link HttpClient} for method chaining.
*/
@SuppressWarnings("unchecked")
public T setBaseUrl(String baseUrl) {
mBaseUrl = (baseUrl == null) ? "" : baseUrl;
return (T) this;
}
/**
* @param timeout the time in milliseconds to wait for a connection before timing out.
* @return {@link HttpClient} for method chaining.
*/
@SuppressWarnings("unchecked")
public T setConnectTimeout(int timeout) {
mConnectTimeout = timeout;
return (T) this;
}
/**
* @param timeout the time in milliseconds to read a response from the server before timing out.
* @return {@link HttpClient} for method chaining.
*/
@SuppressWarnings("unchecked")
public T setReadTimeout(int timeout) {
mReadTimeout = timeout;
return (T) this;
}
/**
* Make a HTTP GET request to using the base url and path provided. If the path is a full url,
* it will be used instead of the previously provided base url.
*
* @param path The path or url to request from the server via GET
* @param callback The {@link HttpResponseCallback} to receive the response or error.
*/
public void get(final String path, final HttpResponseCallback callback) {
if (path == null) {
postCallbackOnMainThread(callback, new IllegalArgumentException("Path cannot be null"));
return;
}
final String url;
if (path.startsWith("http")) {
url = path;
} else {
url = mBaseUrl + path;
}
mThreadPool.submit(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
connection = init(url);
connection.setRequestMethod(METHOD_GET);
postCallbackOnMainThread(callback, parseResponse(connection));
} catch (Exception e) {
postCallbackOnMainThread(callback, e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
});
}
/**
* Make a HTTP POST request using the base url and path provided. If the path is a full url,
* it will be used instead of the previously provided url.
*
* @param path The path or url to request from the server via HTTP POST
* @param data The body of the POST request
* @param callback The {@link HttpResponseCallback} to receive the response or error.
*/
public void post(final String path, final String data, final HttpResponseCallback callback) {
if (path == null) {
postCallbackOnMainThread(callback, new IllegalArgumentException("Path cannot be null"));
return;
}
mThreadPool.submit(new Runnable() {
@Override
public void run() {
try {
postCallbackOnMainThread(callback, post(path, data));
} catch (Exception e) {
postCallbackOnMainThread(callback, e);
}
}
});
}
/**
* Performs a synchronous post request.
*
* @param path the path or url to request from the server via HTTP POST
* @param data the body of the post request
* @return The HTTP body the of the response
*
* @see HttpClient#post(String, String, HttpResponseCallback)
* @throws Exception
*/
public String post(String path, String data) throws Exception {
HttpURLConnection connection = null;
try {
if (path.startsWith("http")) {
connection = init(path);
} else {
connection = init(mBaseUrl + path);
}
connection.setRequestMethod(METHOD_POST);
connection.setDoOutput(true);
writeOutputStream(connection.getOutputStream(), data);
return parseResponse(connection);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
protected HttpURLConnection init(String url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
if (connection instanceof HttpsURLConnection) {
if (mSSLSocketFactory == null) {
throw new SSLException("SSLSocketFactory was not set or failed to initialize");
}
((HttpsURLConnection) connection).setSSLSocketFactory(mSSLSocketFactory);
}
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("User-Agent", mUserAgent);
connection.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage());
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setConnectTimeout(mConnectTimeout);
connection.setReadTimeout(mReadTimeout);
return connection;
}
protected void writeOutputStream(OutputStream outputStream, String data) throws IOException {
Writer out = new OutputStreamWriter(outputStream, UTF_8);
out.write(data, 0, data.length());
out.flush();
out.close();
}
protected String parseResponse(HttpURLConnection connection) throws Exception {
int responseCode = connection.getResponseCode();
boolean gzip = "gzip".equals(connection.getContentEncoding());
switch(responseCode) {
case HTTP_OK: case HTTP_CREATED: case HTTP_ACCEPTED:
return readStream(connection.getInputStream(), gzip);
case HTTP_UNAUTHORIZED:
throw new AuthenticationException(readStream(connection.getErrorStream(), gzip));
case HTTP_FORBIDDEN:
throw new AuthorizationException(readStream(connection.getErrorStream(), gzip));
case 422: // HTTP_UNPROCESSABLE_ENTITY
throw new UnprocessableEntityException(readStream(connection.getErrorStream(), gzip));
case 426: // HTTP_UPGRADE_REQUIRED
throw new UpgradeRequiredException(readStream(connection.getErrorStream(), gzip));
case 429: // HTTP_TOO_MANY_REQUESTS
throw new RateLimitException("You are being rate-limited. Please try again in a few minutes.");
case HTTP_INTERNAL_ERROR:
throw new ServerException(readStream(connection.getErrorStream(), gzip));
case HTTP_UNAVAILABLE:
throw new DownForMaintenanceException(readStream(connection.getErrorStream(), gzip));
default:
throw new UnexpectedException(readStream(connection.getErrorStream(), gzip));
}
}
void postCallbackOnMainThread(final HttpResponseCallback callback, final String response) {
if (callback == null) {
return;
}
mMainThreadHandler.post(new Runnable() {
@Override
public void run() {
callback.success(response);
}
});
}
void postCallbackOnMainThread(final HttpResponseCallback callback, final Exception exception) {
if (callback == null) {
return;
}
mMainThreadHandler.post(new Runnable() {
@Override
public void run() {
callback.failure(exception);
}
});
}
@Nullable
private String readStream(InputStream in, boolean gzip) throws IOException {
if (in == null) {
return null;
}
try {
if (gzip) {
in = new GZIPInputStream(in);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
return new String(out.toByteArray(), UTF_8);
} finally {
try {
in.close();
} catch (IOException ignored) {}
}
}
}
|
package org.openlaszlo.compiler;
import java.lang.Integer;
import java.io.*;
import java.text.ChoiceFormat;
import java.text.MessageFormat;
import java.util.*;
import org.jdom.*;
import org.openlaszlo.css.CSSHandler;
import org.openlaszlo.sc.ScriptCompiler;
import org.openlaszlo.utils.ChainedException;
import org.openlaszlo.utils.FileUtils;
import org.openlaszlo.utils.ListFormat;
import org.openlaszlo.server.LPS;
import org.apache.log4j.*;
/**
* Compiles a Laszlo XML source file, and any files that it
* references, into an object file that can be executed on the client.
*
* The compiler parses the file into XML, and then gets an element
* compiler for each toplevel element.
*/
public class Compiler {
/** Set this to log the modified schema. */
public static Logger SchemaLogger = Logger.getLogger("schema");
public static List KNOWN_RUNTIMES =
Arrays.asList(new String[] {"swf7", "swf8", "swf9", "dhtml", "j2me", "svg", "null"});
public static List SCRIPT_RUNTIMES =
Arrays.asList(new String[] {"swf9", "dhtml", "j2me", "svg", "null"});
public static List SWF_RUNTIMES =
Arrays.asList(new String[] {"swf7", "swf8"});
/** Called to resolve file references (<code>src</code>
* attributes).
*/
protected FileResolver mFileResolver = FileResolver.DEFAULT_FILE_RESOLVER;
/**
* CompilerMediaCache
*/
protected CompilerMediaCache mMediaCache = null;
/** See getProperties.
*/
protected final Properties mProperties = new Properties();
/** Logger
*/
private static Logger mLogger = Logger.getLogger(Compiler.class);
/**
* A <code>Compiler</code>'s <code>Properties</code> stores
* properties that affect the compilation.
*
* <table><tr><th>Name=default</th><th>Meaning</th></tr>
* <tr><td>trace.xml=false</td><td>Display XML that's compiled to
* script, and the script that it compiles to.</td></tr>
* <tr><td>debug=true</td><td>Add in debug features to the output.</td></tr>
* <tr><td>trace.fonts=false</td><td>Additional font traces.</td></tr>
* <tr><td>swf.frame.rate=30</td><td>Output SWF frame rate.</td></tr>
* <tr><td>default.text.height=12</td><td>Default text height for
* fonts.</td></tr>
* <tr><td>text.borders=false</td><td>Display text borders in the output SWF
* for debugging.</td></tr>
* </table>
*
* Properties that one part of the compiler sets for another part to read:
* <table><tr><th>Name=default</th><th>Meaning</th></tr>
* <tr><td>lzc_*</td><td>Source location values.</td></tr>
* </table>
*
* @return a <code>Properties</code> value
*/
public String getProperty(String key) {
return mProperties.getProperty(key);
}
public void setProperty(String key, String value) {
mProperties.setProperty(key, value);
}
public FileResolver getFileResolver() {
return mFileResolver;
}
/** Sets the file resolver for this compiler. The file resolver
* is used to resolve the names used in include directives to
* files.
* @param resolver a FileResolver
*/
public void setFileResolver(FileResolver resolver) {
this.mFileResolver = resolver;
}
/** Sets the media cache for this compiler.
* @param cache a CompilerMediaCache
*/
public void setMediaCache(CompilerMediaCache cache) {
this.mMediaCache = cache;
}
/** Create a CompilationEnvironment with the properties and
* FileResolver of this compiler.
*/
public CompilationEnvironment makeCompilationEnvironment() {
return new CompilationEnvironment(mProperties, mFileResolver, mMediaCache);
}
/** Compiles <var>sourceFile</var> to <var>objectFile</var>. If
* compilation fails, <var>objectFile</var> is deleted.
*
* @param sourceFile source File
* @param objectFile a File to place object code in
* @param url request url, ignore if null
* @throws CompilationError if an error occurs
* @throws IOException if an error occurs
*/
public Canvas compile(File sourceFile, File objectFile, String url)
throws CompilationError, IOException
{
Properties props = new Properties();
return compile(sourceFile, objectFile, props);
}
public static String getObjectFileExtensionForRuntime (String runtime) {
String ext;
if ("swf9".equals(runtime)) {
ext = ".lzr=" + runtime + ".swf";
} else {
ext = SCRIPT_RUNTIMES.contains(runtime) ? ".js" : ".lzr=" + runtime + ".swf";
}
return ext;
}
/** Compiles <var>sourceFile</var> to <var>objectFile</var>. If
* compilation fails, <var>objectFile</var> is deleted.
*
* @param sourceFile source File
* @param objectFile a File to place object code in
* @param props parameters for the compile
* @throws CompilationError if an error occurs
* @throws IOException if an error occurs
* The PROPS parameters for the compile may include
* <ul>
* <li> url, optional, ignore if null
* <li> debug := "true" | "false" include debugger
* <li> logdebug := "true" | "false" makes debug.write() calls get logged to server
* </ul>
*/
public Canvas compile(File sourceFile, File objectFile, Properties props)
throws CompilationError, IOException
{
FileUtils.makeFileAndParentDirs(objectFile);
// Compile to a byte-array, and write out to objectFile, and
// write a copy into sourceFile.[swf|js] if this is a serverless deployment.
CompilationEnvironment env = makeCompilationEnvironment();
ByteArrayOutputStream bstream = new ByteArrayOutputStream();
OutputStream ostream = new FileOutputStream(objectFile);
env.setObjectFile(objectFile);
boolean success = false;
try {
Canvas canvas = compile(sourceFile, bstream, props, env);
bstream.writeTo(ostream);
ostream.close();
// If the app is serverless, write out a .lzx.swf file when compiling
if (canvas != null && !canvas.isProxied()) {
// Create a foo.lzx.[js|swf] serverless deployment file for sourcefile foo.lzx
String runtime = props.getProperty(CompilationEnvironment.RUNTIME_PROPERTY);
String soloExtension = getObjectFileExtensionForRuntime(runtime);
OutputStream fostream = null;
try {
File deploymentFile = new File(sourceFile+soloExtension);
fostream = new FileOutputStream(deploymentFile);
bstream.writeTo(fostream);
} finally {
if (fostream != null) {
fostream.close();
}
}
}
success = true;
return canvas;
} catch (java.lang.OutOfMemoryError e) {
// The runtime gc is necessary in order for subsequent
// compiles to succeed. The System gc is for good luck.
System.gc();
Runtime.getRuntime().gc();
throw new CompilationError("out of memory");
} finally {
if (!success) {
ostream.close();
objectFile.delete();
}
}
}
public Properties getProperties() {
return (Properties)mProperties.clone();
}
ObjectWriter createObjectWriter(Properties props, OutputStream ostr, CompilationEnvironment env, Element root) {
if ("false".equals(props.getProperty(env.LINK_PROPERTY))) {
return new LibraryWriter(props, ostr, mMediaCache, true, env, root);
}
String runtime = props.getProperty(env.RUNTIME_PROPERTY);
// Must be kept in sync with server/sc/lzsc.py compile
if ("null".equals(runtime)) {
return new NullWriter(props, ostr, mMediaCache, true, env);
} else if ("swf9".equals(runtime)) {
return new SWF9Writer(props, ostr, mMediaCache, true, env);
} else if (SCRIPT_RUNTIMES.contains(runtime)) {
return new DHTMLWriter(props, ostr, mMediaCache, true, env);
} else {
return new SWFWriter(props, ostr, mMediaCache, true, env);
}
}
/**
* Compiles <var>file</var>, and write the bytes to
* a stream.
*
* @param file a <code>File</code> value
* @param ostr an <code>OutputStream</code> value
* @param props parameters for the compilation
* @exception CompilationError if an error occurs
* @exception IOException if an error occurs
*
* The parameters currently being looked for in the PROPS arg
* are "debug", "logdebug", "profile", "krank"
*
*/
public Canvas compile(File file, OutputStream ostr, Properties props, CompilationEnvironment env)
throws CompilationError, IOException
{
mLogger.info("compiling " + file + "...");
CompilationErrorHandler errors = env.getErrorHandler();
env.setApplicationFile(file);
// Copy target properties (debug, logdebug, profile, krank,
// runtime) from props arg to CompilationEnvironment
String runtime = props.getProperty(env.RUNTIME_PROPERTY);
boolean linking = (! "false".equals(env.getProperty(CompilationEnvironment.LINK_PROPERTY)));
boolean noCodeGeneration = "true".equals(env.getProperty(CompilationEnvironment.NO_CODE_GENERATION));
if (runtime != null) {
mLogger.info("canvas compiler compiling runtime = " + runtime);
env.setProperty(env.RUNTIME_PROPERTY, runtime);
if (! KNOWN_RUNTIMES.contains(runtime)) {
List runtimes = new Vector();
for (Iterator iter = KNOWN_RUNTIMES.iterator();
iter.hasNext(); ) {
runtimes.add("\"" + iter.next() + "\"");
}
throw new CompilationError(
MessageFormat.format(
"Request for unknown runtime: The \"lzr\" query parameter has the value \"{0}\". It must be {1}{2}.",
new String[] {
runtime,
new ChoiceFormat(
"1#| 2#either | 2<one of ").
format(runtimes.size()),
new ListFormat("or").format(runtimes)
}));
}
}
String proxied = props.getProperty(CompilationEnvironment.PROXIED_PROPERTY);
mLogger.debug(
/* (non-Javadoc)
* @i18n.test
* @org-mes="looking for lzproxied, props= " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
Compiler.class.getName(),"051018-257", new Object[] {props.toString()})
);
if (proxied != null) {
mLogger.debug(
/* (non-Javadoc)
* @i18n.test
* @org-mes="setting lzproxied to " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
Compiler.class.getName(),"051018-266", new Object[] {proxied})
);
env.setProperty(CompilationEnvironment.PROXIED_PROPERTY, proxied);
}
String debug = props.getProperty(CompilationEnvironment.DEBUG_PROPERTY);
if (debug != null) {
env.setProperty(CompilationEnvironment.DEBUG_PROPERTY, debug);
}
String lzconsoledebug = props.getProperty(CompilationEnvironment.CONSOLEDEBUG_PROPERTY);
if (lzconsoledebug != null) {
env.setProperty(CompilationEnvironment.CONSOLEDEBUG_PROPERTY, lzconsoledebug);
}
String backtrace = props.getProperty(CompilationEnvironment.BACKTRACE_PROPERTY);
if (backtrace != null) {
if ("true".equals(backtrace)) {
env.setProperty(CompilationEnvironment.DEBUG_PROPERTY, "true" );
}
env.setProperty(CompilationEnvironment.BACKTRACE_PROPERTY, backtrace);
}
String profile = props.getProperty(CompilationEnvironment.PROFILE_PROPERTY);
if (profile != null) {
env.setProperty(CompilationEnvironment.PROFILE_PROPERTY, profile);
}
String logdebug = props.getProperty(CompilationEnvironment.LOGDEBUG_PROPERTY);
if (logdebug != null) {
env.setProperty(CompilationEnvironment.LOGDEBUG_PROPERTY, logdebug);
}
String sourcelocators = props.getProperty(CompilationEnvironment.SOURCELOCATOR_PROPERTY);
if (sourcelocators != null) {
env.setProperty(CompilationEnvironment.SOURCELOCATOR_PROPERTY, sourcelocators);
}
String trackLines = props.getProperty(CompilationEnvironment.TRACK_LINES);
if (trackLines != null) {
env.setProperty(CompilationEnvironment.TRACK_LINES, trackLines);
}
String nameFunctions = props.getProperty(CompilationEnvironment.NAME_FUNCTIONS);
if (nameFunctions != null) {
env.setProperty(CompilationEnvironment.NAME_FUNCTIONS, nameFunctions);
}
try {
mLogger.debug(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Parsing " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
Compiler.class.getName(),"051018-303", new Object[] {file.getAbsolutePath()})
);
// Initialize the schema from the base LFC interface file
try {
env.getSchema().loadSchema(env);
} catch (org.jdom.JDOMException e) {
throw new ChainedException(e);
}
Document doc = env.getParser().parse(file, env);
Element root = doc.getRootElement();
// Override passed in runtime target properties with the
// canvas values.
if ("true".equals(root.getAttributeValue("debug"))) {
env.setProperty(CompilationEnvironment.DEBUG_PROPERTY, true);
}
if ("true".equals(root.getAttributeValue("profile"))) {
env.setProperty(CompilationEnvironment.PROFILE_PROPERTY, true);
}
// cssfile cannot be set in the canvas tag
String cssfile = props.getProperty(CompilationEnvironment.CSSFILE_PROPERTY);
if (cssfile != null) {
mLogger.info("Got cssfile named: " + cssfile);
cssfile = root.getAttributeValue("cssfile");
throw new CompilationError(
"cssfile attribute of canvas is no longer supported. Use <stylesheet> instead.");
}
mLogger.debug("Making a writer...");
ViewSchema schema = env.getSchema();
Set externalLibraries = null;
// If we are not linking, then we consider all external
// files to have already been imported.
if (! linking) { externalLibraries = env.getImportedLibraryFiles(); }
if (root.getName().intern() !=
(linking ? "canvas" : "library")) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="invalid root element type: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
Compiler.class.getName(),"051018-357", new Object[] {root.getName()})
);
}
Compiler.updateRootSchema(root, env, schema, externalLibraries);
if (noCodeGeneration) {
return null;
}
Properties nprops = (Properties) env.getProperties().clone();
Map compileTimeConstants = new HashMap();
compileTimeConstants.put("$debug", new Boolean(
env.getBooleanProperty(CompilationEnvironment.DEBUG_PROPERTY)));
compileTimeConstants.put("$profile", new Boolean(
env.getBooleanProperty(CompilationEnvironment.PROFILE_PROPERTY)));
boolean backtraceValue = env.getBooleanProperty(CompilationEnvironment.BACKTRACE_PROPERTY);
compileTimeConstants.put("$backtrace", new Boolean(backtraceValue));
runtime = env.getProperty(env.RUNTIME_PROPERTY);
// Must be kept in sync with server/sc/lzsc.py main
compileTimeConstants.put("$runtime", runtime);
compileTimeConstants.put("$swf7", Boolean.valueOf("swf7".equals(runtime)));
compileTimeConstants.put("$swf8", Boolean.valueOf("swf8".equals(runtime)));
compileTimeConstants.put("$as2", Boolean.valueOf(Arrays.asList(new String[] {"swf7", "swf8"}).contains(runtime)));
compileTimeConstants.put("$swf9", Boolean.valueOf("swf9".equals(runtime)));
compileTimeConstants.put("$as3", Boolean.valueOf(Arrays.asList(new String[] {"swf9"}).contains(runtime)));
compileTimeConstants.put("$dhtml", Boolean.valueOf("dhtml".equals(runtime)));
compileTimeConstants.put("$j2me", Boolean.valueOf("j2me".equals(runtime)));
compileTimeConstants.put("$svg", Boolean.valueOf("svg".equals(runtime)));
compileTimeConstants.put("$js1", Boolean.valueOf(Arrays.asList(new String[] {"dhtml", "j2me", "svg"}).contains(runtime)));
// [todo: 2006-04-17 hqm] These compileTimeConstants will be used by the script compiler
// at compile time, but they won't be emitted into the object code for user apps. Only
// the compiled LFC emits code which defines these constants. We need to have some
// better way to ensure that the LFC's constants values match the app code's.
nprops.put("compileTimeConstants", compileTimeConstants);
ObjectWriter writer = createObjectWriter(nprops, ostr, env, root);
env.setObjectWriter(writer);
mLogger.debug("new env..." + env.getProperties().toString());
processCompilerInstructions(root, env);
compileElement(root, env);
if (linking) {
ViewCompiler.checkUnresolvedResourceReferences (env);
}
mLogger.debug("done...");
// This isn't in a finally clause, because it won't generally
// succeed if an error occurs.
writer.close();
Canvas canvas = env.getCanvas();
if (!errors.isEmpty()) {
if (canvas != null) {
canvas.setCompilationWarningText(
errors.toCompilationError().getMessage());
canvas.setCompilationWarningXML(
errors.toXML());
}
System.err.println(errors.toCompilationError().getMessage());
}
if (canvas != null) {
canvas.setBacktrace(backtraceValue);
// set file path (relative to webapp) in canvas
canvas.setFilePath(FileUtils.relativePath(file, LPS.HOME()));
}
mLogger.info("done");
return canvas;
} catch (CompilationError e) {
// TBD: e.initPathname(file.getPath());
e.attachErrors(errors.getErrors());
throw e;
//errors.addError(new CompilationError(e.getMessage() + "; compilation aborted"));
//throw errors.toCompilationError();
} catch (org.openlaszlo.xml.internal.MissingAttributeException e) {
/* The validator will have caught this, but if we simply
* pass the error through, the vaildation warnings will
* never be printed. Create a new message that includes
* them so that we get the source information. */
errors.addError(new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes=p[0] + "; compilation aborted"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
Compiler.class.getName(),"051018-399", new Object[] {e.getMessage()})
));
throw errors.toCompilationError();
}
}
public void compileAndWriteToSWF (String script, String seqnum, OutputStream out, String runtime) {
try {
CompilationEnvironment env = makeCompilationEnvironment();
env.setProperty(CompilationEnvironment.DEBUG_PROPERTY, true);
Properties props = (Properties) env.getProperties().clone();
env.setProperty(env.RUNTIME_PROPERTY, runtime);
byte[] action;
// Try compiling as an expression first. If that fails,
// compile as sequence of statements. If that fails too,
// report the parse error.
try {
String prog;
if (seqnum == null) {
prog = "(function () {\n" +
" #pragma 'scriptElement'\n" +
"_level0.Debug.displayResult(\n"+
script + "\n" +
");\n" +
"}());\n";
} else {
// it's a remote debug request, send a response to client
prog =
"(function () {\n" +
" #pragma 'scriptElement'\n" +
"_level0.Debug.displayResult(\n"+
" _level0.__LzDebug.sockWriteAsXML(\n"+script+","+seqnum+");\n" +
" );\n" +
"}());\n";
}
prog += "this._parent.loader.returnData( this._parent );";
action = ScriptCompiler.compileToByteArray(prog, props);
} catch (org.openlaszlo.sc.parser.ParseException e) {
try {
String wrapper =
" (function () {\n" +
" #pragma 'scriptElement'\n" +
CompilerUtils.sourceLocationDirective(null, new Integer(0), new Integer(0)) +
script+"\n"+
" if (Debug.remoteDebug) { _level0.__LzDebug.sockWriteAsXML(true,"+seqnum+");};\n" +
" }());\n" +
"this._parent.loader.returnData( this._parent )";
action = ScriptCompiler.compileToByteArray(wrapper, props);
} catch (org.openlaszlo.sc.parser.ParseException e2) {
//mLogger.info("not stmt: " + e);
action = ScriptCompiler.compileToByteArray(
"with(_level0) {Debug.__write(" +
ScriptCompiler.quote("Parse error: "+ e2.getMessage()) + ")}\n"
+ "this._parent.loader.returnData( this._parent )", props);
}
}
ScriptCompiler.writeScriptToStream(action, out, LPS.getSWFVersionNum(runtime));
out.flush();
out.close();
} catch (IOException e) {
mLogger.info(
/* (non-Javadoc)
* @i18n.test
* @org-mes="error compiling/writing script: " + p[0] + " :" + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
Compiler.class.getName(),"051018-458", new Object[] {script, e})
);
}
}
public void compileAndWriteToSWF9 (String script, String seqnum, OutputStream out) {
try {
Properties props = new Properties();
props.setProperty(CompilationEnvironment.RUNTIME_PROPERTY, "swf9");
props.setProperty("canvasWidth", "1000");
props.setProperty("canvasHeight", "600");
Map compileTimeConstants = new HashMap();
compileTimeConstants.put("$debug", new Boolean(true));
compileTimeConstants.put("$profile", new Boolean(false));
compileTimeConstants.put("$backtrace", new Boolean(false));
compileTimeConstants.put("$runtime", "swf9");
compileTimeConstants.put("$swf7", Boolean.valueOf(false));
compileTimeConstants.put("$swf8", Boolean.valueOf(false));
compileTimeConstants.put("$as2", Boolean.valueOf(false));
compileTimeConstants.put("$swf9", Boolean.valueOf(true));
compileTimeConstants.put("$as3", Boolean.valueOf(true));
compileTimeConstants.put("$dhtml", Boolean.valueOf(false));
compileTimeConstants.put("$j2me", Boolean.valueOf(false));
compileTimeConstants.put("$svg", Boolean.valueOf(false));
compileTimeConstants.put("$js1", Boolean.valueOf(false));
props.put("compileTimeConstants", compileTimeConstants);
props.setProperty(CompilationEnvironment.DEBUG_EVAL_PROPERTY, "true");
props.setProperty(CompilationEnvironment.DEBUG_PROPERTY, "true");
props.put(org.openlaszlo.sc.Compiler.SWF9_APP_CLASSNAME, SWF9Writer.DEBUG_EVAL_CLASSNAME);
props.put(org.openlaszlo.sc.Compiler.SWF9_WRAPPER_CLASSNAME, SWF9Writer.DEBUG_EVAL_CLASSNAME);
props.put(org.openlaszlo.sc.Compiler.SWF9_APPLICATION_PREAMBLE,
"public class " + SWF9Writer.DEBUG_EVAL_CLASSNAME +
" extends " + SWF9Writer.DEBUG_EVAL_SUPERCLASS + " {\n " + SWF9Writer.imports + "}\n");
byte[] objcode;
String prog = "public class DebugExec extends Sprite {\n" +
"#passthrough (toplevel:true) { \n" +
"import flash.display.*;\n" +
"import flash.errors.*;\n" +
"import flash.events.*;\n" +
"import flash.external.*;\n" +
"import flash.filters.*;\n" +
"import flash.geom.*;\n" +
"import flash.media.*;\n" +
"import flash.net.*;\n" +
"import flash.printing.*;\n" +
"import flash.profiler.*;\n" +
"import flash.sampler.*;\n" +
"import flash.system.*;\n" +
"import flash.text.*;\n" +
"import flash.ui.*;\n" +
"import flash.utils.*;\n" +
"import flash.xml.*;\n" +
"}
"public function DebugExec (...ignore) {runToplevelDefinitions();}\n" +
"public function write(...args):void {lzconsole.write(args.join(\" \"));}\n" +
"public function runToplevelDefinitions() {}\n" +
"}\n";
// Try compiling as an expression first. If that fails,
// compile as sequence of statements. If that fails too,
// report the parse error.
try {
String nprog = prog + "(function () { with(global) { try {\n"
+ "Debug.displayResult("+script +");\n"
+ "} catch (e) { "
+ " Debug.displayResult(e); \n"
+ "}\n"
+ "} })();";
objcode = ScriptCompiler.compileToByteArray(nprog, props);
} catch (org.openlaszlo.sc.parser.ParseException e) {
try {
String nprog = prog + "var mycode = (function () {\n"+
"with (global) { try {" + script +"} catch(e) {Debug.displayResult(e);} }\n});\n"+"mycode();\n";
objcode = ScriptCompiler.compileToByteArray(nprog, props);
} catch (Exception e2) {
mLogger.info("error compiling/writing script: " + e2.getMessage());
objcode = ScriptCompiler.compileToByteArray( prog +
"(function () { \n"
+ "Debug.displayResult(" + ScriptCompiler.quote("Parse error: "+ e2.getMessage()) + ");\n"
+ "})();",
props);
}
}
int total = FileUtils.sendToStream(new ByteArrayInputStream(objcode), out);
out.flush();
out.close();
} catch (IOException e) {
mLogger.info("error compiling/writing script: " + script);
}
}
static ElementCompiler getElementCompiler(Element element,
CompilationEnvironment env) {
if (CanvasCompiler.isElement(element)) {
return new CanvasCompiler(env);
} else if (ImportCompiler.isElement(element)) {
return new ImportCompiler(env);
} else if (LibraryCompiler.isElement(element)) {
return new LibraryCompiler(env);
} else if (ScriptElementCompiler.isElement(element)) {
return new ScriptElementCompiler(env);
} else if (DataCompiler.isElement(element)) {
return new DataCompiler(env);
} else if (SecurityCompiler.isElement(element)) {
return new SecurityCompiler(env);
} else if (SplashCompiler.isElement(element)) {
return new SplashCompiler(env);
} else if (FontCompiler.isElement(element)) {
return new FontCompiler(env);
} else if (ResourceCompiler.isElement(element)) {
return new ResourceCompiler(env);
} else if (ClassCompiler.isElement(element)) {
return new ClassCompiler(env);
} else if (MixinCompiler.isElement(element)) {
return new MixinCompiler(env);
} else if (InterfaceCompiler.isElement(element)) {
return new InterfaceCompiler(env);
} else if (DebugCompiler.isElement(element)) {
return new DebugCompiler(env);
} else if (StyleSheetCompiler.isElement(element)) {
return new StyleSheetCompiler(env);
// The following test tests true for everything, so call
// it last.
} else if (ViewCompiler.isElement(element)) {
return new ViewCompiler(env);
} else {
throw new CompilationError("unknown tag: " + element.getName(),
element);
}
}
/**
* Compile an XML element within the compilation environment.
* Helper function for compile.
*
* @param element an <code>Element</code> value
* @param env a <code>CompilationEnvironment</code> value
* @exception CompilationError if an error occurs
*/
protected static void compileElement(Element element,
CompilationEnvironment env)
throws CompilationError
{
if (element.getAttributeValue("disabled") != null &&
element.getAttributeValue("disabled").intern() == "true") {
return;
}
try {
ElementCompiler compiler = getElementCompiler(element, env);
mLogger.debug("compiling element "+element.getName() + " with compiler "+compiler.getClass().toString());
compiler.compile(element);
} catch (CompilationError e) {
// todo: wrap instead
if (e.getElement() == null && e.getPathname() == null) {
e.initElement(element);
}
throw e;
}
}
static void updateRootSchema(Element root, CompilationEnvironment env,
ViewSchema schema, Set externalLibraries)
{
ElementCompiler ecompiler = getElementCompiler(root, env);
if (! (ecompiler instanceof ToplevelCompiler)) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="invalid root element type: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
Compiler.class.getName(),"051018-357", new Object[] {root.getName()})
);
}
ToplevelCompiler tlc = (ToplevelCompiler) ecompiler;
Set visited = new HashSet();
// Update schema for auto-includes
// Note: this call does _not_ share visited with the update
// calls intentionally.
for (Iterator iter = tlc.getLibraries(env, root, null, externalLibraries, new HashSet()).iterator();
iter.hasNext(); ) {
File library = (File) iter.next();
Compiler.updateSchemaFromLibrary(library, env, schema, visited, externalLibraries);
}
tlc.updateSchema(root, schema, visited);
}
static void updateSchema(Element element, CompilationEnvironment env,
ViewSchema schema, Set visited)
{
getElementCompiler(element, env).updateSchema(element, schema, visited);
}
static void importLibrary(File file, CompilationEnvironment env) {
Element root = LibraryCompiler.resolveLibraryElement(
file, env, env.getImportedLibraryFiles());
if (root != null) {
compileElement(root, env);
}
}
static void updateSchemaFromLibrary(File file, CompilationEnvironment env,
ViewSchema schema, Set visited, Set externalLibraries)
{
Element root = LibraryCompiler.resolveLibraryElement(
file, env, visited);
if (root != null) {
try {
// Library keys are the canonical file name
File key = file.getCanonicalFile();
boolean old = env.getBooleanProperty(CompilationEnvironment._EXTERNAL_LIBRARY);
boolean extern = (externalLibraries != null) ? externalLibraries.contains(key) : false;
try {
env.setProperty(CompilationEnvironment._EXTERNAL_LIBRARY, extern);
Compiler.updateSchema(root, env, schema, visited);
} finally {
env.setProperty(CompilationEnvironment._EXTERNAL_LIBRARY, old);
}
} catch (java.io.IOException e) {
throw new CompilationError(root, e);
}
}
}
protected void processCompilerInstructions(Element element,
CompilationEnvironment env) {
for (Iterator iter = element.getContent().iterator();
iter.hasNext(); ) {
ProcessingInstruction pi;
try {
pi = (ProcessingInstruction) iter.next();
} catch (ClassCastException e) {
continue;
}
if (pi.getTarget().equals("lzc"))
processCompilerInstruction(env, pi);
}
}
protected void processCompilerInstruction(CompilationEnvironment env,
ProcessingInstruction pi) {
if (pi.getPseudoAttributeValue("class") != null)
processClassInstruction(env, pi.getPseudoAttributeValue("class"), pi);
if (pi.getPseudoAttributeValue("classes") != null) {
for (Iterator iter = Arrays.asList(pi.getPseudoAttributeValue("classes").split("\\s+")).iterator(); iter.hasNext(); ) {
processClassInstruction(env, (String) iter.next(), pi);
}
}
}
protected void processClassInstruction(CompilationEnvironment env,
String className,
ProcessingInstruction pi) {
String inlineString = pi.getPseudoAttributeValue("inline-only");
if (inlineString != null) {
boolean inline = Boolean.valueOf(inlineString).booleanValue();
ClassModel classModel = env.getSchema().getClassModel(className);
if (classModel == null) {
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes="A processor instruction refers to a class named \"" + p[0] + "\". No class with this name exists."
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
Compiler.class.getName(),"051018-603", new Object[] {className})
);
return;
}
classModel.setInline(inline);
}
}
}
|
package edu.wustl.catissuecore.flex.dag;
public class DAGConstant {
public static final String QUERY_OBJECT = "queryObject";
public static final String CONSTRAINT_VIEW_NODE ="ConstraintViewNode";
public static final String VIEW_ONLY_NODE="ViewOnlyNode";
public static final String CONSTRAINT_ONLY_NODE ="ConstraintOnlyNode";
public static final String HTML_STR="HTMLSTR";
public static final String EXPRESSION="EXPRESSION";
public static final String ADD_LIMIT="Add";
public static final String EDIT_LIMIT="Edit";
}
|
package net.yadaframework.web;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_AUTOCLOSE;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_BODY;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_CALLSCRIPT;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_REDIRECT;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_RELOADONCLOSE;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_SEVERITY;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_TITLE;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_TOTALSEVERITY;
import static net.yadaframework.core.YadaConstants.VAL_NOTIFICATION_SEVERITY_ERROR;
import static net.yadaframework.core.YadaConstants.VAL_NOTIFICATION_SEVERITY_INFO;
import static net.yadaframework.core.YadaConstants.VAL_NOTIFICATION_SEVERITY_OK;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities.EscapeMode;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StreamUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import net.yadaframework.components.YadaUtil;
import net.yadaframework.core.YadaConfiguration;
import net.yadaframework.core.YadaConstants;
import net.yadaframework.core.YadaLocalEnum;
import net.yadaframework.exceptions.YadaInvalidUsageException;
@Service
public class YadaWebUtil {
private final transient Logger log = LoggerFactory.getLogger(getClass());
@Autowired private YadaConfiguration config;
@Autowired private YadaUtil yadaUtil;
@Autowired private MessageSource messageSource;
public final Pageable FIND_ONE = new PageRequest(0, 1);
private Map<String, List<?>> sortedLocalEnumCache = new HashMap<>();
/**
* Copies the content of a file to the Response then deletes the file.
* To be used when the client needs to download a previously-created temporary file that you don't want to keep on server.
* Remember to set the "produces" attribute on the @RequestMapping with the appropriate content-type.
* @param tempFilename the name (without path) of the existing temporary file, created with Files.createTempFile()
* @param contentType the content-type header
* @param clientFilename the filename that will be used on the client browser
* @param response the HTTP response
* @return true if the file was sent without errors
*/
public boolean downloadTempFile(String tempFilename, String contentType, String clientFilename, HttpServletResponse response) {
Path tempFile = null;
try {
Path dummy = Files.createTempFile("x", null);
Path tempFolder = dummy.getParent();
yadaUtil.deleteFileSilently(dummy);
tempFile = tempFolder.resolve(tempFilename);
if (!Files.exists(tempFile)) {
log.info("Trying to download non-existent file {}", tempFile);
return false;
}
} catch (IOException e) {
log.error("Error sending temporary file to client", e);
return false;
}
return downloadFile(tempFile, true, contentType, clientFilename, response);
}
/**
* Copies the content of a file to the Response then deletes the file.
* To be used when the client needs to download a previously-created file that you don't want to keep on server.
* Remember to set the "produces" attribute on the @RequestMapping with the appropriate content-type.
* @param fileToDownload the existing file to download and delete
* @param thenDeleteFile true to delete the file when download ends (or fails)
* @param contentType the content-type header
* @param clientFilename the filename that will be used on the client browser
* @param response the HTTP response
* @return true if the file was sent without errors
*/
public boolean downloadFile(Path fileToDownload, boolean thenDeleteFile, String contentType, String clientFilename, HttpServletResponse response) {
try (InputStream resultStream = Files.newInputStream(fileToDownload)) {
response.setContentType(contentType);
response.setHeader("Content-Disposition", "attachment; filename=" + clientFilename);
StreamUtils.copy(resultStream, response.getOutputStream()); // StreamUtils doesn't close any stream
return true;
} catch (IOException e) {
log.error("Can't send temporary file to client", e);
} finally {
if (thenDeleteFile) {
boolean deleted = yadaUtil.deleteFileSilently(fileToDownload);
if (!deleted) {
log.error("Temporary file could not be deleted: {}", fileToDownload);
}
}
}
return false;
}
/**
* Create a redirect string to be returned by a @Controller, taking into account the locale in the path.
* If you can do a redirect with a relative url ("some/url") you don't need to use this method because the language path
* won't be overwritten. Otherwise if you need to use an absolute url ("/some/url") then this method inserts the appropriate language path
* in the url (and any parameters at the end too).
* @param targetUrl the redirect target, like "/some/place"
* @param locale can be null if the locale is not in the path, but then why use this method?
* @param params optional request parameters to be set on the url, in the form of comma-separated name,value pairs. E.g. id,123,name,"joe"
* Existing parameters are not replaced. Null values become empty strings. Null names are skipped with their values.
* @return a url like "redirect:/en/some/place?par1=val1&par2=val2"
* @throws YadaInvalidUsageException if path locale is configured and the url is absolute and the locale is null
*/
public String redirectString(String url, Locale locale, String...params) {
if (config.isLocalePathVariableEnabled() && url.startsWith("/") && locale==null) {
throw new YadaInvalidUsageException("Locale is needed when using the locale path variable with an absolute redirect");
}
String enhancedUrl = enhanceUrl(url, locale, params);
return "redirect:" + enhancedUrl;
}
/**
* Creates a new URL string from a starting one, taking into account the locale in the path and optional url parameters.
* @param url the original url, like "/some/place"
* @param locale added as a path in the url, only if the url is absolute. Can be null if the locale is not needed in the path
* @param params optional request parameters to be set on the url, in the form of comma-separated name,value pairs. E.g. "id","123","name","joe".
* Existing parameters are not replaced. Null values become empty strings. Null names are skipped with their values.
* @return a url like "/en/some/place?id=123&name=joe"
*/
public String enhanceUrl(String url, Locale locale, String...params) {
StringBuilder result = new StringBuilder();
if (config.isLocalePathVariableEnabled()) {
// The language is added only to absolute urls, if it doesn't exist yet
if (url.startsWith("/") && locale!=null) {
String language = locale.getLanguage();
if (!url.startsWith("/"+language+"/")) {
result.append("/").append(language);
}
}
}
result.append(url);
if (params!=null && params.length>0) {
boolean isStart = true;
int questionPos = result.indexOf("?");
if (questionPos<0) {
result.append("?");
} else {
if (url.length()>questionPos+1) {
// There is some parameter already
isStart = false;
}
}
boolean isName = true;
String lastName = null;
for (String param : params) {
if (isName && !isStart) {
result.append("&");
}
if (isName) { // name
// null names are skipped together with their value
if (param!=null) {
result.append(param);
result.append("=");
}
lastName = param;
} else { // value
if (lastName!=null) {
// Null values remain empty
if (param!=null) {
result.append(param);
}
} else {
log.debug("Skipping null name and its value '{}'", param);
}
}
isStart=false;
isName=!isName;
}
}
return result.toString();
}
/**
* Make a zip file and send it to the client. The temp file is automatically deleted.
* @param returnedFilename the name of the file to create and send, with extension. E.g.: data.zip
* @param sourceFiles the files to zip
* @param filenamesNoExtension the name of each file in the zip - null to keep the original names
* @param ignoreErrors true to ignore errors when adding a file and keep going, false for an exception when a file can't be zipped
* @param response
*/
public void downloadZip(String returnedFilename, File[] sourceFiles, String[] filenamesNoExtension, boolean ignoreErrors, HttpServletResponse response) throws Exception {
File zipFile = null;
try {
zipFile = File.createTempFile("downloadZip", null);
yadaUtil.createZipFile(zipFile, sourceFiles, filenamesNoExtension, ignoreErrors);
response.setContentType("application/zip");
response.setHeader("Content-disposition", "attachment; filename=" + returnedFilename);
try (OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(zipFile)) {
IOUtils.copy(in,out);
}
} finally {
if (zipFile!=null) {
zipFile.delete();
}
}
}
/**
* Sorts a localized enum according to the locale specified
* @param localEnum the class of the enum, e.g. net.yadaframework.persistence.entity.YadaJobState.class
* @param locale
* @return a list of sorted enums of the given class
*/
public <T extends YadaLocalEnum<?>> List<T> sortLocalEnum(Class<T> localEnum, Locale locale) {
String key = localEnum.getName() + "." + locale.toString();
@SuppressWarnings("unchecked")
List<T> result = (List<T>) sortedLocalEnumCache.get(key);
if (result==null) {
T[] enums = localEnum.getEnumConstants();
Arrays.sort(enums, new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
String v1 = o1.toString(messageSource, locale);
String v2 = o2.toString(messageSource, locale);
return v1.compareTo(v2);
}
});
result = Arrays.asList(enums);
sortedLocalEnumCache.put(key, result);
}
return result;
}
/**
* Returns the first language in the request language header as a string.
* @return the language string, like "en_US", or "" if not found
*/
public String getBrowserLanguage() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String languageHeader = StringUtils.trimToEmpty(request.getHeader("Accept-Language")); // en-US,en-GB;q=0.9,en;q=0.8,it;q=0.7,es;q=0.6,la;q=0.5
int pos = languageHeader.indexOf(',');
if (pos>4) {
try {
return languageHeader.substring(0, pos);
} catch (Exception e) {
// Invalid header - ignored
}
}
return "";
}
/**
* Returns the first country in the request language header as a string.
* @return the country string, like "US", or "" if not found
*/
public String getBrowserCountry() {
String browserLanguage = getBrowserLanguage();
int pos = browserLanguage.indexOf('-');
if (pos>1) {
try {
return browserLanguage.substring(pos+1);
} catch (Exception e) {
// Invalid header - ignored
}
}
return "";
}
public File saveAttachment(MultipartFile attachment) throws IOException {
if (!attachment.isEmpty()) {
File targetFile = File.createTempFile("upload-", null);
saveAttachment(attachment, targetFile);
return targetFile;
}
return null;
}
public void saveAttachment(MultipartFile attachment, Path targetPath) throws IOException {
saveAttachment(attachment, targetPath.toFile());
// try (InputStream inputStream = attachment.getInputStream(); OutputStream outputStream = new FileOutputStream(targetPath.toFile())) {
// IOUtils.copy(inputStream, outputStream);
}
public void saveAttachment(MultipartFile attachment, File targetFile) throws IOException {
attachment.transferTo(targetFile);
// try (InputStream inputStream = attachment.getInputStream(); OutputStream outputStream = new FileOutputStream(targetFile)) {
// IOUtils.copy(inputStream, outputStream);
}
/**
* From a given string, creates a "slug" that can be inserted in a url and still be readable.
* @param source the string to convert
* @return the slug
*/
public String makeSlug(String source) {
return makeSlugStatic(source);
}
/**
* From a given string, creates a "slug" that can be inserted in a url and still be readable.
* It is static so that it can be used in Entity objects (no context)
* @param source the string to convert
* @return the slug, which is empty for a null string
*/
public static String makeSlugStatic(String source) {
if (StringUtils.isBlank(source)) {
return "";
}
String slug = source.trim().toLowerCase().replace('à', 'a').replace('è', 'e').replace('é', 'e').replace('ì', 'i').replace('ò', 'o').replace('ù', 'u').replace('.', '-');
slug = slug.replaceAll(" +", "-"); // Spaces become dashes
slug = slug.replaceAll("[^\\w:,;=&!+~\\(\\)@\\*\\$\\'\\-]", "");
slug = StringUtils.removeEnd(slug, ".");
slug = StringUtils.removeEnd(slug, ";");
slug = StringUtils.removeEnd(slug, "\\");
slug = slug.replaceAll("-+", "-"); // Multiple dashes become one dash
return slug;
}
/**
* Decodes a string with URLDecoder, handling the useless try-catch that is needed
* @param source
* @return
*/
public String urlDecode(String source) {
final String encoding = "UTF-8";
try {
return URLDecoder.decode(source, encoding);
} catch (UnsupportedEncodingException e) {
log.error("Invalid encoding: {}", encoding);
}
return source;
}
/**
* Encodes a string with URLEncoder, handling the useless try-catch that is needed
* @param source
* @return
*/
public String urlEncode(String source) {
final String encoding = "UTF-8";
try {
return URLEncoder.encode(source, encoding);
} catch (UnsupportedEncodingException e) {
log.error("Invalid encoding: {}", encoding);
}
return source;
}
/**
* ATTENZIONE: non sempre va!
* @return
*/
public HttpServletRequest getCurrentRequest() {
return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
}
public boolean isAjaxRequest() {
return isAjaxRequest(getCurrentRequest());
}
public boolean isAjaxRequest(HttpServletRequest request) {
String ajaxHeader = request.getHeader("X-Requested-With");
return "XMLHttpRequest".equalsIgnoreCase(ajaxHeader);
}
/**
* Trasforma /res/img/favicon.ico in /res-0002/img/favicon.ico
* @param urlNotVersioned
* @return
*/
public String versionifyResourceUrl(String urlNotVersioned) {
// Esempio: var urlPrefix=[[@{${@yadaWebUtil.versionifyResourceUrl('/res/js/facebook/sdk.js')}}]];
final String resFolder="/" + config.getResourceDir() + "/"; // "/res/"
final int resLen = resFolder.length();
if (urlNotVersioned.startsWith(resFolder)) {
try {
String prefix = urlNotVersioned.substring(0, resLen-1);
String suffix = urlNotVersioned.substring(resLen-1);
return prefix + "-" + config.getApplicationBuild() + suffix;
} catch (Exception e) {
log.error("Impossibile versionificare la url {} (ignored)", urlNotVersioned, e);
}
}
return urlNotVersioned;
}
/**
* Cleans the html content leaving only the following tags: b, em, i, strong, u, br, cite, em, i, p, strong, img, li, ul, ol, sup, sub, s
* @param content html content
* @param extraTags any other tags that you may want to keep, e. g. "a"
* @return
*/
public String cleanContent(String content, String ... extraTags) {
Whitelist allowedTags = Whitelist.simpleText(); // This whitelist allows only simple text formatting: b, em, i, strong, u. All other HTML (tags and attributes) will be removed.
allowedTags.addTags("br", "cite", "em", "i", "p", "strong", "img", "li", "ul", "ol", "sup", "sub", "s");
allowedTags.addTags(extraTags);
allowedTags.addAttributes("p", "style"); // Serve per l'allineamento a destra e sinistra
allowedTags.addAttributes("img", "src", "style", "class");
if (Arrays.asList(extraTags).contains("a")) {
allowedTags.addAttributes("a", "href", "target");
}
Document dirty = Jsoup.parseBodyFragment(content, "");
Cleaner cleaner = new Cleaner(allowedTags);
Document clean = cleaner.clean(dirty);
clean.outputSettings().escapeMode(EscapeMode.xhtml); // Non fa l'escape dei caratteri utf-8
String safe = clean.body().html();
return safe;
}
public String getWebappAddress(HttpServletRequest request) {
int port = request.getServerPort();
String pattern = port==80||port==443?"%s://%s%s":"%s://%s:%d%s";
String myServerAddress = port==80||port==443?
String.format(pattern, request.getScheme(), request.getServerName(), request.getContextPath())
:
String.format(pattern, request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath());
return myServerAddress;
}
/**
* Indica se l'estensione appartiene a un'immagine accettabile
* @param extension e.g. "jpg"
* @return
*/
public boolean isWebImage(String extension) {
extension = extension.toLowerCase();
return extension.equals("jpg")
|| extension.equals("png")
|| extension.equals("gif")
|| extension.equals("tif")
|| extension.equals("tiff")
|| extension.equals("jpeg");
}
/**
* ritorna ad esempio "jpg" lowercase
* @param multipartFile
* @return
*/
public String getFileExtension(MultipartFile multipartFile) {
String result = null;
if (multipartFile!=null) {
String originalName = multipartFile.getOriginalFilename();
result = yadaUtil.getFileExtension(originalName);
}
return result;
}
/**
* Visualizza un errore se non viene fatto redirect
* @param title
* @param message
* @param model
* @deprecated Use YadaNotify instead
*/
@Deprecated
public String modalError(String title, String message, Model model) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_ERROR, null, model);
return "/yada/modalNotify";
}
/**
*
* @param title
* @param message
* @param model
* @return
* @deprecated Use YadaNotify instead
*/
@Deprecated
public String modalInfo(String title, String message, Model model) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_INFO, null, model);
return "/yada/modalNotify";
}
/**
*
* @param title
* @param message
* @param model
* @return
* @deprecated Use YadaNotify instead
*/
@Deprecated
public String modalOk(String title, String message, Model model) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_OK, null, model);
return "/yada/modalNotify";
}
/**
* Visualizza un errore se viene fatto redirect
* @param title
* @param message
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalError(String title, String message, RedirectAttributes redirectAttributes) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_ERROR, redirectAttributes);
}
/**
*
* @param title
* @param message
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalInfo(String title, String message, RedirectAttributes redirectAttributes) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_INFO, redirectAttributes);
}
/**
*
* @param title
* @param message
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalOk(String title, String message, RedirectAttributes redirectAttributes) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_OK, redirectAttributes);
}
/**
* Set the automatic closing time for the notification - no close button is shown
* @param milliseconds
* @param model
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalAutoclose(long milliseconds, Model model) {
model.addAttribute(KEY_NOTIFICATION_AUTOCLOSE, milliseconds);
}
/**
* Set the automatic closing time for the notification - no close button is shown
* @param milliseconds
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalAutoclose(long milliseconds, RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(KEY_NOTIFICATION_AUTOCLOSE, milliseconds);
}
/**
* Set the page to reload when the modal is closed
* @param model
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalReloadOnClose(Model model) {
model.addAttribute(KEY_NOTIFICATION_RELOADONCLOSE, KEY_NOTIFICATION_RELOADONCLOSE);
}
/**
* Set the page to reload when the modal is closed
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalReloadOnClose(RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(KEY_NOTIFICATION_RELOADONCLOSE, KEY_NOTIFICATION_RELOADONCLOSE);
}
@Deprecated
private void notifyModal(String title, String message, String severity, RedirectAttributes redirectAttributes) {
Map<String, ?> modelMap = redirectAttributes.getFlashAttributes();
// Mette nel flash tre array di stringhe che contengono titolo, messaggio e severity.
if (!modelMap.containsKey(KEY_NOTIFICATION_TITLE)) {
List<String> titles = new ArrayList<>();
List<String> bodies = new ArrayList<>();
List<String> severities = new ArrayList<>();
redirectAttributes.addFlashAttribute(KEY_NOTIFICATION_TITLE, titles);
redirectAttributes.addFlashAttribute(KEY_NOTIFICATION_BODY, bodies);
redirectAttributes.addFlashAttribute(KEY_NOTIFICATION_SEVERITY, severities);
}
// Aggiunge i nuovi valori
((List<String>)modelMap.get(KEY_NOTIFICATION_TITLE)).add(title);
((List<String>)modelMap.get(KEY_NOTIFICATION_BODY)).add(message);
((List<String>)modelMap.get(KEY_NOTIFICATION_SEVERITY)).add(severity);
String newTotalSeverity = calcTotalSeverity(modelMap, severity);
redirectAttributes.addFlashAttribute(KEY_NOTIFICATION_TOTALSEVERITY, newTotalSeverity);
}
/**
* Test if a modal is going to be opened when back to the view (usually after a redirect)
* @param request
* @return true if a modal is going to be opened
* @deprecated Use YadaNotify instead
*/
@Deprecated
public boolean isNotifyModalPending(HttpServletRequest request) {
Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
return flashMap!=null && (
flashMap.containsKey(KEY_NOTIFICATION_TITLE)
|| flashMap.containsKey(KEY_NOTIFICATION_BODY)
|| flashMap.containsKey(KEY_NOTIFICATION_SEVERITY)
);
}
/**
* Da usare direttamente solo quando si vuole fare un redirect dopo aver mostrato un messaggio.
* Se chiamato tante volte, i messaggi si sommano e vengono mostrati tutti all'utente.
* @param title
* @param message
* @param severity a string like YadaConstants.VAL_NOTIFICATION_SEVERITY_OK
* @param redirectSemiurl e.g. "/user/profile"
* @param model
* @see YadaConstants
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void notifyModal(String title, String message, String severity, String redirectSemiurl, Model model) {
if (severity==VAL_NOTIFICATION_SEVERITY_ERROR) {
// Tutte le notifiche di errore vengono loggate a warn (potrebbero non essere degli errori del programma)
log.warn("notifyModal: {} - {}", title, message);
}
// Mette nel model tre array di stringhe che contengono titolo, messaggio e severity.
if (!model.containsAttribute(KEY_NOTIFICATION_TITLE)) {
List<String> titles = new ArrayList<>();
List<String> bodies = new ArrayList<>();
List<String> severities = new ArrayList<>();
model.addAttribute(KEY_NOTIFICATION_TITLE, titles);
model.addAttribute(KEY_NOTIFICATION_BODY, bodies);
model.addAttribute(KEY_NOTIFICATION_SEVERITY, severities);
}
// Aggiunge i nuovi valori
Map<String, Object> modelMap = model.asMap();
((List<String>)modelMap.get(KEY_NOTIFICATION_TITLE)).add(title);
((List<String>)modelMap.get(KEY_NOTIFICATION_BODY)).add(message);
((List<String>)modelMap.get(KEY_NOTIFICATION_SEVERITY)).add(severity);
if (redirectSemiurl!=null) {
model.addAttribute(KEY_NOTIFICATION_REDIRECT, redirectSemiurl);
}
String newTotalSeverity = calcTotalSeverity(modelMap, severity);
model.addAttribute(KEY_NOTIFICATION_TOTALSEVERITY, newTotalSeverity);
}
/**
* Return true if modalError has been called before
* @param model
* @return
* @deprecated Use YadaNotify instead
*/
@Deprecated
public boolean isModalError(Model model) {
return model.asMap().containsValue(VAL_NOTIFICATION_SEVERITY_ERROR);
}
/**
* Return true if for this thread the notifyModal (or a variant) has been called
* @param model
* @return
* @deprecated Use YadaNotify instead
*/
@Deprecated
public boolean isNotifyModalRequested(Model model) {
return model.containsAttribute(KEY_NOTIFICATION_TITLE);
}
@Deprecated
private String calcTotalSeverity(Map<String, ?> modelMap, String lastSeverity) {
// Algoritmo:
// - per cui
String newTotalSeverity = lastSeverity;
String currentTotalSeverity = (String) modelMap.get(KEY_NOTIFICATION_TOTALSEVERITY);
if (VAL_NOTIFICATION_SEVERITY_ERROR.equals(currentTotalSeverity)) {
return currentTotalSeverity; // ERROR wins always
}
if (VAL_NOTIFICATION_SEVERITY_OK.equals(lastSeverity) && VAL_NOTIFICATION_SEVERITY_INFO.equals(currentTotalSeverity)) {
newTotalSeverity = currentTotalSeverity; // INFO wins over OK
}
return newTotalSeverity;
}
// private void notifyModalSetValue(String title, String message, String severity, String redirectSemiurl, Model model) {
// model.addAttribute(KEY_NOTIFICATION_TITLE, title);
// model.addAttribute(KEY_NOTIFICATION_BODY, message);
// model.addAttribute(KEY_NOTIFICATION_SEVERITY, severity);
// if (redirectSemiurl!=null) {
// model.addAttribute(KEY_NOTIFICATION_REDIRECT, redirectSemiurl);
public String getClientIp(HttpServletRequest request) {
String remoteAddr = request.getRemoteAddr();
String forwardedFor = request.getHeader("X-Forwarded-For");
String remoteIp = "?";
if (!StringUtils.isBlank(remoteAddr)) {
remoteIp = remoteAddr;
}
if (!StringUtils.isBlank(forwardedFor)) {
remoteIp = "[for " + forwardedFor + "]";
}
return remoteIp;
}
/**
*
* @param message text to be displayed (can be null for default value)
* @param confirmButton text of the confirm button (can be null for default value)
* @param cancelButton text of the cancel button (can be null for default value)
* @param model
*/
public String modalConfirm(String message, String confirmButton, String cancelButton, Model model) {
return modalConfirm(message, confirmButton, cancelButton, model, false, false);
}
/**
* Show the confirm modal and reloads when the confirm button is pressed, adding the confirmation parameter to the url.
* The modal will be opened on load.
* Usually used by non-ajax methods.
* @param message text to be displayed (can be null for default value)
* @param confirmButton text of the confirm button (can be null for default value)
* @param cancelButton text of the cancel button (can be null for default value)
* @param model
*/
public String modalConfirmAndReload(String message, String confirmButton, String cancelButton, Model model) {
return modalConfirm(message, confirmButton, cancelButton, model, true, true);
}
/**
* Show the confirm modal and optionally reloads when the confirm button is pressed
* @param message text to be displayed (can be null for default value)
* @param confirmButton text of the confirm button (can be null for default value)
* @param cancelButton text of the cancel button (can be null for default value)
* @param model
* @param reloadOnConfirm (optional) when true, the browser will reload on confirm, adding the confirmation parameter to the url
* @param openModal (optional) when true, the modal will be opened. To be used when the call is not ajax
*/
public String modalConfirm(String message, String confirmButton, String cancelButton, Model model, Boolean reloadOnConfirm, Boolean openModal) {
model.addAttribute("message", message);
model.addAttribute("confirmButton", confirmButton);
model.addAttribute("cancelButton", cancelButton);
if (openModal) {
model.addAttribute("openModal", true);
}
if (reloadOnConfirm) {
model.addAttribute("reloadOnConfirm", true);
}
return "/yada/modalConfirm";
}
/**
* Add a script id to call when opening the notification modal
* @param scriptId
* @param model
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void callScriptOnModal(String scriptId, Model model) {
if (!model.containsAttribute(KEY_NOTIFICATION_CALLSCRIPT)) {
List<String> scriptIds = new ArrayList<>();
model.addAttribute(KEY_NOTIFICATION_CALLSCRIPT, scriptIds);
}
Map<String, Object> modelMap = model.asMap();
((List<String>)modelMap.get(KEY_NOTIFICATION_CALLSCRIPT)).add(scriptId);
}
}
|
package me.akuz.mnist.digits.neo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import me.akuz.core.DecimalFmt;
import me.akuz.core.geom.ByteImage;
import me.akuz.core.logs.LocalMonitor;
import me.akuz.core.logs.Monitor;
import me.akuz.core.math.NIGDist;
import me.akuz.core.math.NIGDistUtils;
import me.akuz.core.math.StatsUtils;
import me.akuz.mnist.digits.ProbImage;
/**
* Infers pixel categories from pixel intensities.
*
*/
public final class InferCAT {
private static final int PRIOR_SAMPLES = 1000;
private final List<ByteImage> _pixelImages;
private final List<ProbImage> _featureImages;
// private List<ProbImage> _parentFeatureImages;
// private List<ProbImage> _parentOpacityImages;
private final int _featureDim;
private double[] _featureProbs;
private NIGDist[] _featureDists;
public InferCAT(
final List<ByteImage> images,
final int featureDim) {
if (featureDim < 2 || featureDim > 255) {
throw new IllegalArgumentException("Argument featureDim must within interval [2,255]");
}
_pixelImages = images;
_featureDim = featureDim;
_featureImages = new ArrayList<>(images.size());
for (int i=0; i<images.size(); i++) {
final ByteImage pixelImage = images.get(i);
final ProbImage featureImage = new ProbImage(pixelImage.getRowCount(), pixelImage.getColCount(), featureDim);
_featureImages.add(featureImage);
}
}
public final void execute(
final Monitor parentMonitor,
final int maxIterationCount,
final double logLikeChangeThreshold) {
if (maxIterationCount <= 0) {
throw new IllegalArgumentException("Max iteration count must be positive");
}
if (logLikeChangeThreshold <= 0) {
throw new IllegalArgumentException("LogLike change threshold must be positive");
}
final Monitor monitor = parentMonitor == null ? null : new LocalMonitor(this.getClass().getSimpleName(), parentMonitor);
double[] currFeatureProbs = new double[_featureDim];
Arrays.fill(currFeatureProbs, 1.0 / _featureDim);
double[] nextFeatureProbs = new double[_featureDim];
Arrays.fill(nextFeatureProbs, 0);
NIGDist[] currFeatureDists = NIGDistUtils.createPriorsOnIntervalEvenly(_featureDim, 0.0, 1.0, PRIOR_SAMPLES);
NIGDist[] nextFeatureDists = NIGDistUtils.createPriorsOnIntervalEvenly(_featureDim, 0.0, 1.0, PRIOR_SAMPLES);
int iter = 0;
double prevLogLike = Double.NaN;
double[] logLikes = new double[_featureDim];
if (monitor != null) {
monitor.write("Total " + _pixelImages.size() + " images");
monitor.write("Starting with:");
for (int k=0; k<_featureDim; k++) {
monitor.write("Feature
monitor.write(" Prob: " + DecimalFmt.formatZeroSpacePlus8D(currFeatureProbs[k]));
monitor.write(" Dist: " + currFeatureDists[k]);
}
}
while (true) {
iter += 1;
if (monitor != null) {
monitor.write("Iteration " + iter);
}
double currLogLike = 0;
for (int imageIndex=0; imageIndex<_pixelImages.size(); imageIndex++) {
if (monitor != null) {
if ((imageIndex+1) % 100 == 0) {
monitor.write((imageIndex+1) + " images processed");
}
}
final ByteImage pixelImage = _pixelImages.get(imageIndex);
final ProbImage featureImage = _featureImages.get(imageIndex);
for (int row=0; row<pixelImage.getRowCount(); row++) {
for (int col=0; col<pixelImage.getColCount(); col++) {
// calc pixel feature logLikes
for (int k=0; k<_featureDim; k++) {
logLikes[k]
= Math.log(currFeatureProbs[k])
+ Math.log(currFeatureDists[k].getProb(pixelImage.getIntensity(row, col)));
}
// add to current log likelihood
currLogLike += StatsUtils.logSumExp(logLikes);
// normalize probabilities of features
StatsUtils.logLikesToProbsReplace(logLikes);
// save feature probs to feature image
final double[] featureProbs = featureImage.getFeatureProbs(row, col);
for (int k=0; k<_featureDim; k++) {
featureProbs[k] = logLikes[k];
}
// add to next feature probs
for (int k=0; k<_featureDim; k++) {
nextFeatureProbs[k] += featureProbs[k];
}
for (int k=0; k<_featureDim; k++) {
if (featureProbs[k] > 0) {
nextFeatureDists[k].addObservation(pixelImage.getIntensity(row, col), featureProbs[k]);
}
}
}
}
}
// normalize next probs
StatsUtils.normalize(nextFeatureProbs);
// update current probs
{
double[] tmp = currFeatureProbs;
currFeatureProbs = nextFeatureProbs;
nextFeatureProbs = tmp;
Arrays.fill(nextFeatureProbs, 0);
}
{
currFeatureDists = nextFeatureDists;
nextFeatureDists = NIGDistUtils.createPriorsOnIntervalEvenly(_featureDim, 0.0, 1.0, PRIOR_SAMPLES);
}
if (monitor != null) {
for (int k=0; k<_featureDim; k++) {
monitor.write("Feature
monitor.write(" Prob: " + DecimalFmt.formatZeroSpacePlus8D(currFeatureProbs[k]));
monitor.write(" Dist: " + currFeatureDists[k]);
}
monitor.write("LogLike: " + currLogLike + " (" + prevLogLike + ")");
}
// check log like error
if (Double.isNaN(currLogLike)) {
if (monitor != null) {
monitor.write("Log likelihood is NAN");
}
throw new IllegalStateException("Log likelihood is NAN.");
}
// check log like
if (currLogLike < prevLogLike) {
if (monitor != null) {
monitor.write("Log likelihood fell, but we don't stop");
}
} else {
// check if converged
if (Double.isNaN(prevLogLike) == false &&
Math.abs(prevLogLike - currLogLike) < logLikeChangeThreshold) {
if (monitor != null) {
monitor.write("Log likelihood converged.");
}
break;
}
}
// check if max iterations
if (iter >= maxIterationCount) {
if (monitor != null) {
monitor.write("Done max iterations (" + iter + ").");
}
break;
}
prevLogLike = currLogLike;
}
_featureProbs = currFeatureProbs;
_featureDists = currFeatureDists;
}
public int getFeatureDim() {
return _featureDim;
}
public double[] getFeatureProbs() {
return _featureProbs;
}
public NIGDist[] getFeatureDists() {
return _featureDists;
}
public List<ProbImage> getFeatureImages() {
return _featureImages;
}
}
|
package com.mapswithme.maps.location;
import android.annotation.SuppressLint;
import android.net.SSLCertificateSocketFactory;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.mapswithme.maps.BuildConfig;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
/**
* Implements interface that will be used by the core for
* sending/receiving the raw data trough platform socket interface.
* <p>
* The instance of this class is supposed to be created in JNI layer
* and supposed to be used in the thread safe environment, i.e. thread safety
* should be provided externally (by the client of this class).
* <p>
* <b>All public methods are blocking and shouldn't be called from the main thread.</b>
*/
class PlatformSocket
{
private final static int DEFAULT_TIMEOUT = 30 * 1000;
private final static String TAG = PlatformSocket.class.getSimpleName();
@NonNull
private final static Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.GPS_TRACKING);
private static volatile long sSslConnectionCounter;
@Nullable
private Socket mSocket;
@Nullable
private String mHost;
private int mPort;
private int mTimeout = DEFAULT_TIMEOUT;
PlatformSocket()
{
sSslConnectionCounter = 0;
LOGGER.d(TAG, "***********************************************************************************");
LOGGER.d(TAG, "Platform socket is created by core, ssl connection counter is discarded.");
}
public boolean open(@NonNull String host, int port)
{
if (mSocket != null)
{
LOGGER.e(TAG, "Socket is already opened. Seems that it wasn't closed.");
return false;
}
if (!isPortAllowed(port))
{
LOGGER.e(TAG, "A wrong port number = " + port + ", it must be within (0-65535) range");
return false;
}
mHost = host;
mPort = port;
Socket socket = createSocket(host, port, true);
if (socket != null && socket.isConnected())
{
setReadSocketTimeout(socket, mTimeout);
mSocket = socket;
}
return mSocket != null;
}
private static boolean isPortAllowed(int port)
{
return port >= 0 && port <= 65535;
}
@Nullable
private static Socket createSocket(@NonNull String host, int port, boolean ssl)
{
return ssl ? createSslSocket(host, port) : createRegularSocket(host, port);
}
@Nullable
private static Socket createSslSocket(@NonNull String host, int port)
{
Socket socket = null;
try
{
SocketFactory sf = getSocketFactory();
socket = sf.createSocket(host, port);
sSslConnectionCounter++;
LOGGER.d(TAG, "
LOGGER.d(TAG, sSslConnectionCounter + " ssl connection is established.");
}
catch (IOException e)
{
LOGGER.e(TAG, "Failed to create the ssl socket, mHost = " + host + " mPort = " + port);
}
return socket;
}
@Nullable
private static Socket createRegularSocket(@NonNull String host, int port)
{
Socket socket = null;
try
{
socket = new Socket(host, port);
LOGGER.d(TAG, "Regular socket is created and tcp handshake is passed successfully");
}
catch (IOException e)
{
LOGGER.e(TAG, "Failed to create the socket, mHost = " + host + " mPort = " + port);
}
return socket;
}
@SuppressLint("SSLCertificateSocketFactoryGetInsecure")
@NonNull
private static SocketFactory getSocketFactory()
{
// Trusting to any ssl certificate factory that will be used in
// debug mode, for testing purposes only.
if (BuildConfig.DEBUG)
//TODO: implement the custom KeyStore to make the self-signed certificates work
return SSLCertificateSocketFactory.getInsecure(0, null);
return SSLSocketFactory.getDefault();
}
public void close()
{
if (mSocket == null)
{
LOGGER.d(TAG, "Socket is already closed or it wasn't opened yet\n");
return;
}
try
{
mSocket.close();
LOGGER.d(TAG, "Socket has been closed: " + this + "\n");
} catch (IOException e)
{
LOGGER.e(TAG, "Failed to close socket: " + this + "\n");
} finally
{
mSocket = null;
}
}
public boolean read(@NonNull byte[] data, int count)
{
if (!checkSocketAndArguments(data, count))
return false;
LOGGER.d(TAG, "Reading method is started, data.length = " + data.length + ", count = " + count);
long startTime = SystemClock.elapsedRealtime();
int readBytes = 0;
try
{
if (mSocket == null)
throw new AssertionError("mSocket cannot be null");
InputStream in = mSocket.getInputStream();
while (readBytes != count && (SystemClock.elapsedRealtime() - startTime) < mTimeout)
{
try
{
LOGGER.d(TAG, "Attempting to read " + count + " bytes from offset = " + readBytes);
int read = in.read(data, readBytes, count - readBytes);
if (read == -1)
{
LOGGER.d(TAG, "All data is read from the stream, read bytes count = " + readBytes + "\n");
break;
}
if (read == 0)
{
LOGGER.e(TAG, "0 bytes are obtained. It's considered as error\n");
break;
}
LOGGER.d(TAG, "Read bytes count = " + read + "\n");
readBytes += read;
} catch (SocketTimeoutException e)
{
long readingTime = SystemClock.elapsedRealtime() - startTime;
LOGGER.e(TAG, "Socked timeout has occurred after " + readingTime + " (ms)\n ");
if (readingTime > mTimeout)
{
LOGGER.e(TAG, "Socket wrapper timeout has occurred, requested count = " +
(count - readBytes) + ", readBytes = " + readBytes + "\n");
break;
}
}
}
} catch (IOException e)
{
LOGGER.e(TAG, "Failed to read data from socket: " + this + "\n");
}
return count == readBytes;
}
public boolean write(@NonNull byte[] data, int count)
{
if (!checkSocketAndArguments(data, count))
return false;
LOGGER.d(TAG, "Writing method is started, data.length = " + data.length + ", count = " + count);
long startTime = SystemClock.elapsedRealtime();
try
{
if (mSocket == null)
throw new AssertionError("mSocket cannot be null");
OutputStream out = mSocket.getOutputStream();
out.write(data, 0, count);
LOGGER.d(TAG, count + " bytes are written\n");
return true;
} catch (SocketTimeoutException e)
{
long writingTime = SystemClock.elapsedRealtime() - startTime;
LOGGER.e(TAG, "Socked timeout has occurred after " + writingTime + " (ms)\n");
} catch (IOException e)
{
LOGGER.e(TAG, "Failed to write data to socket: " + this + "\n");
}
return false;
}
private boolean checkSocketAndArguments(@NonNull byte[] data, int count)
{
if (mSocket == null)
{
LOGGER.e(TAG, "Socket must be opened before reading/writing\n");
return false;
}
if (count < 0 || count > data.length)
{
LOGGER.e(TAG, "Illegal arguments, data.length = " + data.length + ", count = " + count + "\n");
return false;
}
return true;
}
public void setTimeout(int millis)
{
mTimeout = millis;
LOGGER.d(TAG, "Setting the socket wrapper timeout = " + millis + " ms\n");
}
private void setReadSocketTimeout(@NonNull Socket socket, int millis)
{
try
{
socket.setSoTimeout(millis);
} catch (SocketException e)
{
LOGGER.e(TAG, "Failed to set system socket timeout: " + millis + "ms, " + this + "\n");
}
}
@Override
public String toString()
{
return "PlatformSocket{" +
"mSocket=" + mSocket +
", mHost='" + mHost + '\'' +
", mPort=" + mPort +
'}';
}
}
|
package cn.crap.service.tool;
import cn.crap.dto.LoginInfoDto;
import cn.crap.dto.PickDto;
import cn.crap.enumer.*;
import cn.crap.framework.MyException;
import cn.crap.model.mybatis.*;
import cn.crap.service.IPickService;
import cn.crap.service.custom.CustomModuleService;
import cn.crap.service.mybatis.ArticleService;
import cn.crap.service.mybatis.ProjectService;
import cn.crap.service.mybatis.RoleService;
import cn.crap.utils.IConst;
import cn.crap.utils.LoginUserHelper;
import cn.crap.utils.MyString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
*
*
*
* @author Ehsan
*/
@Service("adminPickService")
public class AdminPickService implements IPickService{
@Autowired
private ProjectService projectService;
@Autowired
private ArticleService articleService;
@Autowired
private CustomModuleService customModuleService;
@Autowired
private RoleService roleService;
@Override
public List<PickDto> getPickList(String code, String key) throws MyException {
PickCode pickCode = PickCode.getByCode(code);
if (pickCode == null) {
throw new MyException(MyError.E000065, "code ");
}
LoginInfoDto user = LoginUserHelper.getUser();
if (user.getType() != UserType.ADMIN.getType()) {
throw new MyException(MyError.E000065, "");
}
List<PickDto> picks = new ArrayList<>();
PickDto pick = null;
String preUrl = "";
ProjectCriteria projectCriteria = new ProjectCriteria();
ArticleCriteria articleCriteria = new ArticleCriteria();
switch (pickCode) {
case AUTH:
pick = new PickDto(IConst.SEPARATOR, "");
picks.add(pick);
for (DataType dataType : DataType.values()) {
pick = new PickDto(dataType.name(), dataType.getName());
picks.add(pick);
}
return picks;
case ROLE:
pick = new PickDto(IConst.C_SUPER, "");
picks.add(pick);
for (Role r : roleService.selectByExample(new RoleCriteria())) {
pick = new PickDto(r.getId(), r.getRoleName());
picks.add(pick);
}
return picks;
case MODEL_NAME:
pick = new PickDto("modelName_1", "", "");
picks.add(pick);
pick = new PickDto("modelName_2", "", "");
picks.add(pick);
pick = new PickDto("modelName_3", "", "");
picks.add(pick);
pick = new PickDto("modelName_4", "", "");
picks.add(pick);
pick = new PickDto("modelName_5", "", "");
picks.add(pick);
return picks;
case INDEX_PAGE:
for (IndexPageUrl indexPage : IndexPageUrl.values()) {
pick = new PickDto(indexPage.name(), indexPage.getValue(), indexPage.getName());
picks.add(pick);
}
pick = new PickDto(IConst.SEPARATOR, "");
picks.add(pick);
projectCriteria.createCriteria().andStatusEqualTo(ProjectStatus.RECOMMEND.getStatus());
for (Project project : projectService.selectByExample(projectCriteria)) {
pick = new PickDto(project.getId(), String.format(IConst.FRONT_PROJECT_URL, project.getId()), project.getName());
picks.add(pick);
}
pick = new PickDto(IConst.SEPARATOR, "");
picks.add(pick);
pick = new PickDto("recommend_article", "index.do#NULL/article/list/NULL/ARTICLE/NULL/NULL/" + ArticleStatus.RECOMMEND.getStatus(), "");
picks.add(pick);
preUrl = "index.do#/NULL/article/detail/NULL/PAGE/";
articleCriteria.createCriteria().andStatusEqualTo(ArticleStatus.PAGE.getStatus()).andMkeyIsNotNull();
for (Article w : articleService.selectByExample(articleCriteria)) {
pick = new PickDto("wp_" + w.getMkey(), preUrl + w.getMkey(), w.getName()+" []");
picks.add(pick);
}
return picks;
case MENU_URL:
pick = new PickDto(IConst.SEPARATOR, "");
picks.add(pick);
pick = new PickDto("m_myproject", "index.do#/project/list/true/NULL", "");
picks.add(pick);
pick = new PickDto("recommend_project", "index.do#/project/list/false/NULL", "");
picks.add(pick);
pick = new PickDto(IConst.SEPARATOR, "");
picks.add(pick);
projectCriteria.createCriteria().andStatusEqualTo(ProjectStatus.RECOMMEND.getStatus());
for (Project project : projectService.selectByExample(projectCriteria)) {
pick = new PickDto(project.getId(), String.format(IConst.FRONT_PROJECT_URL, project.getId()), project.getName());
picks.add(pick);
}
pick = new PickDto(IConst.SEPARATOR, "");
picks.add(pick);
pick = new PickDto("recommend_article", "index.do#NULL/article/list/NULL/ARTICLE/NULL/NULL/" + ArticleStatus.RECOMMEND.getStatus(), "");
picks.add(pick);
preUrl = "index.do#/NULL/article/detail/NULL/PAGE/";
articleCriteria.createCriteria().andStatusEqualTo(ArticleStatus.PAGE.getStatus()).andMkeyIsNotNull();
for (Article w : articleService.selectByExample(articleCriteria)) {
pick = new PickDto("wp_" + w.getMkey(), preUrl + w.getMkey(), w.getName()+" []");
picks.add(pick);
}
return picks;
case USER_TYPE:
for (UserType type : UserType.values()) {
pick = new PickDto("user-type" + type.getType(), type.getType() + "", type.getName());
picks.add(pick);
}
return picks;
case ARTICLE_STATUS:
for (ArticleStatus status : ArticleStatus.values()) {
pick = new PickDto("article-status" + status.getStatus(), status.getStatus() + "", status.getName());
picks.add(pick);
}
return picks;
}
throw new MyException(MyError.E000065, "");
}
}
|
package org.dukecon.model.user;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.dukecon.model.Identifyable;
/**
* @author Gerd Aschemann <gerd@aschemann.net>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserPreference implements Identifyable {
private String id;
@NonNull private String eventId;
private int version;
}
|
package com.ternaryop.photoshelf.birthday;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.ternaryop.photoshelf.R;
import com.ternaryop.photoshelf.activity.BirthdaysPublisherActivity;
import com.ternaryop.photoshelf.db.Birthday;
import com.ternaryop.photoshelf.db.BirthdayDAO;
import com.ternaryop.photoshelf.db.DBHelper;
import com.ternaryop.photoshelf.db.PostTag;
import com.ternaryop.photoshelf.db.PostTagDAO;
import com.ternaryop.tumblr.Tumblr;
import com.ternaryop.tumblr.TumblrPhotoPost;
import com.ternaryop.utils.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class BirthdayUtils {
private static final String BIRTHDAY_NOTIFICATION_TAG = "com.ternaryop.photoshelf.bday";
private static final int BIRTHDAY_NOTIFICATION_ID = 1;
public static final String DESKTOP_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0";
public static boolean notifyBirthday(Context context) {
BirthdayDAO birthdayDatabaseHelper = DBHelper
.getInstance(context.getApplicationContext())
.getBirthdayDAO();
Calendar now = Calendar.getInstance(Locale.US);
List<Birthday> list = birthdayDatabaseHelper.getBirthdayByDate(now.getTime());
if (list.isEmpty()) {
return false;
}
int currYear = now.get(Calendar.YEAR);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context.getApplicationContext())
.setContentIntent(createPendingIntent(context))
.setSmallIcon(R.drawable.stat_notify_bday);
if (list.size() == 1) {
Birthday birthday = list.get(0);
builder.setContentTitle(context.getResources().getQuantityString(R.plurals.birthday_title, list.size()));
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(birthday.getBirthDate());
int years = currYear - cal.get(Calendar.YEAR);
builder.setContentText(context.getString(R.string.birthday_years_old, birthday.getName(), years));
} else {
builder.setContentTitle(context.getResources().getQuantityString(R.plurals.birthday_title, list.size(), list.size()));
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(context.getString(R.string.birthday_notification_title));
for (Birthday birthday : list) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(birthday.getBirthDate());
int years = currYear - cal.get(Calendar.YEAR);
inboxStyle.addLine(context.getString(R.string.birthday_years_old, birthday.getName(), years));
}
builder.setStyle(inboxStyle);
}
// remove notification when user clicks on it
builder.setAutoCancel(true);
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager)context.getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(BIRTHDAY_NOTIFICATION_TAG, BIRTHDAY_NOTIFICATION_ID, notification);
return true;
}
private static PendingIntent createPendingIntent(Context context) {
// Define Activity to start
Intent resultIntent = new Intent(context, BirthdaysPublisherActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack
stackBuilder.addParentStack(BirthdaysPublisherActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
return resultPendingIntent;
}
public static List<TumblrPhotoPost> getPhotoPosts(final Context context, Calendar birthDate) {
DBHelper dbHelper = DBHelper
.getInstance(context.getApplicationContext());
List<Birthday> birthDays = dbHelper
.getBirthdayDAO()
.getBirthdayByDate(birthDate.getTime());
ArrayList<TumblrPhotoPost> posts = new ArrayList<TumblrPhotoPost>();
PostTagDAO postTagDAO = dbHelper.getPostTagDAO();
Map<String, String> params = new HashMap<String, String>(2);
params.put("type", "photo");
for (Birthday b : birthDays) {
PostTag postTag = postTagDAO.getRandomPostByTag(b.getName(), b.getTumblrName());
if (postTag != null) {
params.put("id", String.valueOf(postTag.getId()));
TumblrPhotoPost post = (TumblrPhotoPost)Tumblr.getSharedTumblr(context)
.getPublicPosts(b.getTumblrName(), params).get(0);
posts.add(post);
}
}
return posts;
}
public static void publishedInAgeRange(Context context, int fromAge, int toAge, int daysPeriod, String postTags, String tumblrName) {
if (fromAge != 0 && toAge != 0) {
throw new IllegalArgumentException("fromAge or toAge can't be both set to 0");
}
String message;
if (fromAge == 0) {
message = context.getString(R.string.week_selection_under_age, toAge);
} else if (toAge == 0) {
message = context.getString(R.string.week_selection_over_age, fromAge);
} else {
throw new IllegalArgumentException("fromAge or toAge are both greater than 0");
}
final int THUMBS_COUNT = 9;
DBHelper dbHelper = DBHelper.getInstance(context);
List<Map<String, String>> birthdays = dbHelper.getBirthdayDAO()
.getBirthdayByAgeRange(fromAge, toAge == 0 ? Integer.MAX_VALUE : toAge, daysPeriod, tumblrName);
Collections.shuffle(birthdays);
StringBuilder sb = new StringBuilder();
Map<String, String> params = new HashMap<String, String>(2);
TumblrPhotoPost post = null;
params.put("type", "photo");
int count = 0;
for (Map<String, String> info : birthdays) {
params.put("id", info.get("postId"));
post = (TumblrPhotoPost)Tumblr.getSharedTumblr(context)
.getPublicPosts(tumblrName, params).get(0);
String imageUrl = post.getClosestPhotoByWidth(250).getUrl();
sb.append("<a href=\"" + post.getPostUrl() + "\">");
sb.append("<p>" + context.getString(R.string.name_with_age, post.getTags().get(0), info.get("age")) + "</p>");
sb.append("<img style=\"width: 250px !important\" src=\"" + imageUrl + "\"/>");
sb.append("</a>");
sb.append("<br/>");
if (++count > THUMBS_COUNT) {
break;
}
}
if (post != null) {
message = message + " (" + formatPeriodDate(-daysPeriod) + ")";
Tumblr.getSharedTumblr(context)
.draftTextPost(tumblrName,
message,
sb.toString(),
postTags);
}
}
private static String formatPeriodDate(int daysPeriod) {
Calendar now = Calendar.getInstance();
Calendar period = Calendar.getInstance();
period.add(Calendar.DAY_OF_MONTH, daysPeriod);
SimpleDateFormat sdf = new SimpleDateFormat("MMMM", Locale.US);
if (now.get(Calendar.YEAR) == period.get(Calendar.YEAR)) {
if (now.get(Calendar.MONTH) == period.get(Calendar.MONTH)) {
return period.get(Calendar.DAY_OF_MONTH) + "-" + now.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(now.getTime()) + ", " + now.get(Calendar.YEAR);
}
return period.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(period.getTime())
+ " - " + now.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(now.getTime())
+ ", " + now.get(Calendar.YEAR);
}
return period.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(period.getTime()) + " " + period.get(Calendar.YEAR)
+ " - " + now.get(Calendar.DAY_OF_MONTH) + " " + sdf.format(now.getTime()) + " " + now.get(Calendar.YEAR);
}
public static Birthday searchGoogleForBirthday(String name, String blogName) throws IOException, ParseException {
String cleanName = name
.replaceAll(" ", "+")
.replaceAll("\"", "");
String url = "https:
String text = Jsoup.connect(url)
.userAgent(DESKTOP_USER_AGENT)
.get()
.text();
// match only dates in expected format (ie. "Born: month_name day, year")
Pattern pattern = Pattern.compile("Born: ([a-zA-Z]+ \\d{1,2}, \\d{4})");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
String textDate = matcher.group(1);
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.US);
Date date = dateFormat.parse(textDate);
return new Birthday(name, date, blogName);
}
return null;
}
public static Birthday searchWikipediaForBirthday(String name, String blogName) throws IOException, ParseException {
String cleanName = StringUtils
.capitalize(name)
.replaceAll(" ", "_")
.replaceAll("\"", "");
String url = "http://en.wikipedia.org/wiki/" + cleanName;
Document document = Jsoup.connect(url)
.userAgent(DESKTOP_USER_AGENT)
.get();
// protect against redirect
if (document.title().toLowerCase(Locale.US).contains(name)) {
Elements el = document.select(".bday");
if (el.size() > 0) {
String birthDate = el.get(0).text();
return new Birthday(name, birthDate, blogName);
}
}
return null;
}
public static Birthday searchBirthday(String name, String blogName) {
Birthday birthday = null;
try {
birthday = BirthdayUtils.searchGoogleForBirthday(name, blogName);
} catch (Exception ex) {
}
if (birthday == null) {
try {
birthday = BirthdayUtils.searchWikipediaForBirthday(name, blogName);
} catch (Exception ex) {
}
}
return birthday;
}
}
|
package ai.elimu.appstore.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import org.greenrobot.greendao.database.Database;
import timber.log.Timber;
public class CustomDaoMaster extends DaoMaster {
public CustomDaoMaster(Database db) {
super(db);
Timber.i("CustomDaoMaster");
}
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Timber.i("Upgrading schema from version " + oldVersion + " to " + newVersion);
if (oldVersion < 1003004) {
dropAllTables(db, true);
onCreate(db);
}
if (oldVersion < 2000003) {
DbMigrationHelper.migrate(db, ApplicationVersionDao.class);
}
if (oldVersion < 2000011) {
// Add checksumMd5
DbMigrationHelper.migrate(db, ApplicationVersionDao.class);
}
}
}
}
|
package com.echopen.asso.echopen;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import com.echopen.asso.echopen.model.Data.UDPToBitmapDisplayer;
import com.echopen.asso.echopen.ui.AbstractActionActivity;
import com.echopen.asso.echopen.custom.CustomActivity;
import com.echopen.asso.echopen.ui.FilterDialogFragment;
import com.echopen.asso.echopen.ui.MainActionController;
import com.echopen.asso.echopen.utils.AppHelper;
import com.echopen.asso.echopen.utils.Config;
import com.echopen.asso.echopen.utils.Constants;
import java.io.IOException;
public class MainActivity extends CustomActivity implements AbstractActionActivity {
private int display;
private MainActionController mainActionController;
public GestureDetector gesture;
public Constants.Settings setting;
protected Uri uri;
private static boolean testEchopen = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.vMiddle);
linearLayout.setBackgroundColor(Color.TRANSPARENT);
initSwipeViews();
initViewComponents();
initActionController();
setupContainer();
Config.getInstance(this);
try {
UDPToBitmapDisplayer udpData = new UDPToBitmapDisplayer(this, mainActionController, Constants.Http.REDPITAYA_UDP_IP, Constants.Http.REDPITAYA_UDP_PORT);
} catch (IOException e) {
e.printStackTrace();
}
}
public void initActionController() {
Activity activity = this;
mainActionController = new MainActionController(activity);
}
private void initViewComponents() {
setTouchNClick(R.id.btnCapture);
setTouchNClick(R.id.btnEffect);
setTouchNClick(R.id.btnPic);
setTouchNClick(R.id.tabBrightness);
setTouchNClick(R.id.tabGrid);
setTouchNClick(R.id.tabSetting);
setTouchNClick(R.id.tabSuffle);
setTouchNClick(R.id.tabTime);
setClick(R.id.btn1);
setClick(R.id.btn2);
setClick(R.id.btn3);
setClick(R.id.btn4);
setClick(R.id.btn5);
//setClickToFilter(R.id.vMiddle);
applyBgTheme(findViewById(R.id.vTop));
applyBgTheme(findViewById(R.id.vBottom));
}
private void setClickToFilter(int mainframe) {
final View mainFrame = findViewById(mainframe);
mainFrame.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
filterDialogFragment.show(manager, "fragment_edit_name");
}
});
}
private void initSwipeViews() {
gesture = new GestureDetector(this, gestureListner);
OnTouchListener otl = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gesture.onTouchEvent(event);
}
};
findViewById(R.id.content_frame).setOnTouchListener(otl);
}
private SimpleOnGestureListener gestureListner = new SimpleOnGestureListener() {
@Override
public boolean onFling(android.view.MotionEvent e1,
android.view.MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(e1.getY() - e2.getY()) > setting.SWIPE_MAX_OFF_PATH)
return false;
else {
try {
if (e1.getX() - e2.getX() > setting.SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > setting.SWIPE_THRESHOLD_VELOCITY) {
if (display != setting.DISPLAY_VIDEO) {
display++;
setupContainer();
}
} else if (e2.getX() - e1.getX() > setting.SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > setting.SWIPE_THRESHOLD_VELOCITY) {
if (display != setting.DISPLAY_PHOTO) {
display
setupContainer();
}
}
} catch (Exception e) {
}
return true;
}
}
};
public void goBackFromFragment(int display) {
this.display = display;
setupContainer();
}
private void setupContainer() {
while (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStackImmediate();
}
/*Fragment f;
f = new FilterFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, f).commit();*/
mainActionController.displayImages();
if (display == setting.DISPLAY_PHOTO) {
mainActionController.displayPhoto();
} else {
mainActionController.displayOtherImage();
}
}
@Override
public void onClick(View v) {
super.onClick(v);
//chooseCamera(v);
//runCamera();
}
private void chooseCamera(View v) {
if (display != setting.DISPLAY_PHOTO
&& (v.getId() == R.id.btnPic || v.getId() == R.id.btn1)) {
display = setting.DISPLAY_PHOTO;
setupContainer();
} else if (v.getId() == R.id.btn2) {
if (display == setting.DISPLAY_VIDEO) {
display = setting.DISPLAY_FILTER;
setupContainer();
} else if (display == setting.DISPLAY_FILTER) {
display = setting.DISPLAY_PHOTO;
setupContainer();
}
} else if (v.getId() == R.id.btn4) {
if (display == setting.DISPLAY_PHOTO) {
display = setting.DISPLAY_FILTER;
setupContainer();
} else if (display == setting.DISPLAY_FILTER) {
display = setting.DISPLAY_VIDEO;
setupContainer();
}
} else if (v.getId() == R.id.btn5 && display == setting.DISPLAY_PHOTO) {
display = setting.DISPLAY_VIDEO;
setupContainer();
} else if (display != setting.DISPLAY_FILTER && v.getId() == R.id.btnEffect) {
display = setting.DISPLAY_FILTER;
setupContainer();
} else if (v.getId() == R.id.btnCapture) {
if (display == setting.DISPLAY_FILTER) {
display = setting.DISPLAY_PHOTO;
setupContainer();
}
} else if (v.getId() == R.id.tabSetting) {
startActivity(new Intent(this, Settings.class));
}
}
private void runCamera() {
if (display == setting.DISPLAY_PHOTO) {
Intent photoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
uri = AppHelper.getFileUri(MainActivity.this, setting.MEDIA_TYPE_IMAGE);
if (uri == null)
AppHelper.getErrorStorageMessage(MainActivity.this);
else {
photoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(photoIntent, setting.TAKE_PHOTO);
}
} else if (display == setting.DISPLAY_VIDEO) {
Intent videoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
uri = AppHelper.getFileUri(MainActivity.this, setting.MEDIA_TYPE_VIDEO);
if (uri == null)
AppHelper.getErrorStorageMessage(MainActivity.this);
else {
videoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
videoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
videoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); // 0 = lowest res
startActivityForResult(videoIntent, setting.TAKE_VIDEO_REQUEST);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
startActivity(new Intent(this, MainActivity.class));
}
}
|
package com.github.slmyldz.islib;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.Date;
import is.Is;
import is.IsApplication;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.output);
startTest();
}
public void startTest(){
text.setText("");
//application
setText("isPackageInstalled : com.github.slmyldz.islib " + Is.application.isPackageInstalled("com.github.slmyldz.islib"));
setText("getApplicationVersionNumber : =>" + Is.application.getApplicationVersionNumber());
setText("getApplicationVersionCode : =>" + Is.application.getApplicationVersionCode());
//basics
setText("isValidCreditCard : 4521235486213215 " + Is.basic.isValidCreditCard("4521235486213215"));
setText("isValidDomainName : www.google.com " + Is.basic.isValidDomainName("www.google.com"));
setText("isValidEmail : slmyldz41@gmail.com " + Is.basic.isValidEmail("slmyldz41@gmail.com"));
setText("isValidIPadress : 191.168.1.1 " + Is.basic.isValidIPadress("191.168.1.1"));
setText("isValidPhone : +90 888 88 88 " + Is.basic.isValidPhone("+90 888 88 88"));
setText("isValidURL : http:
//location
setText("isLocationEnabled : "+Is.location.isLocationEnabled());
//network
setText("isMobileDataEnabled : "+Is.network.isMobileDataEnabled());
setText("isNetworkEnabled : " + Is.network.isNetworkEnabled());
setText("getWifiState : "+ Is.network.getWifiState().name());
//phone
setText("isBrand : LG "+Is.phone.isBrand("LG"));
try {
setText("isLockScreenDisabled : "+Is.phone.isLockScreenDisabled());
} catch (Exception e) {
e.printStackTrace();
}
setText("isPlugged : "+Is.phone.isPlugged());
setText("checkBuildNumber : "+Is.phone.checkBuildNumber(15));
setText("isTabletDevice : Activity " + Is.phone.isTabletDevice(this));
setText("isAirplaneModeOpen : "+Is.phone.isAirplaneModeOpen());
setText("getMaxMemory : "+Is.phone.getMaxMemory());
setText("getDeviceId : "+Is.phone.getDeviceId());
//root
setText("isRooted : "+Is.root.isRooted());
//screen
setText("isScreenLandscape : " + Is.screen.isScreenLandscape());
setText("isScreenPortrait : " + Is.screen.isScreenPortrait());
setText("isScreenSquare : " + Is.screen.isScreenSquare());
setText("getScreenSizes : "+"w:"+Is.screen.getScreenSizes(this)[0]+" h:"+Is.screen.getScreenSizes(this)[1]);
setText("getScreenBrightness : " + Is.screen.getScreenBrightness());
setText("isScreenBrightnessModeAuto : " + Is.screen.isScreenBrightnessModeAuto());
//service
setText("isServiceRunning : com.android.vending " + Is.service.isServiceRunning("com.android.vending"));
//sound
setText("isMax : Sound "+Is.sound.isMax());
setText("isMute : Sound "+Is.sound.isMute());
setText("getMediaVolume : "+Is.sound.getMediaVolume());
setText("getRingVolume : "+Is.sound.getRingVolume());
//file
setText("getAvailableSpaceInBytes : " + Is.file.getAvailableSpaceInBytes());
setText("isSdCardMounted : " + Is.file.isSdCardMounted());
setText("isFileExistsInSDCard \"hello.txt\",\"/sdcard/\" : " + Is.file.isFileExistsInSDCard("hello.txt", "/sdcard/"));
//view
setText("isVisible : text "+Is.view.isVisible(text));
setText("isGone : text "+Is.view.isGone(text));
//date
setText("getCurrentDate : yyyy-MM-dd =>"+ Is.date.getCurrentDate("yyyy-MM-dd"));
setText("isToday : =>"+ Is.date.isToday(new Date()));
setText("isWeekday : =>"+ Is.date.isWeekday(new Date()));
setText("isWeekend : =>"+ Is.date.isWeekend(new Date()));
setText("getCurrentDateTimeStamp : yyyy-MM-dd =>"+ Is.date.getCurrentDateTimeStamp());
setText("todayIsWeekday : =>"+ Is.date.todayIsWeekday());
setText("todayIsWeekend : =>"+ Is.date.todayIsWeekend());
transformToHtml();
}
public void setText(String output){
int b =output.indexOf(':');
output = "<b>"+output.substring(0,b)+"</b> => "+output.substring(b)+"<br>";
text.setText(text.getText() + output + "\n");
}
public void transformToHtml(){
text.setText(Html.fromHtml(text.getText().toString()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.refresh:
startTest();
break;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.marlonjones.safeguard;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import com.afollestad.materialdialogs.MaterialDialog;
import java.util.Timer;
import java.util.TimerTask;
https://xjaphx.wordpress.com/2012/07/07/create-a-service-that-does-a-schedule-task/*/
/*^TODO - TEST NOTIFY_INTERVAL FOR ACCURACY^*/
/*^Those are for the timer and handler so the code
can recognise it^ The last one gives how long the timer runs */
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
/* if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);*/
}
public void startNotification() {
//start up notification timer 15 min
}
public void stopNotification() {
//cancel notification timer service
}
public boolean isNotificationStarted() {
return false;
}
public interface LocalBinder {
SafeService getService();
}
/*class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
// Lollipop or Above
if (Build.VERSION.SDK_INT >= 21) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(SafeService.this);
new NotificationCompat.Builder(SafeService.this);
builder.setSmallIcon(R.drawable.smallplaceholder);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("Safeguard");
builder.setContentText("Be careful, Trainer! Remember to look up and stay aware of your surroundings!!");
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("Be careful, Trainer! Remember to look up and stay aware of your surroundings!!"));
builder.setPriority(Notification.PRIORITY_HIGH);
builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
//Below Lollipop
} else {
new MaterialDialog.Builder(SafeService.this)
.title(R.string.warning_title)
.content(R.string.warning)
.positiveText(R.string.button_ok)
.show();
}
}
});*/
}
|
package com.procleus.brime;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class GetStartedActivity extends AppCompatActivity{
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button buttonSkip, buttonNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.activity_getstarted);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
buttonSkip = (Button) findViewById(R.id.btn_skip);
buttonNext = (Button) findViewById(R.id.btn_next);
layouts = new int[]{
R.layout.get_started_slide1,
R.layout.get_started_slide2,
R.layout.get_started_slide3,
R.layout.get_started_slide4};
addBottomDots(0);
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
buttonNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int current = getItem(+1);
if (current < layouts.length) {
viewPager.setCurrentItem(current);
} else {
Intent intent = new Intent(GetStartedActivity.this, SignupActivity.class);
startActivity(intent);
finish();
}
}
});
buttonSkip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(GetStartedActivity.this, SigninActivity.class);
startActivity(intent);
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0) {
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
}
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
addBottomDots(position);
if (position == layouts.length - 1) {
buttonNext.setText("Got It");
buttonSkip.setVisibility(View.GONE);
} else {
buttonNext.setText("Next");
buttonSkip.setVisibility(View.VISIBLE);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
};
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
@Override
public int getCount() {
return layouts.length;
}
@Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
|
package com.revo.display.views.custom;
import android.content.Context;
import android.util.AttributeSet;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.HashMap;
public class RevoMap extends MapView {
private static float DEFAULT_CAMERA_ZOOM = 14.0f;
private static float MIN_CAMERA_ZOOM = 12.0f;
private PolylineOptions polylineOptions;
private LatLng currCoords;
private float cameraZoom;
public RevoMap(Context context) {
super(context);
setupMap(context);
}
public RevoMap(Context context, AttributeSet attrs) {
super(context, attrs);
setupMap(context);
}
private void setupMap(Context context) {
polylineOptions = new PolylineOptions().geodesic(true);
MapsInitializer.initialize(context);
setZoomListener();
cameraZoom = DEFAULT_CAMERA_ZOOM;
}
// save the users zoom level
private void setZoomListener() {
getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
cameraZoom = Math.max(MIN_CAMERA_ZOOM, cameraPosition.zoom);
}
});
}
});
}
public void handleCoordinate(Object value) {
try {
HashMap<String, Double> coordMap = (HashMap<String, Double>) value;
LatLng coord = new LatLng(coordMap.get("latitude"), coordMap.get("longitude"));
updateCoords(coord);
} catch (ClassCastException e) {
e.printStackTrace();
}
}
private void updateCoords(LatLng coord) {
if (coord != null && newCoords(coord)) {
currCoords = coord;
addMapPosition(currCoords);
}
}
private boolean newCoords(LatLng coord) {
return coord != null &&
(currCoords == null ||
(coord.latitude != currCoords.latitude ||
coord.longitude != currCoords.longitude));
}
private void addMapPosition(LatLng coord) {
GoogleMap gmap = getMap();
gmap.clear();
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(coord, cameraZoom));
polylineOptions.add(coord);
gmap.addPolyline(polylineOptions);
}
}
|
package com.samourai.wallet.send;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.Group;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.google.common.base.Splitter;
import com.samourai.boltzmann.beans.BoltzmannSettings;
import com.samourai.boltzmann.beans.Txos;
import com.samourai.boltzmann.linker.TxosLinkerOptionEnum;
import com.samourai.boltzmann.processor.TxProcessor;
import com.samourai.boltzmann.processor.TxProcessorResult;
import com.samourai.wallet.BatchSendActivity;
import com.samourai.wallet.R;
import com.samourai.wallet.SamouraiWallet;
import com.samourai.wallet.TxAnimUIActivity;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.bip47.rpc.PaymentAddress;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.cahoots.Cahoots;
import com.samourai.wallet.cahoots.CahootsUtil;
import com.samourai.wallet.fragments.CameraFragmentBottomSheet;
import com.samourai.wallet.fragments.PaynymSelectModalFragment;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.paynym.paynymDetails.PayNymDetailsActivity;
import com.samourai.wallet.ricochet.RicochetActivity;
import com.samourai.wallet.ricochet.RicochetMeta;
import com.samourai.wallet.segwit.BIP49Util;
import com.samourai.wallet.segwit.BIP84Util;
import com.samourai.wallet.segwit.SegwitAddress;
import com.samourai.wallet.send.cahoots.ManualCahootsActivity;
import com.samourai.wallet.send.cahoots.SelectCahootsType;
import com.samourai.wallet.tor.TorManager;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.DecimalDigitsInputFilter;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.LogUtil;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.SendAddressUtil;
import com.samourai.wallet.util.WebUtil;
import com.samourai.wallet.utxos.PreSelectUtil;
import com.samourai.wallet.utxos.UTXOSActivity;
import com.samourai.wallet.utxos.models.UTXOCoin;
import com.samourai.wallet.whirlpool.WhirlpoolMeta;
import com.samourai.wallet.widgets.SendTransactionDetailsView;
import org.apache.commons.lang3.tuple.Triple;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.script.Script;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class SendActivity extends AppCompatActivity {
private final static int SCAN_QR = 2012;
private final static int RICOCHET = 2013;
private static final String TAG = "SendActivity";
private SendTransactionDetailsView sendTransactionDetailsView;
private ViewSwitcher amountViewSwitcher;
private EditText toAddressEditText, btcEditText, satEditText;
private TextView tvMaxAmount, tvReviewSpendAmount, tvReviewSpendAmountInSats, tvTotalFee, tvToAddress, tvEstimatedBlockWait, tvSelectedFeeRate, tvSelectedFeeRateLayman, ricochetTitle, ricochetDesc,cahootsStatusText,cahootsNotice;
private Button btnReview, btnSend;
private Switch ricochetHopsSwitch, ricochetStaggeredDelivery;
private ViewGroup totalMinerFeeLayout;
private Switch cahootsSwitch;
private SeekBar feeSeekBar;
private Group ricochetStaggeredOptionGroup;
private boolean shownWalletLoadingMessage = false;
private long balance = 0L;
private String strDestinationBTCAddress = null;
private final static int FEE_LOW = 0;
private final static int FEE_NORMAL = 1;
private final static int FEE_PRIORITY = 2;
private final static int FEE_CUSTOM = 3;
private int FEE_TYPE = FEE_LOW;
public final static int SPEND_SIMPLE = 0;
public final static int SPEND_BOLTZMANN = 1;
public final static int SPEND_RICOCHET = 2;
private int SPEND_TYPE = SPEND_BOLTZMANN;
private boolean openedPaynym = false;
private String strPCode = null;
private long feeLow, feeMed, feeHigh;
private String strPrivacyWarning;
private ArrayList<UTXO> selectedUTXO;
private long _change;
private HashMap<String, BigInteger> receivers;
private int changeType;
private ConstraintLayout cahootsGroup;
private String address;
private String message;
private long amount;
private int change_index;
private String ricochetMessage;
private JSONObject ricochetJsonObj = null;
private int idxBIP44Internal = 0;
private int idxBIP49Internal = 0;
private int idxBIP84Internal = 0;
private int idxBIP84PostMixInternal = 0;
//stub address for entropy calculation
public static String[] stubAddress = {"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", "12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX", "1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1", "1FvzCLoTPGANNjWoUo6jUGuAG3wg1w4YjR", "15ubicBBWFnvoZLT7GiU2qxjRaKJPdkDMG", "1JfbZRwdDHKZmuiZgYArJZhcuuzuw2HuMu", "1GkQmKAmHtNfnD3LHhTkewJxKHVSta4m2a", "16LoW7y83wtawMg5XmT4M3Q7EdjjUmenjM", "1J6PYEzr4CUoGbnXrELyHszoTSz3wCsCaj", "12cbQLTFMXRnSzktFkuoG3eHoMeFtpTu3S", "15yN7NPEpu82sHhB6TzCW5z5aXoamiKeGy ", "1dyoBoF5vDmPCxwSsUZbbYhA5qjAfBTx9", "1PYELM7jXHy5HhatbXGXfRpGrgMMxmpobu", "17abzUBJr7cnqfnxnmznn8W38s9f9EoXiq", "1DMGtVnRrgZaji7C9noZS3a1QtoaAN2uRG", "1CYG7y3fukVLdobqgUtbknwWKUZ5p1HVmV", "16kktFTqsruEfPPphW4YgjktRF28iT8Dby", "1LPBetDzQ3cYwqQepg4teFwR7FnR1TkMCM", "1DJkjSqW9cX9XWdU71WX3Aw6s6Mk4C3TtN", "1P9VmZogiic8d5ZUVZofrdtzXgtpbG9fop", "15ubjFzmWVvj3TqcpJ1bSsb8joJ6gF6dZa"};
private CompositeDisposable compositeDisposables = new CompositeDisposable();
private SelectCahootsType.type selectedCahootsType = SelectCahootsType.type.NONE;
private int account = 0;
private List<UTXOCoin> preselectedUTXOs = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
setSupportActionBar(findViewById(R.id.toolbar_send));
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
setTitle("");
//CustomView for showing and hiding body of th UI
sendTransactionDetailsView = findViewById(R.id.sendTransactionDetailsView);
//ViewSwitcher Element for toolbar section of the UI.
//we can switch between Form and review screen with this element
amountViewSwitcher = findViewById(R.id.toolbar_view_switcher);
//Input elements from toolbar section of the UI
toAddressEditText = findViewById(R.id.edt_send_to);
btcEditText = findViewById(R.id.amountBTC);
satEditText = findViewById(R.id.amountSat);
tvToAddress = findViewById(R.id.to_address_review);
tvReviewSpendAmount = findViewById(R.id.send_review_amount);
tvReviewSpendAmountInSats = findViewById(R.id.send_review_amount_in_sats);
tvMaxAmount = findViewById(R.id.totalBTC);
//view elements from review segment and transaction segment can be access through respective
//methods which returns root viewGroup
btnReview = sendTransactionDetailsView.getTransactionView().findViewById(R.id.review_button);
cahootsSwitch = sendTransactionDetailsView.getTransactionView().findViewById(R.id.cahoots_switch);
ricochetHopsSwitch = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_hops_switch);
ricochetTitle = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_desc);
ricochetDesc = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_title);
ricochetStaggeredDelivery = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_staggered_option);
ricochetStaggeredOptionGroup = sendTransactionDetailsView.getTransactionView().findViewById(R.id.ricochet_staggered_option_group);
tvSelectedFeeRate = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.selected_fee_rate);
tvSelectedFeeRateLayman = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.selected_fee_rate_in_layman);
tvTotalFee = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.total_fee);
btnSend = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.send_btn);
feeSeekBar = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.fee_seekbar);
tvEstimatedBlockWait = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.est_block_time);
feeSeekBar = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.fee_seekbar);
cahootsGroup = sendTransactionDetailsView.findViewById(R.id.cohoots_options);
cahootsStatusText = sendTransactionDetailsView.findViewById(R.id.cahoot_status_text);
totalMinerFeeLayout = sendTransactionDetailsView.getTransactionReview().findViewById(R.id.total_miner_fee_group);
cahootsNotice = sendTransactionDetailsView.findViewById(R.id.cahoots_not_enabled_notice);
btcEditText.addTextChangedListener(BTCWatcher);
btcEditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(8, 8)});
satEditText.addTextChangedListener(satWatcher);
toAddressEditText.addTextChangedListener(AddressWatcher);
btnReview.setOnClickListener(v -> review());
btnSend.setOnClickListener(v -> initiateSpend());
View.OnClickListener clipboardCopy = view -> {
ClipboardManager cm = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = android.content.ClipData
.newPlainText("Miner fee", tvTotalFee.getText());
if (cm != null) {
cm.setPrimaryClip(clipData);
Toast.makeText(this, getString(R.string.copied_to_clipboard), Toast.LENGTH_SHORT).show();
}
};
tvTotalFee.setOnClickListener(clipboardCopy);
tvSelectedFeeRate.setOnClickListener(clipboardCopy);
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey("_account")) {
if (getIntent().getExtras().getInt("_account") == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) {
account = WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix();
}
}
SPEND_TYPE = SPEND_BOLTZMANN;
saveChangeIndexes();
setUpRicochet();
setUpCahoots();
setUpFee();
setBalance();
enableReviewButton(false);
setUpBoltzman();
validateSpend();
checkDeepLinks();
if (getIntent().getExtras().containsKey("preselected")) {
preselectedUTXOs = PreSelectUtil.getInstance().getPreSelected(getIntent().getExtras().getString("preselected"));
setBalance();
} else {
Disposable disposable = APIFactory.getInstance(getApplicationContext())
.walletBalanceObserver
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> {
if (balance == aLong) {
return;
}
setBalance();
}, Throwable::printStackTrace);
compositeDisposables.add(disposable);
// Update fee
Disposable feeDisposable = Observable.fromCallable(() -> APIFactory.getInstance(getApplicationContext()).getDynamicFees())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(t -> {
Log.i(TAG, "Fees : ".concat(t.toString()));
setUpFee();
}, Throwable::printStackTrace);
compositeDisposables.add(feeDisposable);
if (getIntent().getExtras() != null) {
if (!getIntent().getExtras().containsKey("balance")) {
return;
}
balance = getIntent().getExtras().getLong("balance");
}
}
}
private void setUpCahoots() {
if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {
cahootsNotice.setVisibility(View.VISIBLE);
}
cahootsSwitch.setOnCheckedChangeListener((compoundButton, b) -> {
// to check whether bottomsheet is closed or selected a value
final boolean[] chosen = {false};
if (b) {
SelectCahootsType cahootsType = new SelectCahootsType();
cahootsType.show(getSupportFragmentManager(), cahootsType.getTag());
cahootsType.setOnSelectListener(new SelectCahootsType.OnSelectListener() {
@Override
public void onSelect(SelectCahootsType.type type) {
chosen[0] = true;
selectedCahootsType = type;
hideToAddressForStowaway(false);
switch (selectedCahootsType) {
case NONE: {
cahootsStatusText.setText("Off");
cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.warning_yellow));
break;
}
case STOWAWAY: {
cahootsStatusText.setText("Stowaway");
cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.green_ui_2));
hideToAddressForStowaway(true);
break;
}
case STONEWALLX2_MANUAL: {
cahootsStatusText.setText("StonewallX2 Manual");
cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.green_ui_2));
break;
}
case STONEWALLX2_SAMOURAI: {
cahootsStatusText.setText("Stonewallx2 Samourai");
cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.green_ui_2));
break;
}
}
validateSpend();
}
@Override
public void onDismiss() {
if (!chosen[0]) {
compoundButton.setChecked(false);
selectedCahootsType = SelectCahootsType.type.NONE;
hideToAddressForStowaway(false);
}
validateSpend();
}
});
} else {
selectedCahootsType = SelectCahootsType.type.NONE;
cahootsStatusText.setText("Off");
cahootsStatusText.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.warning_yellow));
hideToAddressForStowaway(false);
validateSpend();
enableReviewButton(false);
}
});
}
private void hideToAddressForStowaway(boolean hide){
if(hide){
toAddressEditText.setText("Stowaway Collaborator");
toAddressEditText.setEnabled(false);
address = "";
}else {
toAddressEditText.setEnabled(true);
toAddressEditText.setText("");
address = "";
}
}
@Override
protected void onResume() {
super.onResume();
AppUtil.getInstance(SendActivity.this).setIsInForeground(true);
AppUtil.getInstance(SendActivity.this).checkTimeOut();
}
private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = (compoundButton, checked) -> {
SPEND_TYPE = checked ? SPEND_BOLTZMANN : SPEND_SIMPLE;
compoundButton.setChecked(checked);
new Handler().postDelayed(this::prepareSpend, 100);
};
private void setUpBoltzman() {
sendTransactionDetailsView.getStoneWallSwitch().setChecked(true);
sendTransactionDetailsView.getStoneWallSwitch().setEnabled(WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix() != account);
sendTransactionDetailsView.enableStonewall(true);
sendTransactionDetailsView.getStoneWallSwitch().setOnCheckedChangeListener(onCheckedChangeListener);
}
private void checkRicochetPossibility() {
double btc_amount = 0.0;
try {
btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue();
// Log.i("SendFragment", "amount entered:" + btc_amount);
} catch (NumberFormatException nfe) {
btc_amount = 0.0;
} catch (ParseException pe) {
btc_amount = 0.0;
return;
}
double dAmount = btc_amount;
amount = Math.round(dAmount * 1e8);
if (amount < (balance - (RicochetMeta.samouraiFeeAmountV2.add(BigInteger.valueOf(50000L))).longValue())) {
ricochetDesc.setAlpha(1f);
ricochetTitle.setAlpha(1f);
ricochetHopsSwitch.setAlpha(1f);
ricochetHopsSwitch.setEnabled(true);
if (ricochetHopsSwitch.isChecked()) {
ricochetStaggeredOptionGroup.setVisibility(View.VISIBLE);
}
} else {
ricochetStaggeredOptionGroup.setVisibility(View.GONE);
ricochetDesc.setAlpha(.6f);
ricochetTitle.setAlpha(.6f);
ricochetHopsSwitch.setAlpha(.6f);
ricochetHopsSwitch.setEnabled(false);
}
}
private void enableReviewButton(boolean enable) {
btnReview.setEnabled(enable);
if (enable) {
btnReview.setBackground(getDrawable(R.drawable.button_blue));
} else {
btnReview.setBackground(getDrawable(R.drawable.disabled_grey_button));
}
}
private void setUpFee() {
int multiplier = 10000;
FEE_TYPE = PrefsUtil.getInstance(this).getValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL);
feeLow = FeeUtil.getInstance().getLowFee().getDefaultPerKB().longValue() / 1000L;
feeMed = FeeUtil.getInstance().getNormalFee().getDefaultPerKB().longValue() / 1000L;
feeHigh = FeeUtil.getInstance().getHighFee().getDefaultPerKB().longValue() / 1000L;
float high = ((float) feeHigh / 2) + (float) feeHigh;
int feeHighSliderValue = (int) (high * multiplier);
int feeMedSliderValue = (int) (feeMed * multiplier);
feeSeekBar.setMax(feeHighSliderValue - multiplier);
if (feeLow == feeMed && feeMed == feeHigh) {
feeLow = (long) ((double) feeMed * 0.85);
feeHigh = (long) ((double) feeMed * 1.15);
SuggestedFee lo_sf = new SuggestedFee();
lo_sf.setDefaultPerKB(BigInteger.valueOf(feeLow * 1000L));
FeeUtil.getInstance().setLowFee(lo_sf);
SuggestedFee hi_sf = new SuggestedFee();
hi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L));
FeeUtil.getInstance().setHighFee(hi_sf);
} else if (feeLow == feeMed || feeMed == feeMed) {
feeMed = (feeLow + feeHigh) / 2L;
SuggestedFee mi_sf = new SuggestedFee();
mi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L));
FeeUtil.getInstance().setNormalFee(mi_sf);
} else {
;
}
if (feeLow < 1L) {
feeLow = 1L;
SuggestedFee lo_sf = new SuggestedFee();
lo_sf.setDefaultPerKB(BigInteger.valueOf(feeLow * 1000L));
FeeUtil.getInstance().setLowFee(lo_sf);
}
if (feeMed < 1L) {
feeMed = 1L;
SuggestedFee mi_sf = new SuggestedFee();
mi_sf.setDefaultPerKB(BigInteger.valueOf(feeMed * 1000L));
FeeUtil.getInstance().setNormalFee(mi_sf);
}
if (feeHigh < 1L) {
feeHigh = 1L;
SuggestedFee hi_sf = new SuggestedFee();
hi_sf.setDefaultPerKB(BigInteger.valueOf(feeHigh * 1000L));
FeeUtil.getInstance().setHighFee(hi_sf);
}
// tvEstimatedBlockWait.setText("6 blocks");
tvSelectedFeeRateLayman.setText(getString(R.string.normal));
FeeUtil.getInstance().sanitizeFee();
tvSelectedFeeRate.setText((String.valueOf((int) feeMed).concat(" sats/b")));
feeSeekBar.setProgress((feeMedSliderValue - multiplier) + 1);
DecimalFormat decimalFormat = new DecimalFormat("
setFeeLabels();
feeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
double value = ((double) i + multiplier) / (double) multiplier;
tvSelectedFeeRate.setText(String.valueOf(decimalFormat.format(value)).concat(" sats/b"));
if (value == 0.0) {
value = 1.0;
}
double pct = 0.0;
int nbBlocks = 6;
if (value <= (double) feeLow) {
pct = ((double) feeLow / value);
nbBlocks = ((Double) Math.ceil(pct * 24.0)).intValue();
} else if (value >= (double) feeHigh) {
pct = ((double) feeHigh / value);
nbBlocks = ((Double) Math.ceil(pct * 2.0)).intValue();
if (nbBlocks < 1) {
nbBlocks = 1;
}
} else {
pct = ((double) feeMed / value);
nbBlocks = ((Double) Math.ceil(pct * 6.0)).intValue();
}
tvEstimatedBlockWait.setText(nbBlocks + " blocks");
setFee(value);
setFeeLabels();
restoreChangeIndexes();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
restoreChangeIndexes();
}
});
switch (FEE_TYPE) {
case FEE_LOW:
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee());
FeeUtil.getInstance().sanitizeFee();
break;
case FEE_PRIORITY:
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee());
FeeUtil.getInstance().sanitizeFee();
break;
default:
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee());
FeeUtil.getInstance().sanitizeFee();
break;
}
}
private void setFeeLabels() {
float sliderValue = (((float) feeSeekBar.getProgress()) / feeSeekBar.getMax());
float sliderInPercentage = sliderValue * 100;
if (sliderInPercentage < 33) {
tvSelectedFeeRateLayman.setText(R.string.low);
} else if (sliderInPercentage > 33 && sliderInPercentage < 66) {
tvSelectedFeeRateLayman.setText(R.string.normal);
} else if (sliderInPercentage > 66) {
tvSelectedFeeRateLayman.setText(R.string.urgent);
}
}
private void setFee(double fee) {
double sanitySat = FeeUtil.getInstance().getHighFee().getDefaultPerKB().doubleValue() / 1000.0;
final long sanityValue;
if (sanitySat < 10.0) {
sanityValue = 15L;
} else {
sanityValue = (long) (sanitySat * 1.5);
}
// String val = null;
double d = FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().doubleValue() / 1000.0;
NumberFormat decFormat = NumberFormat.getInstance(Locale.US);
decFormat.setMaximumFractionDigits(3);
decFormat.setMinimumFractionDigits(0);
double customValue = 0.0;
if (PrefsUtil.getInstance(this).getValue(PrefsUtil.USE_TRUSTED_NODE, false)) {
customValue = 0.0;
} else {
try {
customValue = (double) fee;
} catch (Exception e) {
Toast.makeText(this, R.string.custom_fee_too_low, Toast.LENGTH_SHORT).show();
return;
}
}
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFee.setDefaultPerKB(BigInteger.valueOf((long) (customValue * 1000.0)));
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
prepareSpend();
}
private void setUpRicochet() {
if (account != 0) {
ricochetHopsSwitch.setChecked(false);
ricochetStaggeredDelivery.setChecked(false);
ConstraintLayout layoutPremiums = sendTransactionDetailsView.getTransactionView().findViewById(R.id.premium_addons);
layoutPremiums.setVisibility(View.GONE);
return;
}
ricochetHopsSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
sendTransactionDetailsView.enableForRicochet(isChecked);
enableCahoots(!isChecked);
ricochetStaggeredOptionGroup.setVisibility(isChecked ? View.VISIBLE : View.GONE);
if (isChecked) {
SPEND_TYPE = SPEND_RICOCHET;
PrefsUtil.getInstance(this).setValue(PrefsUtil.USE_RICOCHET, true);
} else {
SPEND_TYPE = sendTransactionDetailsView.getStoneWallSwitch().isChecked() ? SPEND_BOLTZMANN : SPEND_SIMPLE;
PrefsUtil.getInstance(this).setValue(PrefsUtil.USE_RICOCHET, false);
}
if (isChecked) {
ricochetStaggeredOptionGroup.setVisibility(View.VISIBLE);
} else {
ricochetStaggeredOptionGroup.setVisibility(View.GONE);
}
});
ricochetHopsSwitch.setChecked(PrefsUtil.getInstance(this).getValue(PrefsUtil.USE_RICOCHET, false));
if (ricochetHopsSwitch.isChecked()) {
ricochetStaggeredOptionGroup.setVisibility(View.VISIBLE);
} else {
ricochetStaggeredOptionGroup.setVisibility(View.GONE);
}
ricochetStaggeredDelivery.setChecked(PrefsUtil.getInstance(this).getValue(PrefsUtil.RICOCHET_STAGGERED, false));
ricochetStaggeredDelivery.setOnCheckedChangeListener((compoundButton, isChecked) -> {
PrefsUtil.getInstance(this).setValue(PrefsUtil.RICOCHET_STAGGERED, isChecked);
// Handle staggered delivery option
});
}
private void enableCahoots(boolean enable) {
if (enable) {
cahootsGroup.setVisibility(View.VISIBLE);
} else {
cahootsGroup.setVisibility(View.GONE);
selectedCahootsType = SelectCahootsType.type.NONE;
}
}
private void setBalance() {
if (preselectedUTXOs != null && preselectedUTXOs.size() > 0) {
long amount = 0;
for (UTXOCoin utxo : preselectedUTXOs) {
amount += utxo.amount;
}
balance = amount;
} else {
try {
if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) {
balance = APIFactory.getInstance(SendActivity.this).getXpubPostMixBalance();
} else {
Long tempBalance = APIFactory.getInstance(SendActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).xpubstr());
if (tempBalance != 0L) {
balance = tempBalance;
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
} catch (java.lang.NullPointerException npe) {
npe.printStackTrace();
}
}
final String strAmount;
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMaximumFractionDigits(8);
nf.setMinimumFractionDigits(1);
nf.setMinimumIntegerDigits(1);
strAmount = nf.format(balance / 1e8);
tvMaxAmount.setOnClickListener(view -> {
btcEditText.setText(strAmount);
});
tvMaxAmount.setText(strAmount + " " + getDisplayUnits());
if (balance == 0L && !APIFactory.getInstance(getApplicationContext()).walletInit) {
//some time, user may navigate to this activity even before wallet initialization completes
//so we will set a delay to reload balance info
Disposable disposable = Completable.timer(700, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribe(this::setBalance);
compositeDisposables.add(disposable);
if (!shownWalletLoadingMessage) {
Snackbar.make(tvMaxAmount.getRootView(), "Please wait... your wallet is still loading ", Snackbar.LENGTH_LONG).show();
shownWalletLoadingMessage = true;
}
}
}
private void checkDeepLinks() {
Bundle extras = getIntent().getExtras();
if (extras != null) {
// bViaMenu = extras.getBoolean("via_menu", false);
String strUri = extras.getString("uri");
if (extras.containsKey("amount")) {
btcEditText.setText(String.valueOf(getBtcValue(extras.getDouble("amount"))));
}
if (extras.getString("pcode") != null)
strPCode = extras.getString("pcode");
if (strPCode != null && strPCode.length() > 0) {
processPCode(strPCode, null);
} else if (strUri != null && strUri.length() > 0) {
processScan(strUri);
}
new Handler().postDelayed(this::validateSpend, 800);
}
}
private TextWatcher BTCWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
satEditText.removeTextChangedListener(satWatcher);
btcEditText.removeTextChangedListener(this);
try {
if (editable.toString().length() == 0) {
satEditText.setText("0");
btcEditText.setText("");
satEditText.setSelection(satEditText.getText().length());
satEditText.addTextChangedListener(satWatcher);
btcEditText.addTextChangedListener(this);
return;
}
Double btc = Double.parseDouble(String.valueOf(editable));
if (btc > 21000000.0) {
btcEditText.setText("0.00");
btcEditText.setSelection(btcEditText.getText().length());
satEditText.setText("0");
satEditText.setSelection(satEditText.getText().length());
Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show();
} else {
DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
String defaultSeparator = Character.toString(symbols.getDecimalSeparator());
int max_len = 8;
NumberFormat btcFormat = NumberFormat.getInstance(Locale.US);
btcFormat.setMaximumFractionDigits(max_len + 1);
try {
double d = NumberFormat.getInstance(Locale.US).parse(editable.toString()).doubleValue();
String s1 = btcFormat.format(d);
if (s1.indexOf(defaultSeparator) != -1) {
String dec = s1.substring(s1.indexOf(defaultSeparator));
if (dec.length() > 0) {
dec = dec.substring(1);
if (dec.length() > max_len) {
btcEditText.setText(s1.substring(0, s1.length() - 1));
btcEditText.setSelection(btcEditText.getText().length());
editable = btcEditText.getEditableText();
btc = Double.parseDouble(btcEditText.getText().toString());
}
}
}
} catch (NumberFormatException nfe) {
;
} catch (ParseException pe) {
;
}
Double sats = getSatValue(Double.valueOf(btc));
satEditText.setText(formattedSatValue(sats));
checkRicochetPossibility();
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
satEditText.addTextChangedListener(satWatcher);
btcEditText.addTextChangedListener(this);
validateSpend();
}
};
private TextWatcher AddressWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.toString().length() != 0) {
validateSpend();
} else {
setToAddress("");
}
}
};
private String formattedSatValue(Object number) {
NumberFormat nformat = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat decimalFormat = (DecimalFormat) nformat;
decimalFormat.applyPattern("
return decimalFormat.format(number).replace(",", " ");
}
private TextWatcher satWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
satEditText.removeTextChangedListener(this);
btcEditText.removeTextChangedListener(BTCWatcher);
try {
if (editable.toString().length() == 0) {
btcEditText.setText("0.00");
satEditText.setText("");
satEditText.addTextChangedListener(this);
btcEditText.addTextChangedListener(BTCWatcher);
return;
}
String cleared_space = editable.toString().replace(" ", "");
Double sats = Double.parseDouble(cleared_space);
Double btc = getBtcValue(sats);
String formatted = formattedSatValue(sats);
satEditText.setText(formatted);
satEditText.setSelection(formatted.length());
btcEditText.setText(String.format(Locale.ENGLISH, "%.8f", btc));
if (btc > 21000000.0) {
btcEditText.setText("0.00");
btcEditText.setSelection(btcEditText.getText().length());
satEditText.setText("0");
satEditText.setSelection(satEditText.getText().length());
Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show();
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
satEditText.addTextChangedListener(this);
btcEditText.addTextChangedListener(BTCWatcher);
checkRicochetPossibility();
validateSpend();
}
};
private void setToAddress(String string) {
tvToAddress.setText(string);
toAddressEditText.removeTextChangedListener(AddressWatcher);
toAddressEditText.setText(string);
toAddressEditText.setSelection(toAddressEditText.getText().length());
toAddressEditText.addTextChangedListener(AddressWatcher);
}
private String getToAddress() {
if (toAddressEditText.getText().toString().trim().length() != 0) {
return toAddressEditText.getText().toString();
}
if (tvToAddress.getText().toString().length() != 0) {
return tvToAddress.getText().toString();
}
return "";
}
private Double getBtcValue(Double sats) {
return (double) (sats / 1e8);
}
private Double getSatValue(Double btc) {
if (btc == 0) {
return (double) 0;
}
return btc * 1e8;
}
private void review() {
setUpBoltzman();
if (validateSpend() && prepareSpend()) {
tvReviewSpendAmount.setText(btcEditText.getText().toString().concat(" BTC"));
try {
tvReviewSpendAmountInSats.setText(formattedSatValue(getSatValue(Double.valueOf(btcEditText.getText().toString()))).concat(" sats"));
} catch (Exception ex) {
ex.printStackTrace();
}
amountViewSwitcher.showNext();
hideKeyboard();
sendTransactionDetailsView.showReview(ricochetHopsSwitch.isChecked());
}
}
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(amountViewSwitcher.getWindowToken(), 0);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (compositeDisposables != null && !compositeDisposables.isDisposed())
compositeDisposables.dispose();
}
private boolean prepareSpend() {
restoreChangeIndexes();
double btc_amount = 0.0;
try {
btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString().trim()).doubleValue();
// Log.i("SendFragment", "amount entered:" + btc_amount);
} catch (NumberFormatException nfe) {
btc_amount = 0.0;
} catch (ParseException pe) {
btc_amount = 0.0;
}
double dAmount = btc_amount;
amount = (long) (Math.round(dAmount * 1e8));
// Log.i("SendActivity", "amount:" + amount);
if (selectedCahootsType == SelectCahootsType.type.STOWAWAY) {
setButtonForStowaway(true);
return true;
} else {
setButtonForStowaway(false);
}
address = strDestinationBTCAddress == null ? toAddressEditText.getText().toString().trim() : strDestinationBTCAddress;
if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) {
changeType = 84;
} else if (PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false) {
changeType = 84;
} else if (FormatsUtil.getInstance().isValidBech32(address) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
changeType = FormatsUtil.getInstance().isValidBech32(address) ? 84 : 49;
} else {
changeType = 44;
}
receivers = new HashMap<String, BigInteger>();
receivers.put(address, BigInteger.valueOf(amount));
if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) {
change_index = idxBIP84PostMixInternal;
} else if (changeType == 84) {
change_index = idxBIP84Internal;
} else if (changeType == 49) {
change_index = idxBIP49Internal;
} else {
change_index = idxBIP44Internal;
}
// if possible, get UTXO by input 'type': p2pkh, p2sh-p2wpkh or p2wpkh, else get all UTXO
long neededAmount = 0L;
if (FormatsUtil.getInstance().isValidBech32(address) || account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) {
neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, 0, UTXOFactory.getInstance().getCountP2WPKH(), 4).longValue();
// Log.d("SendActivity", "segwit:" + neededAmount);
} else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(0, UTXOFactory.getInstance().getCountP2SH_P2WPKH(), 0, 4).longValue();
// Log.d("SendActivity", "segwit:" + neededAmount);
} else {
neededAmount += FeeUtil.getInstance().estimatedFeeSegwit(UTXOFactory.getInstance().getCountP2PKH(), 0, 4).longValue();
// Log.d("SendActivity", "p2pkh:" + neededAmount);
}
neededAmount += amount;
neededAmount += SamouraiWallet.bDust.longValue();
// get all UTXO
List<UTXO> utxos = new ArrayList<>();
if (preselectedUTXOs != null && preselectedUTXOs.size() > 0) {
// List<UTXO> utxos = preselectedUTXOs;
// sort in descending order by value
for (UTXOCoin utxoCoin : preselectedUTXOs) {
UTXO u = new UTXO();
List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>();
outs.add(utxoCoin.getOutPoint());
u.setOutpoints(outs);
utxos.add(u);
}
} else {
utxos = SpendUtil.getUTXOS(SendActivity.this, address, neededAmount, account);
}
List<UTXO> utxosP2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllP2WPKH().values());
List<UTXO> utxosP2SH_P2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllP2SH_P2WPKH().values());
List<UTXO> utxosP2PKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllP2PKH().values());
if ((preselectedUTXOs == null || preselectedUTXOs.size() == 0) && account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) {
utxos = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllPostMix().values());
utxosP2WPKH = new ArrayList<UTXO>(UTXOFactory.getInstance().getAllPostMix().values());
utxosP2PKH.clear();
utxosP2SH_P2WPKH.clear();
}
selectedUTXO = new ArrayList<UTXO>();
long totalValueSelected = 0L;
long change = 0L;
BigInteger fee = null;
boolean canDoBoltzmann = true;
// Log.d("SendActivity", "amount:" + amount);
// Log.d("SendActivity", "balance:" + balance);
// insufficient funds
if (amount > balance) {
Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show();
}
if (preselectedUTXOs != null) {
canDoBoltzmann = false;
SPEND_TYPE = SPEND_SIMPLE;
}
// entire balance (can only be simple spend)
else if (amount == balance) {
// make sure we are using simple spend
SPEND_TYPE = SPEND_SIMPLE;
canDoBoltzmann = false;
// Log.d("SendActivity", "amount == balance");
// take all utxos, deduct fee
selectedUTXO.addAll(utxos);
for (UTXO u : selectedUTXO) {
totalValueSelected += u.getValue();
}
// Log.d("SendActivity", "balance:" + balance);
// Log.d("SendActivity", "total value selected:" + totalValueSelected);
} else {
;
}
org.apache.commons.lang3.tuple.Pair<ArrayList<MyTransactionOutPoint>, ArrayList<TransactionOutput>> pair = null;
if (SPEND_TYPE == SPEND_RICOCHET) {
boolean samouraiFeeViaBIP47 = false;
if (BIP47Meta.getInstance().getOutgoingStatus(BIP47Meta.strSamouraiDonationPCode) == BIP47Meta.STATUS_SENT_CFM) {
samouraiFeeViaBIP47 = true;
}
ricochetJsonObj = RicochetMeta.getInstance(SendActivity.this).script(amount, FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue(), address, 4, strPCode, samouraiFeeViaBIP47, ricochetStaggeredDelivery.isChecked());
if (ricochetJsonObj != null) {
try {
long totalAmount = ricochetJsonObj.getLong("total_spend");
if (totalAmount > balance) {
Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show();
ricochetHopsSwitch.setChecked(false);
return false;
}
long hop0Fee = ricochetJsonObj.getJSONArray("hops").getJSONObject(0).getLong("fee");
long perHopFee = ricochetJsonObj.getJSONArray("hops").getJSONObject(0).getLong("fee_per_hop");
long ricochetFee = hop0Fee + (RicochetMeta.defaultNbHops * perHopFee);
if (selectedCahootsType == SelectCahootsType.type.NONE) {
tvTotalFee.setText(Coin.valueOf(ricochetFee).toPlainString().concat(" BTC"));
} else {
tvTotalFee.setText("__");
}
ricochetMessage = getText(R.string.ricochet_spend1) + " " + address + " " + getText(R.string.ricochet_spend2) + " " + Coin.valueOf(totalAmount).toPlainString() + " " + getText(R.string.ricochet_spend3);
btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue((double) totalAmount)).concat(" BTC")));
return true;
} catch (JSONException je) {
return false;
}
}
return true;
} else if (SPEND_TYPE == SPEND_BOLTZMANN) {
Log.d("SendActivity", "needed amount:" + neededAmount);
List<UTXO> _utxos1 = null;
List<UTXO> _utxos2 = null;
long valueP2WPKH = UTXOFactory.getInstance().getTotalP2WPKH();
long valueP2SH_P2WPKH = UTXOFactory.getInstance().getTotalP2SH_P2WPKH();
long valueP2PKH = UTXOFactory.getInstance().getTotalP2PKH();
if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) {
valueP2WPKH = UTXOFactory.getInstance().getTotalPostMix();
valueP2SH_P2WPKH = 0L;
valueP2PKH = 0L;
}
Log.d("SendActivity", "value P2WPKH:" + valueP2WPKH);
Log.d("SendActivity", "value P2SH_P2WPKH:" + valueP2SH_P2WPKH);
Log.d("SendActivity", "value P2PKH:" + valueP2PKH);
boolean selectedP2WPKH = false;
boolean selectedP2SH_P2WPKH = false;
boolean selectedP2PKH = false;
if ((valueP2WPKH > (neededAmount * 2)) && account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) {
Log.d("SendActivity", "set 1 P2WPKH 2x");
_utxos1 = utxosP2WPKH;
selectedP2WPKH = true;
} else if ((valueP2WPKH > (neededAmount * 2)) && FormatsUtil.getInstance().isValidBech32(address)) {
Log.d("SendActivity", "set 1 P2WPKH 2x");
_utxos1 = utxosP2WPKH;
selectedP2WPKH = true;
} else if (!FormatsUtil.getInstance().isValidBech32(address) && (valueP2SH_P2WPKH > (neededAmount * 2)) && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
Log.d("SendActivity", "set 1 P2SH_P2WPKH 2x");
_utxos1 = utxosP2SH_P2WPKH;
selectedP2SH_P2WPKH = true;
} else if (!FormatsUtil.getInstance().isValidBech32(address) && (valueP2PKH > (neededAmount * 2)) && !Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
Log.d("SendActivity", "set 1 P2PKH 2x");
_utxos1 = utxosP2PKH;
selectedP2PKH = true;
} else if (valueP2WPKH > (neededAmount * 2)) {
Log.d("SendActivity", "set 1 P2WPKH 2x");
_utxos1 = utxosP2WPKH;
selectedP2WPKH = true;
} else if (valueP2SH_P2WPKH > (neededAmount * 2)) {
Log.d("SendActivity", "set 1 P2SH_P2WPKH 2x");
_utxos1 = utxosP2SH_P2WPKH;
selectedP2SH_P2WPKH = true;
} else if (valueP2PKH > (neededAmount * 2)) {
Log.d("SendActivity", "set 1 P2PKH 2x");
_utxos1 = utxosP2PKH;
selectedP2PKH = true;
} else {
;
}
if (_utxos1 == null) {
if (valueP2SH_P2WPKH > neededAmount) {
Log.d("SendActivity", "set 1 P2SH_P2WPKH");
_utxos1 = utxosP2SH_P2WPKH;
selectedP2SH_P2WPKH = true;
} else if (valueP2WPKH > neededAmount) {
Log.d("SendActivity", "set 1 P2WPKH");
_utxos1 = utxosP2WPKH;
selectedP2WPKH = true;
} else if (valueP2PKH > neededAmount) {
Log.d("SendActivity", "set 1 P2PKH");
_utxos1 = utxosP2PKH;
selectedP2PKH = true;
} else {
;
}
}
if (_utxos1 != null && _utxos2 == null) {
if (!selectedP2SH_P2WPKH && valueP2SH_P2WPKH > neededAmount) {
Log.d("SendActivity", "set 2 P2SH_P2WPKH");
_utxos2 = utxosP2SH_P2WPKH;
} else if (!selectedP2WPKH && valueP2WPKH > neededAmount) {
Log.d("SendActivity", "set 2 P2WPKH");
_utxos2 = utxosP2WPKH;
} else if (!selectedP2PKH && valueP2PKH > neededAmount) {
Log.d("SendActivity", "set 2 P2PKH");
_utxos2 = utxosP2PKH;
} else {
;
}
}
if (_utxos1 == null && _utxos2 == null) {
// can't do boltzmann, revert to SPEND_SIMPLE
canDoBoltzmann = false;
SPEND_TYPE = SPEND_SIMPLE;
} else {
Log.d("SendActivity", "boltzmann spend");
Collections.shuffle(_utxos1);
if (_utxos2 != null) {
Collections.shuffle(_utxos2);
}
// boltzmann spend (STONEWALL)
pair = SendFactory.getInstance(SendActivity.this).boltzmann(_utxos1, _utxos2, BigInteger.valueOf(amount), address, account);
if (pair == null) {
// can't do boltzmann, revert to SPEND_SIMPLE
canDoBoltzmann = false;
restoreChangeIndexes();
SPEND_TYPE = SPEND_SIMPLE;
} else {
canDoBoltzmann = true;
}
}
} else {
;
}
if (SPEND_TYPE == SPEND_SIMPLE && amount == balance && preselectedUTXOs == null) {
// do nothing, utxo selection handles above
;
}
// simple spend (less than balance)
else if (SPEND_TYPE == SPEND_SIMPLE) {
List<UTXO> _utxos = utxos;
// sort in ascending order by value
Collections.sort(_utxos, new UTXO.UTXOComparator());
Collections.reverse(_utxos);
// get smallest 1 UTXO > than spend + fee + dust
for (UTXO u : _utxos) {
Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(u.getOutpoints()));
if (u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 2).longValue())) {
selectedUTXO.add(u);
totalValueSelected += u.getValue();
Log.d("SendActivity", "spend type:" + SPEND_TYPE);
Log.d("SendActivity", "single output");
Log.d("SendActivity", "amount:" + amount);
Log.d("SendActivity", "value selected:" + u.getValue());
Log.d("SendActivity", "total value selected:" + totalValueSelected);
Log.d("SendActivity", "nb inputs:" + u.getOutpoints().size());
break;
}
}
if (selectedUTXO.size() == 0) {
// sort in descending order by value
Collections.sort(_utxos, new UTXO.UTXOComparator());
int selected = 0;
int p2pkh = 0;
int p2sh_p2wpkh = 0;
int p2wpkh = 0;
// get largest UTXOs > than spend + fee + dust
for (UTXO u : _utxos) {
selectedUTXO.add(u);
totalValueSelected += u.getValue();
selected += u.getOutpoints().size();
// Log.d("SendActivity", "value selected:" + u.getValue());
// Log.d("SendActivity", "total value selected/threshold:" + totalValueSelected + "/" + (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 2).longValue()));
Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector<MyTransactionOutPoint>(u.getOutpoints()));
p2pkh += outpointTypes.getLeft();
p2sh_p2wpkh += outpointTypes.getMiddle();
p2wpkh += outpointTypes.getRight();
if (totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, 2).longValue())) {
Log.d("SendActivity", "spend type:" + SPEND_TYPE);
Log.d("SendActivity", "multiple outputs");
Log.d("SendActivity", "amount:" + amount);
Log.d("SendActivity", "total value selected:" + totalValueSelected);
Log.d("SendActivity", "nb inputs:" + selected);
break;
}
}
}
} else if (pair != null) {
selectedUTXO.clear();
receivers.clear();
long inputAmount = 0L;
long outputAmount = 0L;
for (MyTransactionOutPoint outpoint : pair.getLeft()) {
UTXO u = new UTXO();
List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>();
outs.add(outpoint);
u.setOutpoints(outs);
totalValueSelected += u.getValue();
selectedUTXO.add(u);
inputAmount += u.getValue();
}
for (TransactionOutput output : pair.getRight()) {
try {
Script script = new Script(output.getScriptBytes());
receivers.put(script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), BigInteger.valueOf(output.getValue().longValue()));
outputAmount += output.getValue().longValue();
} catch (Exception e) {
Toast.makeText(SendActivity.this, R.string.error_bip126_output, Toast.LENGTH_SHORT).show();
return false;
}
}
change = outputAmount - amount;
fee = BigInteger.valueOf(inputAmount - outputAmount);
} else {
Toast.makeText(SendActivity.this, R.string.cannot_select_utxo, Toast.LENGTH_SHORT).show();
return false;
}
// do spend here
if (selectedUTXO.size() > 0) {
// estimate fee for simple spend, already done if boltzmann
if (SPEND_TYPE == SPEND_SIMPLE) {
List<MyTransactionOutPoint> outpoints = new ArrayList<MyTransactionOutPoint>();
for (UTXO utxo : selectedUTXO) {
outpoints.addAll(utxo.getOutpoints());
}
Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(outpoints));
if (amount == balance) {
fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 1);
amount -= fee.longValue();
receivers.clear();
receivers.put(address, BigInteger.valueOf(amount));
// fee sanity check
restoreChangeIndexes();
Transaction tx = SendFactory.getInstance(SendActivity.this).makeTransaction(account, outpoints, receivers);
tx = SendFactory.getInstance(SendActivity.this).signTransaction(tx, account);
byte[] serialized = tx.bitcoinSerialize();
Log.d("SendActivity", "size:" + serialized.length);
Log.d("SendActivity", "vsize:" + tx.getVirtualTransactionSize());
Log.d("SendActivity", "fee:" + fee.longValue());
if ((tx.hasWitness() && (fee.longValue() < tx.getVirtualTransactionSize())) || (!tx.hasWitness() && (fee.longValue() < serialized.length))) {
Toast.makeText(SendActivity.this, R.string.insufficient_fee, Toast.LENGTH_SHORT).show();
return false;
}
} else {
fee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 2);
}
}
Log.d("SendActivity", "spend type:" + SPEND_TYPE);
Log.d("SendActivity", "amount:" + amount);
Log.d("SendActivity", "total value selected:" + totalValueSelected);
Log.d("SendActivity", "fee:" + fee.longValue());
Log.d("SendActivity", "nb inputs:" + selectedUTXO.size());
change = totalValueSelected - (amount + fee.longValue());
// Log.d("SendActivity", "change:" + change);
if (change > 0L && change < SamouraiWallet.bDust.longValue() && SPEND_TYPE == SPEND_SIMPLE) {
AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.change_is_dust)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if (!isFinishing()) {
dlg.show();
}
return false;
}
_change = change;
final BigInteger _fee = fee;
String dest = null;
if (strPCode != null && strPCode.length() > 0) {
dest = BIP47Meta.getInstance().getDisplayLabel(strPCode);
} else {
dest = address;
}
if (SendAddressUtil.getInstance().get(address) == 1) {
strPrivacyWarning = getString(R.string.send_privacy_warning) + "\n\n";
} else {
strPrivacyWarning = "";
}
if (!canDoBoltzmann) {
restoreChangeIndexes();
sendTransactionDetailsView.getStoneWallSwitch().setOnClickListener(null);
sendTransactionDetailsView.getStoneWallSwitch().setEnabled(false);
sendTransactionDetailsView.enableStonewall(false);
sendTransactionDetailsView.setEntropyBarStoneWallX1(null);
sendTransactionDetailsView.getStoneWallSwitch().setOnCheckedChangeListener(onCheckedChangeListener);
}
// String message = strCannotDoBoltzmann + strNoLikedTypeBoltzmann + strPrivacyWarning + "Send " + Coin.valueOf(amount).toPlainString() + " to " + dest + " (fee:" + Coin.valueOf(_fee.longValue()).toPlainString() + ")?\n";
message = strPrivacyWarning + "Send " + Coin.valueOf(amount).toPlainString() + " to " + dest + " (fee:" + Coin.valueOf(_fee.longValue()).toPlainString() + ")?\n";
if (selectedCahootsType == SelectCahootsType.type.NONE) {
tvTotalFee.setText(Coin.valueOf(_fee.longValue()).toPlainString().concat(" BTC"));
} else {
tvTotalFee.setText("__");
}
double value = Double.parseDouble(String.valueOf(_fee.add(BigInteger.valueOf(amount))));
btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue(value))).concat(" BTC"));
switch (selectedCahootsType) {
case STONEWALLX2_MANUAL: {
sendTransactionDetailsView.showStonewallX2Layout("Manual", 1000);
btnSend.setBackgroundResource(R.drawable.button_blue);
btnSend.setText(getString(R.string.begin_stonewallx2));
break;
}
case STONEWALLX2_SAMOURAI: {
sendTransactionDetailsView.showStonewallX2Layout("Samourai Wallet", 1000);
break;
}
case STOWAWAY: {
// mixingPartner.setText("Samourai Wallet");
sendTransactionDetailsView.showStowawayLayout(address, null, 1000);
btnSend.setBackgroundResource(R.drawable.button_blue);
btnSend.setText(getString(R.string.begin_stowaway));
break;
}
case NONE: {
sendTransactionDetailsView.showStonewallx1Layout(null);
// for ricochet entropy will be 0 always
if (SPEND_TYPE == SPEND_RICOCHET) {
break;
}
if (receivers.size() <= 1) {
sendTransactionDetailsView.setEntropyBarStoneWallX1ZeroBits();
break;
}
if (receivers.size() > 8) {
sendTransactionDetailsView.setEntropyBarStoneWallX1(null);
break;
}
CalculateEntropy(selectedUTXO, receivers)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<TxProcessorResult>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(TxProcessorResult entropyResult) {
sendTransactionDetailsView.setEntropyBarStoneWallX1(entropyResult);
}
@Override
public void onError(Throwable e) {
sendTransactionDetailsView.setEntropyBarStoneWallX1(null);
e.printStackTrace();
}
@Override
public void onComplete() {
}
});
break;
}
default: {
btnSend.setBackgroundResource(R.drawable.button_green);
btnSend.setText("send ".concat(String.format(Locale.ENGLISH, "%.8f", getBtcValue((double) amount))).concat(" BTC"));
}
}
return true;
}
return false;
}
private void setButtonForStowaway(boolean prepare) {
if(prepare){
// Sets view with stowaway message
// also hides overlay push icon from button
sendTransactionDetailsView.showStowawayLayout(address, null, 1000);
btnSend.setBackgroundResource(R.drawable.button_blue);
btnSend.setText(getString(R.string.begin_stowaway));
sendTransactionDetailsView.getTransactionReview().findViewById(R.id.transaction_push_icon).setVisibility(View.INVISIBLE);
btnSend.setPadding(0,0,0,0);
}else {
// resets the changes made for stowaway
int paddingDp = 12;
float density = getResources().getDisplayMetrics().density;
int paddingPixel = (int)(paddingDp * density);
btnSend.setBackgroundResource(R.drawable.button_green);
sendTransactionDetailsView.getTransactionReview().findViewById(R.id.transaction_push_icon).setVisibility(View.VISIBLE);
btnSend.setPadding(0,paddingPixel,0,0);
}
}
private void initiateSpend() {
if (selectedCahootsType == SelectCahootsType.type.STOWAWAY || selectedCahootsType == SelectCahootsType.type.STONEWALLX2_MANUAL) {
Intent intent = new Intent(this, ManualCahootsActivity.class);
intent.putExtra("amount", amount);
intent.putExtra("account", account);
intent.putExtra("address", address);
intent.putExtra("type", selectedCahootsType == SelectCahootsType.type.STOWAWAY ? Cahoots.CAHOOTS_STOWAWAY : Cahoots.CAHOOTS_STONEWALLx2);
startActivity(intent);
return;
}
if (SPEND_TYPE == SPEND_RICOCHET) {
ricochetSpend(ricochetStaggeredDelivery.isChecked());
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(SendActivity.this);
builder.setTitle(R.string.app_name);
builder.setMessage(message);
final CheckBox cbShowAgain;
if (strPrivacyWarning.length() > 0) {
cbShowAgain = new CheckBox(SendActivity.this);
cbShowAgain.setText(R.string.do_not_repeat_sent_to);
cbShowAgain.setChecked(false);
builder.setView(cbShowAgain);
} else {
cbShowAgain = null;
}
builder.setCancelable(false);
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>();
for (UTXO u : selectedUTXO) {
outPoints.addAll(u.getOutpoints());
}
// add change
if (_change > 0L) {
if (SPEND_TYPE == SPEND_SIMPLE) {
if (account == WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix()) {
String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(WhirlpoolMeta.getInstance(SendActivity.this).getWhirlpoolPostmix(), AddressFactory.CHANGE_CHAIN, AddressFactory.getInstance(SendActivity.this).getHighestPostChangeIdx()).getBech32AsString();
receivers.put(change_address, BigInteger.valueOf(_change));
} else if (changeType == 84) {
String change_address = BIP84Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getBech32AsString();
receivers.put(change_address, BigInteger.valueOf(_change));
} else if (changeType == 49) {
String change_address = BIP49Util.getInstance(SendActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString();
receivers.put(change_address, BigInteger.valueOf(_change));
} else {
try {
String change_address = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddressAt(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx()).getAddressString();
receivers.put(change_address, BigInteger.valueOf(_change));
} catch (IOException ioe) {
Toast.makeText(SendActivity.this, R.string.error_change_output, Toast.LENGTH_SHORT).show();
return;
} catch (MnemonicException.MnemonicLengthException mle) {
Toast.makeText(SendActivity.this, R.string.error_change_output, Toast.LENGTH_SHORT).show();
return;
}
}
} else if (SPEND_TYPE == SPEND_BOLTZMANN) {
// do nothing, change addresses included
;
} else {
;
}
}
SendParams.getInstance().setParams(outPoints,
receivers,
strPCode,
SPEND_TYPE,
_change,
changeType,
account,
address,
strPrivacyWarning.length() > 0,
cbShowAgain != null ? cbShowAgain.isChecked() : false,
amount,
change_index
);
Intent _intent = new Intent(SendActivity.this, TxAnimUIActivity.class);
startActivity(_intent);
}
});
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
SendActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// btSend.setActivated(true);
// btSend.setClickable(true);
// dialog.dismiss();
}
});
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void ricochetSpend(boolean staggered) {
AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this)
.setTitle(R.string.app_name)
.setMessage(ricochetMessage)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
if (staggered) {
// Log.d("SendActivity", "Ricochet staggered:" + ricochetJsonObj.toString());
try {
if (ricochetJsonObj.has("hops")) {
JSONArray hops = ricochetJsonObj.getJSONArray("hops");
if (hops.getJSONObject(0).has("nTimeLock")) {
JSONArray nLockTimeScript = new JSONArray();
for (int i = 0; i < hops.length(); i++) {
JSONObject hopObj = hops.getJSONObject(i);
int seq = i;
long locktime = hopObj.getLong("nTimeLock");
String hex = hopObj.getString("tx");
JSONObject scriptObj = new JSONObject();
scriptObj.put("hop", i);
scriptObj.put("nlocktime", locktime);
scriptObj.put("tx", hex);
nLockTimeScript.put(scriptObj);
}
JSONObject nLockTimeObj = new JSONObject();
nLockTimeObj.put("script", nLockTimeScript);
// Log.d("SendActivity", "Ricochet nLockTime:" + nLockTimeObj.toString());
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
String url = WebUtil.getAPIUrl(SendActivity.this);
url += "pushtx/schedule";
try {
String result = "";
if (TorManager.getInstance(getApplicationContext()).isRequired()) {
result = WebUtil.getInstance(SendActivity.this).tor_postURL(url, nLockTimeObj);
} else {
result = WebUtil.getInstance(SendActivity.this).postURL("application/json", url, nLockTimeObj.toString());
}
// Log.d("SendActivity", "Ricochet staggered result:" + result);
JSONObject resultObj = new JSONObject(result);
if (resultObj.has("status") && resultObj.getString("status").equalsIgnoreCase("ok")) {
Toast.makeText(SendActivity.this, R.string.ricochet_nlocktime_ok, Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(SendActivity.this, R.string.ricochet_nlocktime_ko, Toast.LENGTH_LONG).show();
finish();
}
} catch (Exception e) {
Log.d("SendActivity", e.getMessage());
Toast.makeText(SendActivity.this, R.string.ricochet_nlocktime_ko, Toast.LENGTH_LONG).show();
finish();
}
Looper.loop();
}
}).start();
}
}
} catch (JSONException je) {
Log.d("SendActivity", je.getMessage());
}
} else {
RicochetMeta.getInstance(SendActivity.this).add(ricochetJsonObj);
Intent intent = new Intent(SendActivity.this, RicochetActivity.class);
startActivityForResult(intent, RICOCHET);
}
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if (!isFinishing()) {
dlg.show();
}
}
private void backToTransactionView() {
amountViewSwitcher.showPrevious();
sendTransactionDetailsView.showTransaction();
}
@Override
public void onBackPressed() {
if (sendTransactionDetailsView.isReview()) {
backToTransactionView();
} else {
super.onBackPressed();
}
}
private void enableAmount(boolean enable) {
btcEditText.setEnabled(enable);
satEditText.setEnabled(enable);
}
private void processScan(String data) {
if (data.contains("https://bitpay.com")) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this)
.setTitle(R.string.app_name)
.setMessage(R.string.no_bitpay)
.setCancelable(false)
.setPositiveButton(R.string.learn_more, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://blog.samouraiwallet.com/post/169222582782/bitpay-qr-codes-are-no-longer-valid-important"));
startActivity(intent);
}
}).setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if (!isFinishing()) {
dlg.show();
}
return;
}
if (Cahoots.isCahoots(data.trim())) {
// CahootsUtil.getInstance(SendActivity.this).processCahoots(data.trim(), account);
Intent cahootsIntent = new Intent(this, ManualCahootsActivity.class);
cahootsIntent.putExtra("account", account);
cahootsIntent.putExtra("payload",data.trim());
startActivity(cahootsIntent);
return;
}
if (FormatsUtil.getInstance().isPSBT(data.trim())) {
CahootsUtil.getInstance(SendActivity.this).doPSBT(data.trim());
return;
}
if (FormatsUtil.getInstance().isValidPaymentCode(data)) {
processPCode(data, null);
return;
}
if (FormatsUtil.getInstance().isBitcoinUri(data)) {
String address = FormatsUtil.getInstance().getBitcoinAddress(data);
String amount = FormatsUtil.getInstance().getBitcoinAmount(data);
setToAddress(address);
if (amount != null) {
try {
NumberFormat btcFormat = NumberFormat.getInstance(Locale.US);
btcFormat.setMaximumFractionDigits(8);
btcFormat.setMinimumFractionDigits(1);
// setToAddress(btcFormat.format(Double.parseDouble(amount) / 1e8));
btcEditText.setText(btcFormat.format(Double.parseDouble(amount) / 1e8));
} catch (NumberFormatException nfe) {
// setToAddress("0.0");
}
}
final String strAmount;
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMinimumIntegerDigits(1);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(8);
strAmount = nf.format(balance / 1e8);
tvMaxAmount.setText(strAmount + " " + getDisplayUnits());
try {
if (amount != null && Double.parseDouble(amount) != 0.0) {
toAddressEditText.setEnabled(false);
// selectPaynymBtn.setEnabled(false);
// selectPaynymBtn.setAlpha(0.5f);
// Toast.makeText(this, R.string.no_edit_BIP21_scan, Toast.LENGTH_SHORT).show();
enableAmount(false);
}
} catch (NumberFormatException nfe) {
enableAmount(true);
}
} else if (FormatsUtil.getInstance().isValidBitcoinAddress(data)) {
if (FormatsUtil.getInstance().isValidBech32(data)) {
setToAddress(data.toLowerCase());
} else {
setToAddress(data);
}
} else if (data.contains("?")) {
String pcode = data.substring(0, data.indexOf("?"));
// not valid BIP21 but seen often enough
if (pcode.startsWith("bitcoin:
pcode = pcode.substring(10);
}
if (pcode.startsWith("bitcoin:")) {
pcode = pcode.substring(8);
}
if (FormatsUtil.getInstance().isValidPaymentCode(pcode)) {
processPCode(pcode, data.substring(data.indexOf("?")));
}
} else {
Toast.makeText(this, R.string.scan_error, Toast.LENGTH_SHORT).show();
}
validateSpend();
}
public String getDisplayUnits() {
return MonetaryUtil.getInstance().getBTCUnits();
}
private void processPCode(String pcode, String meta) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
setBalance();
}
}, 2000);
if (FormatsUtil.getInstance().isValidPaymentCode(pcode)) {
if (BIP47Meta.getInstance().getOutgoingStatus(pcode) == BIP47Meta.STATUS_SENT_CFM) {
try {
PaymentCode _pcode = new PaymentCode(pcode);
PaymentAddress paymentAddress = BIP47Util.getInstance(this).getSendAddress(_pcode, BIP47Meta.getInstance().getOutgoingIdx(pcode));
if (BIP47Meta.getInstance().getSegwit(pcode)) {
SegwitAddress segwitAddress = new SegwitAddress(paymentAddress.getSendECKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
strDestinationBTCAddress = segwitAddress.getBech32AsString();
} else {
strDestinationBTCAddress = paymentAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
strPCode = _pcode.toString();
setToAddress(BIP47Meta.getInstance().getDisplayLabel(strPCode));
toAddressEditText.setEnabled(false);
validateSpend();
} catch (Exception e) {
Toast.makeText(this, R.string.error_payment_code, Toast.LENGTH_SHORT).show();
}
} else {
// Toast.makeText(SendActivity.this, "Payment must be added and notification tx sent", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, PayNymDetailsActivity.class);
intent.putExtra("pcode", pcode);
intent.putExtra("label", "");
if (meta != null && meta.startsWith("?") && meta.length() > 1) {
meta = meta.substring(1);
if (meta.length() > 0) {
String _meta = null;
Map<String, String> map = new HashMap<String, String>();
meta.length();
try {
_meta = URLDecoder.decode(meta, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
map = Splitter.on('&').trimResults().withKeyValueSeparator("=").split(_meta);
intent.putExtra("label", map.containsKey("title") ? map.get("title").trim() : "");
}
}
if (!openedPaynym) {
startActivity(intent);
openedPaynym = true;
}
}
} else {
Toast.makeText(this, R.string.invalid_payment_code, Toast.LENGTH_SHORT).show();
}
}
private boolean validateSpend() {
boolean isValid = false;
boolean insufficientFunds = false;
double btc_amount = 0.0;
String strBTCAddress = getToAddress();
if (strBTCAddress.startsWith("bitcoin:")) {
setToAddress(strBTCAddress.substring(8));
}
setToAddress(strBTCAddress);
try {
btc_amount = NumberFormat.getInstance(Locale.US).parse(btcEditText.getText().toString()).doubleValue();
// Log.i("SendFragment", "amount entered:" + btc_amount);
} catch (NumberFormatException nfe) {
btc_amount = 0.0;
} catch (ParseException pe) {
btc_amount = 0.0;
}
final double dAmount = btc_amount;
// Log.i("SendFragment", "amount entered (converted):" + dAmount);
final long amount = (long) (Math.round(dAmount * 1e8));
Log.i("SendFragment", "amount entered (converted to long):" + amount);
Log.i("SendFragment", "balance:" + balance);
if (amount > balance) {
insufficientFunds = true;
}
if(selectedCahootsType != SelectCahootsType.type.NONE){
totalMinerFeeLayout.setVisibility(View.INVISIBLE);
}else {
totalMinerFeeLayout.setVisibility(View.VISIBLE);
}
if (selectedCahootsType == SelectCahootsType.type.STOWAWAY && !insufficientFunds && amount!=0) {
enableReviewButton(true);
return true;
}
// Log.i("SendFragment", "insufficient funds:" + insufficientFunds);
if (amount >= SamouraiWallet.bDust.longValue() && FormatsUtil.getInstance().isValidBitcoinAddress(getToAddress())) {
isValid = true;
} else
isValid = amount >= SamouraiWallet.bDust.longValue() && strDestinationBTCAddress != null && FormatsUtil.getInstance().isValidBitcoinAddress(strDestinationBTCAddress);
if (insufficientFunds) {
Toast.makeText(this, getString(R.string.insufficient_funds), Toast.LENGTH_SHORT).show();
}
if (!isValid || insufficientFunds) {
enableReviewButton(false);
return false;
} else {
enableReviewButton(true);
return true;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) {
;
} else if (resultCode == Activity.RESULT_OK && requestCode == RICOCHET) {
;
} else if (resultCode == Activity.RESULT_CANCELED && requestCode == RICOCHET) {
;
} else {
;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.send_menu, menu);
if (account != 0) {
menu.findItem(R.id.action_batch).setVisible(false);
menu.findItem(R.id.action_ricochet).setVisible(false);
menu.findItem(R.id.action_empty_ricochet).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (item.getItemId() == android.R.id.home) {
this.onBackPressed();
return true;
}
if (item.getItemId() == R.id.select_paynym) {
PaynymSelectModalFragment paynymSelectModalFragment =
PaynymSelectModalFragment.newInstance(code -> processPCode(code, null));
paynymSelectModalFragment.show(getSupportFragmentManager(), "paynym_select");
return true;
}
// noinspection SimplifiableIfStatement
if (id == R.id.action_scan_qr) {
doScan();
} else if (id == R.id.action_ricochet) {
Intent intent = new Intent(SendActivity.this, RicochetActivity.class);
startActivity(intent);
} else if (id == R.id.action_empty_ricochet) {
emptyRicochetQueue();
} else if (id == R.id.action_utxo) {
doUTXO();
} else if (id == R.id.action_fees) {
doFees();
} else if (id == R.id.action_batch) {
doBatchSpend();
} else if (id == R.id.action_support) {
doSupport();
} else {
;
}
return super.onOptionsItemSelected(item);
}
private void emptyRicochetQueue() {
RicochetMeta.getInstance(this).setLastRicochet(null);
RicochetMeta.getInstance(this).empty();
new Thread(new Runnable() {
@Override
public void run() {
try {
PayloadUtil.getInstance(SendActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(SendActivity.this).getGUID() + AccessFactory.getInstance(SendActivity.this).getPIN()));
} catch (Exception e) {
;
}
}
}).start();
}
private void doScan() {
CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet();
cameraFragmentBottomSheet.show(getSupportFragmentManager(), cameraFragmentBottomSheet.getTag());
cameraFragmentBottomSheet.setQrCodeScanLisenter(code -> {
cameraFragmentBottomSheet.dismissAllowingStateLoss();
processScan(code);
});
}
private void doSupport() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/section/8-sending-bitcoin"));
startActivity(intent);
}
private void doUTXO() {
Intent intent = new Intent(SendActivity.this, UTXOSActivity.class);
if (account != 0) {
intent.putExtra("_account", account);
}
startActivity(intent);
}
private void doBatchSpend() {
Intent intent = new Intent(SendActivity.this, BatchSendActivity.class);
startActivity(intent);
}
private void doFees() {
SuggestedFee highFee = FeeUtil.getInstance().getHighFee();
SuggestedFee normalFee = FeeUtil.getInstance().getNormalFee();
SuggestedFee lowFee = FeeUtil.getInstance().getLowFee();
String message = getText(R.string.current_fee_selection) + " " + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
message += "\n";
message += getText(R.string.current_hi_fee_value) + " " + (highFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
message += "\n";
message += getText(R.string.current_mid_fee_value) + " " + (normalFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
message += "\n";
message += getText(R.string.current_lo_fee_value) + " " + (lowFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.ok, (dialog, whichButton) -> dialog.dismiss());
if (!isFinishing()) {
dlg.show();
}
}
private void saveChangeIndexes() {
idxBIP84PostMixInternal = AddressFactory.getInstance(SendActivity.this).getHighestPostChangeIdx();
idxBIP84Internal = BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx();
idxBIP49Internal = BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().getAddrIdx();
try {
idxBIP44Internal = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx();
} catch (IOException | MnemonicException.MnemonicLengthException e) {
;
}
}
private void restoreChangeIndexes() {
AddressFactory.getInstance(SendActivity.this).setHighestPostChangeIdx(idxBIP84PostMixInternal);
BIP84Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(idxBIP84Internal);
BIP49Util.getInstance(SendActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(idxBIP49Internal);
try {
HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(idxBIP44Internal);
} catch (IOException | MnemonicException.MnemonicLengthException e) {
;
}
}
private Observable<TxProcessorResult> CalculateEntropy(ArrayList<UTXO> selectedUTXO, HashMap<String, BigInteger> receivers) {
return Observable.create(emitter -> {
Map<String, Long> inputs = new HashMap<>();
Map<String, Long> outputs = new HashMap<>();
for (Map.Entry<String, BigInteger> mapEntry : receivers.entrySet()) {
String toAddress = mapEntry.getKey();
BigInteger value = mapEntry.getValue();
outputs.put(toAddress, value.longValue());
}
for (int i = 0; i < selectedUTXO.size(); i++) {
inputs.put(stubAddress[i], selectedUTXO.get(i).getValue());
}
TxProcessor txProcessor = new TxProcessor(BoltzmannSettings.MAX_DURATION_DEFAULT, BoltzmannSettings.MAX_TXOS_DEFAULT);
Txos txos = new Txos(inputs, outputs);
TxProcessorResult result = txProcessor.processTx(txos, 0.005f, TxosLinkerOptionEnum.PRECHECK, TxosLinkerOptionEnum.LINKABILITY, TxosLinkerOptionEnum.MERGE_INPUTS);
emitter.onNext(result);
});
}
}
|
package com.xlythe.sms.adapter;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.LruCache;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.makeramen.roundedimageview.RoundedImageView;
import com.xlythe.sms.R;
import com.xlythe.sms.drawable.ProfileDrawable;
import com.xlythe.sms.util.ColorUtils;
import com.xlythe.sms.util.DateFormatter;
import com.xlythe.textmanager.text.Attachment;
import com.xlythe.textmanager.text.Contact;
import com.xlythe.textmanager.text.Status;
import com.xlythe.textmanager.text.Text;
import com.xlythe.textmanager.text.TextManager;
import com.xlythe.textmanager.text.concurrency.Future;
public class MessageAdapter extends SelectableAdapter<Text, MessageAdapter.MessageViewHolder> {
private static final String TAG = MessageAdapter.class.getSimpleName();
private static final boolean DEBUG = false;
private static final int CACHE_SIZE = 50;
// Duration between considering a text to be part of the same message, or split into different messages
private static final long SPLIT_DURATION = 60 * 1000;
private static final long TIMEOUT = 10 * 1000;
private static final int TYPE_TOP_RIGHT = 0;
private static final int TYPE_MIDDLE_RIGHT = 1;
private static final int TYPE_BOTTOM_RIGHT = 2;
private static final int TYPE_SINGLE_RIGHT = 3;
private static final int TYPE_TOP_LEFT = 4;
private static final int TYPE_MIDDLE_LEFT = 5;
private static final int TYPE_BOTTOM_LEFT = 6;
private static final int TYPE_SINGLE_LEFT = 7;
private static final int TYPE_ATTACHMENT_TOP_LEFT = 8;
private static final int TYPE_ATTACHMENT_MIDDLE_LEFT = 9;
private static final int TYPE_ATTACHMENT_BOTTOM_LEFT = 10;
private static final int TYPE_ATTACHMENT_TOP_RIGHT = 11;
private static final int TYPE_ATTACHMENT_MIDDLE_RIGHT = 12;
private static final int TYPE_ATTACHMENT_BOTTOM_RIGHT = 13;
private static final int TYPE_ATTACHMENT_SINGLE_LEFT = 17;
private static final int TYPE_ATTACHMENT_SINGLE_RIGHT = 18;
private static final SparseIntArray LAYOUT_MAP = new SparseIntArray();
static {
LAYOUT_MAP.put(TYPE_TOP_RIGHT, R.layout.right_top);
LAYOUT_MAP.put(TYPE_MIDDLE_RIGHT, R.layout.right_middle);
LAYOUT_MAP.put(TYPE_BOTTOM_RIGHT, R.layout.right_bottom);
LAYOUT_MAP.put(TYPE_SINGLE_RIGHT, R.layout.right_single);
LAYOUT_MAP.put(TYPE_TOP_LEFT, R.layout.left_top);
LAYOUT_MAP.put(TYPE_MIDDLE_LEFT, R.layout.left_middle);
LAYOUT_MAP.put(TYPE_BOTTOM_LEFT, R.layout.left_bottom);
LAYOUT_MAP.put(TYPE_SINGLE_LEFT, R.layout.left_single);
LAYOUT_MAP.put(TYPE_ATTACHMENT_TOP_LEFT, R.layout.left_attachment_top);
LAYOUT_MAP.put(TYPE_ATTACHMENT_MIDDLE_LEFT, R.layout.left_attachment_middle);
LAYOUT_MAP.put(TYPE_ATTACHMENT_BOTTOM_LEFT, R.layout.left_attachment_bottom);
LAYOUT_MAP.put(TYPE_ATTACHMENT_SINGLE_LEFT, R.layout.left_attachment_single);
LAYOUT_MAP.put(TYPE_ATTACHMENT_TOP_RIGHT, R.layout.right_attachment_top);
LAYOUT_MAP.put(TYPE_ATTACHMENT_MIDDLE_RIGHT, R.layout.right_attachment_middle);
LAYOUT_MAP.put(TYPE_ATTACHMENT_BOTTOM_RIGHT, R.layout.right_attachment_bottom);
LAYOUT_MAP.put(TYPE_ATTACHMENT_SINGLE_RIGHT, R.layout.right_attachment_single);
}
private Text.TextCursor mCursor;
private Context mContext;
private MessageAdapter.OnClickListener mClickListener;
private final LruCache<Integer, Text> mTextLruCache = new LruCache<>(CACHE_SIZE);
private int mMemberSize = -1;
public static boolean hasFailed(Text text) {
// This is kinda hacky because if the app force closes then the message status isn't updated
return text.getStatus() == Status.FAILED
|| (text.getStatus() == Status.PENDING
&& System.currentTimeMillis() - text.getTimestamp() > TIMEOUT);
}
public static class MessageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
private Text mText;
private Context mContext;
MessageAdapter.OnClickListener mListener;
public TextView mDate;
public TextView mTextView;
public FrameLayout mFrame;
public MessageViewHolder(View v, MessageAdapter.OnClickListener listener) {
super(v);
mListener = listener;
v.setOnClickListener(this);
v.setOnLongClickListener(this);
mDate = (TextView) v.findViewById(R.id.date);
mFrame = (FrameLayout) v.findViewById(R.id.frame);
mTextView = (TextView) v.findViewById(R.id.message);
}
public void setMessage(Context context, Text text, boolean selected) {
mText = text;
mContext = context;
if (mText.getStatus() == Status.PENDING) {
setDateText(getContext().getString(R.string.message_pending));
} else {
setDateText(DateFormatter.getFormattedDate(text));
}
if (hasFailed(text)) {
mTextView.setLinksClickable(false);
} else {
mTextView.setLinksClickable(true);
}
if (mDate != null) {
if (hasFailed(text)) {
mDate.setTextColor(context.getResources().getColor(android.R.color.holo_red_light));
mDate.setText(R.string.message_failed_to_send);
} else {
mDate.setTextColor(context.getResources().getColor(R.color.date_text_color));
}
}
setBodyText(text.getBody());
if (selected) {
setColor(tintColor(Color.WHITE));
} else {
setColor(context.getResources().getColor(android.R.color.white));
}
// We set this here because of attachments
if (hasFailed(text)) {
mFrame.setAlpha(0.4f);
} else {
mFrame.setAlpha(1f);
}
}
public void setColor(int color) {
mFrame.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
}
public void setBodyText(String body) {
if (body == null) {
mFrame.setVisibility(View.GONE);
} else {
mFrame.setVisibility(View.VISIBLE);
mTextView.setText(body);
}
}
public void setDateText(String dateText) {
if (mDate != null) {
mDate.setText(dateText);
}
}
@Override
public void onClick(View v) {
if (mListener != null) {
mListener.onItemClicked(getMessage());
}
}
@Override
public boolean onLongClick(View v) {
return mListener != null && mListener.onItemLongClicked(getMessage());
}
public Text getMessage() {
return mText;
}
public Context getContext() {
return mContext;
}
public TextManager getManager() {
return TextManager.getInstance(mContext);
}
}
public static class LeftViewHolder extends MessageViewHolder {
private ImageView mProfile;
public LeftViewHolder(View v, MessageAdapter.OnClickListener listener) {
super(v, listener);
mProfile = (ImageView) v.findViewById(R.id.profile_image);
}
@Override
public void setMessage(Context context, Text text, boolean selected) {
super.setMessage(context, text, selected);
if (selected) {
setColor(tintColor(ColorUtils.getColor(text.getThreadIdAsLong())));
} else {
setColor(ColorUtils.getColor(text.getThreadIdAsLong()));
}
// This is if a message failed to download
if (mDate != null) {
if (hasFailed(text)) {
mDate.setText("Message failed to download");
}
}
if (mProfile != null) {
getManager().getSender(getMessage()).get(new Future.Callback<Contact>() {
@Override
public void get(Contact instance) {
mProfile.setImageDrawable(new ProfileDrawable(getContext(), instance));
}
});
}
}
public void setBodyText(String body) {
if (body == null) {
if (hasFailed(getMessage())) {
mFrame.setVisibility(View.VISIBLE);
mTextView.setText("Tap to retry");
} else {
mFrame.setVisibility(View.GONE);
}
} else {
mFrame.setVisibility(View.VISIBLE);
mTextView.setText(body);
}
}
}
public static class AttachmentViewHolder extends MessageViewHolder {
private RoundedImageView mImageView;
private ImageButton mShare;
private ImageView mVideoLabel;
public AttachmentViewHolder(View v, MessageAdapter.OnClickListener listener) {
super(v, listener);
mImageView = (RoundedImageView) v.findViewById(R.id.image);
mShare = (ImageButton) v.findViewById(R.id.share);
mVideoLabel = (ImageView) v.findViewById(R.id.video_label);
mShare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) {
mListener.onShareClicked(getMessage());
}
}
});
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) {
mListener.onAttachmentClicked(getMessage());
}
}
});
}
@Override
public void setMessage(Context context, Text text, boolean selected) {
super.setMessage(context, text, selected);
setImage();
if (selected) {
setColor(context.getResources().getColor(R.color.select_tint));
} else {
mImageView.clearColorFilter();
}
if (selected) {
setColorText(tintColor(Color.WHITE));
} else {
setColorText(context.getResources().getColor(android.R.color.white));
}
}
public void setColorText(int color) {
mFrame.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
}
@Override
public void setColor(int color) {
mImageView.setColorFilter(color);
}
public void setImage() {
if (getMessage().getAttachment().getType() == Attachment.Type.VIDEO){
mVideoLabel.setVisibility(View.VISIBLE);
} else {
mVideoLabel.setVisibility(View.GONE);
}
Glide.with(getContext())
.load(getMessage().getAttachment().getUri())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.dontAnimate()
.placeholder(R.color.loading)
.into(mImageView);
}
}
public static class LeftAttachmentViewHolder extends AttachmentViewHolder {
private ImageView mProfile;
public LeftAttachmentViewHolder(View v, MessageAdapter.OnClickListener listener) {
super(v, listener);
mProfile = (ImageView) v.findViewById(R.id.profile_image);
}
@Override
public void setMessage(Context context, Text text, boolean selected) {
super.setMessage(context, text, selected);
if (selected) {
setColorText(tintColor(ColorUtils.getColor(text.getThreadIdAsLong())));
} else {
setColorText(ColorUtils.getColor(text.getThreadIdAsLong()));
}
if (mProfile != null) {
getManager().getSender(getMessage()).get(new Future.Callback<Contact>() {
@Override
public void get(Contact instance) {
mProfile.setImageDrawable(new ProfileDrawable(getContext(), instance));
}
});
}
}
}
public MessageAdapter(Context context, Text.TextCursor cursor) {
mCursor = cursor;
mContext = context;
}
public void setOnClickListener(MessageAdapter.OnClickListener onClickListener) {
mClickListener = onClickListener;
}
// Create new views (invoked by the layout manager)
@Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(mContext).inflate(LAYOUT_MAP.get(viewType), parent, false);
switch(viewType) {
case TYPE_TOP_RIGHT:
case TYPE_MIDDLE_RIGHT:
case TYPE_BOTTOM_RIGHT:
case TYPE_SINGLE_RIGHT:
return new MessageViewHolder(layout, mClickListener);
case TYPE_TOP_LEFT:
case TYPE_MIDDLE_LEFT:
case TYPE_BOTTOM_LEFT:
case TYPE_SINGLE_LEFT:
return new LeftViewHolder(layout, mClickListener);
case TYPE_ATTACHMENT_TOP_LEFT:
case TYPE_ATTACHMENT_MIDDLE_LEFT:
case TYPE_ATTACHMENT_BOTTOM_LEFT:
case TYPE_ATTACHMENT_SINGLE_LEFT:
return new LeftAttachmentViewHolder(layout, mClickListener);
case TYPE_ATTACHMENT_TOP_RIGHT:
case TYPE_ATTACHMENT_MIDDLE_RIGHT:
case TYPE_ATTACHMENT_BOTTOM_RIGHT:
case TYPE_ATTACHMENT_SINGLE_RIGHT:
return new AttachmentViewHolder(layout, mClickListener);
default:
return new MessageViewHolder(layout, mClickListener);
}
}
@Override
public int getItemViewType(int position) {
TextManager manager = TextManager.getInstance(mContext);
Text text = getText(position);
if (mMemberSize == -1) {
mMemberSize = manager.getMembers(text).get().size();
}
Text prevText = null;
if (position > 0) {
prevText = getText(position - 1);
}
Text nextText = null;
if (position + 1 < mCursor.getCount()) {
nextText = getText(position + 1);
}
// Get the date of the current, previous and next message.
long dateCurrent = text.getTimestamp();
long datePrevious = 0;
long dateNext = 0;
// Get the sender of the current, previous and next message. (returns true if you)
boolean userCurrent = text.isIncoming();
boolean userPrevious;
boolean userNext;
// This should improve speed
Contact contactCurrent;
if (!text.isIncoming()) {
contactCurrent = manager.getSelf();
} else if (mMemberSize == 2) {
contactCurrent = null;
} else {
contactCurrent = manager.getSender(text).get();
}
Contact contactPrevious = contactCurrent;
Contact contactNext = null;
// Check if previous message exists, then get the date and sender.
if (prevText != null) {
datePrevious = prevText.getTimestamp();
if (!prevText.isIncoming()) {
contactPrevious = manager.getSelf();
} else if (mMemberSize == 2) {
contactPrevious = null;
} else {
contactPrevious = manager.getSender(prevText).get();
}
}
// Check if next message exists, then get the date and sender.
if (nextText != null) {
dateNext = nextText.getTimestamp();
if (!nextText.isIncoming()) {
contactNext = manager.getSelf();
} else if (mMemberSize == 2) {
contactNext = null;
} else {
contactNext = manager.getSender(nextText).get();
}
}
if (contactCurrent == null) {
userNext = null == contactNext;
userPrevious = null == contactPrevious;
} else {
userNext = contactCurrent.equals(contactNext);
userPrevious = contactCurrent.equals(contactPrevious);
}
// Calculate time gap.
boolean largePC = dateCurrent - datePrevious > SPLIT_DURATION;
boolean largeCN = dateNext - dateCurrent > SPLIT_DURATION;
if (DEBUG) {
Log.d(TAG, String.format(
"userCurrent=%s, userPrevious=%s, userNext=%s," +
"dateCurrent=%s, datePrevious=%s, dateNext=%s," +
"largePC=%s, largeCN=%s",
userCurrent, userPrevious, userNext,
dateCurrent, datePrevious, dateNext,
largePC, largeCN));
}
if (!userCurrent && (userPrevious || largePC) && (!userNext && !largeCN)) {
if (text.isMms()) {
if (text.getAttachment() != null) {
return TYPE_ATTACHMENT_TOP_RIGHT;
}
}
return TYPE_TOP_RIGHT;
} else if (!userCurrent && (!userPrevious && !largePC) && (!userNext && !largeCN)) {
if (text.isMms()) {
if (text.getAttachment() != null) {
return TYPE_ATTACHMENT_MIDDLE_RIGHT;
}
}
return TYPE_MIDDLE_RIGHT;
} else if (!userCurrent && (!userPrevious && !largePC)) {
if (text.isMms()) {
if (text.getAttachment() != null) {
return TYPE_ATTACHMENT_BOTTOM_RIGHT;
}
}
return TYPE_BOTTOM_RIGHT;
} else if (!userCurrent) {
if (text.isMms()) {
if (text.getAttachment() != null) {
return TYPE_ATTACHMENT_SINGLE_RIGHT;
}
}
return TYPE_SINGLE_RIGHT;
} else if ((!userPrevious || largePC) && (userNext && !largeCN)) {
if (text.isMms()) {
if (text.getAttachment() != null) {
return TYPE_ATTACHMENT_TOP_LEFT;
}
}
return TYPE_TOP_LEFT;
} else if ((userPrevious && !largePC) && (userNext && !largeCN)) {
if (text.isMms()) {
if (text.getAttachment() != null) {
return TYPE_ATTACHMENT_MIDDLE_LEFT;
}
}
return TYPE_MIDDLE_LEFT;
} else if (userPrevious && !largePC) {
if (text.isMms()) {
if (text.getAttachment() != null) {
return TYPE_ATTACHMENT_BOTTOM_LEFT;
}
}
return TYPE_BOTTOM_LEFT;
} else {
if (text.isMms()) {
if (text.getAttachment() != null) {
return TYPE_ATTACHMENT_SINGLE_LEFT;
}
}
return TYPE_SINGLE_LEFT;
}
}
private Text getText(int position) {
Text text = mTextLruCache.get(position);
if (text == null) {
mCursor.moveToPosition(position);
text = mCursor.getText();
mTextLruCache.put(position, text);
}
return text;
}
@Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
boolean selected = isSelected(getText(position));
holder.setMessage(mContext, getText(position), selected);
}
@Override
public int getItemCount() {
return mCursor.getCount();
}
public Cursor getCursor() {
return mCursor;
}
public void destroy() {
if (!mCursor.isClosed()) {
mCursor.close();
}
}
public static int tintColor(int color) {
int red = color >> 16 & 0x0000ff;
int green = color >> 8 & 0x0000ff;
int blue = color & 0x0000ff;
red = (int)((double)red * 0.7);
green = (int)((double)green * 0.7);
blue = (int)((double)blue * 0.7);
return Color.argb(255, red, green, blue);
}
public void swapCursor(Text.TextCursor cursor) {
if (!mCursor.isClosed()) {
mCursor.close();
}
mCursor = cursor;
mTextLruCache.evictAll();
notifyDataSetChanged();
}
public interface OnClickListener {
void onItemClicked(Text text);
boolean onItemLongClicked(Text text);
void onAttachmentClicked(Text text);
void onShareClicked(Text text);
}
}
|
package it.unical.mat.dlv;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DlvAnswerSetMatcher extends Thread{
private CyclicBarrier cyclicBarrier;
private ArrayList<String> answerSets;
private String outputToParse;
public DlvAnswerSetMatcher(String outPutToParse,
CyclicBarrier cyclicBarrier) {
this.outputToParse = outPutToParse;
this.cyclicBarrier = cyclicBarrier;
this.answerSets = new ArrayList<String>();
}
public void run() {
Pattern pattern = Pattern.compile("[{](.)*[}]");
Matcher matcher = pattern.matcher(outputToParse);
while (matcher.find()) {
answerSets.add(matcher.group());
}
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<String> getAnswerSets(){
return answerSets;
}
}
|
package net.formula97.fakegpbase;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.FormatException;
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.provider.Settings;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.gson.Gson;
import net.formula97.fakegpbase.Databases.GunplaInfo;
import net.formula97.fakegpbase.Databases.GunplaInfoModel;
import net.formula97.fakegpbase.fragments.GunplaSelectionDialogs;
import net.formula97.fakegpbase.fragments.MessageDialogs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends Activity
implements MessageDialogs.DialogsButtonSelectionCallback,
GunplaSelectionDialogs.OnGunplaSelectedListener {
private TextView tvBuilderName;
private TextView tvFighterName;
private TextView tvScale;
private TextView tvClass;
private TextView tvModelNo;
private TextView tvGunplaName;
private boolean mAlreadyShown = false;
private final String KeyAlreadyShown = "KeyAlreadyShown";
private final String KeyGunplaInfoJson = "KeyGunplaInfoJson";
private String mBuilderName;
private String mFighterName;
private String mScaleVal;
private String mClassVal;
private String mModelNo;
private String mGunplaName;
private String mGunplaInfoJson;
private GunplaInfo gunplaInfo;
private NfcAdapter mNfcAdapter;
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvBuilderName = (TextView) findViewById(R.id.tvBuilderName);
tvFighterName = (TextView) findViewById(R.id.tvFighterName);
tvScale = (TextView) findViewById(R.id.tvScale);
tvClass = (TextView) findViewById(R.id.tvClass);
tvModelNo = (TextView) findViewById(R.id.tvModelNo);
tvGunplaName = (TextView) findViewById(R.id.tvGunplaName);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
initValiables();
}
/**
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/**
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent setting = new Intent(this, SettingActivity.class);
startActivity(setting);
return true;
case R.id.action_register_gunpla:
Intent register = new Intent(this, GunplaRegisterActivity.class);
startActivity(register);
return true;
case R.id.action_select_gunpla:
// DialogFragment
GunplaInfoModel model = new GunplaInfoModel(this);
List<GunplaInfo> gunplaInfoList = model.findAll();
if (gunplaInfoList == null || gunplaInfoList.size() == 0) {
MessageDialogs dialogs = MessageDialogs.getInstance(
getString(R.string.dialgo_info),
getString(R.string.no_gunpla_registered),
MessageDialogs.BUTTON_POSITIVE);
dialogs.show(getFragmentManager(), MessageDialogs.FRAGMENT_TAG);
} else {
GunplaSelectionDialogs d = GunplaSelectionDialogs.newInstance();
d.show(getFragmentManager(), GunplaSelectionDialogs.FRAGMENT_TAG);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* @see net.formula97.fakegpbase.fragments.MessageDialogs.DialogsButtonSelectionCallback#onButtonPressed(String, int)
*/
@Override
public void onButtonPressed(String messageBody, int which) {
if (messageBody.equals(getString(R.string.wish_to_enable))) {
mAlreadyShown = true;
if (which == MessageDialogs.PRESSED_POSITIVE) {
// startActivity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
} else {
startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
}
} else if (messageBody.equals(getString(R.string.no_nfc_present))) {
mAlreadyShown = true;
}
}
/**
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
// NFCDialog
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled() && !mAlreadyShown) {
MessageDialogs dialogs = MessageDialogs.getInstance(
getString(R.string.dialgo_info),
getString(R.string.wish_to_enable),
MessageDialogs.BUTTON_BOTH
);
dialogs.show(getFragmentManager(), MessageDialogs.FRAGMENT_TAG);
} else {
// NFC
Intent i = new Intent(this, this.getClass());
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0 ,i, PendingIntent.FLAG_UPDATE_CURRENT);
mNfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
} else {
if (!mAlreadyShown) {
MessageDialogs dialogs = MessageDialogs.getInstance(
getString(R.string.dialog_warn),
getString(R.string.no_nfc_present),
MessageDialogs.BUTTON_POSITIVE);
dialogs.show(getFragmentManager(), MessageDialogs.FRAGMENT_TAG);
}
}
tvBuilderName.setText(mBuilderName);
tvFighterName.setText(mFighterName);
tvClass.setText(mClassVal);
tvScale.setText(mScaleVal);
tvModelNo.setText(mModelNo);
tvGunplaName.setText(mGunplaName);
}
/**
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
// NFC
if (mNfcAdapter != null) {
mNfcAdapter.disableForegroundDispatch(this);
}
}
/**
* @see android.app.Activity#onNewIntent(android.content.Intent)
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
if (intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
// NFC
setGunplaInfo(readTag(intent));
}
}
}
/**
* NFCTEXT
*
* @param i NFCIntent
* @return null
*/
private GunplaInfo readTag(Intent i) {
GunplaInfo info = null;
if (i != null) {
Parcelable[] parcelables = i.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NfcUtils nfcUtils = new NfcUtils();
GunplaInfoModel model = new GunplaInfoModel(this);
if (parcelables != null) {
for (Parcelable p : parcelables) {
NdefMessage msg = (NdefMessage) p;
NdefRecord[] records = msg.getRecords();
for (NdefRecord record : records) {
try {
NfcTextRecord nfcTextRecord = nfcUtils.parse(record);
info = model.findGunplaInfoByTagId(nfcTextRecord.getText());
if (info != null) {
break;
}
} catch (FormatException e) {
if (BuildConfig.DEBUG) {
// StackTrace
e.printStackTrace();
}
}
}
}
}
}
return info;
}
/**
*
*
* @param gunplaInfo
*/
private void setGunplaInfo(GunplaInfo gunplaInfo) {
// GSONJSON
Gson gson = new Gson();
this.gunplaInfo = gunplaInfo;
mGunplaInfoJson = gson.toJson(gunplaInfo, GunplaInfo.class);
setToFields(gunplaInfo);
setViewFromEntity(gunplaInfo);
}
/**
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KeyAlreadyShown, mAlreadyShown);
if (!TextUtils.isEmpty(mGunplaInfoJson)) {
outState.putString(KeyGunplaInfoJson, mGunplaInfoJson);
}
}
/**
* @see android.app.Activity#onRestoreInstanceState(android.os.Bundle)
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mAlreadyShown = savedInstanceState.getBoolean(KeyAlreadyShown);
mGunplaInfoJson = savedInstanceState.getString(KeyGunplaInfoJson);
if (!TextUtils.isEmpty(mGunplaInfoJson)) {
// JSONJSON
Gson gson = new Gson();
gunplaInfo = gson.fromJson(mGunplaInfoJson, GunplaInfo.class);
setToFields(gunplaInfo);
}
}
/**
*
*
* @param gunplaInfoEntity
*/
private void setToFields(GunplaInfo gunplaInfoEntity) {
mBuilderName = gunplaInfoEntity.getBuilderName();
mFighterName = gunplaInfoEntity.getFighterName();
mClassVal = gunplaInfoEntity.getClassValue();
mScaleVal = gunplaInfoEntity.getScaleValue();
mModelNo = gunplaInfoEntity.getModelNo();
mGunplaName = gunplaInfoEntity.getGunplaName();
}
/**
* Bundle
*/
private void initValiables() {
mBuilderName = "";
mFighterName = "";
mScaleVal = "";
mClassVal = "";
mModelNo = "";
mGunplaName = "";
mGunplaInfoJson = "";
gunplaInfo = null;
}
@Override
public void onGunplaSelected(GunplaInfo info) {
Gson gson = new Gson();
mGunplaInfoJson = gson.toJson(info, GunplaInfo.class);
setViewFromEntity(info);
}
/**
* DB
*
* @param info DB
*/
private void setViewFromEntity(GunplaInfo info) {
tvBuilderName.setText(info.getBuilderName());
tvFighterName.setText(info.getFighterName());
tvScale.setText(info.getScaleValue());
tvClass.setText(info.getClassValue());
tvModelNo.setText(info.getModelNo());
tvGunplaName.setText(info.getGunplaName());
}
}
|
package org.wikipedia.history;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ActionMode;
import androidx.fragment.app.Fragment;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.snackbar.Snackbar;
import org.wikipedia.BackPressedHandler;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.FragmentUtil;
import org.wikipedia.database.DatabaseClient;
import org.wikipedia.database.contract.PageHistoryContract;
import org.wikipedia.main.MainFragment;
import org.wikipedia.page.PageAvailableOfflineHandler;
import org.wikipedia.readinglist.database.ReadingList;
import org.wikipedia.settings.Prefs;
import org.wikipedia.util.DeviceUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.views.DefaultViewHolder;
import org.wikipedia.views.MultiSelectActionModeCallback;
import org.wikipedia.views.PageItemView;
import org.wikipedia.views.SearchEmptyView;
import org.wikipedia.views.SwipeableItemTouchHelperCallback;
import org.wikipedia.views.ViewUtil;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Completable;
import io.reactivex.schedulers.Schedulers;
import static org.wikipedia.Constants.HISTORY_FRAGMENT_LOADER_ID;
import static org.wikipedia.views.PageItemView.IMAGE_CONTAINER_MARGIN;
public class HistoryFragment extends Fragment implements BackPressedHandler {
public interface Callback {
void onLoadPage(@NonNull HistoryEntry entry);
void onClearHistory();
}
private Unbinder unbinder;
@BindView(R.id.history_list) RecyclerView historyList;
@BindView(R.id.history_empty_container) View historyEmptyView;
@BindView(R.id.search_empty_view) SearchEmptyView searchEmptyView;
private WikipediaApp app;
private String currentSearchQuery;
private LoaderCallback loaderCallback = new LoaderCallback();
private HistoryEntryItemAdapter adapter = new HistoryEntryItemAdapter();
private ItemCallback itemCallback = new ItemCallback();
private ActionMode actionMode;
private SearchActionModeCallback searchActionModeCallback = new HistorySearchCallback();
private MultiSelectCallback multiSelectCallback = new MultiSelectCallback();
private HashSet<Integer> selectedIndices = new HashSet<>();
@NonNull public static HistoryFragment newInstance() {
return new HistoryFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
app = WikipediaApp.getInstance();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_history, container, false);
unbinder = ButterKnife.bind(this, view);
searchEmptyView.setEmptyText(R.string.search_history_no_results);
SwipeableItemTouchHelperCallback touchCallback = new SwipeableItemTouchHelperCallback(requireContext());
touchCallback.setSwipeableEnabled(true);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(touchCallback);
itemTouchHelper.attachToRecyclerView(historyList);
historyList.setLayoutManager(new LinearLayoutManager(getContext()));
historyList.setAdapter(adapter);
requireActivity().getSupportLoaderManager().initLoader(HISTORY_FRAGMENT_LOADER_ID, null, loaderCallback);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
updateEmptyState();
}
@Override
public void onDestroyView() {
requireActivity().getSupportLoaderManager().destroyLoader(HISTORY_FRAGMENT_LOADER_ID);
historyList.setAdapter(null);
adapter.setCursor(null);
unbinder.unbind();
unbinder = null;
super.onDestroyView();
}
@Override
public void setUserVisibleHint(boolean visible) {
if (!isAdded()) {
return;
}
if (!visible && actionMode != null) {
actionMode.finish();
}
}
@Override
public boolean onBackPressed() {
if (actionMode != null) {
actionMode.finish();
return true;
}
return false;
}
private void updateEmptyState() {
updateEmptyState(null);
}
private void updateEmptyState(@Nullable String searchQuery) {
if (TextUtils.isEmpty(searchQuery)) {
searchEmptyView.setVisibility(View.GONE);
setEmptyContainerVisibility(adapter.isEmpty());
} else {
searchEmptyView.setVisibility(adapter.isEmpty() ? View.VISIBLE : View.GONE);
setEmptyContainerVisibility(false);
}
historyList.setVisibility(adapter.isEmpty() ? View.GONE : View.VISIBLE);
}
private void setEmptyContainerVisibility(boolean visible) {
if (visible) {
historyEmptyView.setVisibility(View.VISIBLE);
requireActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
} else {
historyEmptyView.setVisibility(View.GONE);
DeviceUtil.setWindowSoftInputModeResizable(requireActivity());
}
}
@Override
public void onDestroy() {
super.onDestroy();
app.getRefWatcher().watch(this);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_history, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
boolean isHistoryAvailable = !adapter.isEmpty();
menu.findItem(R.id.menu_clear_all_history)
.setVisible(isHistoryAvailable)
.setEnabled(isHistoryAvailable);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_clear_all_history:
new AlertDialog.Builder(requireContext())
.setTitle(R.string.dialog_title_clear_history)
.setMessage(R.string.dialog_message_clear_history)
.setPositiveButton(R.string.dialog_message_clear_history_yes, (dialog, which) -> {
// Clear history!
Completable.fromAction(() -> app.getDatabaseClient(HistoryEntry.class).deleteAll())
.subscribeOn(Schedulers.io()).subscribe();
onClearHistoryClick();
})
.setNegativeButton(R.string.dialog_message_clear_history_no, null).create().show();
return true;
case R.id.menu_search_history:
if (actionMode == null) {
actionMode = ((AppCompatActivity) requireActivity())
.startSupportActionMode(searchActionModeCallback);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void onPageClick(@NonNull HistoryEntry entry) {
Callback callback = callback();
if (callback != null) {
callback.onLoadPage(entry);
}
}
private void onClearHistoryClick() {
Callback callback = callback();
if (callback != null) {
callback.onClearHistory();
}
}
private void finishActionMode() {
if (actionMode != null) {
actionMode.finish();
}
}
private void beginMultiSelect() {
if (HistorySearchCallback.is(actionMode)) {
finishActionMode();
}
if (!MultiSelectCallback.is(actionMode)) {
((AppCompatActivity) requireActivity()).startSupportActionMode(multiSelectCallback);
}
}
private void toggleSelectPage(@Nullable IndexedHistoryEntry indexedEntry) {
if (indexedEntry == null) {
return;
}
if (selectedIndices.contains(indexedEntry.getIndex())) {
selectedIndices.remove(indexedEntry.getIndex());
} else {
selectedIndices.add(indexedEntry.getIndex());
}
int selectedCount = selectedIndices.size();
if (selectedCount == 0) {
finishActionMode();
} else if (actionMode != null) {
actionMode.setTitle(getString(R.string.multi_select_items_selected, selectedCount));
}
adapter.notifyDataSetChanged();
}
public void refresh() {
adapter.notifyDataSetChanged();
if (!app.isOnline() && Prefs.shouldShowHistoryOfflineArticlesToast()) {
Toast.makeText(requireContext(), R.string.history_offline_articles_toast, Toast.LENGTH_SHORT).show();
Prefs.shouldShowHistoryOfflineArticlesToast(false);
}
}
private void unselectAllPages() {
selectedIndices.clear();
adapter.notifyDataSetChanged();
}
private void deleteSelectedPages() {
List<HistoryEntry> selectedEntries = new ArrayList<>();
for (int index : selectedIndices) {
HistoryEntry entry = adapter.getItem(index);
if (entry != null) {
selectedEntries.add(entry);
app.getDatabaseClient(HistoryEntry.class).delete(entry,
PageHistoryContract.PageWithImage.SELECTION);
}
}
selectedIndices.clear();
if (!selectedEntries.isEmpty()) {
showDeleteItemsUndoSnackbar(selectedEntries);
adapter.notifyDataSetChanged();
}
}
private void showDeleteItemsUndoSnackbar(final List<HistoryEntry> entries) {
String message = entries.size() == 1
? String.format(getString(R.string.history_item_deleted), entries.get(0).getTitle().getDisplayText())
: String.format(getString(R.string.history_items_deleted), entries.size());
Snackbar snackbar = FeedbackUtil.makeSnackbar(getActivity(), message,
FeedbackUtil.LENGTH_DEFAULT);
snackbar.setAction(R.string.history_item_delete_undo, (v) -> {
DatabaseClient<HistoryEntry> client = app.getDatabaseClient(HistoryEntry.class);
for (HistoryEntry entry : entries) {
client.upsert(entry, PageHistoryContract.PageWithImage.SELECTION);
}
adapter.notifyDataSetChanged();
});
snackbar.show();
}
private void restartLoader() {
requireActivity().getSupportLoaderManager().restartLoader(HISTORY_FRAGMENT_LOADER_ID, null, loaderCallback);
}
private class LoaderCallback implements LoaderManager.LoaderCallbacks<Cursor> {
@NonNull @Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String titleCol = PageHistoryContract.PageWithImage.TITLE.qualifiedName();
String selection = null;
String[] selectionArgs = null;
String searchStr = currentSearchQuery;
if (!TextUtils.isEmpty(searchStr)) {
searchStr = searchStr.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
selection = "UPPER(" + titleCol + ") LIKE UPPER(?) ESCAPE '\\'";
selectionArgs = new String[]{"%" + searchStr + "%"};
}
Uri uri = PageHistoryContract.PageWithImage.URI;
final String[] projection = null;
String order = PageHistoryContract.PageWithImage.ORDER_MRU;
return new CursorLoader(requireContext().getApplicationContext(),
uri, projection, selection, selectionArgs, order);
}
@Override
public void onLoadFinished(@NonNull Loader<Cursor> cursorLoader, Cursor cursor) {
adapter.setCursor(cursor);
if (!isAdded()) {
return;
}
updateEmptyState(currentSearchQuery);
requireActivity().invalidateOptionsMenu();
}
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
adapter.setCursor(null);
}
}
private static class IndexedHistoryEntry {
private final int index;
@NonNull private final HistoryEntry entry;
IndexedHistoryEntry(@NonNull HistoryEntry entry, int index) {
this.entry = entry;
this.index = index;
}
public int getIndex() {
return index;
}
@NonNull public HistoryEntry getEntry() {
return entry;
}
}
private class HistoryEntryItemHolder extends DefaultViewHolder<PageItemView<IndexedHistoryEntry>>
implements SwipeableItemTouchHelperCallback.Callback {
private int index;
HistoryEntryItemHolder(PageItemView<IndexedHistoryEntry> itemView) {
super(itemView);
}
void bindItem(@NonNull Cursor cursor) {
index = cursor.getPosition();
String imageUrl = PageHistoryContract.PageWithImage.IMAGE_NAME.val(cursor);
IndexedHistoryEntry indexedEntry
= new IndexedHistoryEntry(HistoryEntry.DATABASE_TABLE.fromCursor(cursor), index);
getView().setItem(indexedEntry);
getView().setTitle(indexedEntry.getEntry().getTitle().getDisplayText());
getView().setDescription(indexedEntry.getEntry().getTitle().getDescription());
getView().setImageUrl(imageUrl);
getView().setImageContainerEndMargin(IMAGE_CONTAINER_MARGIN);
getView().setSelected(selectedIndices.contains(indexedEntry.getIndex()), imageUrl);
PageAvailableOfflineHandler.INSTANCE.check(indexedEntry.getEntry().getTitle(), available -> getView().setViewsGreyedOut(!available));
// Check the previous item, see if the times differ enough
// If they do, display the section header.
// Always do it this is the first item.
String curTime = getDateString(indexedEntry.getEntry().getTimestamp());
String prevTime = "";
if (cursor.getPosition() != 0) {
cursor.moveToPrevious();
HistoryEntry prevEntry = HistoryEntry.DATABASE_TABLE.fromCursor(cursor);
prevTime = getDateString(prevEntry.getTimestamp());
cursor.moveToNext();
}
getView().setHeaderText(curTime.equals(prevTime) ? null : curTime);
}
private String getDateString(Date date) {
return DateFormat.getDateInstance().format(date);
}
@Override
public void onSwipe() {
selectedIndices.add(index);
deleteSelectedPages();
}
}
private final class HistoryEntryItemAdapter extends RecyclerView.Adapter<HistoryEntryItemHolder> {
@Nullable private Cursor cursor;
@Override
public int getItemCount() {
return cursor == null ? 0 : cursor.getCount();
}
public boolean isEmpty() {
return getItemCount() == 0;
}
@Nullable public HistoryEntry getItem(int position) {
if (cursor == null) {
return null;
}
int prevPosition = cursor.getPosition();
cursor.moveToPosition(position);
HistoryEntry entry = HistoryEntry.DATABASE_TABLE.fromCursor(cursor);
cursor.moveToPosition(prevPosition);
return entry;
}
public void setCursor(@Nullable Cursor newCursor) {
if (cursor == newCursor) {
return;
}
if (cursor != null) {
cursor.close();
}
cursor = newCursor;
this.notifyDataSetChanged();
}
@Override
public HistoryEntryItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {
return new HistoryEntryItemHolder(new PageItemView<>(requireContext()));
}
@Override
public void onBindViewHolder(@NonNull HistoryEntryItemHolder holder, int pos) {
if (cursor == null) {
return;
}
cursor.moveToPosition(pos);
holder.bindItem(cursor);
}
@Override public void onViewAttachedToWindow(@NonNull HistoryEntryItemHolder holder) {
super.onViewAttachedToWindow(holder);
holder.getView().setCallback(itemCallback);
}
@Override public void onViewDetachedFromWindow(HistoryEntryItemHolder holder) {
holder.getView().setCallback(null);
super.onViewDetachedFromWindow(holder);
}
}
private class ItemCallback implements PageItemView.Callback<IndexedHistoryEntry> {
@Override
public void onClick(@Nullable IndexedHistoryEntry indexedEntry) {
if (MultiSelectCallback.is(actionMode)) {
toggleSelectPage(indexedEntry);
} else if (indexedEntry != null) {
onPageClick(new HistoryEntry(indexedEntry.getEntry().getTitle(), HistoryEntry.SOURCE_HISTORY));
}
}
@Override
public boolean onLongClick(@Nullable IndexedHistoryEntry indexedEntry) {
beginMultiSelect();
toggleSelectPage(indexedEntry);
return true;
}
@Override
public void onThumbClick(@Nullable IndexedHistoryEntry indexedEntry) {
onClick(indexedEntry);
}
@Override
public void onActionClick(@Nullable IndexedHistoryEntry entry, @NonNull View view) {
}
@Override
public void onSecondaryActionClick(@Nullable IndexedHistoryEntry entry, @NonNull View view) {
}
@Override
public void onListChipClick(@Nullable ReadingList readingList) {
}
}
private class HistorySearchCallback extends SearchActionModeCallback {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
actionMode = mode;
ViewUtil.finishActionModeWhenTappingOnView(getView(), actionMode);
ViewUtil.finishActionModeWhenTappingOnView(historyList, actionMode);
return super.onCreateActionMode(mode, menu);
}
@Override
protected void onQueryChange(String s) {
currentSearchQuery = s.trim();
((MainFragment) getParentFragment())
.setBottomNavVisible(currentSearchQuery.length() == 0);
restartLoader();
}
@Override
public void onDestroyActionMode(ActionMode mode) {
super.onDestroyActionMode(mode);
if (!TextUtils.isEmpty(currentSearchQuery)) {
currentSearchQuery = "";
restartLoader();
}
actionMode = null;
}
@Override
protected String getSearchHintString() {
return requireContext().getResources().getString(R.string.search_hint_search_history);
}
@Override
protected boolean finishActionModeIfKeyboardHiding() {
return true;
}
@Override
protected Context getParentContext() {
return requireContext();
}
}
private class MultiSelectCallback extends MultiSelectActionModeCallback {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
super.onCreateActionMode(mode, menu);
mode.getMenuInflater().inflate(R.menu.menu_action_mode_history, menu);
actionMode = mode;
selectedIndices.clear();
return super.onCreateActionMode(mode, menu);
}
@Override
protected void onDeleteSelected() {
deleteSelectedPages();
finishActionMode();
}
@Override
public void onDestroyActionMode(ActionMode mode) {
unselectAllPages();
actionMode = null;
super.onDestroyActionMode(mode);
}
}
@Nullable private Callback callback() {
return FragmentUtil.getCallback(this, Callback.class);
}
}
|
package radiancetops.com.resistora;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
public class MarkerView extends View {
private Paint paint;
private float width = -1;
private float height = -1;
private boolean firstTime = true;
private ArrayList<Integer> bandLocation;
private ArrayList<Integer> colorIndexes;
private int [] presetRGB;
public MarkerView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
firstTime = true;
width = -1;
bandLocation = new ArrayList<Integer>();
colorIndexes = new ArrayList<Integer>();
presetRGB = new int [12];
presetRGB[0] = rgbToInt(0,0,0);
presetRGB[1] = rgbToInt(102, 51, 50);
presetRGB[2] = rgbToInt(255,0,0);
presetRGB[3] = rgbToInt(255, 102, 0);
presetRGB[4] = rgbToInt(255, 255, 0);
presetRGB[5] = rgbToInt(0, 255, 0);
presetRGB[6] = rgbToInt(0, 0, 255);
presetRGB[7] = rgbToInt(206, 101, 255);
presetRGB[8] = rgbToInt(130, 130, 130);
presetRGB[9] = rgbToInt(255, 255, 255);
presetRGB[10] = rgbToInt(205, 153, 51);
presetRGB[11] = rgbToInt(204, 204, 204);
}
private int rgbToInt(int locR, int locG, int locB){
int a = 255;
return (((a<<8)+locR<<8)+locG<<8)+locB;
}
public void setup() {
//Only ran once when the view is first created
if (!firstTime)
return;
firstTime = false;
//Sets up the width and height of the gameControl on the screen
//The gameControl is centered in the screen with a possible border around them
width = getWidth();
height = getHeight();
}//initialisation of the gameboard
public void setBandLocation (int [] bandLocation, int [] colorIndexes){
this.bandLocation = new ArrayList<Integer>();
for (int i = 0; i < bandLocation.length; i++){
this.bandLocation.add(bandLocation[i]);
this.colorIndexes.add(colorIndexes[i]);
}
Log.v("band size",""+bandLocation.length);
invalidate();
}
@Override
public void onDraw(Canvas canvas) {
//super.onDraw(canvas);
setup();
paint.setStrokeWidth(4);
for (int i = 0; i < bandLocation.size(); i++){
paint.setColor(presetRGB[colorIndexes.get(i)]);
canvas.drawLine(bandLocation.get(i),0 , bandLocation.get(i), height, paint);
Log.v("band location",""+bandLocation.get(i));
}
canvas.drawLine(0, 0, width, 0, paint);
canvas.drawLine(0, height, width, height, paint);
Log.v("band dims", "" + width + " " + height);
}
}
|
package ca.junctionbox.cljbuck.build.graph;
import ca.junctionbox.cljbuck.build.rules.BuildRule;
import ca.junctionbox.cljbuck.build.rules.ClojureBinary;
import com.google.common.graph.MutableGraph;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
public class BuildGraph {
private final MutableGraph<BuildRule> graph;
private final ConcurrentHashMap<String, BuildRule> map;
public BuildGraph(final MutableGraph<BuildRule> graph, final ConcurrentHashMap<String, BuildRule> map) {
this.graph = graph;
this.map = map;
}
public int size() {
return map.size();
}
public boolean contains(final String name) {
return map.get(name) != null;
}
public Set<BuildRule> successors(final String name) throws NotFoundException {
final BuildRule buildRule = map.get(name);
if (buildRule == null) {
throw new NotFoundException(name);
}
return graph.successors(buildRule);
}
public Set<BuildRule> predecessors(final String name) throws NotFoundException {
final BuildRule buildRule = map.get(name);
if (buildRule == null) {
throw new NotFoundException(name);
}
return graph.predecessors(buildRule);
}
public void forEach(final Walken christopher) {
for (final String key : map.keySet()) {
christopher.step(map.get(key), 0);
}
}
public void depthFirstFrom(final String start, final Walken christopher) {
final Stack<BuildRule> buildRules = new Stack<>();
final Set<String> seen = new HashSet<>();
final BuildRule startRule = map.get(start);
buildRules.push(map.get(start));
seen.add(startRule.getName());
christopher.step(startRule, 0);
while (!buildRules.isEmpty()) {
final BuildRule parent = buildRules.peek();
final int depth = buildRules.size();
final BuildRule child = unseenChild(parent, seen, depth);
if (null != child) {
seen.add(depth + ":" + child.getName());
christopher.step(child, depth);
buildRules.push(child);
} else {
buildRules.pop();
}
}
}
private BuildRule unseenChild(final BuildRule parent, final Set<String> seen, final int depth) {
final Set<BuildRule> children = graph.predecessors(parent);
BuildRule child = null;
for (final BuildRule n : children) {
if (seen.contains(depth + ":" + n.getName())) {
continue;
}
child = n;
break;
}
return child;
}
public void breadthFirstFrom(final String start, final Walken christopher) {
final Queue<BuildRule> buildRules = new LinkedList<>();
final BuildRule startRule = map.get(start);
int depth = 0;
buildRules.add(startRule);
christopher.step(startRule, depth);
while (!buildRules.isEmpty()) {
final BuildRule parent = buildRules.remove();
depth++;
final Set<BuildRule> children = graph.predecessors(parent);
for (final BuildRule child : children) {
christopher.step(child, depth);
buildRules.add(child);
}
}
}
public String mainFor(final String nodeName) {
final ClojureBinary clojureBinary = (ClojureBinary) map.get(nodeName);
if (null == clojureBinary) {
return "";
}
return clojureBinary.getMain();
}
}
|
package ucar.nc2.dataset;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ucar.nc2.constants.CDM;
import ucar.nc2.constants.CF;
import ucar.nc2.dataset.conv.CF1Convention;
import ucar.nc2.dataset.conv.COARDSConvention;
import ucar.nc2.time.*;
import ucar.nc2.time.Calendar;
import ucar.nc2.units.TimeUnit;
import ucar.nc2.Variable;
import ucar.nc2.Dimension;
import ucar.nc2.Attribute;
import ucar.nc2.util.NamedAnything;
import ucar.nc2.util.NamedObject;
import ucar.ma2.*;
import java.util.*;
import java.io.IOException;
import ucar.nc2.units.DateRange;
/**
* A 1-dimensional Coordinate Axis representing Calendar time.
* Its coordinate values can be represented as Dates.
* <p/>
* May use udunit dates, or ISO Strings.
*
* @author caron
*/
public class CoordinateAxis1DTime extends CoordinateAxis1D {
static private final Logger logger = LoggerFactory.getLogger(CoordinateAxis1DTime.class);
static public CoordinateAxis1DTime factory(NetcdfDataset ncd, VariableDS org, Formatter errMessages) throws IOException {
if (org.getDataType() == DataType.CHAR)
return new CoordinateAxis1DTime(ncd, org, errMessages, org.getDimension(0).getName());
else if (org.getDataType() == DataType.STRING)
return new CoordinateAxis1DTime(ncd, org, errMessages, org.getDimensionsString());
else
return new CoordinateAxis1DTime(ncd, org, errMessages);
}
private final ucar.nc2.time.Calendar calendar;
private List<CalendarDate> cdates = null;
// for section and slice
@Override
protected Variable copy() {
return new CoordinateAxis1DTime(this.ncd, this);
}
// copy constructor
private CoordinateAxis1DTime(NetcdfDataset ncd, CoordinateAxis1DTime org) {
super(ncd, org);
this.calendar = org.calendar;
this.cdates = org.cdates;
}
@Override
public CoordinateAxis1D section(Range r) throws InvalidRangeException {
CoordinateAxis1D s = super.section(r);
List<CalendarDate> cdates = getCalendarDates();
List<CalendarDate> cdateSection = new ArrayList<CalendarDate>(cdates.size());
for (int i = r.first(), j = 0; i <= r.last(); i += r.stride(), ++j) {
cdateSection.add(cdates.get(i));
}
((CoordinateAxis1DTime)s).cdates = cdateSection;
return s;
}
/**
* Get the the ith CalendarDate.
* @param idx index
* @return the ith CalendarDate
*/
public CalendarDate getCalendarDate (int idx) {
List<CalendarDate> cdates = getCalendarDates();
return cdates.get(idx);
}
/**
* Get calendar date range
* @return calendar date range
*/
public CalendarDateRange getCalendarDateRange() {
List<CalendarDate> cd = getCalendarDates();
int last = cd.size();
return (last > 0) ? CalendarDateRange.of(cd.get(0), cd.get(last-1)) : null;
}
@Override
public List<NamedObject> getNames() {
List<CalendarDate> cdates = getCalendarDates();
List<NamedObject> names = new ArrayList<NamedObject>(cdates.size());
for (CalendarDate cd : cdates)
names.add(new NamedAnything(CalendarDateFormatter.toDateTimeString(cd), "calendar date"));
return names;
}
/**
* only if isRegular() LOOK REDO
*
* @return time unit
* @throws Exception on bad unit string
*/
public TimeUnit getTimeResolution() throws Exception {
String tUnits = getUnitsString();
StringTokenizer stoker = new StringTokenizer(tUnits);
double tResolution = getIncrement();
return new TimeUnit(tResolution, stoker.nextToken());
}
/**
* Given a Date, find the corresponding time index on the time coordinate axis.
* Can only call this is hasDate() is true.
* This will return
* <ul>
* <li> i, if time(i) <= d < time(i+1).
* <li> 0, if d < time(0)
* <li> n-1, if d > time(n-1), where n is length of time coordinates
* </ul>
*
* @param d date to look for
* @return corresponding time index on the time coordinate axis
* @throws UnsupportedOperationException is no time axis or isDate() false
*/
public int findTimeIndexFromCalendarDate(CalendarDate d) {
List<CalendarDate> cdates = getCalendarDates();
int index = 0;
while (index < cdates.size()) {
if (d.compareTo(cdates.get(index)) < 0)
break;
index++;
}
return Math.max(0, index - 1);
}
/**
* See if the given CalendarDate appears as a coordinate
*
* @param date test this
* @return true if equals a coordinate
*/
public boolean hasCalendarDate(CalendarDate date) {
List<CalendarDate> cdates = getCalendarDates();
for (CalendarDate cd : cdates) {
if (date.equals(cd))
return true;
}
return false;
}
/**
* Get the list of datetimes in this coordinate as CalendarDate objects.
* @return list of CalendarDates.
*/
public List<CalendarDate> getCalendarDates() {
return cdates;
}
private ucar.nc2.time.Calendar getCalendarFromAttribute() {
Attribute cal = findAttribute(CF.CALENDAR);
String s = (cal == null) ? null : cal.getStringValue();
if (s == null) {
Attribute convention = (ncd == null) ? null : ncd.getRootGroup().findAttribute(CDM.CONVENTIONS);
if (convention != null) {
String hasName = convention.getStringValue();
int version = CF1Convention.getVersion(hasName);
if (version > 0) {
if (version < 7 ) return Calendar.gregorian;
if (version >= 7 ) return Calendar.proleptic_gregorian;
}
if (COARDSConvention.isMine(hasName)) return Calendar.gregorian;
}
}
return ucar.nc2.time.Calendar.get(s);
}
private CoordinateAxis1DTime(NetcdfDataset ncd, VariableDS org, Formatter errMessages, String dims) throws IOException {
super(ncd, org.getParentGroup(), org.getShortName(), DataType.STRING, dims, org.getUnitsString(), org.getDescription());
this.ncd = ncd;
this.orgName = org.orgName;
this.calendar = getCalendarFromAttribute();
if (org.getDataType() == DataType.CHAR)
cdates = makeTimesFromChar(org, errMessages);
else
cdates = makeTimesFromStrings(org, errMessages);
List<Attribute> atts = org.getAttributes();
for (Attribute att : atts) {
addAttribute(att);
}
}
private List<CalendarDate> makeTimesFromChar(VariableDS org, Formatter errMessages) throws IOException {
int ncoords = (int) org.getSize();
int rank = org.getRank();
int strlen = org.getShape(rank - 1);
ncoords /= strlen;
List<CalendarDate> result = new ArrayList<CalendarDate>(ncoords);
ArrayChar data = (ArrayChar) org.read();
ArrayChar.StringIterator ii = data.getStringIterator();
ArrayObject.D1 sdata = new ArrayObject.D1(String.class, ncoords);
for (int i = 0; i < ncoords; i++) {
String coordValue = ii.next();
CalendarDate cd = makeCalendarDateFromStringCoord(coordValue, org, errMessages);
sdata.set(i, coordValue);
result.add( cd);
}
setCachedData(sdata, true);
return result;
}
private List<CalendarDate> makeTimesFromStrings( VariableDS org, Formatter errMessages) throws IOException {
int ncoords = (int) org.getSize();
List<CalendarDate> result = new ArrayList<CalendarDate>(ncoords);
ArrayObject data = (ArrayObject) org.read();
IndexIterator ii = data.getIndexIterator();
for (int i = 0; i < ncoords; i++) {
String coordValue = (String) ii.getObjectNext();
CalendarDate cd = makeCalendarDateFromStringCoord( coordValue, org, errMessages);
result.add(cd);
}
return result;
}
private CalendarDate makeCalendarDateFromStringCoord(String coordValue, VariableDS org, Formatter errMessages) throws IOException {
CalendarDate cd = CalendarDateFormatter.isoStringToCalendarDate(calendar, coordValue);
if (cd == null) {
if (errMessages != null) {
errMessages.format("String time coordinate must be ISO formatted= %s\n", coordValue);
logger.info("Char time coordinate must be ISO formatted= {} file = {}", coordValue, org.getDatasetLocation());
}
throw new IllegalArgumentException();
}
return cd;
}
/**
* Constructor for numeric values - must have units
* @param ncd the containing dataset
* @param org the underlying Variable
* @param errMessages put error messages here; may be null
* @throws IOException on read error
*/
private CoordinateAxis1DTime(NetcdfDataset ncd, VariableDS org, Formatter errMessages) throws IOException {
super(ncd, org);
this.calendar = getCalendarFromAttribute();
CalendarDateUnit dateUnit = CalendarDateUnit.withCalendar(calendar, getUnitsString()); // this will throw exception on failure
// make the coordinates
int ncoords = (int) org.getSize();
List<CalendarDate> result = new ArrayList<CalendarDate>(ncoords);
Array data = org.read();
int count = 0;
IndexIterator ii = data.getIndexIterator();
for (int i = 0; i < ncoords; i++) {
double val = ii.getDoubleNext();
if (Double.isNaN(val)) continue;
result.add( dateUnit.makeCalendarDate(val));
count++;
}
// if we encountered NaNs, shorten it up
if (count != ncoords) {
Dimension localDim = new Dimension(getShortName(), count, false);
setDimension(0, localDim);
// set the shortened values
Array shortData = Array.factory(data.getElementType(), new int[]{count});
Index ima = shortData.getIndex();
int count2 = 0;
ii = data.getIndexIterator();
for (int i = 0; i < ncoords; i++) {
double val = ii.getDoubleNext();
if (Double.isNaN(val)) continue;
shortData.setDouble(ima.set0(count2), val);
count2++;
}
// here we have to decouple from the original variable
cache = new Cache();
setCachedData(shortData, true);
}
cdates = result;
}
/**
* Does not handle non-standard Calendars
* @deprecated use getCalendarDates() to correctly interpret calendars
*/
public java.util.Date[] getTimeDates() {
List<CalendarDate> cdates = getCalendarDates();
Date[] timeDates = new Date[cdates.size()];
int index = 0;
for (CalendarDate cd : cdates)
timeDates[index++] = cd.toDate();
return timeDates;
}
/**
* Does not handle non-standard Calendars
* @deprecated use getCalendarDate()
*/
public java.util.Date getTimeDate (int idx) {
return getCalendarDate(idx).toDate();
}
/**
* Does not handle non-standard Calendars
* @deprecated use getCalendarDateRange()
*/
public DateRange getDateRange() {
CalendarDateRange cdr = getCalendarDateRange();
return cdr.toDateRange();
}
/**
* Does not handle non-standard Calendars
* @deprecated use findTimeIndexFromCalendarDate
*/
public int findTimeIndexFromDate(java.util.Date d) {
return findTimeIndexFromCalendarDate( CalendarDate.of(d));
}
/**
* Does not handle non-standard Calendars
* @deprecated use hasCalendarDate
*/
public boolean hasTime(Date date) {
List<CalendarDate> cdates = getCalendarDates();
for (CalendarDate cd : cdates) {
if (date.equals(cd.toDate()))
return true;
}
return false;
}
}
|
package ucar.nc2.dt;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
/** A collection of data at unconnected radar station.
* User can subset by stations, bounding box and by date range.
* Underlying data can be of any type, but all points have the same type.
* @author
* @version $Revision: $
*/
public interface StationaryRadarCollection {
/** Get all the Stations in the collection.
* @return List of Station */
public List getRadarStations() throws IOException;
/** Get all the Stations in the collection, allow user to cancel.
* @param cancel allow user to cancel. Implementors should return ASAP.
* @return List of Station */
public List getRadarStations(ucar.nc2.util.CancelTask cancel) throws IOException;
/** Get all the Stations within a bounding box.
* @return List of Station */
public List getRadarStations(ucar.unidata.geoloc.LatLonRect boundingBox) throws IOException;
/** Get all the Stations within a bounding box, allow user to cancel.
* @param cancel allow user to cancel. Implementors should return ASAP.
* @return List of Station */
public List getRadarStations(ucar.unidata.geoloc.LatLonRect boundingBox, ucar.nc2.util.CancelTask cancel) throws IOException;
/** Find a Station by name */
//public Station getRadarStation( String name);
/** check if the product available for all stations.
* @return true of false */
public boolean checkStationProduct(String product);
/** check if the product available for one station
* @return true of false */
public boolean checkStationProduct(Station s, String product);
/**
* How many Data Products are available for this Station?
* @param s station, and product requested
* @return count or -1 if unknown.
*/
public List getStationDataProducts( Station s);
/** Get all specific data within the specified bounding box.
* @return List of type RadialDatasetSweep data
*/
// public List getData( String product, ucar.unidata.geoloc.LatLonRect boundingBox) throws IOException;
/** Get all specific data within the specified bounding box, allow user to cancel.
* @param cancel allow user to cancel. Implementors should return ASAP.
* @return List of type RadialDatasetSweep data
*/
// public List getData( String product, ucar.unidata.geoloc.LatLonRect boundingBox, ucar.nc2.util.CancelTask cancel) throws IOException;
/** Get all specific data within the specified bounding box and date range.
* @return List of type RadialDatasetSweep data
*/
// public List getData( String product, ucar.unidata.geoloc.LatLonRect boundingBox, Date start, Date end) throws IOException;
/** Get all specific data within the specified bounding box and date range, allow user to cancel.
* @param cancel allow user to cancel. Implementors should return ASAP.
* @return List of type RadialDatasetSweep data
*/
// public List getData( String product, ucar.unidata.geoloc.LatLonRect boundingBox, Date start, Date end, ucar.nc2.util.CancelTask cancel) throws IOException;
/** Get data for this Station within the specified date range.
* @param sName radar station name
* @param start the start time
* @param end the end time
* @param interval the time interval
* @param preInt the time range before interval
* @param postInt the time range after interval
* @return List of getDataClass() */
public ArrayList getData( String sName, Date start, Date end, int interval, int roundTo, int preInt,
int postInt) throws IOException;
/** Get data for this Station within the specified date range.
* @param sName radar station name
* @param start the start time
* @param end the end time
* @param interval the time interval
* @param preInt the time range before interval
* @param postInt the time range after interval
* @return List of getDataClass() */
public ArrayList getDataURIs( String sName, Date start, Date end, int interval, int roundTo, int preInt,
int postInt) throws IOException;
/** Get data for this Station within the specified date range, allow user to cancel.
* @param cancel allow user to cancel. Implementors should return ASAP.
* @param sName radar station name
* @param start the start time
* @param end the end time
* @param interval the time interval
* @param preInt the time range before interval
* @param postInt the time range after interval
* @return List of RadialDatasetSweep data
*/
public ArrayList getData( String sName, Date start, Date end, int interval, int roundTo, int preInt,
int postInt, ucar.nc2.util.CancelTask cancel) throws IOException;
/** Get data for this Station within the specified date range.
* @param sName radar station name
* @param start the start time
* @param end the end time
* @param interval the time interval
* @param preInt the time range before interval
* @param postInt the time range after interval
* @param cancel allow user to cancel. Implementors should return ASAP.
* @return List of getDataClass() */
public ArrayList getDataURIs( String sName, Date start, Date end, int interval, int roundTo, int preInt,
int postInt, ucar.nc2.util.CancelTask cancel) throws IOException;
/** Get all data for a list of Stations.
* @return List of RadialDatasetSweep data
*/
//public List getData(List stations, String product) throws IOException;
/** Get all data for a list of Stations, allow user to cancel.
* @param cancel allow user to cancel. Implementors should return ASAP.
* @return List of RadialDatasetSweep data
*/
// public List getData(List stations, String product, ucar.nc2.util.CancelTask cancel) throws IOException;
/** Get data for a list of Stations within the specified date range.
* @return List of RadialDatasetSweep data
*/
// public List getData(List stations, Date start, Date end) throws IOException;
/** Get data for a list of Stations within the specified date range, allow user to cancel.
* @param cancel allow user to cancel. Implementors should return ASAP.
* @return List of RadialDatasetSweep data
*/
// public List getData(List stations, String product, Date start, Date end, ucar.nc2.util.CancelTask cancel) throws IOException;
}
|
package ru.job4j.multiformity;
import java.io.IOException;
public class StartUi {
/**
* Starting method of the program.
* @throws IOException - Exception.
*/
public void init() throws IOException {
char answer;
char ignore;
ConcoleInput ci = new ConcoleInput();
for (;;) {
do {
ci.showMenu();
answer = (char) System.in.read();
do {
ignore = (char) System.in.read();
} while (ignore != '\n');
} while (!ci.isValid(Character.toString(answer)));
if (ci.getEXIT().equals(Character.toString(answer))) {
break;
}
System.out.println(" ");
ci.trackerOn(Character.toString(answer));
}
}
/**
* Start program.
* @param args - array.
* @throws IOException - Exception.
*/
public static void main(String[] args) throws IOException {
new StartUi().init();
}
}
|
package ru.job4j.taskIterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Class for iterator for prime number in array.
* @author atrifonov.
* @since 16.08.2017.
* @version 1.
*/
public class PrimeIt implements Iterator<Integer> {
/**
* Internal array for store data.
*/
private final int[] array;
/**
* Index.
*/
private int position = 0;
/**
* Construct PrimeIt.
* @param array array for iterator.
*/
public PrimeIt(int[] array) {
this.array = array;
}
@Override
public boolean hasNext() {
boolean hasEven = false;
if(position < array.length) {
hasEven = isPrime(array[position]);
}
while (!hasEven && position < array.length){
position++;
hasEven = isPrime(array[position]);
}
return hasEven;
}
@Override
public Integer next() {
if(hasNext()) {
return array[position++];
} else {
throw new NoSuchElementException();
}
}
private boolean isPrime(int number) {
boolean isPrime = true;
if(number > 1) {
for (int i = 2; i < number; i++) {
if(number % i == 0) {
isPrime = false;
break;
}
}
} else {
isPrime = false;
}
return isPrime;
}
}
|
package org.openqa.selenium.chrome;
import org.openqa.selenium.Platform;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.Proxy.ProxyType;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ChromeBinary {
private static final int BACKOFF_INTERVAL = 2500;
private static int linearBackoffCoefficient = 1;
private final ChromeProfile profile;
private final ChromeExtension extension;
Process chromeProcess = null;
/**
* Creates a new instance for managing an instance of Chrome using the given
* {@code profile} and {@code extension}.
*
* @param profile The Chrome profile to use.
* @param extension The extension to launch Chrome with.
*/
public ChromeBinary(ChromeProfile profile, ChromeExtension extension) {
this.profile = profile;
this.extension = extension;
}
/**
* Starts the Chrome process for WebDriver.
* Assumes the passed directories exist.
* @param serverUrl URL from which commands should be requested
* @throws IOException wrapped in WebDriverException if process couldn't be
* started.
*/
public void start(String serverUrl) throws IOException {
try {
List<String> commandline = getCommandline(serverUrl);
chromeProcess = new ProcessBuilder(commandline)
.start();
} catch (IOException e) {
throw new WebDriverException(e);
}
try {
Thread.sleep(BACKOFF_INTERVAL * linearBackoffCoefficient);
} catch (InterruptedException e) {
//Nothing sane to do here
}
}
// Visible for testing.
public List<String> getCommandline(String serverUrl) throws IOException {
ArrayList<String> commandline = new ArrayList<String>(Arrays.asList(
getChromeFile(),
"--user-data-dir=" + profile.getDirectory().getAbsolutePath(),
"--load-extension=" + extension.getDirectory().getAbsolutePath(),
"--activate-on-launch",
"--homepage=about:blank",
"--no-first-run",
"--disable-hang-monitor",
"--disable-popup-blocking",
"--disable-prompt-on-repost",
"--no-default-browser-check"
));
appendProxyArguments(commandline)
.add(serverUrl);
return commandline;
}
private ArrayList<String> appendProxyArguments(ArrayList<String> commandline) {
Proxy proxy = profile.getProxy();
if (proxy == null) {
return commandline;
}
if (proxy.getProxyAutoconfigUrl() != null) {
commandline.add("--proxy-pac-url=" + proxy.getProxyAutoconfigUrl());
} else if (proxy.getHttpProxy() != null) {
commandline.add("--proxy-server=" + proxy.getHttpProxy());
} else if (proxy.isAutodetect()) {
commandline.add("--proxy-auto-detect");
} else if (proxy.getProxyType() == ProxyType.DIRECT) {
commandline.add("--no-proxy-server");
} else if (proxy.getProxyType() != ProxyType.SYSTEM) {
throw new IllegalStateException("Unsupported proxy setting");
}
return commandline;
}
public void kill() {
if (chromeProcess != null) {
chromeProcess.destroy();
chromeProcess = null;
}
}
public void incrementBackoffBy(int diff) {
linearBackoffCoefficient += diff;
}
/**
* Locates the Chrome executable on the current platform.
* First looks in the webdriver.chrome.bin property, then searches
* through the default expected locations.
* @return chrome.exe
* @throws IOException if file could not be found/accessed
*/
protected String getChromeFile() throws IOException {
String chromeFileString = System.getProperty("webdriver.chrome.bin");
if (chromeFileString == null) {
if (Platform.getCurrent().is(Platform.WINDOWS)) {
chromeFileString = getWindowsBinaryLocation();
} else if (Platform.getCurrent().is(Platform.UNIX)) {
chromeFileString = "/usr/bin/google-chrome";
} else if (Platform.getCurrent().is(Platform.MAC)) {
String[] paths = new String[] {
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Users/" + System.getProperty("user.name") +
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"};
for (String path : paths) {
File binary = new File(path);
if (binary.exists()) {
chromeFileString = binary.getCanonicalFile().getAbsoluteFile().toString();
break;
}
}
} else {
throw new WebDriverException("Unsupported operating system. " +
"Could not locate Chrome. Set webdriver.chrome.bin");
}
if (chromeFileString == null ||
!new File(chromeFileString.toString()).exists()) {
throw new WebDriverException("Couldn't locate Chrome. " +
"Set webdriver.chrome.bin");
}
}
return chromeFileString;
}
/**
* Returns null if couldn't read value from registry
*/
protected static final String getWindowsBinaryLocation() {
//TODO: Promote org.openqa.selenium.server.browserlaunchers.WindowsUtils
//to common and reuse that to read the registry
if (!Platform.WINDOWS.is(Platform.getCurrent())) {
throw new UnsupportedOperationException("Cannot get registry value on non-Windows systems");
}
try {
Process process = Runtime.getRuntime().exec(
"reg query \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe\" /v \"\"");
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
process.waitFor();
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(" ")) {
String[] tokens = line.split("REG_SZ");
return tokens[tokens.length - 1].trim();
}
}
} catch (IOException e) {
//Drop through to return null
} catch (InterruptedException e) {
//Drop through to return null
}
return null;
}
}
|
package org.spine3.base;
import com.google.common.testing.NullPointerTester;
import com.google.protobuf.Timestamp;
import org.junit.Test;
import org.spine3.test.identifiers.IdWithPrimitiveFields;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.spine3.base.Identifiers.idToString;
import static org.spine3.test.Tests.assertHasPrivateParameterlessCtor;
public class StringifiersShould {
@Test
public void have_private_constructor() {
assertHasPrivateParameterlessCtor(Stringifiers.class);
}
private static final Stringifier<IdWithPrimitiveFields> ID_TO_STRING_CONVERTER =
new Stringifier<IdWithPrimitiveFields>() {
@Override
protected String toString(IdWithPrimitiveFields id) {
return id.getName();
}
@Override
protected IdWithPrimitiveFields fromString(String str) {
return IdWithPrimitiveFields.newBuilder()
.setName(str)
.build();
}
};
@Test
public void convert_to_string_registered_id_message_type() {
StringifierRegistry.getInstance()
.register(ID_TO_STRING_CONVERTER, IdWithPrimitiveFields.class);
final String testId = "testId 123456";
final IdWithPrimitiveFields id = IdWithPrimitiveFields.newBuilder()
.setName(testId)
.build();
final String result = idToString(id);
assertEquals(testId, result);
}
@SuppressWarnings("OptionalGetWithoutIsPresent")
// OK as these are standard Stringifiers we add ourselves.
@Test
public void handle_null_in_standard_converters() {
final StringifierRegistry registry = StringifierRegistry.getInstance();
assertNull(registry.get(Timestamp.class)
.get()
.convert(null));
assertNull(registry.get(EventId.class)
.get()
.convert(null));
assertNull(registry.get(CommandId.class)
.get()
.convert(null));
}
@Test
public void return_false_on_attempt_to_find_unregistered_type() {
assertFalse(StringifierRegistry.getInstance()
.hasStringifierFor(Random.class));
}
@Test
public void pass_the_null_tolerance_check() {
final NullPointerTester tester = new NullPointerTester();
tester.testStaticMethods(Stringifiers.class, NullPointerTester.Visibility.PACKAGE);
}
@SuppressWarnings("EmptyClass") // is the part of the test.
@Test(expected = MissingStringifierException.class)
public void raise_exception_on_missing_stringifer() {
Stringifiers.toString(new Object() {
});
}
}
|
package org.jetel.util.file;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.jetel.test.CloverTestCase;
import org.jetel.util.exec.PlatformUtils;
import org.jetel.util.file.FileUtils.ArchiveURLStreamHandler;
import org.jetel.util.protocols.proxy.ProxyHandler;
import org.jetel.util.protocols.sftp.SFTPStreamHandler;
public class FileUtilsTest extends CloverTestCase {
public void testGetJavaFile() throws MalformedURLException {
File file = FileUtils.getJavaFile(FileUtils.getFileURL("./kokon/"), "neco/data.txt");
assertEquals(file.getAbsolutePath(), new File("kokon/neco/data.txt").getAbsolutePath());
}
public void testGetFileURL() throws MalformedURLException {
String contextURLString = "file:/c:/project/";
String fileURL = "c:/otherProject/data.txt";
if (PlatformUtils.isWindowsPlatform()) {
URL contextURL = FileUtils.getFileURL(contextURLString);
assertEquals(new URL("file:/c:/project/"), contextURL);
String result1 = FileUtils.getFile(contextURL, fileURL);
assertEquals("c:/otherProject/data.txt", result1);
URL result2 = FileUtils.getFileURL(contextURLString, fileURL);
assertEquals(new URL("file:/c:/otherProject/data.txt"), result2);
URL result3 = FileUtils.getFileURL(contextURL, fileURL);
assertEquals(new URL("file:/c:/otherProject/data.txt"), result3);
fileURL = "zip:(./data-out/ordersByCountry.zip)#ordersByCountry.xls";
URL result4 = FileUtils.getFileURL(contextURLString, fileURL);
assertEquals(new URL(null, "zip:(file:/c:/project/data-out/ordersByCountry.zip)#ordersByCountry.xls", new ArchiveURLStreamHandler()), result4);
URL result5 = FileUtils.getFileURL(new URL("file:/c:/project/"), "c:/otherProject/data.txt");
assertEquals(new URL("file:/c:/otherProject/data.txt"), result5);
URL result6 = FileUtils.getFileURL(new URL("file:c:/project/"), "c:/otherProject/data.txt");
assertEquals(new URL("file:/c:/otherProject/data.txt"), result6);
//assertEquals("c:/project and project/", FileUtils.convertUrlToFile(new File("c:/project and project/").toURI().toURL()).toString());
String result7 = FileUtils.normalizeFilePath(FileUtils.getFile(new URL("file:c:/project/"), "c:/other Project/data.txt"));
assertEquals("c:/other Project/data.txt", result7);
URL result8 = FileUtils.getFileURL("C:/Windows", "C:/Users");
assertEquals(new URL("file:/C:/Users"), result8);
{
URL result;
// result = FileUtils.getFileURL("jar:file:/home/duke/duke.jar!/", "baz/entry.txt");
// assertEquals(new URL("jar:file:/home/duke/duke.jar!/baz/entry.txt"), result);
// result = FileUtils.getFileURL((URL) null, "jar:file:/home/duke/duke.jar!/");
// assertEquals(new URL("jar:file:/home/duke/duke.jar!/"), result);
result = FileUtils.getFileURL((URL) null, "jar:file:/C:/proj/parser/jar/parser.jar!/test");
assertEquals(new URL("jar:file:/C:/proj/parser/jar/parser.jar!/test"), result);
result = FileUtils.getFileURL(new URL("jar:file:/C:/proj/parser/jar/parser.jar!/"), "test");
assertEquals(new URL("jar:file:/C:/proj/parser/jar/parser.jar!/test"), result);
}
}
try {
FileUtils.getFileURL("C:/Windows", "unknownprotocol://home/agad/fileManipulation/graph/");
fail("MalformedURLException expected");
} catch (MalformedURLException ex) {}
try {
FileUtils.getFileURL("unknownprotocol://home/agad/fileManipulation/graph/", "home/user");
fail("MalformedURLException expected");
} catch (MalformedURLException ex) {}
try {
FileUtils.getFileURL("C:/Windows", "unknownprotocol:(C:/Users/file.txt)");
fail("MalformedURLException expected");
} catch (MalformedURLException ex) {}
}
public void testGetFileURLLinux() throws MalformedURLException {
URL contextURL = FileUtils.getFileURL("/home/user/workspace/myproject/");
assertEquals(new URL("file:/home/user/workspace/myproject/"), contextURL);
contextURL = FileUtils.getFileURL("/home/user/workspace/myproject");
assertEquals(new URL("file:/home/user/workspace/myproject"), contextURL);
contextURL = FileUtils.getFileURL("/home/user/workspace/my project");
assertEquals(new URL("file:/home/user/workspace/my project"), contextURL);
contextURL = FileUtils.getFileURL("file:/home/user/workspace/myproject");
assertEquals(new URL("file:/home/user/workspace/myproject"), contextURL);
//relative path
URL fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "data-in/myfile.txt");
assertEquals(new URL("file:/home/user/workspace/myproject/data-in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("file:/home/user/workspace/myproject/", "data-in/myfile.txt");
assertEquals(new URL("file:/home/user/workspace/myproject/data-in/myfile.txt"), fileURL);
//absolute path
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "/home/user/location/myfile.txt");
assertEquals(new URL("file:/home/user/location/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("/home/user/workspace/myproject/", "/home/user/location/myfile.txt");
assertEquals(new URL("file:/home/user/location/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "file:/home/user/location/myfile.txt");
assertEquals(new URL("file:/home/user/location/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("/home/user/workspace/myproject/", "file:/home/user/location/myfile.txt");
assertEquals(new URL("file:/home/user/location/myfile.txt"), fileURL);
//file with white space
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "data in/myfile.txt");
assertEquals(new URL("file:/home/user/workspace/myproject/data in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("/home/user/workspace/myproject/", "data in/myfile.txt");
assertEquals(new URL("file:/home/user/workspace/myproject/data in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/my project/"), "data-in/myfile.txt");
assertEquals(new URL("file:/home/user/workspace/my project/data-in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("/home/user/workspace/my project/", "data-in/myfile.txt");
assertEquals(new URL("file:/home/user/workspace/my project/data-in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/my project/"), "data in/myfile.txt");
assertEquals(new URL("file:/home/user/workspace/my project/data in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("/home/user/workspace/my project/", "data in/myfile.txt");
assertEquals(new URL("file:/home/user/workspace/my project/data in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "/home/user/another location/myfile.txt");
assertEquals(new URL("file:/home/user/another location/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("/home/user/workspace/myproject/", "/home/user/another location/myfile.txt");
assertEquals(new URL("file:/home/user/another location/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/my project/"), "/home/user/another location/myfile.txt");
assertEquals(new URL("file:/home/user/another location/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("/home/user/workspace/my project/", "/home/user/another location/myfile.txt");
assertEquals(new URL("file:/home/user/another location/myfile.txt"), fileURL);
//without context
fileURL = FileUtils.getFileURL("data in/myfile.txt");
assertEquals(new URL("file:data in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("data-in/myfile.txt");
assertEquals(new URL("file:data-in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("file:data-in/myfile.txt");
assertEquals(new URL("file:data-in/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("/home/user/another location/myfile.txt");
assertEquals(new URL("file:/home/user/another location/myfile.txt"), fileURL);
//ftp
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "ftp://user@server/myfile.txt");
assertEquals(new URL("ftp://user@server/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL("ftp://user@server/myfile.txt");
assertEquals(new URL("ftp://user@server/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "ftp://user:password@server/myfile.txt");
assertEquals(new URL("ftp://user:password@server/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "ftp://user:password@server:123/myfile.txt");
assertEquals(new URL("ftp://user:password@server:123/myfile.txt"), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "proxy://user:password@proxyserver:1234");
assertEquals(new URL(null, "proxy://user:password@proxyserver:1234", new ProxyHandler()), fileURL);
// TODO: is it possible to check full URL with proxy?
// fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "ftp:(proxy://user:password@proxyserver:1234)//seznam.cz");
//sftp
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "sftp://user@server/myfile.txt");
assertEquals(new URL(null, "sftp://user@server/myfile.txt", new SFTPStreamHandler()), fileURL);
fileURL = FileUtils.getFileURL("sftp://user@server/myfile.txt");
assertEquals(new URL(null, "sftp://user@server/myfile.txt", new SFTPStreamHandler()), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "sftp://user:password@server/myfile.txt");
assertEquals(new URL(null, "sftp://user:password@server/myfile.txt", new SFTPStreamHandler()), fileURL);
fileURL = FileUtils.getFileURL(new URL("file:/home/user/workspace/myproject/"), "sftp://user:password@server:123/myfile.txt");
assertEquals(new URL(null, "sftp://user:password@server:123/myfile.txt", new SFTPStreamHandler()), fileURL);
fileURL = FileUtils.getFileURL(new URL("jar:file:/clover-executor/clover-executor-86.0.0-SNAPSHOT.jar!/com/gooddata/clover"), "/home/test");
assertEquals(new URL("file:/home/test"), fileURL);
fileURL = FileUtils.getFileURL(new URL("http:
assertEquals(new URL("file:/home/test"), fileURL);
try {
FileUtils.getFileURL("/home/user", "unknownprotocol://home/agad/fileManipulation/graph/");
fail("MalformedURLException expected");
} catch (MalformedURLException ex) {}
try {
FileUtils.getFileURL("unknownprotocol://home/agad/fileManipulation/graph/", "home/user");
fail("MalformedURLException expected");
} catch (MalformedURLException ex) {}
try {
FileUtils.getFileURL("/home/user", "unknownprotocol:(/home/test)");
fail("MalformedURLException expected");
} catch (MalformedURLException ex) {}
{
URL result;
result = FileUtils.getFileURL("jar:file:/home/duke/duke.jar!/", "baz/entry.txt");
assertEquals(new URL("jar:file:/home/duke/duke.jar!/baz/entry.txt"), result);
result = FileUtils.getFileURL((URL) null, "jar:file:/home/duke/duke.jar!/");
assertEquals(new URL("jar:file:/home/duke/duke.jar!/"), result);
}
}
// this issue was commented out due low priority and non-trivial possible fix
// public void testInvalidURL() {
// String urlString;
// Exception ex = null;
// try {
// FileUtils.getFileURL(new URL("file://home/user/workspace/myproject/"), urlString);
// try {
// new URL(urlString);
// }catch (MalformedURLException e) {
// ex = e;
// fail("Should fail for url: " + urlString + " with reason: " + ex);
// } catch (MalformedURLException e) {
public void testNormalizeFilePath() {
if (PlatformUtils.isWindowsPlatform()) {
assertEquals("c:/project/data.txt", FileUtils.normalizeFilePath("c:\\project\\data.txt"));
assertEquals("c:/project/data.txt", FileUtils.normalizeFilePath("/c:/project/data.txt"));
assertEquals("c:/project/data.txt", FileUtils.normalizeFilePath("\\c:\\project\\data.txt"));
}
assertEquals("../project/data.txt", FileUtils.normalizeFilePath("../project/data.txt"));
}
public void testIsMultiURL() {
assertFalse(FileUtils.isMultiURL(null));
assertFalse(FileUtils.isMultiURL(""));
assertFalse(FileUtils.isMultiURL("abc"));
assertTrue(FileUtils.isMultiURL("abc;"));
assertTrue(FileUtils.isMultiURL("abc*defg"));
assertTrue(FileUtils.isMultiURL("?defg"));
assertTrue(FileUtils.isMultiURL(";abc?defg*"));
}
public void testGetFileURLWeblogicHandler() throws MalformedURLException {
final String credentials = "user:pass@";
final String fileSpec = "http://" + credentials + "javlin.eu/file";
final URL contexUrl = null;
URL urlWithCredentials = FileUtils.getFileURL(contexUrl, fileSpec);
String serializedUrl = urlWithCredentials.toExternalForm();
String toStringUrl = urlWithCredentials.toString();
assertNotNull(serializedUrl);
assertTrue(serializedUrl.contains(credentials));
assertNotNull(toStringUrl);
assertTrue(toStringUrl.contains(credentials));
}
}
|
/* Leonardo Kazuhiko Kawazoe - 8641959
Leonardo Piccioni de Almeida - 8516094 */
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class GLC{
static final String VAZIO = "&"; /* cadeia vazia */
static String INICIAL; /* variavel inicial da gramatica */
static ArrayList<String> variaveis = new ArrayList<String>();
static ArrayList<String> terminais = new ArrayList<String>();
static ArrayList<Regra> regras = new ArrayList<Regra>();
static ArrayList<String> cadeias = new ArrayList<String>();
public static void main(String[] args){
try{
obtemGLC(new File("inp-glc.txt")); /* obtem a gramatica livre do contexto a partir do arquivo */
obtemCadeias(new File("inp-cadeias.txt")); /* obtem as cadeias a ser analisadas a partir do arquivo */
/* referenciacao aos arquivos de saida */
String diretorioAtual = System.getProperty("user.dir");
File out_status = new File(diretorioAtual + "/out-status.txt");
if(!out_status.exists()) out_status.createNewFile();
BufferedWriter pw_status = new BufferedWriter(new FileWriter(out_status.getPath(), true));
File out_tabela = new File(diretorioAtual + "/out-tabela.txt");
if(!out_tabela.exists()) out_tabela.createNewFile();
BufferedWriter pw_tabela = new BufferedWriter(new FileWriter(out_tabela.getPath(), true));
pw_tabela.write(cadeias.size() + "\n");
for(String cadeia : cadeias){
if(cadeia.equals(VAZIO)){
/* tratamento de cadeia vazia */
Lista l = new Lista();
for(Regra regra : regras)
if(regra.dir.equals(VAZIO)) l.add(regra.esq);
if(l.inicio != null) pw_status.write("1");
else pw_status.write("0");
if(cadeias.get(cadeias.size() - 1) != cadeia) pw_status.write(" ");
pw_tabela.write(cadeia + "\n");
}
else{
int max = Math.round(cadeia.length() / 2) + 1; /* tamanho do lado da matriz quadrada */
Lista[][] tabela = new Lista[max][max]; /* tabela contendo listas ligadas para o valor de cada indice*/
/* obtendo a diagonal exterior */
for(int i = 0; i < max; i++){
tabela[i][i] = new Lista();
String terminal = String.valueOf(cadeia.charAt(2 * i)); /* caracteres sao divididos por espacos */
for(Regra regra : regras)
if(regra.dir.equals(terminal)) tabela[i][i].add(regra.esq);
}
/* entao o resto da tabela */
for(int d = 1; d < max; d++) /* diagonal */
for(int i = 0, j = d; j < max; i++, j++){
tabela[i][j] = new Lista();
for(int ix = i + 1, jx = i; jx < j; jx++, ix++)
for(Regra regra : regras)
if(tabela[i][jx] != null && tabela[ix][j] != null)
for(No n1 = tabela[i][jx].inicio; n1 != null; n1 = n1.prox)
for(No n2 = tabela[ix][j].inicio; n2 != null; n2 = n2.prox)
if(regra.dir.equals(n1.valor + " " + n2.valor)) tabela[i][j].add(regra.esq);
}
/* gerando o log */
if(tabela[0][max - 1].contem(INICIAL)) pw_status.write("1");
else pw_status.write("0");
if(cadeias.get(cadeias.size() - 1) != cadeia) pw_status.write(" ");
pw_tabela.write(cadeia + "\n");
for(int i = 0; i < max; i++)
for(int j = i; j < max; j++){
pw_tabela.write((i + 1) + " " + ((int)j + 1));
if(tabela[i][j] != null)
for(No n = tabela[i][j].inicio; n != null; n = n.prox)
pw_tabela.write(" " + n.valor);
pw_tabela.write("\n");
}
}
}
pw_status.close();
pw_tabela.close();
}
catch(FileNotFoundException e){
System.out.println("Arquivo nao encontrado.");
}
catch(IOException e){
System.out.println("Nao foi possivel escrever/sobrescrever o arquivo.");
}
}
static void obtemGLC(File f) throws FileNotFoundException{
Scanner sc = new Scanner(f);
int num_variaveis = sc.nextInt();
int num_terminais = sc.nextInt();
int num_regras = sc.nextInt();
for(int i = 0; i < num_variaveis; i++) variaveis.add(sc.next());
INICIAL = variaveis.get(0);
for(int i = 0; i < num_terminais; i++) terminais.add(sc.next());
for(int i = 0; i < num_regras; i++)
while(sc.hasNext()){
String esq = sc.next();
sc.useDelimiter(" "); /* utiliza espaco em branco como delimitador de caracteres */
sc.next(); /* pula o simbolo ">" */
sc.reset(); /* remove delimitador de caracteres */
String dir = sc.next();
if(!ehTerminal(dir) && !dir.equals(VAZIO))
dir += " " + sc.next();
regras.add(new Regra(esq, dir));
}
}
static void obtemCadeias(File f) throws FileNotFoundException{
Scanner sc = new Scanner(f);
int num_cadeias = sc.nextInt();
sc.nextLine(); /* pula para a linha da primeira cadeia */
for(int i = 0; i < num_cadeias; i++) cadeias.add(sc.nextLine());
}
static boolean ehTerminal(String dir){ /* verifica se regra gera terminal */
for(String s: terminais)
if(dir.equals(s)) return true;
return false;
}
}
class Regra{
/* esq > dir */
public String esq; /* variavel do lado esquerdo da regra */
public String dir; /* variaveis do lado direito da regra*/
public Regra(String e, String d){
this.esq = e;
this.dir = d;
}
}
class Lista{
No inicio = null;
public void add(String s){ /* adicional lado esquerdo da regra em lista ligada */
if(inicio == null)
inicio = new No(s);
else if(!contem(s)){
No aux = inicio;
while(aux.prox != null)
aux = aux.prox;
aux.prox = new No(s);
}
}
boolean contem(String s){ /* verifica se lista ligada contem variavel */
No aux = inicio;
if(aux == null) return false;
do{
if(aux.valor.equals(s)) return true;
aux = aux.prox;
} while(aux != null);
return false;
}
public Lista(){
inicio = null;
}
}
class No{
String valor; /* lado esquerdo de regra */
No prox;
public No(String s){
valor = s;
prox = null;
}
}
|
package org.jetel.database;
import java.io.*;
import java.sql.*;
import java.util.Properties;
import org.jetel.util.ComponentXMLAttributes;
/**
* CloverETL's class for connecting to databases.<br>
* It practically wraps around JDBC's Connection class and adds some useful
* methods.
*
* <table border="1">
* <th>XML attributes:</th>
* <tr><td><b>id</b></td><td>connection identification</td>
* <tr><td><b>dbConfig</b><i>optional</i></td><td>filename of the config file from which to take connection parameters<br>
* If used, then all other attributes are ignored.</td></tr>
* <tr><td><b>dbDriver</b></td><td>name of the JDBC driver</td></tr>
* <tr><td><b>dbURL</b></td><td>URL of the database (aka connection string)</td></tr>
* <tr><td><b>user</b><br><i>optional</i></td><td>username to use when connecting to DB</td></tr>
* <tr><td><b>password</b><br><i>optional</i></td><td>password to use when connecting to DB</td></tr>
* </table>
*
* <h4>Example:</h4>
* <pre><Node id="OUTPUT" type="DB_OUTPUT_TABLE" dbConnection="NorthwindDB" dbTable="employee_z"/></pre>
*
*@author dpavlis
*@created January 15, 2003
*/
public class DBConnection {
String dbDriverName;
String dbURL;
String user;
String password;
Driver dbDriver;
Connection dbConnection;
/**
* Constructor for the DBConnection object
*
*@param dbDriver Description of the Parameter
*@param dbURL Description of the Parameter
*@param user Description of the Parameter
*@param password Description of the Parameter
*/
public DBConnection(String dbDriver, String dbURL, String user, String password) {
this.dbDriverName = dbDriver;
this.dbURL = dbURL;
this.user = user;
this.password = password;
}
/**
* Constructor for the DBConnection object
*
*@param configFilename properties filename containing definition of driver, dbURL, username, password
*/
public DBConnection(String configFilename) {
Properties config = new Properties();
try {
InputStream stream = new BufferedInputStream(new FileInputStream(configFilename));
config.load(stream);
stream.close();
this.dbDriverName = config.getProperty("dbDriver");
this.dbURL = config.getProperty("dbURL");
this.user = config.getProperty("user");
this.password = config.getProperty("password");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Description of the Method
*/
public void connect() {
Properties property = new Properties();
if (user != null) {
property.setProperty("user", user);
}
if (password != null) {
property.setProperty("password", password);
}
try {
dbDriver = (Driver) Class.forName(dbDriverName).newInstance();
dbConnection = dbDriver.connect(dbURL, property);
} catch (SQLException ex) {
throw new RuntimeException("Can't connect to DB :" + ex.getMessage());
} catch (Exception ex) {
throw new RuntimeException("Can't load DB driver :" + ex.getMessage());
}
if (dbConnection == null) {
throw new RuntimeException("Not suitable driver for specified DB URL : " + dbDriver + " ; " + dbURL);
}
}
/**
* Description of the Method
*
*@exception SQLException Description of the Exception
*/
public void close() throws SQLException {
dbConnection.close();
}
/**
* Gets the connection attribute of the DBConnection object
*
*@return The connection value
*/
public Connection getConnection() {
return dbConnection;
}
/**
* Gets the statement attribute of the DBConnection object
*
*@return The statement value
*@exception SQLException Description of the Exception
*/
public Statement getStatement() throws SQLException {
return dbConnection.createStatement();
}
/**
* Description of the Method
*
*@param sql Description of the Parameter
*@return Description of the Return Value
*@exception SQLException Description of the Exception
*/
public PreparedStatement prepareStatement(String sql) throws SQLException {
return dbConnection.prepareStatement(sql);
}
/**
* Description of the Method
*
*@param nodeXML Description of the Parameter
*@return Description of the Return Value
*/
public static DBConnection fromXML(org.w3c.dom.Node nodeXML) {
ComponentXMLAttributes xattribs=new ComponentXMLAttributes(nodeXML);
try{
// do we have dbConfig parameter specified ??
if (xattribs.exists("dbConfig")){
return new DBConnection(xattribs.getString("dbConfig"));
}else{
String dbDriver = xattribs.getString("dbDriver");
String dbURL = xattribs.getString("dbURL");
String user=null;
String password=null;
if (xattribs.exists("user")){
user = xattribs.getString("user");
}
if (xattribs.exists("password")){
user = xattribs.getString("password");
}
return new DBConnection(dbDriver, dbURL, user, password);
}
}catch(Exception ex){
System.err.println(ex.getMessage());
return null;
}
}
}
|
package biomodelsim;
import gcm2sbml.gui.GCM2SBMLEditor;
import gcm2sbml.network.GeneticNetwork;
import gcm2sbml.parser.CompatibilityFixer;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.parser.GCMParser;
import gcm2sbml.util.GlobalConstants;
import lhpn2sbml.parser.LhpnFile;
import lhpn2sbml.parser.Translator;
import lhpn2sbml.gui.*;
import graph.Graph;
import stategraph.StateGraph;
import java.awt.AWTError;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.Point;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener; //import java.awt.event.ComponentListener;
//import java.awt.event.ComponentEvent;
import java.awt.event.WindowFocusListener; //import java.awt.event.FocusListener;
//import java.awt.event.FocusEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Scanner;
import java.util.prefs.Preferences;
import java.util.regex.Pattern; //import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JViewport; //import javax.swing.tree.TreePath;
import tabs.CloseAndMaxTabbedPane;
import com.apple.eawt.ApplicationAdapter;
import com.apple.eawt.ApplicationEvent;
import com.apple.eawt.Application;
import learn.Learn;
import learn.LearnLHPN;
import synthesis.Synthesis;
import verification.*;
import org.sbml.libsbml.*;
import reb2sac.Reb2Sac;
import reb2sac.Run;
import sbmleditor.SBML_Editor;
import buttons.Buttons;
import datamanager.DataManager;
import java.net.*;
import uk.ac.ebi.biomodels.*;
import att.grappa.*;
//import datamanager.DataManagerLHPN;
/**
* This class creates a GUI for the Tstubd program. It implements the
* ActionListener class. This allows the GUI to perform actions when menu items
* are selected.
*
* @author Curtis Madsen
*/
public class BioSim implements MouseListener, ActionListener, MouseMotionListener,
MouseWheelListener, WindowFocusListener {
private JFrame frame; // Frame where components of the GUI are displayed
private JMenuBar menuBar;
private JMenu file, edit, view, tools, help, saveAsMenu, importMenu, exportMenu, newMenu,
viewModel; // The
// file
// menu
private JMenuItem newProj; // The new menu item
private JMenuItem newModel; // The new menu item
private JMenuItem newCircuit; // The new menu item
private JMenuItem newVhdl; // The new vhdl menu item
private JMenuItem newS; // The new assembly file menu item
private JMenuItem newInst; // The new instruction file menu item
private JMenuItem newLhpn; // The new lhpn menu item
private JMenuItem newG; // The new petri net menu item
private JMenuItem newCsp; // The new csp menu item
private JMenuItem newHse; // The new handshaking extension menu item
private JMenuItem newUnc; // The new extended burst mode menu item
private JMenuItem newRsg; // The new rsg menu item
private JMenuItem newSpice; // The new spice circuit item
private JMenuItem exit; // The exit menu item
private JMenuItem importSbml; // The import sbml menu item
private JMenuItem importBioModel; // The import sbml menu item
private JMenuItem importDot; // The import dot menu item
private JMenuItem importVhdl; // The import vhdl menu item
private JMenuItem importS; // The import assembly file menu item
private JMenuItem importInst; // The import instruction file menu item
private JMenuItem importLpn; // The import lpn menu item
private JMenuItem importG; // The import .g file menu item
private JMenuItem importCsp; // The import csp menu item
private JMenuItem importHse; // The import handshaking extension menu
// item
private JMenuItem importUnc; // The import extended burst mode menu item
private JMenuItem importRsg; // The import rsg menu item
private JMenuItem importSpice; // The import spice circuit item
private JMenuItem manual; // The manual menu item
private JMenuItem about; // The about menu item
private JMenuItem openProj; // The open menu item
private JMenuItem pref; // The preferences menu item
private JMenuItem graph; // The graph menu item
private JMenuItem probGraph, exportCsv, exportDat, exportEps, exportJpg, exportPdf, exportPng,
exportSvg, exportTsd;
private String root; // The root directory
private FileTree tree; // FileTree
private CloseAndMaxTabbedPane tab; // JTabbedPane for different tools
private JToolBar toolbar; // Tool bar for common options
private JButton saveButton, runButton, refreshButton, saveasButton, checkButton, exportButton; // Tool
// Bar
// options
private JPanel mainPanel; // the main panel
public Log log; // the log
private JPopupMenu popup; // popup menu
private String separator;
private KeyEventDispatcher dispatcher;
private JMenuItem recentProjects[];
private String recentProjectPaths[];
private int numberRecentProj;
private int ShortCutKey;
public boolean checkUndeclared, checkUnits;
private JCheckBox Undeclared, Units, viewerCheck;
private JTextField viewerField;
private JLabel viewerLabel;
private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*");
private boolean async, treeSelected = false, popupFlag = false, menuFlag = false;
public boolean atacs, lema;
private String viewer;
private String[] BioModelIds = null;
private JMenuItem copy, rename, delete, save, saveAs, saveAsGcm, saveAsGraph, saveAsSbml,
saveAsTemplate, saveAsLhpn, check, run, export, refresh, viewCircuit, viewRules,
viewTrace, viewLog, viewCoverage, viewVHDL, viewVerilog, viewLHPN, saveSbml, saveTemp,
saveModel, viewSG, viewModGraph, viewModBrowser, createAnal, createLearn, createSbml,
createSynth, createVer, close, closeAll;
public String ENVVAR;
public static final int SBML_LEVEL = 2;
public static final int SBML_VERSION = 4;
public static final Object[] OPTIONS = { "Yes", "No", "Yes To All", "No To All", "Cancel" };
public static final int YES_OPTION = JOptionPane.YES_OPTION;
public static final int NO_OPTION = JOptionPane.NO_OPTION;
public static final int YES_TO_ALL_OPTION = JOptionPane.CANCEL_OPTION;
public static final int NO_TO_ALL_OPTION = 3;
public static final int CANCEL_OPTION = 4;
public class MacOSAboutHandler extends Application {
public MacOSAboutHandler() {
addApplicationListener(new AboutBoxHandler());
}
class AboutBoxHandler extends ApplicationAdapter {
public void handleAbout(ApplicationEvent event) {
about();
event.setHandled(true);
}
}
}
public class MacOSPreferencesHandler extends Application {
public MacOSPreferencesHandler() {
addApplicationListener(new PreferencesHandler());
}
class PreferencesHandler extends ApplicationAdapter {
public void handlePreferences(ApplicationEvent event) {
preferences();
event.setHandled(true);
}
}
}
public class MacOSQuitHandler extends Application {
public MacOSQuitHandler() {
addApplicationListener(new QuitHandler());
}
class QuitHandler extends ApplicationAdapter {
public void handleQuit(ApplicationEvent event) {
exit();
event.setHandled(true);
}
}
}
/**
* This is the constructor for the Proj class. It initializes all the input
* fields, puts them on panels, adds the panels to the frame, and then
* displays the frame.
*
* @throws Exception
*/
public BioSim(boolean lema, boolean atacs) {
this.lema = lema;
this.atacs = atacs;
async = lema || atacs;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
if (atacs) {
ENVVAR = System.getenv("ATACSGUI");
}
else if (lema) {
ENVVAR = System.getenv("LEMA");
}
else {
ENVVAR = System.getenv("BIOSIM");
}
// Creates a new frame
if (lema) {
frame = new JFrame("LEMA");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons"
+ separator + "LEMA.png").getImage());
}
else if (atacs) {
frame = new JFrame("ATACS");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons"
+ separator + "ATACS.png").getImage());
}
else {
frame = new JFrame("iBioSim");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons"
+ separator + "iBioSim.png").getImage());
}
// Makes it so that clicking the x in the corner closes the program
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
exit.doClick();
}
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) {
}
};
frame.addWindowListener(w);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowFocusListener(this);
popup = new JPopupMenu();
popup.addMouseListener(this);
// popup.addFocusListener(this);
// popup.addComponentListener(this);
// Sets up the Tool Bar
toolbar = new JToolBar();
String imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "save.png";
saveButton = makeToolButton(imgName, "save", "Save", "Save");
// toolButton = new JButton("Save");
toolbar.add(saveButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "saveas.png";
saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As");
toolbar.add(saveasButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "run-icon.jpg";
runButton = makeToolButton(imgName, "run", "Save and Run", "Run");
// toolButton = new JButton("Run");
toolbar.add(runButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "refresh.jpg";
refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh");
toolbar.add(refreshButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "savecheck.png";
checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check");
toolbar.add(checkButton);
imgName = ENVVAR + separator + "gui" + separator + "icons" + separator + "export.jpg";
exportButton = makeToolButton(imgName, "export", "Export", "Export");
toolbar.add(exportButton);
saveButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
saveasButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// Creates a menu for the frame
menuBar = new JMenuBar();
file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
help = new JMenu("Help");
help.setMnemonic(KeyEvent.VK_H);
edit = new JMenu("Edit");
edit.setMnemonic(KeyEvent.VK_E);
importMenu = new JMenu("Import");
exportMenu = new JMenu("Export");
newMenu = new JMenu("New");
saveAsMenu = new JMenu("Save As");
view = new JMenu("View");
viewModel = new JMenu("Model");
tools = new JMenu("Tools");
menuBar.add(file);
menuBar.add(edit);
menuBar.add(view);
menuBar.add(tools);
menuBar.add(help);
// menuBar.addFocusListener(this);
// menuBar.addMouseListener(this);
// file.addMouseListener(this);
// edit.addMouseListener(this);
// view.addMouseListener(this);
// tools.addMouseListener(this);
// help.addMouseListener(this);
copy = new JMenuItem("Copy");
rename = new JMenuItem("Rename");
delete = new JMenuItem("Delete");
manual = new JMenuItem("Manual");
about = new JMenuItem("About");
openProj = new JMenuItem("Open Project");
close = new JMenuItem("Close");
closeAll = new JMenuItem("Close All");
pref = new JMenuItem("Preferences");
newProj = new JMenuItem("Project");
newCircuit = new JMenuItem("Genetic Circuit Model");
newModel = new JMenuItem("SBML Model");
newSpice = new JMenuItem("Spice Circuit");
newVhdl = new JMenuItem("VHDL-AMS Model");
newS = new JMenuItem("Assembly File");
newInst = new JMenuItem("Instruction File");
newLhpn = new JMenuItem("Labeled Petri Net");
newG = new JMenuItem("Petri Net");
newCsp = new JMenuItem("CSP Model");
newHse = new JMenuItem("Handshaking Expansion");
newUnc = new JMenuItem("Extended Burst Mode Machine");
newRsg = new JMenuItem("Reduced State Graph");
graph = new JMenuItem("TSD Graph");
probGraph = new JMenuItem("Histogram");
importSbml = new JMenuItem("SBML Model");
importBioModel = new JMenuItem("BioModel");
importDot = new JMenuItem("Genetic Circuit Model");
importG = new JMenuItem("Petri Net");
importLpn = new JMenuItem("Labeled Petri Net");
importVhdl = new JMenuItem("VHDL-AMS Model");
importS = new JMenuItem("Assembly File");
importInst = new JMenuItem("Instruction File");
importSpice = new JMenuItem("Spice Circuit");
importCsp = new JMenuItem("CSP Model");
importHse = new JMenuItem("Handshaking Expansion");
importUnc = new JMenuItem("Extended Burst Mode Machine");
importRsg = new JMenuItem("Reduced State Graph");
exportCsv = new JMenuItem("Comma Separated Values (csv)");
exportDat = new JMenuItem("Tab Delimited Data (dat)");
exportEps = new JMenuItem("Encapsulated Postscript (eps)");
exportJpg = new JMenuItem("JPEG (jpg)");
exportPdf = new JMenuItem("Portable Document Format (pdf)");
exportPng = new JMenuItem("Portable Network Graphics (png)");
exportSvg = new JMenuItem("Scalable Vector Graphics (svg)");
exportTsd = new JMenuItem("Time Series Data (tsd)");
save = new JMenuItem("Save");
if (async) {
saveModel = new JMenuItem("Save Models");
}
else {
saveModel = new JMenuItem("Save GCM");
}
saveAs = new JMenuItem("Save As");
saveAsGcm = new JMenuItem("Genetic Circuit Model");
saveAsGraph = new JMenuItem("Graph");
saveAsSbml = new JMenuItem("Save SBML Model");
saveAsTemplate = new JMenuItem("Save SBML Template");
// saveGcmAsLhpn = new JMenuItem("Save LPN Model");
saveAsLhpn = new JMenuItem("LPN");
run = new JMenuItem("Save and Run");
check = new JMenuItem("Save and Check");
saveSbml = new JMenuItem("Save as SBML");
saveTemp = new JMenuItem("Save as SBML Template");
// saveParam = new JMenuItem("Save Parameters");
refresh = new JMenuItem("Refresh");
export = new JMenuItem("Export");
viewCircuit = new JMenuItem("Circuit");
viewRules = new JMenuItem("Production Rules");
viewTrace = new JMenuItem("Error Trace");
viewLog = new JMenuItem("Log");
viewCoverage = new JMenuItem("Coverage Report");
viewVHDL = new JMenuItem("VHDL-AMS Model");
viewVerilog = new JMenuItem("Verilog-AMS Model");
viewLHPN = new JMenuItem("LPN Model");
viewModGraph = new JMenuItem("Model");
viewModBrowser = new JMenuItem("Model in Browser");
viewSG = new JMenuItem("State Graph");
createAnal = new JMenuItem("Analysis Tool");
createLearn = new JMenuItem("Learn Tool");
createSbml = new JMenuItem("Create SBML File");
createSynth = new JMenuItem("Synthesis Tool");
createVer = new JMenuItem("Verification Tool");
exit = new JMenuItem("Exit");
copy.addActionListener(this);
rename.addActionListener(this);
delete.addActionListener(this);
openProj.addActionListener(this);
close.addActionListener(this);
closeAll.addActionListener(this);
pref.addActionListener(this);
manual.addActionListener(this);
newProj.addActionListener(this);
newCircuit.addActionListener(this);
newModel.addActionListener(this);
newVhdl.addActionListener(this);
newS.addActionListener(this);
newInst.addActionListener(this);
newLhpn.addActionListener(this);
newG.addActionListener(this);
newCsp.addActionListener(this);
newHse.addActionListener(this);
newUnc.addActionListener(this);
newRsg.addActionListener(this);
newSpice.addActionListener(this);
exit.addActionListener(this);
about.addActionListener(this);
importSbml.addActionListener(this);
importBioModel.addActionListener(this);
importDot.addActionListener(this);
importVhdl.addActionListener(this);
importS.addActionListener(this);
importInst.addActionListener(this);
importLpn.addActionListener(this);
importG.addActionListener(this);
importCsp.addActionListener(this);
importHse.addActionListener(this);
importUnc.addActionListener(this);
importRsg.addActionListener(this);
importSpice.addActionListener(this);
exportCsv.addActionListener(this);
exportDat.addActionListener(this);
exportEps.addActionListener(this);
exportJpg.addActionListener(this);
exportPdf.addActionListener(this);
exportPng.addActionListener(this);
exportSvg.addActionListener(this);
exportTsd.addActionListener(this);
graph.addActionListener(this);
probGraph.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
saveAsSbml.addActionListener(this);
saveAsTemplate.addActionListener(this);
// saveGcmAsLhpn.addActionListener(this);
run.addActionListener(this);
check.addActionListener(this);
saveSbml.addActionListener(this);
saveTemp.addActionListener(this);
saveModel.addActionListener(this);
// saveParam.addActionListener(this);
export.addActionListener(this);
viewCircuit.addActionListener(this);
viewRules.addActionListener(this);
viewTrace.addActionListener(this);
viewLog.addActionListener(this);
viewCoverage.addActionListener(this);
viewVHDL.addActionListener(this);
viewVerilog.addActionListener(this);
viewLHPN.addActionListener(this);
viewModGraph.addActionListener(this);
viewModBrowser.addActionListener(this);
viewSG.addActionListener(this);
createAnal.addActionListener(this);
createLearn.addActionListener(this);
createSbml.addActionListener(this);
createSynth.addActionListener(this);
createVer.addActionListener(this);
save.setActionCommand("save");
saveAs.setActionCommand("saveas");
run.setActionCommand("run");
check.setActionCommand("check");
refresh.setActionCommand("refresh");
export.setActionCommand("export");
if (atacs) {
viewModGraph.setActionCommand("viewModel");
}
else {
viewModGraph.setActionCommand("graph");
}
viewModBrowser.setActionCommand("browse");
viewSG.setActionCommand("stateGraph");
createLearn.setActionCommand("createLearn");
createSbml.setActionCommand("createSBML");
createSynth.setActionCommand("createSynthesis");
createVer.setActionCommand("createVerify");
ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey));
rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey));
// newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
// ShortCutKey));
openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey));
close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey));
closeAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey
| KeyEvent.SHIFT_MASK));
// saveAsMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// importMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// exportMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// viewModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
// ShortCutKey));
// newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
// ShortCutKey));
// newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
// ShortCutKey));
// newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
// ShortCutKey));
// about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
// ShortCutKey));
manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey));
run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey));
check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey));
pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey));
viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
if (lema) {
// viewCoverage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,
// 0)); // SB
viewVHDL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0));
viewVerilog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
viewLHPN.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
viewTrace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0));
}
else {
viewCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey));
createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey));
}
Action newAction = new NewAction();
Action saveAction = new SaveAction();
Action importAction = new ImportAction();
Action exportAction = new ExportAction();
Action modelAction = new ModelAction();
newMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "new");
newMenu.getActionMap().put("new", newAction);
saveAsMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"save");
saveAsMenu.getActionMap().put("save", saveAction);
importMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_I, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"import");
importMenu.getActionMap().put("import", importAction);
exportMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"export");
exportMenu.getActionMap().put("export", exportAction);
viewModel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"model");
viewModel.getActionMap().put("model", modelAction);
// graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
// ShortCutKey));
// probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
// ShortCutKey));
// if (!lema) {
// importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
// ShortCutKey));
// else {
// importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
// ShortCutKey));
// importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B,
// ShortCutKey));
// importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
// ShortCutKey));
newMenu.setMnemonic(KeyEvent.VK_N);
saveAsMenu.setMnemonic(KeyEvent.VK_A);
importMenu.setMnemonic(KeyEvent.VK_I);
exportMenu.setMnemonic(KeyEvent.VK_E);
viewModel.setMnemonic(KeyEvent.VK_M);
copy.setMnemonic(KeyEvent.VK_C);
rename.setMnemonic(KeyEvent.VK_R);
delete.setMnemonic(KeyEvent.VK_D);
exit.setMnemonic(KeyEvent.VK_X);
newProj.setMnemonic(KeyEvent.VK_P);
openProj.setMnemonic(KeyEvent.VK_O);
close.setMnemonic(KeyEvent.VK_W);
newCircuit.setMnemonic(KeyEvent.VK_G);
newModel.setMnemonic(KeyEvent.VK_S);
newVhdl.setMnemonic(KeyEvent.VK_V);
newLhpn.setMnemonic(KeyEvent.VK_L);
newG.setMnemonic(KeyEvent.VK_N);
newSpice.setMnemonic(KeyEvent.VK_P);
about.setMnemonic(KeyEvent.VK_A);
manual.setMnemonic(KeyEvent.VK_M);
graph.setMnemonic(KeyEvent.VK_T);
probGraph.setMnemonic(KeyEvent.VK_H);
if (!async) {
importDot.setMnemonic(KeyEvent.VK_G);
}
else {
importLpn.setMnemonic(KeyEvent.VK_L);
}
importSbml.setMnemonic(KeyEvent.VK_S);
// importBioModel.setMnemonic(KeyEvent.VK_S);
importVhdl.setMnemonic(KeyEvent.VK_V);
importSpice.setMnemonic(KeyEvent.VK_P);
save.setMnemonic(KeyEvent.VK_S);
run.setMnemonic(KeyEvent.VK_R);
check.setMnemonic(KeyEvent.VK_K);
exportCsv.setMnemonic(KeyEvent.VK_C);
exportEps.setMnemonic(KeyEvent.VK_E);
exportDat.setMnemonic(KeyEvent.VK_D);
exportJpg.setMnemonic(KeyEvent.VK_J);
exportPdf.setMnemonic(KeyEvent.VK_F);
exportPng.setMnemonic(KeyEvent.VK_G);
exportSvg.setMnemonic(KeyEvent.VK_S);
exportTsd.setMnemonic(KeyEvent.VK_T);
pref.setMnemonic(KeyEvent.VK_P);
viewModGraph.setMnemonic(KeyEvent.VK_G);
viewModBrowser.setMnemonic(KeyEvent.VK_B);
createAnal.setMnemonic(KeyEvent.VK_A);
createLearn.setMnemonic(KeyEvent.VK_L);
importDot.setEnabled(false);
importSbml.setEnabled(false);
importBioModel.setEnabled(false);
importVhdl.setEnabled(false);
importS.setEnabled(false);
importInst.setEnabled(false);
importLpn.setEnabled(false);
importG.setEnabled(false);
importCsp.setEnabled(false);
importHse.setEnabled(false);
importUnc.setEnabled(false);
importRsg.setEnabled(false);
importSpice.setEnabled(false);
exportMenu.setEnabled(false);
// exportCsv.setEnabled(false);
// exportDat.setEnabled(false);
// exportEps.setEnabled(false);
// exportJpg.setEnabled(false);
// exportPdf.setEnabled(false);
// exportPng.setEnabled(false);
// exportSvg.setEnabled(false);
// exportTsd.setEnabled(false);
newCircuit.setEnabled(false);
newModel.setEnabled(false);
newVhdl.setEnabled(false);
newS.setEnabled(false);
newInst.setEnabled(false);
newLhpn.setEnabled(false);
newG.setEnabled(false);
newCsp.setEnabled(false);
newHse.setEnabled(false);
newUnc.setEnabled(false);
newRsg.setEnabled(false);
newSpice.setEnabled(false);
graph.setEnabled(false);
probGraph.setEnabled(false);
save.setEnabled(false);
saveModel.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
run.setEnabled(false);
check.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
// saveParam.setEnabled(false);
refresh.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
viewSG.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
edit.add(copy);
edit.add(rename);
// edit.add(refresh);
edit.add(delete);
// edit.addSeparator();
// edit.add(pref);
file.add(newMenu);
newMenu.add(newProj);
if (!async) {
newMenu.add(newCircuit);
newMenu.add(newLhpn);
newMenu.add(newModel);
}
else if (atacs) {
newMenu.add(newVhdl);
newMenu.add(newG);
newMenu.add(newLhpn);
newMenu.add(newCsp);
newMenu.add(newHse);
newMenu.add(newUnc);
newMenu.add(newRsg);
}
else {
newMenu.add(newVhdl);
newMenu.add(newS);
newMenu.add(newInst);
newMenu.add(newLhpn);
// newMenu.add(newSpice);
}
newMenu.add(graph);
if (!async) {
newMenu.add(probGraph);
}
file.add(openProj);
// openMenu.add(openProj);
file.addSeparator();
file.add(close);
file.add(closeAll);
file.addSeparator();
file.add(save);
// file.add(saveAsMenu);
if (!async) {
saveAsMenu.add(saveAsGcm);
saveAsMenu.add(saveAsGraph);
saveAsMenu.add(saveAsSbml);
saveAsMenu.add(saveAsTemplate);
// saveAsMenu.add(saveGcmAsLhpn);
}
else {
saveAsMenu.add(saveAsLhpn);
saveAsMenu.add(saveAsGraph);
}
file.add(saveAs);
if (!async) {
file.add(saveAsSbml);
file.add(saveAsTemplate);
// file.add(saveGcmAsLhpn);
}
file.add(saveModel);
// file.add(saveParam);
file.add(run);
if (!async) {
file.add(check);
}
file.addSeparator();
file.add(importMenu);
if (!async) {
importMenu.add(importDot);
importMenu.add(importLpn);
importMenu.add(importSbml);
importMenu.add(importBioModel);
}
else if (atacs) {
importMenu.add(importVhdl);
importMenu.add(importG);
importMenu.add(importLpn);
importMenu.add(importCsp);
importMenu.add(importHse);
importMenu.add(importUnc);
importMenu.add(importRsg);
}
else {
importMenu.add(importVhdl);
importMenu.add(importS);
importMenu.add(importInst);
importMenu.add(importLpn);
// importMenu.add(importSpice);
}
file.add(exportMenu);
exportMenu.add(exportCsv);
exportMenu.add(exportDat);
exportMenu.add(exportEps);
exportMenu.add(exportJpg);
exportMenu.add(exportPdf);
exportMenu.add(exportPng);
exportMenu.add(exportSvg);
exportMenu.add(exportTsd);
file.addSeparator();
// file.add(save);
// file.add(saveAs);
// file.add(run);
// file.add(check);
// if (!lema) {
// file.add(saveParam);
// file.addSeparator();
// file.add(export);
// if (!lema) {
// file.add(saveSbml);
// file.add(saveTemp);
help.add(manual);
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
edit.addSeparator();
edit.add(pref);
file.add(exit);
file.addSeparator();
help.add(about);
}
if (lema) {
view.add(viewVHDL);
view.add(viewVerilog);
view.add(viewLHPN);
view.addSeparator();
view.add(viewCoverage);
view.add(viewLog);
view.add(viewTrace);
}
else if (atacs) {
view.add(viewModGraph);
view.add(viewCircuit);
view.add(viewRules);
view.add(viewTrace);
view.add(viewLog);
}
else {
view.add(viewModGraph);
view.add(viewModBrowser);
view.add(viewSG);
view.add(viewLog);
view.addSeparator();
view.add(refresh);
}
if (!async) {
tools.add(createAnal);
}
if (!atacs) {
tools.add(createLearn);
}
if (atacs) {
tools.add(createSynth);
}
if (async) {
tools.add(createVer);
}
// else {
// tools.add(createSbml);
root = null;
// Create recent project menu items
numberRecentProj = 0;
recentProjects = new JMenuItem[5];
recentProjectPaths = new String[5];
for (int i = 0; i < 5; i++) {
recentProjects[i] = new JMenuItem();
recentProjects[i].addActionListener(this);
recentProjects[i].setActionCommand("recent" + i);
recentProjectPaths[i] = "";
}
recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey));
recentProjects[0].setMnemonic(KeyEvent.VK_1);
recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey));
recentProjects[1].setMnemonic(KeyEvent.VK_2);
recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey));
recentProjects[2].setMnemonic(KeyEvent.VK_3);
recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey));
recentProjects[3].setMnemonic(KeyEvent.VK_4);
recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey));
recentProjects[4].setMnemonic(KeyEvent.VK_5);
Preferences biosimrc = Preferences.userRoot();
viewer = biosimrc.get("biosim.general.viewer", "");
for (int i = 0; i < 5; i++) {
if (atacs) {
recentProjects[i].setText(biosimrc.get("atacs.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("atacs.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
else if (lema) {
recentProjects[i].setText(biosimrc.get("lema.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("lema.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
else {
recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
}
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
// file.add(pref);
// file.add(exit);
help.add(about);
}
if (biosimrc.get("biosim.check.undeclared", "").equals("false")) {
checkUndeclared = false;
}
else {
checkUndeclared = true;
}
if (biosimrc.get("biosim.check.units", "").equals("false")) {
checkUnits = false;
}
else {
checkUnits = true;
}
if (biosimrc.get("biosim.general.file_browser", "").equals("")) {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KREP_VALUE", ".5");
}
if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KACT_VALUE", ".0033");
}
if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KBIO_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2");
}
if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001");
}
if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.OCR_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075");
}
if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.RNAP_VALUE", "30");
}
if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033");
}
if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10");
}
if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2");
}
if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25");
}
if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1");
}
if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.INITIAL_VALUE", "0");
}
if (biosimrc.get("biosim.sim.abs", "").equals("")) {
biosimrc.put("biosim.sim.abs", "None");
}
if (biosimrc.get("biosim.sim.type", "").equals("")) {
biosimrc.put("biosim.sim.type", "ODE");
}
if (biosimrc.get("biosim.sim.sim", "").equals("")) {
biosimrc.put("biosim.sim.sim", "rkf45");
}
if (biosimrc.get("biosim.sim.limit", "").equals("")) {
biosimrc.put("biosim.sim.limit", "100.0");
}
if (biosimrc.get("biosim.sim.useInterval", "").equals("")) {
biosimrc.put("biosim.sim.useInterval", "Print Interval");
}
if (biosimrc.get("biosim.sim.interval", "").equals("")) {
biosimrc.put("biosim.sim.interval", "1.0");
}
if (biosimrc.get("biosim.sim.step", "").equals("")) {
biosimrc.put("biosim.sim.step", "inf");
}
if (biosimrc.get("biosim.sim.min.step", "").equals("")) {
biosimrc.put("biosim.sim.min.step", "0");
}
if (biosimrc.get("biosim.sim.error", "").equals("")) {
biosimrc.put("biosim.sim.error", "1.0E-9");
}
if (biosimrc.get("biosim.sim.seed", "").equals("")) {
biosimrc.put("biosim.sim.seed", "314159");
}
if (biosimrc.get("biosim.sim.runs", "").equals("")) {
biosimrc.put("biosim.sim.runs", "1");
}
if (biosimrc.get("biosim.sim.rapid1", "").equals("")) {
biosimrc.put("biosim.sim.rapid1", "0.1");
}
if (biosimrc.get("biosim.sim.rapid2", "").equals("")) {
biosimrc.put("biosim.sim.rapid2", "0.1");
}
if (biosimrc.get("biosim.sim.qssa", "").equals("")) {
biosimrc.put("biosim.sim.qssa", "0.1");
}
if (biosimrc.get("biosim.sim.concentration", "").equals("")) {
biosimrc.put("biosim.sim.concentration", "15");
}
if (biosimrc.get("biosim.learn.tn", "").equals("")) {
biosimrc.put("biosim.learn.tn", "2");
}
if (biosimrc.get("biosim.learn.tj", "").equals("")) {
biosimrc.put("biosim.learn.tj", "2");
}
if (biosimrc.get("biosim.learn.ti", "").equals("")) {
biosimrc.put("biosim.learn.ti", "0.5");
}
if (biosimrc.get("biosim.learn.bins", "").equals("")) {
biosimrc.put("biosim.learn.bins", "4");
}
if (biosimrc.get("biosim.learn.equaldata", "").equals("")) {
biosimrc.put("biosim.learn.equaldata", "Equal Data Per Bins");
}
if (biosimrc.get("biosim.learn.autolevels", "").equals("")) {
biosimrc.put("biosim.learn.autolevels", "Auto");
}
if (biosimrc.get("biosim.learn.ta", "").equals("")) {
biosimrc.put("biosim.learn.ta", "1.15");
}
if (biosimrc.get("biosim.learn.tr", "").equals("")) {
biosimrc.put("biosim.learn.tr", "0.75");
}
if (biosimrc.get("biosim.learn.tm", "").equals("")) {
biosimrc.put("biosim.learn.tm", "0.0");
}
if (biosimrc.get("biosim.learn.tt", "").equals("")) {
biosimrc.put("biosim.learn.tt", "0.025");
}
if (biosimrc.get("biosim.learn.debug", "").equals("")) {
biosimrc.put("biosim.learn.debug", "0");
}
if (biosimrc.get("biosim.learn.succpred", "").equals("")) {
biosimrc.put("biosim.learn.succpred", "Successors");
}
if (biosimrc.get("biosim.learn.findbaseprob", "").equals("")) {
biosimrc.put("biosim.learn.findbaseprob", "False");
}
// Open .biosimrc here
// Packs the frame and displays it
mainPanel = new JPanel(new BorderLayout());
tree = new FileTree(null, this, lema, atacs);
log = new Log();
tab = new CloseAndMaxTabbedPane(false, this);
tab.setPreferredSize(new Dimension(1100, 550));
tab.getPaneUI().addMouseListener(this);
mainPanel.add(tree, "West");
mainPanel.add(tab, "Center");
mainPanel.add(log, "South");
mainPanel.add(toolbar, "North");
frame.setContentPane(mainPanel);
frame.setJMenuBar(menuBar);
frame.getGlassPane().setVisible(true);
frame.getGlassPane().addMouseListener(this);
frame.getGlassPane().addMouseMotionListener(this);
frame.getGlassPane().addMouseWheelListener(this);
frame.addMouseListener(this);
menuBar.addMouseListener(this);
frame.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
frame.setSize(frameSize);
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
frame.setSize(frameSize);
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
frame.setLocation(x, y);
frame.setVisible(true);
dispatcher = new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_TYPED) {
if (e.getKeyChar() == '') {
if (tab.getTabCount() > 0) {
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.removeKeyEventDispatcher(dispatcher);
if (save(tab.getSelectedIndex(), 0) != 0) {
tab.remove(tab.getSelectedIndex());
}
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(dispatcher);
}
}
}
return false;
}
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
}
public void preferences() {
if (!async) {
Undeclared = new JCheckBox("Check for undeclared units in SBML");
if (checkUndeclared) {
Undeclared.setSelected(true);
}
else {
Undeclared.setSelected(false);
}
Units = new JCheckBox("Check units in SBML");
if (checkUnits) {
Units.setSelected(true);
}
else {
Units.setSelected(false);
}
Preferences biosimrc = Preferences.userRoot();
JCheckBox dialog = new JCheckBox("Use File Dialog");
if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) {
dialog.setSelected(true);
}
else {
dialog.setSelected(false);
}
final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.ACTIVED_VALUE", ""));
final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", ""));
final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE",
""));
final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", ""));
final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE",
""));
final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.COOPERATIVITY_VALUE", ""));
final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.KASSOCIATION_VALUE", ""));
final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", ""));
final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.PROMOTER_COUNT_VALUE", ""));
final JTextField INITIAL_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.INITIAL_VALUE", ""));
final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.MAX_DIMER_VALUE", ""));
final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", ""));
final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.RNAP_BINDING_VALUE", ""));
final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", ""));
final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.STOICHIOMETRY_VALUE", ""));
JPanel labels = new JPanel(new GridLayout(15, 1));
labels
.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.COOPERATIVITY_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.KASSOCIATION_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.PROMOTER_COUNT_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING)
+ "):"));
labels
.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.RNAP_BINDING_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.STOICHIOMETRY_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING)
+ "):"));
JPanel fields = new JPanel(new GridLayout(15, 1));
fields.add(ACTIVED_VALUE);
fields.add(KACT_VALUE);
fields.add(KBASAL_VALUE);
fields.add(KBIO_VALUE);
fields.add(KDECAY_VALUE);
fields.add(COOPERATIVITY_VALUE);
fields.add(KASSOCIATION_VALUE);
fields.add(RNAP_VALUE);
fields.add(PROMOTER_COUNT_VALUE);
fields.add(INITIAL_VALUE);
fields.add(MAX_DIMER_VALUE);
fields.add(OCR_VALUE);
fields.add(RNAP_BINDING_VALUE);
fields.add(KREP_VALUE);
fields.add(STOICHIOMETRY_VALUE);
JPanel gcmPrefs = new JPanel(new GridLayout(1, 2));
gcmPrefs.add(labels);
gcmPrefs.add(fields);
String[] choices = { "None", "Abstraction", "Logical Abstraction" };
JTextField simCommand = new JTextField(biosimrc.get("biosim.sim.command", ""));
final JComboBox abs = new JComboBox(choices);
abs.setSelectedItem(biosimrc.get("biosim.sim.abs", ""));
if (abs.getSelectedItem().equals("None")) {
choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" };
}
else if (abs.getSelectedItem().equals("Abstraction")) {
choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" };
}
else {
choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser",
"LPN" };
}
final JComboBox type = new JComboBox(choices);
type.setSelectedItem(biosimrc.get("biosim.sim.type", ""));
if (type.getSelectedItem().equals("ODE")) {
choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" };
}
else if (type.getSelectedItem().equals("Monte Carlo")) {
choices = new String[] { "gillespie", "mpde", "mp", "mp-adaptive", "mp-event",
"emc-sim", "bunker", "nmc" };
}
else if (type.getSelectedItem().equals("Markov")) {
choices = new String[] { "markov-chain-analysis", "atacs", "ctmc-transient" };
}
else {
choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" };
}
final JComboBox sim = new JComboBox(choices);
sim.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
abs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (abs.getSelectedItem().equals("None")) {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("ODE");
type.addItem("Monte Carlo");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.setSelectedItem(o);
}
else if (abs.getSelectedItem().equals("Abstraction")) {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("ODE");
type.addItem("Monte Carlo");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.setSelectedItem(o);
}
else {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("Monte Carlo");
type.addItem("Markov");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.addItem("LPN");
type.setSelectedItem(o);
}
}
});
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (type.getSelectedItem() == null) {
}
else if (type.getSelectedItem().equals("ODE")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("euler");
sim.addItem("gear1");
sim.addItem("gear2");
sim.addItem("rk4imp");
sim.addItem("rk8pd");
sim.addItem("rkf45");
sim.setSelectedIndex(5);
sim.setSelectedItem(o);
}
else if (type.getSelectedItem().equals("Monte Carlo")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("gillespie");
sim.addItem("mpde");
sim.addItem("mp");
sim.addItem("mp-adaptive");
sim.addItem("mp-event");
sim.addItem("emc-sim");
sim.addItem("bunker");
sim.addItem("nmc");
sim.setSelectedItem(o);
}
else if (type.getSelectedItem().equals("Markov")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("atacs");
sim.addItem("ctmc-transient");
sim.setSelectedItem(o);
}
else {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("euler");
sim.addItem("gear1");
sim.addItem("gear2");
sim.addItem("rk4imp");
sim.addItem("rk8pd");
sim.addItem("rkf45");
sim.setSelectedIndex(5);
sim.setSelectedItem(o);
}
}
});
JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", ""));
JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", ""));
JTextField minStep = new JTextField(biosimrc.get("biosim.sim.min.step", ""));
JTextField step = new JTextField(biosimrc.get("biosim.sim.step", ""));
JTextField error = new JTextField(biosimrc.get("biosim.sim.error", ""));
JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", ""));
JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", ""));
JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", ""));
JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", ""));
JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", ""));
JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", ""));
choices = new String[] { "Print Interval", "Minimum Print Interval", "Number Of Steps" };
JComboBox useInterval = new JComboBox(choices);
useInterval.setSelectedItem(biosimrc.get("biosim.sim.useInterval", ""));
JPanel analysisLabels = new JPanel(new GridLayout(15, 1));
analysisLabels.add(new JLabel("Simulation Command:"));
analysisLabels.add(new JLabel("Abstraction:"));
analysisLabels.add(new JLabel("Simulation Type:"));
analysisLabels.add(new JLabel("Possible Simulators/Analyzers:"));
analysisLabels.add(new JLabel("Time Limit:"));
analysisLabels.add(useInterval);
analysisLabels.add(new JLabel("Minimum Time Step:"));
analysisLabels.add(new JLabel("Maximum Time Step:"));
analysisLabels.add(new JLabel("Absolute Error:"));
analysisLabels.add(new JLabel("Random Seed:"));
analysisLabels.add(new JLabel("Runs:"));
analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:"));
analysisLabels.add(new JLabel("Rapid Equilibrium Cojdition 2:"));
analysisLabels.add(new JLabel("QSSA Condition:"));
analysisLabels.add(new JLabel("Max Concentration Threshold:"));
JPanel analysisFields = new JPanel(new GridLayout(15, 1));
analysisFields.add(simCommand);
analysisFields.add(abs);
analysisFields.add(type);
analysisFields.add(sim);
analysisFields.add(limit);
analysisFields.add(interval);
analysisFields.add(minStep);
analysisFields.add(step);
analysisFields.add(error);
analysisFields.add(seed);
analysisFields.add(runs);
analysisFields.add(rapid1);
analysisFields.add(rapid2);
analysisFields.add(qssa);
analysisFields.add(concentration);
JPanel analysisPrefs = new JPanel(new GridLayout(1, 2));
analysisPrefs.add(analysisLabels);
analysisPrefs.add(analysisFields);
final JTextField tn = new JTextField(biosimrc.get("biosim.learn.tn", ""));
final JTextField tj = new JTextField(biosimrc.get("biosim.learn.tj", ""));
final JTextField ti = new JTextField(biosimrc.get("biosim.learn.ti", ""));
choices = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
final JComboBox bins = new JComboBox(choices);
bins.setSelectedItem(biosimrc.get("biosim.learn.bins", ""));
choices = new String[] { "Equal Data Per Bins", "Equal Spacing Of Bins" };
final JComboBox equaldata = new JComboBox(choices);
equaldata.setSelectedItem(biosimrc.get("biosim.learn.equaldata", ""));
choices = new String[] { "Auto", "User" };
final JComboBox autolevels = new JComboBox(choices);
autolevels.setSelectedItem(biosimrc.get("biosim.learn.autolevels", ""));
final JTextField ta = new JTextField(biosimrc.get("biosim.learn.ta", ""));
final JTextField tr = new JTextField(biosimrc.get("biosim.learn.tr", ""));
final JTextField tm = new JTextField(biosimrc.get("biosim.learn.tm", ""));
final JTextField tt = new JTextField(biosimrc.get("biosim.learn.tt", ""));
choices = new String[] { "0", "1", "2", "3" };
final JComboBox debug = new JComboBox(choices);
debug.setSelectedItem(biosimrc.get("biosim.learn.debug", ""));
choices = new String[] { "Successors", "Predecessors", "Both" };
final JComboBox succpred = new JComboBox(choices);
succpred.setSelectedItem(biosimrc.get("biosim.learn.succpred", ""));
choices = new String[] { "True", "False" };
final JComboBox findbaseprob = new JComboBox(choices);
findbaseprob.setSelectedItem(biosimrc.get("biosim.learn.findbaseprob", ""));
JPanel learnLabels = new JPanel(new GridLayout(13, 1));
learnLabels.add(new JLabel("Minimum Number Of Initial Vectors (Tn):"));
learnLabels.add(new JLabel("Maximum Influence Vector Size (Tj):"));
learnLabels.add(new JLabel("Score For Empty Influence Vector (Ti):"));
learnLabels.add(new JLabel("Number Of Bins:"));
learnLabels.add(new JLabel("Divide Bins:"));
learnLabels.add(new JLabel("Generate Levels:"));
learnLabels.add(new JLabel("Ratio For Activation (Ta):"));
learnLabels.add(new JLabel("Ratio For Repression (Tr):"));
learnLabels.add(new JLabel("Merge Influence Vectors Delta (Tm):"));
learnLabels.add(new JLabel("Relax Thresholds Delta (Tt):"));
learnLabels.add(new JLabel("Debug Level:"));
learnLabels.add(new JLabel("Successors Or Predecessors:"));
learnLabels.add(new JLabel("Basic FindBaseProb:"));
JPanel learnFields = new JPanel(new GridLayout(13, 1));
learnFields.add(tn);
learnFields.add(tj);
learnFields.add(ti);
learnFields.add(bins);
learnFields.add(equaldata);
learnFields.add(autolevels);
learnFields.add(ta);
learnFields.add(tr);
learnFields.add(tm);
learnFields.add(tt);
learnFields.add(debug);
learnFields.add(succpred);
learnFields.add(findbaseprob);
JPanel learnPrefs = new JPanel(new GridLayout(1, 2));
learnPrefs.add(learnLabels);
learnPrefs.add(learnFields);
JPanel generalPrefs = new JPanel(new BorderLayout());
generalPrefs.add(dialog, "North");
JPanel sbmlPrefsBordered = new JPanel(new BorderLayout());
JPanel sbmlPrefs = new JPanel();
sbmlPrefsBordered.add(Undeclared, "North");
sbmlPrefsBordered.add(Units, "Center");
sbmlPrefs.add(sbmlPrefsBordered);
((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT);
JTabbedPane prefTabs = new JTabbedPane();
prefTabs.addTab("General Preferences", dialog);
prefTabs.addTab("SBML Preferences", sbmlPrefs);
prefTabs.addTab("GCM Preferences", gcmPrefs);
prefTabs.addTab("Analysis Preferences", analysisPrefs);
prefTabs.addTab("Learn Preferences", learnPrefs);
Object[] options = { "Save", "Cancel" };
int value = JOptionPane
.showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (dialog.isSelected()) {
biosimrc.put("biosim.general.file_browser", "FileDialog");
}
else {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
if (Undeclared.isSelected()) {
checkUndeclared = true;
biosimrc.put("biosim.check.undeclared", "true");
}
else {
checkUndeclared = false;
biosimrc.put("biosim.check.undeclared", "false");
}
if (Units.isSelected()) {
checkUnits = true;
biosimrc.put("biosim.check.units", "true");
}
else {
checkUnits = false;
biosimrc.put("biosim.check.units", "false");
}
try {
Double.parseDouble(KREP_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KACT_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KBIO_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim());
biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KASSOCIATION_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KBASAL_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(OCR_VALUE.getText().trim());
biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KDECAY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(RNAP_VALUE.getText().trim());
biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(RNAP_BINDING_VALUE.getText().trim());
biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(COOPERATIVITY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(ACTIVED_VALUE.getText().trim());
biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(MAX_DIMER_VALUE.getText().trim());
biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(INITIAL_VALUE.getText().trim());
biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
biosimrc.put("biosim.sim.command", simCommand.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(limit.getText().trim());
biosimrc.put("biosim.sim.limit", limit.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(interval.getText().trim());
biosimrc.put("biosim.sim.interval", interval.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(minStep.getText().trim());
biosimrc.put("biosim.min.sim.step", minStep.getText().trim());
}
catch (Exception e1) {
}
try {
if (step.getText().trim().equals("inf")) {
biosimrc.put("biosim.sim.step", step.getText().trim());
}
else {
Double.parseDouble(step.getText().trim());
biosimrc.put("biosim.sim.step", step.getText().trim());
}
}
catch (Exception e1) {
}
try {
Double.parseDouble(error.getText().trim());
biosimrc.put("biosim.sim.error", error.getText().trim());
}
catch (Exception e1) {
}
try {
Long.parseLong(seed.getText().trim());
biosimrc.put("biosim.sim.seed", seed.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(runs.getText().trim());
biosimrc.put("biosim.sim.runs", runs.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(rapid1.getText().trim());
biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(rapid2.getText().trim());
biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(qssa.getText().trim());
biosimrc.put("biosim.sim.qssa", qssa.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(concentration.getText().trim());
biosimrc.put("biosim.sim.concentration", concentration.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.sim.useInterval", (String) useInterval.getSelectedItem());
biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem());
biosimrc.put("biosim.sim.type", (String) type.getSelectedItem());
biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem());
try {
Integer.parseInt(tn.getText().trim());
biosimrc.put("biosim.learn.tn", tn.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(tj.getText().trim());
biosimrc.put("biosim.learn.tj", tj.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(ti.getText().trim());
biosimrc.put("biosim.learn.ti", ti.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.learn.bins", (String) bins.getSelectedItem());
biosimrc.put("biosim.learn.equaldata", (String) equaldata.getSelectedItem());
biosimrc.put("biosim.learn.autolevels", (String) autolevels.getSelectedItem());
try {
Double.parseDouble(ta.getText().trim());
biosimrc.put("biosim.learn.ta", ta.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tr.getText().trim());
biosimrc.put("biosim.learn.tr", tr.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tm.getText().trim());
biosimrc.put("biosim.learn.tm", tm.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tt.getText().trim());
biosimrc.put("biosim.learn.tt", tt.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.learn.debug", (String) debug.getSelectedItem());
biosimrc.put("biosim.learn.succpred", (String) succpred.getSelectedItem());
biosimrc.put("biosim.learn.findbaseprob", (String) findbaseprob.getSelectedItem());
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).contains(".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters();
((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters();
}
}
}
else {
}
}
else {
Preferences biosimrc = Preferences.userRoot();
JPanel prefPanel = new JPanel(new GridLayout(0, 2));
JLabel verCmdLabel = new JLabel("Verification command:");
JTextField verCmd = new JTextField(biosimrc.get("biosim.verification.command", ""));
viewerLabel = new JLabel("External Editor for non-LPN files:");
viewerField = new JTextField(biosimrc.get("biosim.general.viewer", ""));
prefPanel.add(verCmdLabel);
prefPanel.add(verCmd);
prefPanel.add(viewerLabel);
prefPanel.add(viewerField);
// Preferences biosimrc = Preferences.userRoot();
// JPanel vhdlPrefs = new JPanel();
// JPanel lhpnPrefs = new JPanel();
// JTabbedPane prefTabsNoLema = new JTabbedPane();
// prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs);
// prefTabsNoLema.addTab("LPN Preferences", lhpnPrefs);
JCheckBox dialog = new JCheckBox("Use File Dialog");
if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) {
dialog.setSelected(true);
}
else {
dialog.setSelected(false);
}
prefPanel.add(dialog);
Object[] options = { "Save", "Cancel" };
int value = JOptionPane
.showOptionDialog(frame, prefPanel, "Preferences", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
viewer = viewerField.getText();
biosimrc.put("biosim.general.viewer", viewer);
biosimrc.put("biosim.verification.command", verCmd.getText());
if (dialog.isSelected()) {
biosimrc.put("biosim.general.file_browser", "FileDialog");
}
else {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
}
}
}
public void about() {
final JFrame f = new JFrame("About");
// frame.setIconImage(new ImageIcon(ENVVAR +
// File.separator
// + "gui"
// + File.separator + "icons" + File.separator +
// "iBioSim.png").getImage());
JLabel name;
JLabel version;
final String developers;
if (lema) {
name = new JLabel("LEMA", JLabel.CENTER);
version = new JLabel("Version 1.3.1", JLabel.CENTER);
developers = "Satish Batchu\nKevin Jones\nScott Little\nCurtis Madsen\nChris Myers\nNicholas Seegmiller\n"
+ "Robert Thacker\nDavid Walter";
}
else if (atacs) {
name = new JLabel("ATACS", JLabel.CENTER);
version = new JLabel("Version 6.3.1", JLabel.CENTER);
developers = "Wendy Belluomini\nJeff Cuthbert\nHans Jacobson\nKevin Jones\nSung-Tae Jung\n"
+ "Christopher Krieger\nScott Little\nCurtis Madsen\nEric Mercer\nChris Myers\n"
+ "Curt Nelson\nEric Peskin\nNicholas Seegmiller\nDavid Walter\nHao Zheng";
}
else {
name = new JLabel("iBioSim", JLabel.CENTER);
version = new JLabel("Version 1.3.1", JLabel.CENTER);
developers = "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n"
+ "Curtis Madsen\nChris Myers\nNam Nguyen";
}
Font font = name.getFont();
font = font.deriveFont(Font.BOLD, 36.0f);
name.setFont(font);
JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER);
JButton credits = new JButton("Credits");
credits.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = { "Close" };
JOptionPane.showOptionDialog(f, developers, "Credits", JOptionPane.YES_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
});
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel buttons = new JPanel();
buttons.add(credits);
buttons.add(close);
JPanel aboutPanel = new JPanel(new BorderLayout());
JPanel uOfUPanel = new JPanel(new BorderLayout());
uOfUPanel.add(name, "North");
uOfUPanel.add(version, "Center");
uOfUPanel.add(uOfU, "South");
if (lema) {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator
+ "gui" + separator + "icons" + separator + "LEMA.png")), "North");
}
else if (atacs) {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator
+ "gui" + separator + "icons" + separator + "ATACS.png")), "North");
}
else {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + separator
+ "gui" + separator + "icons" + separator + "iBioSim.png")), "North");
}
// aboutPanel.add(bioSim, "North");
aboutPanel.add(uOfUPanel, "Center");
aboutPanel.add(buttons, "South");
f.setContentPane(aboutPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
public void exit() {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
Preferences biosimrc = Preferences.userRoot();
for (int i = 0; i < numberRecentProj; i++) {
if (atacs) {
biosimrc.put("atacs.recent.project." + i, recentProjects[i].getText());
biosimrc.put("atacs.recent.project.path." + i, recentProjectPaths[i]);
}
else if (lema) {
biosimrc.put("lema.recent.project." + i, recentProjects[i].getText());
biosimrc.put("lema.recent.project.path." + i, recentProjectPaths[i]);
}
else {
biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText());
biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]);
}
}
System.exit(1);
}
/**
* This method performs different functions depending on what menu items are
* selected.
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == viewCircuit) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewGcm();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLhpn();
}
}
else if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).viewLhpn();
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Verification) {
((Verification) array[0]).viewCircuit();
}
else if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewCircuit();
}
}
}
else if (e.getSource() == viewLog) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
if (new File(root + separator + "atacs.log").exists()) {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(frame(), "No log exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame(), "Unable to view log.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof Verification) {
((Verification) comp).viewLog();
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewLog();
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewLog();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLog();
}
}
}
else if (e.getSource() == viewCoverage) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
JOptionPane.showMessageDialog(frame(), "No Coverage report exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewCoverage();
}
}
}
else if (e.getSource() == viewVHDL) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
String vhdFile = tree.getFile();
if (new File(vhdFile).exists()) {
File vhdlAmsFile = new File(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(this.frame(), scrolls, "VHDL-AMS Model",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"VHDL-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(this.frame(), "Unable to view VHDL-AMS model.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewVHDL();
}
}
}
else if (e.getSource() == viewVerilog) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
String vamsFileName = tree.getFile();
if (new File(vamsFileName).exists()) {
File vamsFile = new File(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(this.frame(), scrolls, "Verilog-AMS Model",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"Verilog-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(this.frame(), "Unable to view Verilog-AMS model.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewVerilog();
}
}
}
else if (e.getSource() == viewLHPN) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "File cannot be read", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (InterruptedException e2) {
e2.printStackTrace();
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLhpn();
}
}
}
// else if (e.getSource() == saveParam) {
// Component comp = tab.getSelectedComponent();
// if (comp instanceof JTabbedPane) {
// Component component = ((JTabbedPane) comp).getSelectedComponent();
// if (component instanceof Learn) {
// ((Learn) component).save();
// else if (component instanceof LearnLHPN) {
// ((LearnLHPN) component).save();
// else {
// ((Reb2Sac) ((JTabbedPane) comp).getComponentAt(0)).save();
else if (e.getSource() == saveModel) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
for (Component component : ((JTabbedPane) comp).getComponents()) {
if (component instanceof Learn) {
((Learn) component).saveGcm();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).saveLhpn();
}
}
}
}
else if (e.getSource() == saveSbml) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("SBML");
}
else if (e.getSource() == saveTemp) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("template");
}
else if (e.getSource() == saveAsGcm) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("GCM");
}
// else if (e.getSource() == saveGcmAsLhpn) {
// Component comp = tab.getSelectedComponent();
// ((GCM2SBMLEditor) comp).save("LHPN");
else if (e.getSource() == saveAsLhpn) {
Component comp = tab.getSelectedComponent();
((LHPNEditor) comp).save();
}
else if (e.getSource() == saveAsGraph) {
Component comp = tab.getSelectedComponent();
((Graph) comp).save();
}
else if (e.getSource() == saveAsSbml) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("Save as SBML");
}
else if (e.getSource() == saveAsTemplate) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("Save as SBML template");
}
else if (e.getSource() == close && tab.getSelectedComponent() != null) {
Component comp = tab.getSelectedComponent();
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(),
point.x, point.y, 0, false), tab.getSelectedIndex());
}
else if (e.getSource() == closeAll) {
while (tab.getSelectedComponent() != null) {
int index = tab.getSelectedIndex();
Component comp = tab.getComponent(index);
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(),
e.getModifiers(), point.x, point.y, 0, false), index);
}
}
else if (e.getSource() == viewRules) {
Component comp = tab.getSelectedComponent();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).viewRules();
}
else if (e.getSource() == viewTrace) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Verification) {
((Verification) comp).viewTrace();
}
else if (comp instanceof Synthesis) {
((Synthesis) comp).viewTrace();
}
}
else if (e.getSource() == exportCsv) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(5);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(5);
}
}
else if (e.getSource() == exportDat) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(6);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export();
}
}
else if (e.getSource() == exportEps) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(3);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(3);
}
}
else if (e.getSource() == exportJpg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(0);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(0);
}
}
else if (e.getSource() == exportPdf) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(2);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(2);
}
}
else if (e.getSource() == exportPng) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(1);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(1);
}
}
else if (e.getSource() == exportSvg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(4);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(4);
}
}
else if (e.getSource() == exportTsd) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(7);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(7);
}
}
else if (e.getSource() == about) {
about();
}
else if (e.getSource() == manual) {
try {
String directory = "";
String theFile = "";
if (!async) {
theFile = "iBioSim.html";
}
else if (atacs) {
theFile = "ATACS.html";
}
else {
theFile = "LEMA.html";
}
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
directory = ENVVAR + "/docs/";
command = "open ";
}
else {
directory = ENVVAR + "\\docs\\";
command = "cmd /c start ";
}
File work = new File(directory);
log.addText("Executing:\n" + command + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec(command + theFile, null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the exit menu item is selected
else if (e.getSource() == exit) {
exit();
}
// if the open popup menu is selected on a sim directory
else if (e.getActionCommand().equals("openSim")) {
openSim();
// Translator t1 = new Translator();
// t1.BuildTemplate(tree.getFile());
// t1.outputSBML();
}
else if (e.getActionCommand().equals("openLearn")) {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
else if (e.getActionCommand().equals("openSynth")) {
openSynth();
}
else if (e.getActionCommand().equals("openVerification")) {
openVerify();
}
else if (e.getActionCommand().equals("convertToSBML")) {
Translator t1 = new Translator();
t1.BuildTemplate(tree.getFile());
t1.outputSBML();
refreshTree();
}
else if (e.getActionCommand().equals("createAnalysis")) {
// TODO
// new Translator().BuildTemplate(tree.getFile());
// refreshTree();
try {
simulate(2);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"You must select a valid lpn file for simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the create simulation popup menu is selected on a dot file
else if (e.getActionCommand().equals("createSim")) {
try {
simulate(1);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"You must select a valid gcm file for simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the simulate popup menu is selected on an sbml file
else if (e.getActionCommand().equals("simulate")) {
try {
simulate(0);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame,
"You must select a valid sbml file for simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the synthesis popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createSynthesis")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:",
"Synthesis View ID", JOptionPane.PLAIN_MESSAGE);
if (synthName != null && !synthName.trim().equals("")) {
synthName = synthName.trim();
try {
if (overwrite(root + separator + synthName, synthName)) {
new File(root + separator + synthName).mkdir();
// new FileWriter(new File(root + separator +
// synthName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + synthName.trim() + separator
+ synthName.trim() + ".syn"));
out
.write(("synthesis.file=" + circuitFileNoPath + "\n")
.getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to save parameter file!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
}
try {
FileInputStream in = new FileInputStream(new File(root + separator
+ circuitFileNoPath));
FileOutputStream out = new FileOutputStream(new File(root
+ separator + synthName.trim() + separator
+ circuitFileNoPath));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to copy circuit file!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
}
refreshTree();
String work = root + separator + synthName;
String circuitFile = root + separator + synthName.trim() + separator
+ circuitFileNoPath;
JPanel synthPane = new JPanel();
Synthesis synth = new Synthesis(work, circuitFile, log, this);
// synth.addMouseListener(this);
synthPane.add(synth);
/*
* JLabel noData = new JLabel("No data available");
* Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn",
* noData);
* lrnTab.getComponentAt(lrnTab.getComponents
* ().length - 1).setName("Learn"); JLabel noData1 =
* new JLabel("No data available"); font =
* noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt
* (lrnTab.getComponents().length -
* 1).setName("TSD Graph");
*/
addTab(synthName, synthPane, "Synthesis");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to create Synthesis View directory.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the verify popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createVerify")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:",
"Verification View ID", JOptionPane.PLAIN_MESSAGE);
if (verName != null && !verName.trim().equals("")) {
verName = verName.trim();
// try {
if (overwrite(root + separator + verName, verName)) {
new File(root + separator + verName).mkdir();
// new FileWriter(new File(root + separator +
// synthName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ verName.trim() + separator + verName.trim() + ".ver"));
out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
/*
* try { FileInputStream in = new FileInputStream(new
* File(root + separator + circuitFileNoPath));
* FileOutputStream out = new FileOutputStream(new
* File(root + separator + verName.trim() + separator +
* circuitFileNoPath)); int read = in.read(); while
* (read != -1) { out.write(read); read = in.read(); }
* in.close(); out.close(); } catch (Exception e1) {
* JOptionPane.showMessageDialog(frame, "Unable to copy
* circuit file!", "Error Saving File",
* JOptionPane.ERROR_MESSAGE); }
*/
refreshTree();
// String work = root + separator + verName;
// log.addText(circuitFile);
// JTabbedPane verTab = new JTabbedPane();
// JPanel verPane = new JPanel();
Verification verify = new Verification(root + separator + verName, verName,
circuitFileNoPath, log, this, lema, atacs);
// verify.addMouseListener(this);
verify.save();
// verPane.add(verify);
// JPanel abstPane = new JPanel();
// AbstPane abst = new AbstPane(root + separator +
// verName, verify,
// circuitFileNoPath, log, this, lema, atacs);
// abstPane.add(abst);
// verTab.addTab("verify", verPane);
// verTab.addTab("abstract", abstPane);
/*
* JLabel noData = new JLabel("No data available"); Font
* font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font); noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn",
* noData); lrnTab.getComponentAt(lrnTab.getComponents
* ().length - 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font =
* noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("TSD Graph",
* noData1); lrnTab.getComponentAt
* (lrnTab.getComponents().length -
* 1).setName("TSD Graph");
*/
addTab(verName, verify, "Verification");
}
// catch (Exception e1) {
// JOptionPane.showMessageDialog(frame,
// "Unable to create Verification View directory.", "Error",
// JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the delete popup menu is selected
else if (e.getActionCommand().contains("delete") || e.getSource() == delete) {
if (!tree.getFile().equals(root)) {
if (new File(tree.getFile()).isDirectory()) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.remove(i);
}
}
File dir = new File(tree.getFile());
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
refreshTree();
}
else {
String[] views = canDelete(tree.getFile().split(separator)[tree.getFile()
.split(separator).length - 1]);
if (views.length == 0) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.remove(i);
}
}
System.gc();
new File(tree.getFile()).delete();
refreshTree();
}
else {
String view = "";
for (int i = 0; i < views.length; i++) {
if (i == views.length - 1) {
view += views[i];
}
else {
view += views[i] + "\n";
}
}
String message = "Unable to delete the selected file."
+ "\nIt is linked to the following views:\n" + view
+ "\nDelete these views first.";
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(frame, scroll, "Unable To Delete File",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("createSBML")) {
try {
String theFile = "";
String filename = tree.getFile();
GCMFile gcm = new GCMFile(root);
gcm.load(filename);
GCMParser parser = new GCMParser(filename);
GeneticNetwork network = null;
try {
network = parser.buildNetwork();
}
catch (IllegalStateException e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
network.loadProperties(gcm);
if (filename.lastIndexOf('/') >= 0) {
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
if (new File(root + separator + theFile.replace(".gcm", "") + ".xml").exists()) {
String[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "")
+ ".xml already exists. Overwrite file?", "Save file",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
GeneticNetwork.setRoot(root + separator);
network.mergeSBML(root + separator + theFile.replace(".gcm", "") + ".xml");
log.addText("Saving GCM file as SBML file:\n" + root + separator
+ theFile.replace(".gcm", "") + ".xml\n");
refreshTree();
updateOpenSBML(theFile.replace(".gcm", "") + ".xml");
}
else {
// Do nothing
}
}
else {
GeneticNetwork.setRoot(root + separator);
network.mergeSBML(root + separator + theFile.replace(".gcm", "") + ".xml");
log.addText("Saving GCM file as SBML file:\n" + root + separator
+ theFile.replace(".gcm", "") + ".xml\n");
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("createLHPN")) {
try {
String theFile = "";
String filename = tree.getFile();
GCMFile gcm = new GCMFile(root);
gcm.load(filename);
if (filename.lastIndexOf('/') >= 0) {
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
if (new File(root + separator + theFile.replace(".gcm", "") + ".lpn").exists()) {
String[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "")
+ ".lpn already exists. Overwrite file?", "Save file",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
gcm.createLogicalModel(root + separator + theFile.replace(".gcm", "")
+ ".lpn", log, this, theFile.replace(".gcm", "") + ".lpn");
}
else {
// Do nothing
}
}
else {
gcm.createLogicalModel(root + separator + theFile.replace(".gcm", "") + ".lpn",
log, this, theFile.replace(".gcm", "") + ".lpn");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create LPN file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("dotEditor")) {
try {
String directory = "";
String theFile = "";
String filename = tree.getFile();
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
File work = new File(directory);
GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this,
log, false, null, null, null);
// gcm.addMouseListener(this);
addTab(theFile, gcm, "GCM Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the edit popup menu is selected on an sbml file
else if (e.getActionCommand().equals("sbmlEditor")) {
try {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new SBML_Editor(tree.getFile(), null, log, this, null, null),
"SBML Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("stateGraph")) {
try {
String directory = root + separator + tab.getTitleAt(tab.getSelectedIndex());
File work = new File(directory);
for (String f : new File(directory).list()) {
if (f.contains("_sg.dot")) {
Runtime exec = Runtime.getRuntime();
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + separator + f + "\n");
exec.exec("dotty " + f, null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + separator + f + "\n");
exec.exec("open " + f, null, work);
}
else {
log.addText("Executing:\ndotty " + directory + separator + f + "\n");
exec.exec("dotty " + f, null, work);
}
return;
}
}
JOptionPane.showMessageDialog(frame, "State graph file has not been generated.",
"Error", JOptionPane.ERROR_MESSAGE);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error viewing state graph.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the graph popup menu is selected on an sbml file
else if (e.getActionCommand().equals("graph")) {
String directory = "";
String theFile = "";
if (!treeSelected) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewGcm();
return;
}
}
else if (comp instanceof LHPNEditor) {
try {
String filename = tab.getTitleAt(tab.getSelectedIndex());
String[] findTheFile = filename.split("\\.");
theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith(
"mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
return;
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this lpn.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
}
else if (comp instanceof SBML_Editor) {
directory = root + separator;
theFile = tab.getTitleAt(tab.getSelectedIndex());
}
else if (comp instanceof GCM2SBMLEditor) {
directory = root + separator;
theFile = tab.getTitleAt(tab.getSelectedIndex());
}
}
else {
String filename = tree.getFile();
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
}
File work = new File(directory);
String out = theFile;
try {
if (out.contains(".lpn")) {
String file = theFile;
String[] findTheFile = file.split("\\.");
theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + file;
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
return;
}
if (out.length() > 4
&& out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".gcm")) {
try {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("cp " + theFile + " " + theFile + ".dot", null, work);
exec = Runtime.getRuntime();
exec.exec("open " + theFile + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
return;
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
dummy.setSelected(false);
JList empty = new JList();
run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1,
new String[0], new String[0], "tsd.printer", "amount",
(directory + theFile).split(separator), "none", frame, directory + theFile,
0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty);
log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out
+ ".dot " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot "
+ theFile, null, work);
String error = "";
String output = "";
InputStream reb = graph.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = graph.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
graph.waitFor();
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".dot\n");
exec.exec("open " + out + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
}
String remove;
if (theFile.substring(theFile.length() - 4).equals("sbml")) {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4)
+ "properties";
}
else {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4)
+ ".properties";
}
System.gc();
new File(remove).delete();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the browse popup menu is selected on an sbml file
else if (e.getActionCommand().equals("browse")) {
String directory;
String theFile;
if (!treeSelected) {
Component comp = tab.getSelectedComponent();
if (comp instanceof SBML_Editor) {
if (save(tab.getSelectedIndex(), 0) != 1) {
return;
}
theFile = tab.getTitleAt(tab.getSelectedIndex());
directory = root + separator;
}
else {
return;
}
}
else {
String filename = tree.getFile();
directory = "";
theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
try {
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
JList empty = new JList();
dummy.setSelected(false);
run.createProperties(0, "Print Interval", 1, 1, 1, 1, directory, 314159, 1,
new String[0], new String[0], "tsd.printer", "amount",
(directory + theFile).split(separator), "none", frame, directory + theFile,
0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty);
log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out
+ ".xhtml " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out
+ ".xhtml " + theFile, null, work);
String error = "";
String output = "";
InputStream reb = browse.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = browse.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
browse.waitFor();
String command = "";
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open ";
}
else {
command = "cmd /c start ";
}
log.addText("Executing:\n" + command + directory + out + ".xhtml\n");
exec.exec(command + out + ".xhtml", null, work);
}
String remove;
if (theFile.substring(theFile.length() - 4).equals("sbml")) {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4)
+ "properties";
}
else {
remove = (directory + theFile).substring(0, (directory + theFile).length() - 4)
+ ".properties";
}
System.gc();
new File(remove).delete();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the graph dot popup menu is selected
/*
* else if (e.getActionCommand().equals("graphDot")) { if
* (!treeSelected) { Component comp = tab.getSelectedComponent(); if
* (comp instanceof JTabbedPane) { Component component = ((JTabbedPane)
* comp).getSelectedComponent(); if (component instanceof Learn) {
* ((Learn) component).viewGcm(); } } } else { try { String filename =
* tree.getFile(); String directory = ""; String theFile = ""; if
* (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0,
* filename.lastIndexOf('/') + 1); theFile =
* filename.substring(filename.lastIndexOf('/') + 1); } if
* (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0,
* filename.lastIndexOf('\\') + 1); theFile =
* filename.substring(filename.lastIndexOf('\\') + 1); } File work = new
* File(directory); if
* (System.getProperty("os.name").contentEquals("Linux")) {
* log.addText("Executing:\ndotty " + directory + theFile + "\n");
* Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile,
* null, work); } else if
* (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
* log.addText("Executing:\nopen " + directory + theFile + "\n");
* Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " "
* + theFile + ".dot", null, work); exec = Runtime.getRuntime();
* exec.exec("open " + theFile + ".dot", null, work); } else {
* log.addText("Executing:\ndotty " + directory + theFile + "\n");
* Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile,
* null, work); } } catch (Exception e1) {
* JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.",
* "Error", JOptionPane.ERROR_MESSAGE); } } }
*/
// if the save button is pressed on the Tool Bar
else if (e.getActionCommand().equals("save")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).save();
}
else if (comp instanceof GCM2SBMLEditor) {
((GCM2SBMLEditor) comp).save("Save GCM");
}
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(false, "", true);
}
else if (comp instanceof Graph) {
((Graph) comp).save();
}
else if (comp instanceof Verification) {
((Verification) comp).save();
}
else if (comp instanceof JTabbedPane) {
for (Component component : ((JTabbedPane) comp).getComponents()) {
int index = ((JTabbedPane) comp).getSelectedIndex();
if (component instanceof Graph) {
((Graph) component).save();
}
else if (component instanceof Learn) {
((Learn) component).save();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
}
else if (component instanceof DataManager) {
((DataManager) component).saveChanges(((JTabbedPane) comp)
.getTitleAt(index));
}
else if (component instanceof SBML_Editor) {
((SBML_Editor) component).save(false, "", true);
}
else if (component instanceof GCM2SBMLEditor) {
((GCM2SBMLEditor) component).saveParams(false, "");
}
else if (component instanceof Reb2Sac) {
((Reb2Sac) component).save();
}
}
}
if (comp instanceof JPanel) {
if (comp.getName().equals("Synthesis")) {
// ((Synthesis) tab.getSelectedComponent()).save();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).save();
}
}
else if (comp instanceof JScrollPane) {
String fileName = tab.getTitleAt(tab.getSelectedIndex());
try {
File output = new File(root + separator + fileName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + fileName);
this.updateAsyncViews(fileName);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + fileName, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the save as button is pressed on the Tool Bar
else if (e.getActionCommand().equals("saveas")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
String newName = JOptionPane.showInputDialog(frame(), "Enter LPN name:",
"LPN Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".lpn")) {
newName = newName + ".lpn";
}
((LHPNEditor) comp).saveAs(newName);
tab.setTitleAt(tab.getSelectedIndex(), newName);
}
else if (comp instanceof GCM2SBMLEditor) {
String newName = JOptionPane.showInputDialog(frame(), "Enter GCM name:",
"GCM Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (newName.contains(".gcm")) {
newName = newName.replace(".gcm", "");
}
((GCM2SBMLEditor) comp).saveAs(newName);
}
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).saveAs();
}
else if (comp instanceof Graph) {
((Graph) comp).saveAs();
}
else if (comp instanceof Verification) {
((Verification) comp).saveAs();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).saveAs();
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Synthesis")) {
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).saveAs();
}
}
else if (comp instanceof JScrollPane) {
String fileName = tab.getTitleAt(tab.getSelectedIndex());
String newName = "";
if (fileName.endsWith(".vhd")) {
newName = JOptionPane.showInputDialog(frame(), "Enter VHDL name:", "VHDL Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".vhd")) {
newName = newName + ".vhd";
}
}
else if (fileName.endsWith(".s")) {
newName = JOptionPane.showInputDialog(frame(), "Enter Assembly File Name:",
"Assembly File Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".s")) {
newName = newName + ".s";
}
}
else if (fileName.endsWith(".inst")) {
newName = JOptionPane.showInputDialog(frame(), "Enter Instruction File Name:",
"Instruction File Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".inst")) {
newName = newName + ".inst";
}
}
else if (fileName.endsWith(".g")) {
newName = JOptionPane.showInputDialog(frame(), "Enter Petri net name:",
"Petri net Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".g")) {
newName = newName + ".g";
}
}
else if (fileName.endsWith(".csp")) {
newName = JOptionPane.showInputDialog(frame(), "Enter CSP name:", "CSP Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".csp")) {
newName = newName + ".csp";
}
}
else if (fileName.endsWith(".hse")) {
newName = JOptionPane.showInputDialog(frame(), "Enter HSE name:", "HSE Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".hse")) {
newName = newName + ".hse";
}
}
else if (fileName.endsWith(".unc")) {
newName = JOptionPane.showInputDialog(frame(), "Enter UNC name:", "UNC Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".unc")) {
newName = newName + ".unc";
}
}
else if (fileName.endsWith(".rsg")) {
newName = JOptionPane.showInputDialog(frame(), "Enter RSG name:", "RSG Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".rsg")) {
newName = newName + ".rsg";
}
}
try {
File output = new File(root + separator + newName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + newName);
File oldFile = new File(root + separator + fileName);
oldFile.delete();
tab.setTitleAt(tab.getSelectedIndex(), newName);
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + newName, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the run button is selected on the tool bar
else if (e.getActionCommand().equals("run")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
int index = -1;
for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) {
if (((JTabbedPane) comp).getComponent(i) instanceof Reb2Sac) {
index = i;
break;
}
}
if (component instanceof Graph) {
if (index != -1) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton()
.doClick();
}
else {
((Graph) component).save();
((Graph) component).run();
}
}
else if (component instanceof Learn) {
((Learn) component).save();
new Thread((Learn) component).start();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
((LearnLHPN) component).learn();
}
else if (component instanceof SBML_Editor) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof Reb2Sac) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof JPanel) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof JScrollPane) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
}
else if (comp instanceof Verification) {
((Verification) comp).save();
new Thread((Verification) comp).start();
}
else if (comp instanceof Synthesis) {
((Synthesis) comp).save();
new Thread((Synthesis) comp).start();
}
}
else if (e.getActionCommand().equals("refresh")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).refresh();
}
}
else if (comp instanceof Graph) {
((Graph) comp).refresh();
}
}
else if (e.getActionCommand().equals("check")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(true, "", true);
((SBML_Editor) comp).check();
}
}
else if (e.getActionCommand().equals("export")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).export();
}
}
}
// if the new menu item is selected
else if (e.getSource() == newProj) {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.project_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.project_dir", ""));
}
String filename = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY,
"New", -1);
if (!filename.trim().equals("")) {
filename = filename.trim();
biosimrc.put("biosim.general.project_dir", filename);
File f = new File(filename);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(filename);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return;
}
}
new File(filename).mkdir();
try {
if (lema) {
new FileWriter(new File(filename + separator + "LEMA.prj")).close();
}
else if (atacs) {
new FileWriter(new File(filename + separator + "ATACS.prj")).close();
}
else {
new FileWriter(new File(filename + separator + "BioSim.prj")).close();
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
root = filename;
refresh();
tab.removeAll();
addRecentProject(filename);
importDot.setEnabled(true);
importSbml.setEnabled(true);
importBioModel.setEnabled(true);
importVhdl.setEnabled(true);
importS.setEnabled(true);
importInst.setEnabled(true);
importLpn.setEnabled(true);
importG.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newCircuit.setEnabled(true);
newModel.setEnabled(true);
newVhdl.setEnabled(true);
newS.setEnabled(true);
newInst.setEnabled(true);
newLhpn.setEnabled(true);
newG.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
}
// if the open project menu item is selected
else if (e.getSource() == pref) {
preferences();
}
else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0])
|| (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2])
|| (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
Preferences biosimrc = Preferences.userRoot();
String projDir = "";
if (e.getSource() == openProj) {
File file;
if (biosimrc.get("biosim.general.project_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.project_dir", ""));
}
projDir = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY, "Open",
-1);
if (projDir.endsWith(".prj")) {
biosimrc.put("biosim.general.project_dir", projDir);
String[] tempArray = projDir.split(separator);
projDir = "";
for (int i = 0; i < tempArray.length - 1; i++) {
projDir = projDir + tempArray[i] + separator;
}
}
}
else if (e.getSource() == recentProjects[0]) {
projDir = recentProjectPaths[0];
}
else if (e.getSource() == recentProjects[1]) {
projDir = recentProjectPaths[1];
}
else if (e.getSource() == recentProjects[2]) {
projDir = recentProjectPaths[2];
}
else if (e.getSource() == recentProjects[3]) {
projDir = recentProjectPaths[3];
}
else if (e.getSource() == recentProjects[4]) {
projDir = recentProjectPaths[4];
}
// log.addText(projDir);
if (!projDir.equals("")) {
biosimrc.put("biosim.general.project_dir", projDir);
if (new File(projDir).isDirectory()) {
boolean isProject = false;
for (String temp : new File(projDir).list()) {
if (temp.equals(".prj")) {
isProject = true;
}
if (lema && temp.equals("LEMA.prj")) {
isProject = true;
}
else if (atacs && temp.equals("ATACS.prj")) {
isProject = true;
}
else if (temp.equals("BioSim.prj")) {
isProject = true;
}
}
if (isProject) {
root = projDir;
refresh();
tab.removeAll();
addRecentProject(projDir);
importDot.setEnabled(true);
importSbml.setEnabled(true);
importBioModel.setEnabled(true);
importVhdl.setEnabled(true);
importS.setEnabled(true);
importInst.setEnabled(true);
importLpn.setEnabled(true);
importG.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newCircuit.setEnabled(true);
newModel.setEnabled(true);
newVhdl.setEnabled(true);
newS.setEnabled(true);
newInst.setEnabled(true);
newLhpn.setEnabled(true);
newG.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new circuit model menu item is selected
else if (e.getSource() == newCircuit) {
if (root != null) {
try {
String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (simName.length() > 3) {
if (!simName.substring(simName.length() - 4).equals(".gcm")) {
simName += ".gcm";
}
}
else {
simName += ".gcm";
}
String modelID = "";
if (simName.length() > 3) {
if (simName.substring(simName.length() - 4).equals(".gcm")) {
modelID = simName.substring(0, simName.length() - 4);
}
else {
modelID = simName.substring(0, simName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + simName, simName)) {
File f = new File(root + separator + simName);
f.createNewFile();
new GCMFile(root).save(f.getAbsolutePath());
int i = getTab(f.getName());
if (i != -1) {
tab.remove(i);
}
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, f
.getName(), this, log, false, null, null, null);
// gcm.addMouseListener(this);
addTab(f.getName(), gcm, "GCM Editor");
refreshTree();
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new SBML model menu item is selected
else if (e.getSource() == newModel) {
if (root != null) {
try {
String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (simName.length() > 4) {
if (!simName.substring(simName.length() - 5).equals(".sbml")
&& !simName.substring(simName.length() - 4).equals(".xml")) {
simName += ".xml";
}
}
else {
simName += ".xml";
}
String modelID = "";
if (simName.length() > 4) {
if (simName.substring(simName.length() - 5).equals(".sbml")) {
modelID = simName.substring(0, simName.length() - 5);
}
else {
modelID = simName.substring(0, simName.length() - 4);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + simName, simName)) {
String f = new String(root + separator + simName);
SBMLDocument document = new SBMLDocument();
document.createModel();
// document.setLevel(2);
document.setLevelAndVersion(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
Compartment c = document.getModel().createCompartment();
c.setId("default");
c.setSize(1.0);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + simName);
SBML_Editor sbml = new SBML_Editor(f, null, log, this, null, null);
// sbml.addMouseListener(this);
addTab(f.split(separator)[f.split(separator).length - 1], sbml,
"SBML Editor");
refreshTree();
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new vhdl menu item is selected
else if (e.getSource() == newVhdl) {
if (root != null) {
try {
String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (vhdlName != null && !vhdlName.trim().equals("")) {
vhdlName = vhdlName.trim();
if (vhdlName.length() > 3) {
if (!vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) {
vhdlName += ".vhd";
}
}
else {
vhdlName += ".vhd";
}
String modelID = "";
if (vhdlName.length() > 3) {
if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) {
modelID = vhdlName.substring(0, vhdlName.length() - 4);
}
else {
modelID = vhdlName.substring(0, vhdlName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + vhdlName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + vhdlName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(vhdlName, scroll, "VHDL Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new assembly menu item is selected
else if (e.getSource() == newS) {
if (root != null) {
try {
String SName = JOptionPane.showInputDialog(frame, "Enter Assembly File Name:",
"Assembly File Name", JOptionPane.PLAIN_MESSAGE);
if (SName != null && !SName.trim().equals("")) {
SName = SName.trim();
if (SName.length() > 1) {
if (!SName.substring(SName.length() - 2).equals(".s")) {
SName += ".s";
}
}
else {
SName += ".s";
}
String modelID = "";
if (SName.length() > 1) {
if (SName.substring(SName.length() - 2).equals(".s")) {
modelID = SName.substring(0, SName.length() - 2);
}
else {
modelID = SName.substring(0, SName.length() - 1);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A assembly file name can only contain letters, numbers, and underscores.",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + SName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + SName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(SName, scroll, "Assembly File Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new assembly file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new instruction file menu item is selected
else if (e.getSource() == newInst) {
if (root != null) {
try {
String InstName = JOptionPane.showInputDialog(frame,
"Enter Instruction File Name:", "Instruction File Name",
JOptionPane.PLAIN_MESSAGE);
if (InstName != null && !InstName.trim().equals("")) {
InstName = InstName.trim();
if (InstName.length() > 4) {
if (!InstName.substring(InstName.length() - 5).equals(".inst")) {
InstName += ".inst";
}
}
else {
InstName += ".inst";
}
String modelID = "";
if (InstName.length() > 4) {
if (InstName.substring(InstName.length() - 5).equals(".inst")) {
modelID = InstName.substring(0, InstName.length() - 5);
}
else {
modelID = InstName.substring(0, InstName.length() - 4);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A instruction file name can only contain letters, numbers, and underscores.",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + InstName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + InstName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(InstName, scroll, "Instruction File Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new instruction file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new petri net menu item is selected
else if (e.getSource() == newG) {
if (root != null) {
try {
String vhdlName = JOptionPane.showInputDialog(frame,
"Enter Petri Net Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (vhdlName != null && !vhdlName.trim().equals("")) {
vhdlName = vhdlName.trim();
if (vhdlName.length() > 1) {
if (!vhdlName.substring(vhdlName.length() - 2).equals(".g")) {
vhdlName += ".g";
}
}
else {
vhdlName += ".g";
}
String modelID = "";
if (vhdlName.length() > 1) {
if (vhdlName.substring(vhdlName.length() - 2).equals(".g")) {
modelID = vhdlName.substring(0, vhdlName.length() - 2);
}
else {
modelID = vhdlName.substring(0, vhdlName.length() - 1);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + vhdlName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + vhdlName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(vhdlName, scroll, "Petri Net Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new lhpn menu item is selected
else if (e.getSource() == newLhpn) {
if (root != null) {
try {
String lhpnName = JOptionPane.showInputDialog(frame, "Enter LPN Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (lhpnName != null && !lhpnName.trim().equals("")) {
lhpnName = lhpnName.trim();
if (lhpnName.length() > 3) {
if (!lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) {
lhpnName += ".lpn";
}
}
else {
lhpnName += ".lpn";
}
String modelID = "";
if (lhpnName.length() > 3) {
if (lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) {
modelID = lhpnName.substring(0, lhpnName.length() - 4);
}
else {
modelID = lhpnName.substring(0, lhpnName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
// if (overwrite(root + separator + lhpnName,
// lhpnName)) {
// File f = new File(root + separator + lhpnName);
// f.delete();
// f.createNewFile();
// new LHPNFile(log).save(f.getAbsolutePath());
// int i = getTab(f.getName());
// if (i != -1) {
// tab.remove(i);
// addTab(f.getName(), new LHPNEditor(root +
// separator, f.getName(),
// null, this, log), "LPN Editor");
// refreshTree();
if (overwrite(root + separator + lhpnName, lhpnName)) {
File f = new File(root + separator + lhpnName);
f.createNewFile();
new LhpnFile(log).save(f.getAbsolutePath());
int i = getTab(f.getName());
if (i != -1) {
tab.remove(i);
}
LHPNEditor lhpn = new LHPNEditor(root + separator, f.getName(),
null, this, log);
// lhpn.addMouseListener(this);
addTab(f.getName(), lhpn, "LHPN Editor");
refreshTree();
}
// File f = new File(root + separator + lhpnName);
// f.createNewFile();
// String[] command = { "emacs", f.getName() };
// Runtime.getRuntime().exec(command);
// refreshTree();
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new csp menu item is selected
else if (e.getSource() == newCsp) {
if (root != null) {
try {
String cspName = JOptionPane.showInputDialog(frame, "Enter CSP Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (cspName != null && !cspName.trim().equals("")) {
cspName = cspName.trim();
if (cspName.length() > 3) {
if (!cspName.substring(cspName.length() - 4).equals(".csp")) {
cspName += ".csp";
}
}
else {
cspName += ".csp";
}
String modelID = "";
if (cspName.length() > 3) {
if (cspName.substring(cspName.length() - 4).equals(".csp")) {
modelID = cspName.substring(0, cspName.length() - 4);
}
else {
modelID = cspName.substring(0, cspName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + cspName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + cspName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(cspName, scroll, "CSP Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new hse menu item is selected
else if (e.getSource() == newHse) {
if (root != null) {
try {
String hseName = JOptionPane.showInputDialog(frame,
"Enter Handshaking Expansion Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (hseName != null && !hseName.trim().equals("")) {
hseName = hseName.trim();
if (hseName.length() > 3) {
if (!hseName.substring(hseName.length() - 4).equals(".hse")) {
hseName += ".hse";
}
}
else {
hseName += ".hse";
}
String modelID = "";
if (hseName.length() > 3) {
if (hseName.substring(hseName.length() - 4).equals(".hse")) {
modelID = hseName.substring(0, hseName.length() - 4);
}
else {
modelID = hseName.substring(0, hseName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + hseName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + hseName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(hseName, scroll, "HSE Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new unc menu item is selected
else if (e.getSource() == newUnc) {
if (root != null) {
try {
String uncName = JOptionPane.showInputDialog(frame,
"Enter Extended Burst Mode Machine ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (uncName != null && !uncName.trim().equals("")) {
uncName = uncName.trim();
if (uncName.length() > 3) {
if (!uncName.substring(uncName.length() - 4).equals(".unc")) {
uncName += ".unc";
}
}
else {
uncName += ".unc";
}
String modelID = "";
if (uncName.length() > 3) {
if (uncName.substring(uncName.length() - 4).equals(".unc")) {
modelID = uncName.substring(0, uncName.length() - 4);
}
else {
modelID = uncName.substring(0, uncName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + uncName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + uncName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(uncName, scroll, "UNC Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new rsg menu item is selected
else if (e.getSource() == newRsg) {
if (root != null) {
try {
String rsgName = JOptionPane.showInputDialog(frame,
"Enter Reduced State Graph Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (rsgName != null && !rsgName.trim().equals("")) {
rsgName = rsgName.trim();
if (rsgName.length() > 3) {
if (!rsgName.substring(rsgName.length() - 4).equals(".rsg")) {
rsgName += ".rsg";
}
}
else {
rsgName += ".rsg";
}
String modelID = "";
if (rsgName.length() > 3) {
if (rsgName.substring(rsgName.length() - 4).equals(".rsg")) {
modelID = rsgName.substring(0, rsgName.length() - 4);
}
else {
modelID = rsgName.substring(0, rsgName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + rsgName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + rsgName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(rsgName, scroll, "RSG Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new rsg menu item is selected
else if (e.getSource() == newSpice) {
if (root != null) {
try {
String spiceName = JOptionPane.showInputDialog(frame,
"Enter Spice Circuit ID:", "Circuit ID", JOptionPane.PLAIN_MESSAGE);
if (spiceName != null && !spiceName.trim().equals("")) {
spiceName = spiceName.trim();
if (spiceName.length() > 3) {
if (!spiceName.substring(spiceName.length() - 4).equals(".cir")) {
spiceName += ".cir";
}
}
else {
spiceName += ".cir";
}
String modelID = "";
if (spiceName.length() > 3) {
if (spiceName.substring(spiceName.length() - 4).equals(".cir")) {
modelID = spiceName.substring(0, spiceName.length() - 4);
}
else {
modelID = spiceName.substring(0, spiceName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + spiceName);
f.createNewFile();
refreshTree();
if (!viewer.equals("")) {
String command = viewer + " " + root + separator + spiceName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(spiceName, scroll, "Spice Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import sbml menu item is selected
else if (e.getSource() == importSbml) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null,
JFileChooser.FILES_AND_DIRECTORIES, "Import SBML", -1);
if (!filename.trim().equals("")) {
biosimrc.put("biosim.general.import_dir", filename.trim());
if (new File(filename.trim()).isDirectory()) {
JTextArea messageArea = new JTextArea();
messageArea.append("Imported SBML files contain the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n");
boolean display = false;
for (String s : new File(filename.trim()).list()) {
if (s.endsWith(".xml") || s.endsWith(".sbml")) {
try {
SBMLDocument document = readSBML(filename.trim() + separator
+ s);
checkModelCompleteness(document);
if (overwrite(root + separator + s, s)) {
long numErrors = document.checkConsistency();
if (numErrors > 0) {
display = true;
messageArea
.append("
messageArea.append(s);
messageArea
.append("\n
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
}
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + s);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import files.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
refreshTree();
if (display) {
final JFrame f = new JFrame("SBML Errors and Warnings");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
}
else {
String[] file = filename.trim().split(separator);
try {
SBMLDocument document = readSBML(filename.trim());
if (overwrite(root + separator + file[file.length - 1],
file[file.length - 1])) {
checkModelCompleteness(document);
long numErrors = document.checkConsistency();
if (numErrors > 0) {
final JFrame f = new JFrame("SBML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea
.append("Imported SBML file contains the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n");
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
SBMLWriter writer = new SBMLWriter();
writer
.writeSBML(document, root + separator
+ file[file.length - 1]);
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importBioModel) {
if (root != null) {
final BioModelsWSClient client = new BioModelsWSClient();
if (BioModelIds == null) {
try {
BioModelIds = client.getAllCuratedModelsId();
}
catch (BioModelsWSException e2) {
JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
JPanel BioModelsPanel = new JPanel(new BorderLayout());
final JList ListOfBioModels = new JList();
sort(BioModelIds);
ListOfBioModels.setListData(BioModelIds);
ListOfBioModels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLabel TextBioModels = new JLabel("List of BioModels");
JScrollPane ScrollBioModels = new JScrollPane();
ScrollBioModels.setMinimumSize(new Dimension(520, 250));
ScrollBioModels.setPreferredSize(new Dimension(552, 250));
ScrollBioModels.setViewportView(ListOfBioModels);
JPanel GetButtons = new JPanel();
JButton GetNames = new JButton("Get Names");
JButton GetDescription = new JButton("Get Description");
JButton GetReference = new JButton("Get Reference");
GetNames.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < BioModelIds.length; i++) {
try {
BioModelIds[i] += " " + client.getModelNameById(BioModelIds[i]);
}
catch (BioModelsWSException e1) {
JOptionPane.showMessageDialog(frame,
"Error Contacting BioModels Database", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
ListOfBioModels.setListData(BioModelIds);
}
});
GetDescription.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String SelectedModel = ((String) ListOfBioModels.getSelectedValue())
.split(" ")[0];
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open http:
+ SelectedModel;
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open http:
+ SelectedModel;
}
else {
command = "cmd /c start http:
+ SelectedModel;
}
log.addText("Executing:\n" + command + "\n");
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open model description.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
GetReference.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String SelectedModel = ((String) ListOfBioModels.getSelectedValue())
.split(" ")[0];
try {
String Pub = (client.getSimpleModelById(SelectedModel))
.getPublicationId();
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open http:
+ Pub;
}
else if (System.getProperty("os.name").toLowerCase().startsWith(
"mac os")) {
command = "open http:
+ Pub;
}
else {
command = "cmd /c start http:
+ Pub;
}
log.addText("Executing:\n" + command + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec(command);
}
catch (BioModelsWSException e2) {
JOptionPane.showMessageDialog(frame,
"Error Contacting BioModels Database", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open model description.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
GetButtons.add(GetNames);
GetButtons.add(GetDescription);
GetButtons.add(GetReference);
BioModelsPanel.add(TextBioModels, "North");
BioModelsPanel.add(ScrollBioModels, "Center");
BioModelsPanel.add(GetButtons, "South");
Object[] options = { "OK", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, BioModelsPanel,
"List of BioModels", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
/*
* String modelNumber = JOptionPane.showInputDialog(frame,
* "Enter BioModel Number:", "BioModel Number",
* JOptionPane.PLAIN_MESSAGE);
*/
// if (modelNumber != null && !modelNumber.equals("")) {
if (value == JOptionPane.YES_OPTION && ListOfBioModels.getSelectedValue() != null) {
String BMurl = "http:
String filename = ((String) ListOfBioModels.getSelectedValue()).split(" ")[0];
/*
* String filename = "BIOMD"; for (int i = 0; i < 10 -
* modelNumber.length(); i++) { filename += "0"; } filename
* += modelNumber + ".xml";
*/
filename += ".xml";
try {
URL url = new URL(BMurl + filename);
/*
* System.out.println("Opening connection to " + BMurl +
* filename + "...");
*/
URLConnection urlC = url.openConnection();
InputStream is = url.openStream();
/*
* System.out.println("Copying resource (type: " +
* urlC.getContentType() + ")..."); System.out.flush();
*/
if (overwrite(root + separator + filename, filename)) {
FileOutputStream fos = null;
fos = new FileOutputStream(root + separator + filename);
int oneChar, count = 0;
while ((oneChar = is.read()) != -1) {
fos.write(oneChar);
count++;
}
is.close();
fos.close();
// System.out.println(count + " byte(s) copied");
String[] file = filename.trim().split(separator);
SBMLDocument document = readSBML(root + separator + filename.trim());
long numErrors = document.checkConsistency();
if (numErrors > 0) {
final JFrame f = new JFrame("SBML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea
.append("Imported SBML file contains the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n");
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + file[file.length - 1]);
refreshTree();
}
}
catch (MalformedURLException e1) {
JOptionPane.showMessageDialog(frame, e1.toString(), "Error",
JOptionPane.ERROR_MESSAGE);
filename = "";
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, filename + " not found.", "Error",
JOptionPane.ERROR_MESSAGE);
filename = "";
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import dot menu item is selected
else if (e.getSource() == importDot) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null,
JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit", -1);
if (filename != null && !filename.trim().equals("")) {
biosimrc.put("biosim.general.import_dir", filename.trim());
}
if (new File(filename.trim()).isDirectory()) {
for (String s : new File(filename.trim()).list()) {
if (!(filename.trim() + separator + s).equals("")
&& (filename.trim() + separator + s).length() > 3
&& (filename.trim() + separator + s).substring(
(filename.trim() + separator + s).length() - 4,
(filename.trim() + separator + s).length()).equals(".gcm")) {
try {
// GCMParser parser =
new GCMParser((filename.trim() + separator + s));
if (overwrite(root + separator + s, s)) {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + s));
FileInputStream in = new FileInputStream(new File((filename
.trim()
+ separator + s)));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
if (filename.trim().length() > 3
&& !filename.trim().substring(filename.trim().length() - 4,
filename.trim().length()).equals(".gcm")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid gcm file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.trim().equals("")) {
String[] file = filename.trim().split(separator);
try {
// GCMParser parser =
new GCMParser(filename.trim());
if (overwrite(root + separator + file[file.length - 1],
file[file.length - 1])) {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename.trim()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import vhdl menu item is selected
else if (e.getSource() == importVhdl) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import VHDL Model", -1);
if (filename.length() > 3
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".vhd")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid vhdl file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importS) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Assembly File", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 2, filename.length()).equals(
".s")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid assembly file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importInst) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Instruction File", -1);
if (filename.length() > 4
&& !filename.substring(filename.length() - 5, filename.length()).equals(
".inst")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid instruction file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importLpn) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import LPN", -1);
if ((filename.length() > 1 && !filename.substring(filename.length() - 2,
filename.length()).equals(".g"))
&& (filename.length() > 3 && !filename.substring(filename.length() - 4,
filename.length()).equals(".lpn"))) {
JOptionPane.showMessageDialog(frame,
"You must select a valid LPN file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
if (new File(filename).exists()) {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
// log.addText(filename);
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
if (filename.substring(filename.length() - 2, filename.length()).equals(
".g")) {
// log.addText(filename + file[file.length - 1]);
File work = new File(root);
String oldName = root + separator + file[file.length - 1];
// String newName = oldName.replace(".lpn",
// "_NEW.g");
Process atacs = Runtime.getRuntime().exec("atacs -lgsl " + oldName,
null, work);
atacs.waitFor();
String lpnName = oldName.replace(".g", ".lpn");
String newName = oldName.replace(".g", "_NEW.lpn");
atacs = Runtime.getRuntime().exec("atacs -llsl " + lpnName, null, work);
atacs.waitFor();
FileOutputStream out = new FileOutputStream(new File(lpnName));
FileInputStream in = new FileInputStream(new File(newName));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
new File(newName).delete();
}
refreshTree();
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importG) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Net", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 2, filename.length()).equals(
".g")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid Petri net file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import csp menu item is selected
else if (e.getSource() == importCsp) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import CSP", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".csp")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid csp file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import hse menu item is selected
else if (e.getSource() == importHse) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import HSE", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".hse")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid handshaking expansion file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import unc menu item is selected
else if (e.getSource() == importUnc) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import UNC", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".unc")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid expanded burst mode machine file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import rsg menu item is selected
else if (e.getSource() == importRsg) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import RSG", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".rsg")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid rsg file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import spice menu item is selected
else if (e.getSource() == importSpice) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Spice Circuit", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".cir")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid spice circuit file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the Graph data menu item is clicked
else if (e.getSource() == graph) {
if (root != null) {
String graphName = JOptionPane.showInputDialog(frame,
"Enter A Name For The TSD Graph:", "TSD Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "Number of molecules", graphName.trim()
.substring(0, graphName.length() - 4), "tsd.printer", root, "Time",
this, null, log, graphName.trim(), true, false);
addTab(graphName.trim(), g, "TSD Graph");
g.save();
refreshTree();
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == probGraph) {
if (root != null) {
String graphName = JOptionPane.showInputDialog(frame,
"Enter A Name For The Probability Graph:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "Number of Molecules", graphName.trim()
.substring(0, graphName.length() - 4), "tsd.printer", root, "Time",
this, null, log, graphName.trim(), false, false);
addTab(graphName.trim(), g, "Probability Graph");
g.save();
refreshTree();
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("createLearn")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:",
"Learn View ID", JOptionPane.PLAIN_MESSAGE);
if (lrnName != null && !lrnName.trim().equals("")) {
lrnName = lrnName.trim();
// try {
if (overwrite(root + separator + lrnName, lrnName)) {
new File(root + separator + lrnName).mkdir();
// new FileWriter(new File(root + separator +
// lrnName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String sbmlFileNoPath = getFilename[getFilename.length - 1];
if (sbmlFileNoPath.endsWith(".vhd")) {
try {
File work = new File(root);
Runtime.getRuntime().exec("atacs -lvsl " + sbmlFileNoPath, null,
work);
sbmlFileNoPath = sbmlFileNoPath.replace(".vhd", ".lpn");
log.addText("atacs -lvsl " + sbmlFileNoPath + "\n");
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to generate LPN from VHDL file!",
"Error Generating File", JOptionPane.ERROR_MESSAGE);
}
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ lrnName.trim() + separator + lrnName.trim() + ".lrn"));
if (lema) {
out.write(("learn.file=" + sbmlFileNoPath + "\n").getBytes());
}
else {
out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes());
}
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
refreshTree();
JTabbedPane lrnTab = new JTabbedPane();
DataManager data = new DataManager(root + separator + lrnName, this, lema);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName(
"Data Manager");
if (lema) {
LearnLHPN learn = new LearnLHPN(root + separator + lrnName, log, this);
lrnTab.addTab("Learn", learn);
}
else {
Learn learn = new Learn(root + separator + lrnName, log, this);
lrnTab.addTab("Learn", learn);
}
// learn.addMouseListener(this);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph;
tsdGraph = new Graph(null, "Number of molecules", lrnName + " data",
"tsd.printer", root + separator + lrnName, "Time", this, null, log,
null, true, false);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName(
"TSD Graph");
/*
* JLabel noData = new JLabel("No data available"); Font
* font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font); noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn",
* noData); lrnTab.getComponentAt(lrnTab.getComponents
* ().length - 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font =
* noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("TSD Graph",
* noData1); lrnTab.getComponentAt
* (lrnTab.getComponents().length -
* 1).setName("TSD Graph");
*/
addTab(lrnName, lrnTab, null);
}
// catch (Exception e1) {
// JOptionPane.showMessageDialog(frame,
// "Unable to create Learn View directory.", "Error",
// JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("viewState")) {
if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(tree.getFile());
log.addText("Creating state graph.");
StateGraph sg = new StateGraph(lhpnFile);
sg.outputStateGraph(tree.getFile().replace(".lpn", "_sg.dot"), false);
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
log.addText("Executing:\n" + command + root + separator
+ (file.replace(".lpn", "_sg.dot")) + "\n");
Runtime exec = Runtime.getRuntime();
File work = new File(root);
try {
exec.exec(command + (file.replace(".lpn", "_sg.dot")), null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("markov")) {
if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
LhpnFile lhpnFile = new LhpnFile();
lhpnFile.load(tree.getFile());
log.addText("Creating state graph.");
StateGraph sg = new StateGraph(lhpnFile);
log.addText("Performing Markov Chain analysis.");
sg.performMarkovianAnalysis(null);
sg.outputStateGraph(tree.getFile().replace(".lpn", "_sg.dot"), true);
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
log.addText("Executing:\n" + command + root + separator
+ (file.replace(".lpn", "_sg.dot")) + "\n");
Runtime exec = Runtime.getRuntime();
File work = new File(root);
try {
exec.exec(command + (file.replace(".lpn", "_sg.dot")), null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("viewModel")) {
try {
if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPlgodpe " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
try {
String vhdFile = tree.getFile();
if (new File(vhdFile).exists()) {
File vhdlAmsFile = new File(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(this.frame(), scrolls, "VHDL-AMS Model",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"VHDL-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(this.frame(),
"Unable to view VHDL-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
/*
* String filename =
* tree.getFile().split(separator)[tree.getFile().split(
* separator).length - 1]; String cmd = "atacs -lvslllodpl "
* + filename; File work = new File(root); Runtime exec =
* Runtime.getRuntime(); Process view = exec.exec(cmd, null,
* work); log.addText("Executing:\n" + cmd); String[]
* findTheFile = filename.split("\\."); view.waitFor(); //
* String directory = ""; String theFile = findTheFile[0] +
* ".dot"; if (new File(root + separator +
* theFile).exists()) { String command = ""; if
* (System.getProperty("os.name").contentEquals("Linux")) {
* // directory = ENVVAR + "/docs/"; command =
* "gnome-open "; } else if
* (System.getProperty("os.name").toLowerCase
* ().startsWith("mac os")) { // directory = ENVVAR +
* "/docs/"; command = "open "; } else { // directory =
* ENVVAR + "\\docs\\"; command = "dotty start "; }
* log.addText(command + root + theFile + "\n");
* exec.exec(command + theFile, null, work); } else { File
* log = new File(root + 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(frame(), scrolls, "Log",
* JOptionPane.INFORMATION_MESSAGE); }
*/
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
try {
String vamsFileName = tree.getFile();
if (new File(vamsFileName).exists()) {
File vamsFile = new File(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(this.frame(), scrolls,
"Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"Verilog-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(this.frame(),
"Unable to view Verilog-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lcslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lhslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lxodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lsodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "File cannot be read", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (InterruptedException e2) {
e2.printStackTrace();
}
}
else if (e.getActionCommand().equals("copy") || e.getSource() == copy) {
if (!tree.getFile().equals(root)) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String modelID = null;
String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy",
JOptionPane.PLAIN_MESSAGE);
if (copy != null) {
copy = copy.trim();
}
else {
return;
}
try {
if (!copy.equals("")) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".xml")) {
if (copy.length() > 4) {
if (!copy.substring(copy.length() - 5).equals(".sbml")
&& !copy.substring(copy.length() - 4).equals(".xml")) {
copy += ".xml";
}
}
else {
copy += ".xml";
}
if (copy.length() > 4) {
if (copy.substring(copy.length() - 5).equals(".sbml")) {
modelID = copy.substring(0, copy.length() - 5);
}
else {
modelID = copy.substring(0, copy.length() - 4);
}
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".gcm")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".gcm")) {
copy += ".gcm";
}
}
else {
copy += ".gcm";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".vhd")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".vhd")) {
copy += ".vhd";
}
}
else {
copy += ".vhd";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".s")) {
if (copy.length() > 1) {
if (!copy.substring(copy.length() - 2).equals(".s")) {
copy += ".s";
}
}
else {
copy += ".s";
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".inst")) {
if (copy.length() > 4) {
if (!copy.substring(copy.length() - 5).equals(".inst")) {
copy += ".inst";
}
}
else {
copy += ".inst";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".g")) {
if (copy.length() > 1) {
if (!copy.substring(copy.length() - 2).equals(".g")) {
copy += ".g";
}
}
else {
copy += ".g";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".lpn")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".lpn")) {
copy += ".lpn";
}
}
else {
copy += ".lpn";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".csp")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".csp")) {
copy += ".csp";
}
}
else {
copy += ".csp";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".hse")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".hse")) {
copy += ".hse";
}
}
else {
copy += ".hse";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".unc")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".unc")) {
copy += ".unc";
}
}
else {
copy += ".unc";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".rsg")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".rsg")) {
copy += ".rsg";
}
}
else {
copy += ".rsg";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".grf")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".grf")) {
copy += ".grf";
}
}
else {
copy += ".grf";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".prb")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".prb")) {
copy += ".prb";
}
}
else {
copy += ".prb";
}
}
}
if (copy
.equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to copy file."
+ "\nNew filename must be different than old filename.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (overwrite(root + separator + copy, copy)) {
if (modelID != null) {
SBMLDocument document = readSBML(tree.getFile());
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy);
}
else if ((tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".gcm")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".grf")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".vhd")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".csp")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".hse")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".lpn")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".unc") || tree.getFile().substring(
tree.getFile().length() - 4).equals(".rsg"))
|| (tree.getFile().length() >= 2 && tree.getFile().substring(
tree.getFile().length() - 2).equals(".s"))
|| (tree.getFile().length() >= 5 && tree.getFile().substring(
tree.getFile().length() - 5).equals(".inst"))
|| (tree.getFile().length() >= 2 && tree.getFile().substring(
tree.getFile().length() - 2).equals(".g"))) {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ copy));
FileInputStream in = new FileInputStream(new File(tree.getFile()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else {
boolean sim = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
}
if (sim) {
new File(root + separator + copy).mkdir();
// new FileWriter(new File(root + separator +
// copy +
// separator +
// ".sim")).close();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 4
&& ss.substring(ss.length() - 5).equals(".sbml")
|| ss.length() > 3
&& ss.substring(ss.length() - 4).equals(".xml")) {
SBMLDocument document = readSBML(tree.getFile() + separator
+ ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy
+ separator + ss);
}
else if (ss.length() > 10
&& ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + copy + separator + ss));
FileInputStream in = new FileInputStream(new File(tree
.getFile()
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd")
|| ss.substring(ss.length() - 4).equals(".dat")
|| ss.substring(ss.length() - 4).equals(".sad")
|| ss.substring(ss.length() - 4).equals(".pms") || ss
.substring(ss.length() - 4).equals(".sim"))
&& !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator
+ copy + separator + copy + ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator
+ copy + separator + copy + ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator
+ copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree
.getFile()
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
else {
new File(root + separator + copy).mkdir();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd") || ss
.substring(ss.length() - 4).equals(".lrn"))) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".lrn")) {
out = new FileOutputStream(new File(root + separator
+ copy + separator + copy + ".lrn"));
}
else {
out = new FileOutputStream(new File(root + separator
+ copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree
.getFile()
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
}
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("rename") || e.getSource() == rename) {
if (!tree.getFile().equals(root)) {
try {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String modelID = null;
String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:",
"Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".xml")) {
if (rename.length() > 4) {
if (!rename.substring(rename.length() - 5).equals(".sbml")
&& !rename.substring(rename.length() - 4).equals(".xml")) {
rename += ".xml";
}
}
else {
rename += ".xml";
}
if (rename.length() > 4) {
if (rename.substring(rename.length() - 5).equals(".sbml")) {
modelID = rename.substring(0, rename.length() - 5);
}
else {
modelID = rename.substring(0, rename.length() - 4);
}
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".gcm")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".gcm")) {
rename += ".gcm";
}
}
else {
rename += ".gcm";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".vhd")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".vhd")) {
rename += ".vhd";
}
}
else {
rename += ".vhd";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".g")) {
if (rename.length() > 1) {
if (!rename.substring(rename.length() - 2).equals(".g")) {
rename += ".g";
}
}
else {
rename += ".g";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".s")) {
if (rename.length() > 1) {
if (!rename.substring(rename.length() - 2).equals(".s")) {
rename += ".s";
}
}
else {
rename += ".s";
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".inst")) {
if (rename.length() > 4) {
if (!rename.substring(rename.length() - 5).equals(".inst")) {
rename += ".inst";
}
}
else {
rename += ".inst";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".lpn")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".lpn")) {
rename += ".lpn";
}
}
else {
rename += ".lpn";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".csp")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".csp")) {
rename += ".csp";
}
}
else {
rename += ".csp";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".hse")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".hse")) {
rename += ".hse";
}
}
else {
rename += ".hse";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".unc")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".unc")) {
rename += ".unc";
}
}
else {
rename += ".unc";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".rsg")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".rsg")) {
rename += ".rsg";
}
}
else {
rename += ".rsg";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".grf")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".grf")) {
rename += ".grf";
}
}
else {
rename += ".grf";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".prb")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".prb")) {
rename += ".prb";
}
}
else {
rename += ".prb";
}
}
if (rename.equals(tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to rename file."
+ "\nNew filename must be different than old filename.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (overwrite(root + separator + rename, rename)) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".xml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".gcm")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".lpn")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".vhd")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".csp")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".hse")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".unc")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".rsg")) {
String oldName = tree.getFile().split(separator)[tree.getFile()
.split(separator).length - 1];
reassignViews(oldName, rename);
}
new File(tree.getFile()).renameTo(new File(root + separator + rename));
if (modelID != null) {
SBMLDocument document = readSBML(root + separator + rename);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + rename);
}
if (rename.length() >= 5
&& rename.substring(rename.length() - 5).equals(".sbml")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".xml")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".gcm")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".lpn")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".vhd")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".csp")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".hse")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".unc")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".rsg")) {
updateAsyncViews(rename);
}
if (new File(root + separator + rename).isDirectory()) {
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".sim").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".sim")
.renameTo(new File(root + separator + rename
+ separator + rename + ".sim"));
}
else if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".pms").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".pms")
.renameTo(new File(root + separator + rename
+ separator + rename + ".sim"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".lrn").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".lrn")
.renameTo(new File(root + separator + rename
+ separator + rename + ".lrn"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".ver").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".ver")
.renameTo(new File(root + separator + rename
+ separator + rename + ".ver"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".grf").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".grf")
.renameTo(new File(root + separator + rename
+ separator + rename + ".grf"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".prb").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".prb")
.renameTo(new File(root + separator + rename
+ separator + rename + ".prb"));
}
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
if (tree.getFile().length() > 4
&& tree.getFile()
.substring(tree.getFile().length() - 5).equals(
".sbml")
|| tree.getFile().length() > 3
&& tree.getFile()
.substring(tree.getFile().length() - 4).equals(
".xml")) {
((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID);
((SBML_Editor) tab.getComponentAt(i)).setFile(root
+ separator + rename);
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3
&& (tree.getFile().substring(
tree.getFile().length() - 4).equals(".grf") || tree
.getFile().substring(
tree.getFile().length() - 4).equals(
".prb"))) {
((Graph) tab.getComponentAt(i)).setGraphName(rename);
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3
&& tree.getFile()
.substring(tree.getFile().length() - 4).equals(
".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename
.substring(0, rename.length() - 4));
}
else if (tree.getFile().length() > 3
&& tree.getFile()
.substring(tree.getFile().length() - 4).equals(
".lpn")) {
((LHPNEditor) tab.getComponentAt(i)).reload(rename
.substring(0, rename.length() - 4));
tab.setTitleAt(i, rename);
}
else if (tab.getComponentAt(i) instanceof JTabbedPane) {
JTabbedPane t = new JTabbedPane();
int selected = ((JTabbedPane) tab.getComponentAt(i))
.getSelectedIndex();
boolean analysis = false;
ArrayList<Component> comps = new ArrayList<Component>();
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i))
.getTabCount(); j++) {
Component c = ((JTabbedPane) tab.getComponentAt(i))
.getComponent(j);
comps.add(c);
}
for (Component c : comps) {
if (c instanceof Reb2Sac) {
((Reb2Sac) c).setSim(rename);
analysis = true;
}
else if (c instanceof SBML_Editor) {
String properties = root + separator + rename
+ separator + rename + ".sim";
new File(properties).renameTo(new File(properties
.replace(".sim", ".temp")));
boolean dirty = ((SBML_Editor) c).isDirty();
((SBML_Editor) c).setParamFileAndSimDir(properties,
root + separator + rename);
((SBML_Editor) c).save(false, "", true);
((SBML_Editor) c).updateSBML(i, 0);
((SBML_Editor) c).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp"))
.renameTo(new File(properties));
}
else if (c instanceof Graph) {
// c.addMouseListener(this);
Graph g = ((Graph) c);
g.setDirectory(root + separator + rename);
if (g.isTSDGraph()) {
g.setGraphName(rename + ".grf");
}
else {
g.setGraphName(rename + ".prb");
}
}
else if (c instanceof Learn) {
Learn l = ((Learn) c);
l.setDirectory(root + separator + rename);
}
else if (c instanceof DataManager) {
DataManager d = ((DataManager) c);
d.setDirectory(root + separator + rename);
}
if (analysis) {
if (c instanceof Reb2Sac) {
t.addTab("Simulation Options", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("Simulate");
}
else if (c instanceof SBML_Editor) {
t.addTab("Parameter Editor", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("SBML Editor");
}
else if (c instanceof GCM2SBMLEditor) {
t.addTab("Parameter Editor", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("GCM Editor");
}
else if (c instanceof Graph) {
if (((Graph) c).isTSDGraph()) {
t.addTab("TSD Graph", c);
t.getComponentAt(
t.getComponents().length - 1)
.setName("TSD Graph");
}
else {
t.addTab("Probability Graph", c);
t.getComponentAt(
t.getComponents().length - 1)
.setName("ProbGraph");
}
}
else {
t.addTab("Abstraction Options", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("");
}
}
}
if (analysis) {
t.setSelectedIndex(selected);
tab.setComponentAt(i, t);
}
tab.setTitleAt(i, rename);
tab.getComponentAt(i).setName(rename);
}
else {
tab.setTitleAt(i, rename);
tab.getComponentAt(i).setName(rename);
}
}
}
refreshTree();
// updateAsyncViews(rename);
updateViewNames(tree.getFile(), rename);
}
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to rename selected file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("openGraph")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
.contains(".grf")) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Number of molecules", "title", "tsd.printer", root,
"Time", this, tree.getFile(), log, tree.getFile().split(
separator)[tree.getFile().split(separator).length - 1],
true, false), "TSD Graph");
}
else {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Percent", "title", "tsd.printer", root, "Time", this,
tree.getFile(), log, tree.getFile().split(separator)[tree
.getFile().split(separator).length - 1], false, false),
"Probability Graph");
}
}
}
}
public int getTab(String name) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(name)) {
return i;
}
}
return -1;
}
public void deleteDir(File dir) {
int count = 0;
do {
File[] list = dir.listFiles();
System.gc();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
deleteDir(list[i]);
}
else {
list[i].delete();
}
}
count++;
}
while (!dir.delete() && count != 100);
if (count == 100) {
JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* This method adds a new project to recent list
*/
public void addRecentProject(String projDir) {
// boolean newOne = true;
for (int i = 0; i < numberRecentProj; i++) {
if (recentProjectPaths[i].equals(projDir)) {
for (int j = 0; j <= i; j++) {
String save = recentProjectPaths[j];
recentProjects[j]
.setText(projDir.split(separator)[projDir.split(separator).length - 1]);
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[j]);
}
recentProjectPaths[j] = projDir;
projDir = save;
}
for (int j = i + 1; j < numberRecentProj; j++) {
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[j]);
}
}
return;
}
}
if (numberRecentProj < 5) {
numberRecentProj++;
}
for (int i = 0; i < numberRecentProj; i++) {
String save = recentProjectPaths[i];
recentProjects[i]
.setText(projDir.split(separator)[projDir.split(separator).length - 1]);
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[i], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[i]);
}
recentProjectPaths[i] = projDir;
projDir = save;
}
}
/**
* This method refreshes the menu.
*/
public void refresh() {
mainPanel.remove(tree);
tree = new FileTree(new File(root), this, lema, atacs);
mainPanel.add(tree, "West");
mainPanel.validate();
}
/**
* This method refreshes the tree.
*/
public void refreshTree() {
tree.fixTree();
updateGCM();
mainPanel.validate();
}
/**
* This method adds the given Component to a tab.
*/
public void addTab(String name, Component panel, String tabName) {
tab.addTab(name, panel);
// panel.addMouseListener(this);
if (tabName != null) {
tab.getComponentAt(tab.getTabCount() - 1).setName(tabName);
}
else {
tab.getComponentAt(tab.getTabCount() - 1).setName(name);
}
tab.setSelectedIndex(tab.getTabCount() - 1);
}
/**
* This method removes the given component from the tabs.
*/
public void removeTab(Component component) {
tab.remove(component);
}
public JTabbedPane getTab() {
return tab;
}
/**
* Prompts the user to save work that has been done.
*/
public int save(int index, int autosave) {
if (tab.getComponentAt(index).getName().contains(("GCM"))
|| tab.getComponentAt(index).getName().contains("LHPN")) {
if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) {
GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
editor.save("gcm");
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
editor.save("gcm");
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
editor.save("gcm");
return 2;
}
else {
return 3;
}
}
}
else if (tab.getComponentAt(index) instanceof LHPNEditor) {
LHPNEditor editor = (LHPNEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
editor.save();
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
editor.save();
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
editor.save();
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else if (tab.getComponentAt(index).getName().equals("SBML Editor")) {
if (tab.getComponentAt(index) instanceof SBML_Editor) {
if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else if (tab.getComponentAt(index).getName().contains("Graph")) {
if (tab.getComponentAt(index) instanceof Graph) {
if (((Graph) tab.getComponentAt(index)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Graph) tab.getComponentAt(index)).save();
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Graph) tab.getComponentAt(index)).save();
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
((Graph) tab.getComponentAt(index)).save();
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else {
if (tab.getComponentAt(index) instanceof JTabbedPane) {
for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() != null) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName()
.equals("Simulate")) {
if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save simulation option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("SBML Editor")) {
if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save(false, "", true);
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save(false, "", true);
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save(false, "", true);
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("GCM Editor")) {
if (((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveParams(false, "");
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveParams(false, "");
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveParams(false, "");
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("Learn")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) {
if (((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for "
+ tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
}
}
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) {
if (((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for "
+ tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i))
.save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i))
.save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("Data Manager")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) {
((DataManager) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveChanges(tab.getTitleAt(index));
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().contains("Graph")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) {
if (((Graph) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save graph changes for "
+ tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i));
g.save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i));
g.save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i));
g.save();
}
}
}
}
}
}
}
}
else if (tab.getComponentAt(index) instanceof JPanel) {
if ((tab.getComponentAt(index)).getName().equals("Synthesis")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Synthesis) {
if (((Synthesis) array[0]).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save synthesis option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
}
}
}
}
else if (tab.getComponentAt(index).getName().equals("Verification")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Verification) {
if (((Verification) array[0]).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save verification option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Verification) array[0]).save();
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Verification) array[0]).save();
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((Verification) array[0]).save();
}
}
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveGcm(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
FileOutputStream out = new FileOutputStream(new File(root + separator + filename));
FileInputStream in = new FileInputStream(new File(path));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveLhpn(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
BufferedWriter out = new BufferedWriter(new FileWriter(root + separator + filename));
BufferedReader in = new BufferedReader(new FileReader(path));
String str;
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
out = new BufferedWriter(new FileWriter(root + separator
+ filename.replace(".lpn", ".vhd")));
in = new BufferedReader(new FileReader(path.replace(".lpn", ".vhd")));
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
out = new BufferedWriter(new FileWriter(root + separator
+ filename.replace(".lpn", ".vams")));
in = new BufferedReader(new FileReader(path.replace(".lpn", ".vams")));
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
out = new BufferedWriter(new FileWriter(root + separator
+ filename.replace(".lpn", "_top.vams")));
String[] learnPath = path.split(separator);
String topVFile = path.replace(learnPath[learnPath.length - 1], "top.vams");
String[] cktPath = filename.split(separator);
in = new BufferedReader(new FileReader(topVFile));
while ((str = in.readLine()) != null) {
str = str.replace("module top", "module "
+ cktPath[cktPath.length - 1].replace(".lpn", "_top"));
out.write(str + "\n");
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save LPN.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void updateMenu(boolean logEnabled, boolean othersEnabled) {
viewVHDL.setEnabled(othersEnabled);
viewVerilog.setEnabled(othersEnabled);
viewLHPN.setEnabled(othersEnabled);
viewCoverage.setEnabled(othersEnabled);
save.setEnabled(othersEnabled);
viewLog.setEnabled(logEnabled);
// Do saveas & save button too
}
/**
* Returns the frame.
*/
public JFrame frame() {
return frame;
}
public void mousePressed(MouseEvent e) {
// log.addText(e.getSource().toString());
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(),
e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
}
else {
if (e.isPopupTrigger() && tree.getFile() != null) {
frame.getGlassPane().setVisible(false);
popup.removeAll();
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("sbmlEditor");
JMenuItem graph = new JMenuItem("View Model");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem browse = new JMenuItem("View Model in Browser");
browse.addActionListener(this);
browse.addMouseListener(this);
browse.setActionCommand("browse");
JMenuItem simulate = new JMenuItem("Create Analysis View");
simulate.addActionListener(this);
simulate.addMouseListener(this);
simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(simulate);
popup.add(createLearn);
popup.addSeparator();
popup.add(graph);
popup.add(browse);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createSBML = new JMenuItem("Create SBML File");
createSBML.addActionListener(this);
createSBML.addMouseListener(this);
createSBML.setActionCommand("createSBML");
// JMenuItem createLHPN = new JMenuItem("Create LPN File");
// createLHPN.addActionListener(this);
// createLHPN.addMouseListener(this);
// createLHPN.setActionCommand("createLHPN");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem graph = new JMenuItem("View Model");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.add(createSBML);
// popup.add(createLHPN);
popup.addSeparator();
popup.add(graph);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (lema) {
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
// if (lema) {
// popup.add(createLearn);
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
// //////// TODO
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createAnalysis");
// createAnalysis.setActionCommand("simulate");
// JMenuItem simulate = new
// JMenuItem("Create Analysis View");
// simulate.addActionListener(this);
// simulate.addMouseListener(this);
// simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem convertToSBML = new JMenuItem("Convert To SBML");
convertToSBML.addActionListener(this);
convertToSBML.addMouseListener(this);
convertToSBML.setActionCommand("convertToSBML");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem viewStateGraph = new JMenuItem("View State Graph");
viewStateGraph.addActionListener(this);
viewStateGraph.addMouseListener(this);
viewStateGraph.setActionCommand("viewState");
JMenuItem markovAnalysis = new JMenuItem("Perform Markovian Analysis");
markovAnalysis.addActionListener(this);
markovAnalysis.addMouseListener(this);
markovAnalysis.setActionCommand("markov");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
if (atacs || lema) {
popup.add(createVerification);
popup.addSeparator();
}
popup.add(convertToSBML);
// popup.add(createAnalysis); // TODO
popup.add(viewModel);
popup.add(viewStateGraph);
popup.add(markovAnalysis);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) {
// JMenuItem createAnalysis = new
// JMenuItem("Create Analysis View");
// createAnalysis.addActionListener(this);
// createAnalysis.addMouseListener(this);
// createAnalysis.setActionCommand("createSim");
// JMenuItem createVerification = new
// JMenuItem("Create Verification View");
// createVerification.addActionListener(this);
// createVerification.addMouseListener(this);
// createVerification.setActionCommand("createVerify");
// JMenuItem viewModel = new JMenuItem("View Model");
// viewModel.addActionListener(this);
// viewModel.addMouseListener(this);
// viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
// popup.add(createVerification);
// popup.addSeparator();
// popup.add(viewModel);
// popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) {
// JMenuItem createAnalysis = new
// JMenuItem("Create Analysis View");
// createAnalysis.addActionListener(this);
// createAnalysis.addMouseListener(this);
// createAnalysis.setActionCommand("createSim");
// JMenuItem createVerification = new
// JMenuItem("Create Verification View");
// createVerification.addActionListener(this);
// createVerification.addMouseListener(this);
// createVerification.setActionCommand("createVerify");
// JMenuItem viewModel = new JMenuItem("View Model");
// viewModel.addActionListener(this);
// viewModel.addMouseListener(this);
// viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
// popup.add(createVerification);
// popup.addSeparator();
// popup.add(viewModel);
// popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
JMenuItem open;
if (sim) {
open = new JMenuItem("Open Analysis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSim");
popup.add(open);
}
else if (synth) {
open = new JMenuItem("Open Synthesis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSynth");
popup.add(open);
}
else if (ver) {
open = new JMenuItem("Open Verification View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openVerification");
popup.add(open);
}
else if (learn) {
open = new JMenuItem("Open Learn View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openLearn");
popup.add(open);
}
if (sim || ver || synth || learn) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("deleteSim");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (tree.getFile() != null) {
int index = tab.getSelectedIndex();
enableTabMenu(index);
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".sbml") || tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
try {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
SBML_Editor sbml = new SBML_Editor(tree.getFile(), null, log, this,
null, null);
// sbml.addMouseListener(this);
addTab(tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1], sbml, "SBML Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"You must select a valid sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(),
theFile, this, log, false, null, null, null);
// gcm.addMouseListener(this);
addTab(theFile, gcm, "GCM Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "VHDL Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Assembly File Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to view this assembly file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".inst")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Instruction File Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to view this instruction file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".vams")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "VHDL Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to view this Verilog-AMS file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Petri Net Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this .g file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
LhpnFile lhpn = new LhpnFile(log);
if (new File(directory + theFile).length() > 0) {
// log.addText("here");
lhpn.load(directory + theFile);
// log.addText("there");
}
// log.addText("load completed");
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
// log.addText("make Editor");
LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile,
lhpn, this, log);
// editor.addMouseListener(this);
addTab(theFile, editor, "LHPN Editor");
// log.addText("Editor made");
}
// String[] cmd = { "emacs", filename };
// Runtime.getRuntime().exec(cmd);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to view this LPN file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "CSP Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this csp file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "HSE Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this hse file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "UNC Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this unc file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "RSG Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this rsg file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (!viewer.equals("")) {
String command = viewer + " " + directory + separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Spice Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this spice file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Number of molecules", "title", "tsd.printer",
root, "Time", this, tree.getFile(), log, tree.getFile()
.split(separator)[tree.getFile().split(
separator).length - 1], true, false),
"TSD Graph");
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Percent", "title", "tsd.printer", root,
"Time", this, tree.getFile(), log, tree.getFile()
.split(separator)[tree.getFile().split(
separator).length - 1], false, false),
"Probability Graph");
}
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
if (sim) {
openSim();
}
else if (synth) {
openSynth();
}
else if (ver) {
openVerify();
}
else if (learn) {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
}
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities
.convertPoint(glassPane, glassPanePoint, container);
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(),
e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
try {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
if (e != null) {
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e
.getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e
.getClickCount(), e.isPopupTrigger()));
}
if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) {
enableTreeMenu();
}
else {
enableTabMenu(tab.getSelectedIndex());
}
}
catch (Exception e1) {
e1.printStackTrace();
}
}
}
else {
if (tree.getFile() != null) {
if (e.isPopupTrigger() && tree.getFile() != null) {
frame.getGlassPane().setVisible(false);
popup.removeAll();
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".sbml") || tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("sbmlEditor");
JMenuItem graph = new JMenuItem("View Model");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem browse = new JMenuItem("View Model in Browser");
browse.addActionListener(this);
browse.addMouseListener(this);
browse.setActionCommand("browse");
// TODO
JMenuItem simulate = new JMenuItem("Create Analysis View");
simulate.addActionListener(this);
simulate.addMouseListener(this);
simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(simulate);
popup.add(createLearn);
popup.addSeparator();
popup.add(graph);
popup.add(browse);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createSBML = new JMenuItem("Create SBML File");
createSBML.addActionListener(this);
createSBML.addMouseListener(this);
createSBML.setActionCommand("createSBML");
// JMenuItem createLHPN = new
// JMenuItem("Create LPN File");
// createLHPN.addActionListener(this);
// createLHPN.addMouseListener(this);
// createLHPN.setActionCommand("createLHPN");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem graph = new JMenuItem("View Model");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.add(createSBML);
// popup.add(createLHPN);
popup.addSeparator();
popup.add(graph);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
// if (lema) {
// popup.add(createLearn);
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem viewStateGraph = new JMenuItem("View State Graph");
viewStateGraph.addActionListener(this);
viewStateGraph.addMouseListener(this);
viewStateGraph.setActionCommand("viewState");
JMenuItem markovAnalysis = new JMenuItem("Perform Markovian Analysis");
markovAnalysis.addActionListener(this);
markovAnalysis.addMouseListener(this);
markovAnalysis.setActionCommand("markov");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
if (atacs || lema) {
popup.add(createVerification);
popup.addSeparator();
}
popup.add(viewModel);
popup.add(viewStateGraph);
popup.add(markovAnalysis);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
JMenuItem open;
if (sim) {
open = new JMenuItem("Open Analysis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSim");
popup.add(open);
}
else if (synth) {
open = new JMenuItem("Open Synthesis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSynth");
popup.add(open);
}
else if (ver) {
open = new JMenuItem("Open Verification View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openVerification");
popup.add(open);
}
else if (learn) {
open = new JMenuItem("Open Learn View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openLearn");
popup.add(open);
}
if (sim || ver | learn | synth) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("deleteSim");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
else if (!popup.isVisible()) {
frame.getGlassPane().setVisible(true);
}
}
}
}
public void mouseMoved(MouseEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
}
public void mouseWheelMoved(MouseWheelEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseWheelEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e
.getWheelRotation()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseWheelEvent(deepComponent, e.getID(), e.getWhen(),
e.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e
.getWheelRotation()));
}
}
public void windowGainedFocus(WindowEvent e) {
setGlassPane(true);
}
private void simulate(int fileType) throws Exception {
/*
* if (fileType == 1) { String simName =
* JOptionPane.showInputDialog(frame, "Enter Analysis ID:",
* "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null &&
* !simName.trim().equals("")) { simName = simName.trim(); if
* (overwrite(root + separator + simName, simName)) { new File(root +
* separator + simName).mkdir(); // new FileWriter(new File(root +
* separator + simName + // separator + // ".sim")).close(); String[]
* dot = tree.getFile().split(separator); String sbmlFile = root +
* separator + simName + separator + (dot[dot.length - 1].substring(0,
* dot[dot.length - 1].length() - 3) + "sbml"); GCMParser parser = new
* GCMParser(tree.getFile()); GeneticNetwork network =
* parser.buildNetwork(); GeneticNetwork.setRoot(root + separator);
* network.mergeSBML(root + separator + simName + separator + sbmlFile);
* try { FileOutputStream out = new FileOutputStream(new File(root +
* separator + simName.trim() + separator + simName.trim() + ".sim"));
* out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); }
* catch (IOException e1) { JOptionPane.showMessageDialog(frame,
* "Unable to save parameter file!", "Error Saving File",
* JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator
* + sbmlFile); refreshTree(); sbmlFile = root + separator + simName +
* separator + (dot[dot.length - 1].substring(0, dot[dot.length -
* 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane();
* Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this,
* simName.trim(), log, simTab, null, dot[dot.length - 1]); //
* reb2sac.addMouseListener(this); simTab.addTab("Simulation Options",
* reb2sac); simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced();
* // abstraction.addMouseListener(this);
* simTab.addTab("Abstraction Options", abstraction);
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* // simTab.addTab("Advanced Options", // reb2sac.getProperties()); //
* simTab.getComponentAt(simTab.getComponents().length - //
* 1).setName(""); if (dot[dot.length - 1].contains(".gcm")) {
* GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator,
* dot[dot.length - 1], this, log, true, simName.trim(), root +
* separator + simName.trim() + separator + simName.trim() + ".sim",
* reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this);
* simTab.addTab("Parameter Editor", gcm);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("GCM Editor"); if (!gcm.getSBMLFile().equals("--none--"))
* { SBML_Editor sbml = new SBML_Editor(root + separator +
* gcm.getSBMLFile(), reb2sac, log, this, root + separator +
* simName.trim(), root + separator + simName.trim() + separator +
* simName.trim() + ".sim"); simTab.addTab("SBML Elements",
* sbml.getElementsPanel());
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* gcm.setSBMLParamFile(sbml); } else { JScrollPane scroll = new
* JScrollPane(); scroll.setViewportView(new JPanel());
* simTab.addTab("SBML Elements", scroll);
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* gcm.setSBMLParamFile(null); } } else { SBML_Editor sbml = new
* SBML_Editor(sbmlFile, reb2sac, log, this, root + separator +
* simName.trim(), root + separator + simName.trim() + separator +
* simName.trim() + ".sim"); reb2sac.setSbml(sbml); //
* sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("SBML Editor"); simTab.addTab("SBML Elements",
* sbml.getElementsPanel());
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* } Graph tsdGraph = reb2sac.createGraph(null); //
* tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph",
* tsdGraph); simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); Graph probGraph =
* reb2sac.createProbGraph(null); // probGraph.addMouseListener(this);
* simTab.addTab("Probability Graph", probGraph);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*
* addTab(simName, simTab, null); } } } else if (fileType == 2) { String
* simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:",
* "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null &&
* !simName.trim().equals("")) { simName = simName.trim(); if
* (overwrite(root + separator + simName, simName)) { new File(root +
* separator + simName).mkdir(); // new FileWriter(new File(root +
* separator + simName + // separator + // ".sim")).close(); String[]
* dot = tree.getFile().split(separator); String sbmlFile = root +
* separator + simName + separator + (dot[dot.length - 1].substring(0,
* dot[dot.length - 1].length() - 3) + "sbml"); Translator t1 = new
* Translator(); t1.BuildTemplate(tree.getFile()); t1.setFilename(root +
* separator + simName + separator + sbmlFile); t1.outputSBML(); try {
* FileOutputStream out = new FileOutputStream(new File(root + separator
* + simName.trim() + separator + simName.trim() + ".sim"));
* out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); }
* catch (IOException e1) { JOptionPane.showMessageDialog(frame,
* "Unable to save parameter file!", "Error Saving File",
* JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator
* + sbmlFile); refreshTree(); sbmlFile = root + separator + simName +
* separator + (dot[dot.length - 1].substring(0, dot[dot.length -
* 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane();
* Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this,
* simName.trim(), log, simTab, null, dot[dot.length - 1]); //
* reb2sac.addMouseListener(this); simTab.addTab("Simulation Options",
* reb2sac); simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced();
* // abstraction.addMouseListener(this);
* simTab.addTab("Abstraction Options", abstraction);
* simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
* // simTab.addTab("Advanced Options", // reb2sac.getProperties()); //
* simTab.getComponentAt(simTab.getComponents().length - //
* 1).setName(""); Graph tsdGraph = reb2sac.createGraph(null); //
* tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph",
* tsdGraph); simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); Graph probGraph =
* reb2sac.createProbGraph(null); // probGraph.addMouseListener(this);
* simTab.addTab("Probability Graph", probGraph);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); addTab(simName, simTab, null); } } } else {
*/
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (fileType == 0) {
SBMLDocument document = readSBML(tree.getFile());
}
String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID",
JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (overwrite(root + separator + simName, simName)) {
new File(root + separator + simName).mkdir();
// new FileWriter(new File(root + separator + simName +
// separator +
// ".sim")).close();
String sbmlFile = tree.getFile();
String[] sbml1 = tree.getFile().split(separator);
String sbmlFileProp;
if (fileType == 1) {
sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1]
.length() - 3) + "sbml");
GCMParser parser = new GCMParser(tree.getFile());
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + separator);
network.mergeSBML(root + separator + simName + separator + sbmlFile);
sbmlFileProp = root
+ separator
+ simName
+ separator
+ (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1]
.length() - 3) + "sbml");
sbmlFile = sbmlFileProp;
}
else if (fileType == 2) {
sbmlFile = (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1]
.length() - 3) + "sbml");
Translator t1 = new Translator();
t1.BuildTemplate(tree.getFile());
t1.setFilename(root + separator + simName + separator + sbmlFile);
t1.outputSBML();
sbmlFileProp = root
+ separator
+ simName
+ separator
+ (sbml1[sbml1.length - 1].substring(0, sbml1[sbml1.length - 1]
.length() - 3) + "sbml");
sbmlFile = sbmlFileProp;
}
else {
sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1];
new FileOutputStream(new File(sbmlFileProp)).close();
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ simName.trim() + separator + simName.trim() + ".sim"));
out.write((sbml1[sbml1.length - 1] + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
/*
* try { FileOutputStream out = new FileOutputStream(new
* File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); String
* doc = writer.writeToString(document); byte[] output =
* doc.getBytes(); out.write(output); out.close(); } catch
* (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable
* to copy sbml file to output location.", "Error",
* JOptionPane.ERROR_MESSAGE); }
*/
refreshTree();
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName.trim(),
log, simTab, null, sbml1[sbml1.length - 1]);
// reb2sac.addMouseListener(this);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
JPanel abstraction = reb2sac.getAdvanced();
// abstraction.addMouseListener(this);
simTab.addTab("Abstraction Options", abstraction);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");boolean
if (sbml1[sbml1.length - 1].contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator,
sbml1[sbml1.length - 1], this, log, true, simName.trim(), root
+ separator + simName.trim() + separator + simName.trim()
+ ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(),
reb2sac, log, this, root + separator + simName.trim(), root
+ separator + simName.trim() + separator + simName.trim()
+ ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(null);
}
}
else if (sbml1[sbml1.length - 1].contains(".sbml")
|| sbml1[sbml1.length - 1].contains(".xml")) {
SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root
+ separator + simName.trim(), root + separator + simName.trim()
+ separator + simName.trim() + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
addTab(simName, simTab, null);
}
}
}
private void openLearn() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
DataManager data = new DataManager(tree.getFile(), this, lema);
// data.addMouseListener(this);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
Learn learn = new Learn(tree.getFile(), log, this);
// learn.addMouseListener(this);
lrnTab.addTab("Learn", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph = new Graph(null, "Number of molecules",
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "Time", this, open, log,
null, true, true);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
/*
* else { lrnTab.addTab("Data Manager", new
* DataManager(tree.getFile(), this));
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Data Manager"); JLabel noData = new JLabel("No data
* available"); Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font = noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
lrnTab, null);
}
}
private void openLearnLHPN() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
DataManager data = new DataManager(tree.getFile(), this, lema);
// data.addMouseListener(this);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this);
// learn.addMouseListener(this);
lrnTab.addTab("Learn", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph = new Graph(null, "Number of molecules",
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "Time", this, open, log,
null, true, true);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
/*
* else { lrnTab.addTab("Data Manager", new
* DataManager(tree.getFile(), this));
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Data Manager"); JLabel noData = new JLabel("No data
* available"); Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font = noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
lrnTab, null);
}
}
private void openSynth() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JPanel synthPanel = new JPanel();
// String graphFile = "";
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
}
}
}
String synthFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".syn";
String synthFile2 = tree.getFile() + separator + ".syn";
Properties load = new Properties();
String synthesisFile = "";
try {
if (new File(synthFile2).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile2));
load.load(in);
in.close();
new File(synthFile2).delete();
}
if (new File(synthFile).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile));
load.load(in);
in.close();
if (load.containsKey("synthesis.file")) {
synthesisFile = load.getProperty("synthesis.file");
synthesisFile = synthesisFile.split(separator)[synthesisFile
.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(synthesisFile));
load.store(out, synthesisFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(synthesisFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + synthesisFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Synthesis synth = new Synthesis(tree.getFile(), "flag", log, this);
// synth.addMouseListener(this);
synthPanel.add(synth);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
synthPanel, "Synthesis");
}
}
private void openVerify() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
// JPanel verPanel = new JPanel();
// JPanel abstPanel = new JPanel();
// JPanel verTab = new JTabbedPane();
// String graphFile = "";
/*
* if (new File(tree.getFile()).isDirectory()) { String[] list = new
* File(tree.getFile()).list(); int run = 0; for (int i = 0; i <
* list.length; i++) { if (!(new File(list[i]).isDirectory()) &&
* list[i].length() > 4) { String end = ""; for (int j = 1; j < 5;
* j++) { end = list[i].charAt(list[i].length() - j) + end; } if
* (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv"))
* { if (list[i].contains("run-")) { int tempNum =
* Integer.parseInt(list[i].substring(4, list[i] .length() -
* end.length())); if (tempNum > run) { run = tempNum; // graphFile
* = tree.getFile() + separator + // list[i]; } } } } } }
*/
String verName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String verFile = tree.getFile() + separator + verName + ".ver";
Properties load = new Properties();
String verifyFile = "";
try {
if (new File(verFile).exists()) {
FileInputStream in = new FileInputStream(new File(verFile));
load.load(in);
in.close();
if (load.containsKey("verification.file")) {
verifyFile = load.getProperty("verification.file");
verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1];
}
}
// FileOutputStream out = new FileOutputStream(new
// File(verifyFile));
// load.store(out, verifyFile);
// out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(verifyFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(verFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Verification ver = new Verification(root + separator + verName, verName, "flag", log,
this, lema, atacs);
// ver.addMouseListener(this);
// verPanel.add(ver);
// AbstPane abst = new AbstPane(root + separator + verName, ver,
// "flag", log, this, lema,
// atacs);
// abstPanel.add(abst);
// verTab.add("verify", verPanel);
// verTab.add("abstract", abstPanel);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
ver, "Verification");
}
}
private void openSim() {
String filename = tree.getFile();
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
filename.split(separator)[filename.split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
if (filename != null && !filename.equals("")) {
if (new File(filename).isDirectory()) {
if (new File(filename + separator + ".sim").exists()) {
new File(filename + separator + ".sim").delete();
}
String[] list = new File(filename).list();
String getAFile = "";
// String probFile = "";
String openFile = "";
// String graphFile = "";
String open = null;
String openProb = null;
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals("sbml")) {
getAFile = filename + separator + list[i];
}
else if (end.equals(".xml") && getAFile.equals("")) {
getAFile = filename + separator + list[i];
}
else if (end.equals(".txt") && list[i].contains("sim-rep")) {
// probFile = filename + separator + list[i];
}
else if (end.equals("ties") && list[i].contains("properties")
&& !(list[i].equals("species.properties"))) {
openFile = filename + separator + list[i];
}
else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")
|| end.contains("=")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = filename + separator +
// list[i];
}
}
else if (list[i].contains("euler-run.")
|| list[i].contains("gear1-run.")
|| list[i].contains("gear2-run.")
|| list[i].contains("rk4imp-run.")
|| list[i].contains("rk8pd-run.")
|| list[i].contains("rkf45-run.")) {
// graphFile = filename + separator +
// list[i];
}
else if (end.contains("=")) {
// graphFile = filename + separator +
// list[i];
}
}
else if (end.equals(".grf")) {
open = filename + separator + list[i];
}
else if (end.equals(".prb")) {
openProb = filename + separator + list[i];
}
}
else if (new File(filename + separator + list[i]).isDirectory()) {
String[] s = new File(filename + separator + list[i]).list();
for (int j = 0; j < s.length; j++) {
if (s[j].contains("sim-rep")) {
// probFile = filename + separator + list[i]
// + separator +
}
else if (s[j].contains(".tsd")) {
// graphFile = filename + separator +
// list[i] + separator +
}
}
}
}
if (!getAFile.equals("")) {
String[] split = filename.split(separator);
String simFile = root + separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim";
String pmsFile = root + separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".pms";
if (new File(pmsFile).exists()) {
if (new File(simFile).exists()) {
new File(pmsFile).delete();
}
else {
new File(pmsFile).renameTo(new File(simFile));
}
}
String sbmlLoadFile = "";
String gcmFile = "";
if (new File(simFile).exists()) {
try {
Scanner s = new Scanner(new File(simFile));
if (s.hasNextLine()) {
sbmlLoadFile = s.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1];
if (sbmlLoadFile.equals("")) {
JOptionPane
.showMessageDialog(
frame,
"Unable to open view because "
+ "the sbml linked to this view is missing.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!(new File(root + separator + sbmlLoadFile).exists())) {
JOptionPane.showMessageDialog(frame,
"Unable to open view because " + sbmlLoadFile
+ " is missing.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator
+ sbmlLoadFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + separator);
sbmlLoadFile = root + separator
+ split[split.length - 1].trim() + separator
+ sbmlLoadFile.replace(".gcm", ".sbml");
network.mergeSBML(sbmlLoadFile);
}
else if (sbmlLoadFile.contains(".lpn")) {
Translator t1 = new Translator();
t1.BuildTemplate(root + separator + sbmlLoadFile);
sbmlLoadFile = root + separator
+ split[split.length - 1].trim() + separator
+ sbmlLoadFile.replace(".lpn", ".sbml");
t1.setFilename(sbmlLoadFile);
t1.outputSBML();
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (s.hasNextLine()) {
s.nextLine();
}
s.close();
File f = new File(sbmlLoadFile);
if (!f.exists()) {
sbmlLoadFile = root + separator + f.getName();
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
else {
sbmlLoadFile = root
+ separator
+ getAFile.split(separator)[getAFile.split(separator).length - 1];
if (!new File(sbmlLoadFile).exists()) {
sbmlLoadFile = getAFile;
/*
* JOptionPane.showMessageDialog(frame, "Unable
* to load sbml file.", "Error",
* JOptionPane.ERROR_MESSAGE); return;
*/
}
}
if (!new File(sbmlLoadFile).exists()) {
JOptionPane.showMessageDialog(frame,
"Unable to open view because "
+ sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1] + " is missing.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this,
split[split.length - 1].trim(), log, simTab, openFile, gcmFile);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1)
.setName("Simulate");
simTab.addTab("Abstraction Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile,
this, log, true, split[split.length - 1].trim(), root
+ separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim",
reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(root + separator
+ gcm.getSBMLFile(), reb2sac, log, this, root + separator
+ split[split.length - 1].trim(), root + separator
+ split[split.length - 1].trim() + separator
+ split[split.length - 1].trim() + ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1)
.setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1)
.setName("");
gcm.setSBMLParamFile(null);
}
}
else if (gcmFile.contains(".sbml") || gcmFile.contains(".xml")) {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this,
root + separator + split[split.length - 1].trim(), root
+ separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
// if (open != null) {
Graph tsdGraph = reb2sac.createGraph(open);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"TSD Graph");
/*
* } else if (!graphFile.equals("")) {
* simTab.addTab("TSD Graph",
* reb2sac.createGraph(open));
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); } / else { JLabel noData =
* new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
// if (openProb != null) {
Graph probGraph = reb2sac.createProbGraph(openProb);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"ProbGraph");
/*
* } else if (!probFile.equals("")) {
* simTab.addTab("Probability Graph",
* reb2sac.createProbGraph(openProb));
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); } else { JLabel noData1 =
* new JLabel("No data available"); Font font1 =
* noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font1);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); }
*/
addTab(split[split.length - 1], simTab, null);
}
}
}
}
}
private class NewAction extends AbstractAction {
NewAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(newProj);
if (!async) {
popup.add(newCircuit);
popup.add(newModel);
}
else if (atacs) {
popup.add(newVhdl);
popup.add(newLhpn);
popup.add(newCsp);
popup.add(newHse);
popup.add(newUnc);
popup.add(newRsg);
}
else {
popup.add(newVhdl);
popup.add(newLhpn);
popup.add(newSpice);
}
popup.add(graph);
popup.add(probGraph);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class SaveAction extends AbstractAction {
SaveAction() {
super();
}
public void actionPerformed(ActionEvent e) {
if (!lema) {
popup.add(saveAsGcm);
}
else {
popup.add(saveAsLhpn);
}
popup.add(saveAsGraph);
if (!lema) {
popup.add(saveAsSbml);
popup.add(saveAsTemplate);
}
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class ImportAction extends AbstractAction {
ImportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
if (!lema) {
popup.add(importDot);
popup.add(importSbml);
popup.add(importBioModel);
}
else if (atacs) {
popup.add(importVhdl);
popup.add(importLpn);
popup.add(importCsp);
popup.add(importHse);
popup.add(importUnc);
popup.add(importRsg);
}
else {
popup.add(importVhdl);
popup.add(importS);
popup.add(importInst);
popup.add(importLpn);
popup.add(importSpice);
}
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class ExportAction extends AbstractAction {
ExportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(exportCsv);
popup.add(exportDat);
popup.add(exportEps);
popup.add(exportJpg);
popup.add(exportPdf);
popup.add(exportPng);
popup.add(exportSvg);
popup.add(exportTsd);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class ModelAction extends AbstractAction {
ModelAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(viewModGraph);
popup.add(viewModBrowser);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
public void mouseClicked(MouseEvent e) {
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(),
e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) {
enableTreeMenu();
}
else {
enableTabMenu(tab.getSelectedIndex());
}
}
}
}
public void mouseEntered(MouseEvent e) {
if (e.getSource() == tree.tree) {
setGlassPane(false);
}
else if (e.getSource() == popup) {
popupFlag = true;
setGlassPane(false);
}
else if (e.getSource() instanceof JMenuItem) {
menuFlag = true;
setGlassPane(false);
}
}
public void mouseExited(MouseEvent e) {
if (e.getSource() == tree.tree && !popupFlag && !menuFlag) {
setGlassPane(true);
}
else if (e.getSource() == popup) {
popupFlag = false;
if (!menuFlag) {
setGlassPane(true);
}
}
else if (e.getSource() instanceof JMenuItem) {
menuFlag = false;
if (!popupFlag) {
setGlassPane(true);
}
}
}
public void mouseDragged(MouseEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
try {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
catch (Exception e1) {
}
}
}
// public void componentHidden(ComponentEvent e) {
// log.addText("hidden");
// setGlassPane(true);
// public void componentResized(ComponentEvent e) {
// log.addText("resized");
// public void componentMoved(ComponentEvent e) {
// log.addText("moved");
// public void componentShown(ComponentEvent e) {
// log.addText("shown");
public void windowLostFocus(WindowEvent e) {
}
// public void focusGained(FocusEvent e) {
// public void focusLost(FocusEvent e) {
// log.addText("focus lost");
public JMenuItem getExitButton() {
return exit;
}
/**
* This is the main method. It excecutes the BioSim GUI FrontEnd program.
*/
public static void main(String args[]) {
boolean lemaFlag = false, atacsFlag = false;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-lema")) {
lemaFlag = true;
}
else if (args[i].equals("-atacs")) {
atacsFlag = true;
}
}
}
if (!lemaFlag && !atacsFlag) {
String varname;
if (System.getProperty("mrj.version") != null)
varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
else
varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
try {
System.loadLibrary("sbmlj");
// For extra safety, check that the jar file is in the
// classpath.
Class.forName("org.sbml.libsbml.libsbml");
}
catch (UnsatisfiedLinkError e) {
System.err.println("Error: could not link with the libSBML library."
+ " It is likely\nyour " + varname
+ " environment variable does not include\nthe"
+ " directory containing the libsbml library file.");
System.exit(1);
}
catch (ClassNotFoundException e) {
System.err.println("Error: unable to load the file libsbmlj.jar."
+ " It is likely\nyour " + varname + " environment"
+ " variable or CLASSPATH variable\ndoes not include"
+ " the directory containing the libsbmlj.jar file.");
System.exit(1);
}
catch (SecurityException e) {
System.err.println("Could not load the libSBML library files due to a"
+ " security exception.");
System.exit(1);
}
}
new BioSim(lemaFlag, atacsFlag);
}
public void copySim(String newSim) {
try {
new File(root + separator + newSim).mkdir();
// new FileWriter(new File(root + separator + newSim + separator +
// ".sim")).close();
String oldSim = tab.getTitleAt(tab.getSelectedIndex());
String[] s = new File(root + separator + oldSim).list();
String sbmlFile = "";
String propertiesFile = "";
String sbmlLoadFile = null;
String gcmFile = null;
for (String ss : s) {
if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")
|| ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) {
SBMLDocument document = readSBML(root + separator + oldSim + separator + ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + newSim + separator + ss);
sbmlFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root + separator + newSim
+ separator + ss));
FileInputStream in = new FileInputStream(new File(root + separator + oldSim
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
propertiesFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".dat")
|| ss.substring(ss.length() - 4).equals(".sad")
|| ss.substring(ss.length() - 4).equals(".pms") || ss.substring(
ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator + newSim + separator
+ newSim + ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator + newSim + separator
+ newSim + ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator + newSim + separator
+ ss));
}
FileInputStream in = new FileInputStream(new File(root + separator + oldSim
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
if (ss.substring(ss.length() - 4).equals(".pms")) {
if (new File(root + separator + newSim + separator
+ ss.substring(0, ss.length() - 4) + ".sim").exists()) {
new File(root + separator + newSim + separator + ss).delete();
}
else {
new File(root + separator + newSim + separator + ss).renameTo(new File(
root + separator + newSim + separator
+ ss.substring(0, ss.length() - 4) + ".sim"));
}
ss = ss.substring(0, ss.length() - 4) + ".sim";
}
if (ss.substring(ss.length() - 4).equals(".sim")) {
try {
Scanner scan = new Scanner(new File(root + separator + newSim
+ separator + ss));
if (scan.hasNextLine()) {
sbmlLoadFile = scan.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1];
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator
+ sbmlLoadFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + separator);
sbmlLoadFile = root + separator + newSim + separator
+ sbmlLoadFile.replace(".gcm", ".sbml");
network.mergeSBML(sbmlLoadFile);
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (scan.hasNextLine()) {
scan.nextLine();
}
scan.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
refreshTree();
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab,
propertiesFile, gcmFile);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
simTab.addTab("Abstraction Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options", reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true,
newSim, root + separator + newSim + separator + newSim + ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(),
reb2sac, log, this, root + separator + newSim, root + separator
+ newSim + separator + newSim + ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(null);
}
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root
+ separator + newSim, root + separator + newSim + separator + newSim
+ ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
tab.setComponentAt(tab.getSelectedIndex(), simTab);
tab.setTitleAt(tab.getSelectedIndex(), newSim);
tab.getComponentAt(tab.getSelectedIndex()).setName(newSim);
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void refreshLearn(String learnName, boolean data) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnName)) {
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals(
"TSD Graph")) {
// if (data) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) {
((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j))
.refresh();
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null,
"Number of molecules", learnName + " data", "tsd.printer", root
+ separator + learnName, "Time", this, null, log, null,
true, true));
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName(
"TSD Graph");
}
/*
* } else { JLabel noData1 = new
* JLabel("No data available"); Font font =
* noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER); ((JTabbedPane)
* tab.getComponentAt(i)).setComponentAt(j, noData1);
* ((JTabbedPane)
* tab.getComponentAt(i)).getComponentAt(j
* ).setName("TSD Graph"); }
*/
}
else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName()
.equals("Learn")) {
// if (data) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) {
}
else {
if (lema) {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j,
new LearnLHPN(root + separator + learnName, log, this));
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn(
root + separator + learnName, log, this));
}
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)
.setName("Learn");
}
/*
* } else { JLabel noData = new
* JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* ((JTabbedPane)
* tab.getComponentAt(i)).setComponentAt(j, noData);
* ((JTabbedPane)
* tab.getComponentAt(i)).getComponentAt(j
* ).setName("Learn"); }
*/
}
}
}
}
}
private void updateGCM() {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).contains(".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles();
tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename());
}
}
}
public void updateAsyncViews(String updatedFile) {
// log.addText(updatedFile);
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
String properties = root + separator + tab + separator + tab + ".ver";
String properties1 = root + separator + tab + separator + tab + ".synth";
String properties2 = root + separator + tab + separator + tab + ".lrn";
// log.addText(properties + "\n" + properties1 + "\n" + properties2
if (new File(properties).exists()) {
// String check = "";
// try {
// Scanner s = new Scanner(new File(properties));
// if (s.hasNextLine()) {
// check = s.nextLine();
// check = check.split(separator)[check.split(separator).length
// s.close();
// catch (Exception e) {
// if (check.equals(updatedFile)) {
Verification verify = ((Verification) (this.tab.getComponentAt(i)));
verify.reload(updatedFile);
}
if (new File(properties1).exists()) {
// String check = "";
// try {
// Scanner s = new Scanner(new File(properties1));
// if (s.hasNextLine()) {
// check = s.nextLine();
// check = check.split(separator)[check.split(separator).length
// s.close();
// catch (Exception e) {
// if (check.equals(updatedFile)) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
if (sim.getComponentAt(j).getName().equals("Synthesis")) {
// new File(properties).renameTo(new
// File(properties.replace(".synth",
// ".temp")));
// boolean dirty = ((SBML_Editor)
// (sim.getComponentAt(j))).isDirty();
((Synthesis) (sim.getComponentAt(j))).reload(updatedFile);
// if (updatedFile.contains(".g")) {
// GCMParser parser = new GCMParser(root + separator +
// updatedFile);
// GeneticNetwork network = parser.buildNetwork();
// GeneticNetwork.setRoot(root + File.separator);
// network.mergeSBML(root + separator + tab + separator
// + updatedFile.replace(".g", ".vhd"));
// ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i,
// j, root
// + separator + tab + separator
// + updatedFile.replace(".g", ".vhd"));
// else {
// ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i,
// j, root
// + separator + updatedFile);
// ((SBML_Editor)
// (sim.getComponentAt(j))).setDirty(dirty);
// new File(properties).delete();
// new File(properties.replace(".synth",
// ".temp")).renameTo(new
// File(
// properties));
// sim.setComponentAt(j + 1, ((SBML_Editor)
// (sim.getComponentAt(j)))
// .getElementsPanel());
// sim.getComponentAt(j + 1).setName("");
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn")) {
((LearnLHPN) (learn.getComponentAt(j))).updateSpecies(root + separator
+ updatedFile);
((LearnLHPN) (learn.getComponentAt(j))).reload(updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
}
}
public void updateViews(String updatedFile) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
String properties = root + separator + tab + separator + tab + ".sim";
String properties2 = root + separator + tab + separator + tab + ".lrn";
if (new File(properties).exists()) {
String check = "";
try {
Scanner s = new Scanner(new File(properties));
if (s.hasNextLine()) {
check = s.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
s.close();
}
catch (Exception e) {
}
if (check.equals(updatedFile)) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
if (sim.getComponentAt(j).getName().equals("SBML Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim",
".temp")));
boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty();
((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true);
if (updatedFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator + updatedFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + separator);
network.mergeSBML(root + separator + tab + separator
+ updatedFile.replace(".gcm", ".sbml"));
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root
+ separator + tab + separator
+ updatedFile.replace(".gcm", ".sbml"));
}
else {
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root
+ separator + updatedFile);
}
((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(
properties));
sim.setComponentAt(j + 1, ((SBML_Editor) (sim.getComponentAt(j)))
.getElementsPanel());
sim.getComponentAt(j + 1).setName("");
}
else if (sim.getComponentAt(j).getName().equals("GCM Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim",
".temp")));
boolean dirty = ((GCM2SBMLEditor) (sim.getComponentAt(j))).isDirty();
((GCM2SBMLEditor) (sim.getComponentAt(j))).saveParams(false, "");
((GCM2SBMLEditor) (sim.getComponentAt(j))).reload(check.replace(".gcm",
""));
((GCM2SBMLEditor) (sim.getComponentAt(j))).refresh();
((GCM2SBMLEditor) (sim.getComponentAt(j))).loadParams();
((GCM2SBMLEditor) (sim.getComponentAt(j))).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(
properties));
if (!((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile().equals(
"--none
SBML_Editor sbml = new SBML_Editor(root + separator
+ ((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile(),
((Reb2Sac) sim.getComponentAt(0)), log, this, root
+ separator + tab, root + separator + tab
+ separator + tab + ".sim");
sim.setComponentAt(j + 1, sbml.getElementsPanel());
sim.getComponentAt(j + 1).setName("");
((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
sim.setComponentAt(j + 1, scroll);
sim.getComponentAt(j + 1).setName("");
((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(null);
}
}
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn")) {
((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator
+ updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
ArrayList<String> saved = new ArrayList<String>();
if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) {
saved.add(this.tab.getTitleAt(i));
GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i);
if (gcm.getSBMLFile().equals(updatedFile)) {
gcm.save("save");
}
}
String[] files = new File(root).list();
for (String s : files) {
if (s.contains(".gcm") && !saved.contains(s)) {
GCMFile gcm = new GCMFile(root);
gcm.load(root + separator + s);
if (gcm.getSBMLFile().equals(updatedFile)) {
updateViews(s);
}
}
}
}
}
private void updateViewNames(String oldname, String newname) {
File work = new File(root);
String[] fileList = work.list();
String[] temp = oldname.split(separator);
oldname = temp[temp.length - 1];
for (int i = 0; i < fileList.length; i++) {
String tabTitle = fileList[i];
String properties = root + separator + tabTitle + separator + tabTitle + ".ver";
String properties1 = root + separator + tabTitle + separator + tabTitle + ".synth";
String properties2 = root + separator + tabTitle + separator + tabTitle + ".lrn";
if (new File(properties).exists()) {
String check;
Properties p = new Properties();
try {
FileInputStream load = new FileInputStream(new File(properties));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("verification.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties));
p.store(out, properties);
}
}
catch (Exception e) {
// log.addText("verification");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties1).exists()) {
String check;
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties1));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("synthesis.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties1));
p.store(out, properties1);
}
}
catch (Exception e) {
// log.addText("synthesis");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("learn.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties2));
p.store(out, properties2);
}
}
catch (Exception e) {
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
}
updateAsyncViews(newname);
}
public void enableTabMenu(int selectedTab) {
treeSelected = false;
// log.addText("tab menu");
if (selectedTab != -1) {
tab.setSelectedIndex(selectedTab);
}
Component comp = tab.getSelectedComponent();
// if (comp != null) {
// log.addText(comp.toString());
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
viewSG.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
if (comp instanceof GCM2SBMLEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(true);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(true);
saveAsTemplate.setEnabled(true);
// saveGcmAsLhpn.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(true);
saveTemp.setEnabled(true);
viewModGraph.setEnabled(true);
}
else if (comp instanceof LHPNEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(true);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(true);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
viewModGraph.setEnabled(true);
}
else if (comp instanceof SBML_Editor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(true);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(true);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(true);
saveTemp.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(true);
}
else if (comp instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(true);
checkButton.setEnabled(false);
exportButton.setEnabled(true);
save.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(true);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(true);
refresh.setEnabled(true);
check.setEnabled(false);
export.setEnabled(true);
exportMenu.setEnabled(true);
if (((Graph) comp).isTSDGraph()) {
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
else {
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportTsd.setEnabled(false);
}
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
Boolean learn = false;
for (Component c : ((JTabbedPane) comp).getComponents()) {
if (c instanceof Learn) {
learn = true;
}
else if (c instanceof GCM2SBMLEditor) {
for (String s : new File(root + separator
+ tab.getTitleAt(tab.getSelectedIndex())).list()) {
if (s.contains("_sg.dot")) {
viewSG.setEnabled(true);
}
}
}
}
// int index = tab.getSelectedIndex();
if (component instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
if (learn) {
runButton.setEnabled(false);
}
else {
runButton.setEnabled(true);
}
refreshButton.setEnabled(true);
checkButton.setEnabled(false);
exportButton.setEnabled(true);
save.setEnabled(true);
if (learn) {
run.setEnabled(false);
saveModel.setEnabled(true);
}
else {
run.setEnabled(true);
saveModel.setEnabled(false);
}
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(true);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(true);
check.setEnabled(false);
export.setEnabled(true);
exportMenu.setEnabled(true);
if (((Graph) component).isTSDGraph()) {
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
else {
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportTsd.setEnabled(false);
}
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof Reb2Sac) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof SBML_Editor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof GCM2SBMLEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof Learn) {
if (((Learn) component).isComboSelected()) {
frame.getGlassPane().setVisible(false);
}
// saveButton.setEnabled(((Learn)
// component).getSaveGcmEnabled());
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// save.setEnabled(((Learn) component).getSaveGcmEnabled());
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewModGraph.setEnabled(((Learn) component).getViewGcmEnabled());
viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled());
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(((Learn) component).getViewLogEnabled());
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// viewCoverage.setEnabled(((Learn)
// component).getViewCoverageEnabled()); // SB
// saveParam.setEnabled(true);
saveModel.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof LearnLHPN) {
if (((LearnLHPN) component).isComboSelected()) {
frame.getGlassPane().setVisible(false);
}
// saveButton.setEnabled(((LearnLHPN)
// component).getSaveLhpnEnabled());
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// save.setEnabled(((LearnLHPN)
// component).getSaveLhpnEnabled());
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled());
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled());
viewCoverage.setEnabled(((LearnLHPN) component).getViewCoverageEnabled());
viewVHDL.setEnabled(((LearnLHPN) component).getViewVHDLEnabled());
viewVerilog.setEnabled(((LearnLHPN) component).getViewVerilogEnabled());
viewLHPN.setEnabled(((LearnLHPN) component).getViewLhpnEnabled());
// saveParam.setEnabled(true);
saveModel.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof DataManager) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(true);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// /saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof JPanel) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof JScrollPane) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Verification")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(true);
viewRules.setEnabled(false); // always false??
// viewTrace.setEnabled(((Verification)
// comp).getViewTraceEnabled());
viewTrace.setEnabled(((Verification) comp).getViewTraceEnabled()); // Should
// true
// only
// verification
// Result
// available???
viewCircuit.setEnabled(false); // always true???
// viewLog.setEnabled(((Verification)
// comp).getViewLogEnabled());
viewLog.setEnabled(((Verification) comp).getViewLogEnabled()); // Should
// true
// only
// log
// available???
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
}
else if (comp.getName().equals("Synthesis")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true); // always true??
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(true);
// viewRules.setEnabled(((Synthesis)
// comp).getViewRulesEnabled());
// viewTrace.setEnabled(((Synthesis)
// comp).getViewTraceEnabled());
// viewCircuit.setEnabled(((Synthesis)
// comp).getViewCircuitEnabled());
// viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled());
viewRules.setEnabled(((Synthesis) comp).getViewRulesEnabled());
viewTrace.setEnabled(((Synthesis) comp).getViewTraceEnabled()); // Always
viewCircuit.setEnabled(((Synthesis) comp).getViewCircuitEnabled()); // Always
viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled());
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
}
}
else if (comp instanceof JScrollPane) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else {
saveButton.setEnabled(false);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// /saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
}
private void enableTreeMenu() {
treeSelected = true;
// log.addText(tree.getFile());
saveButton.setEnabled(false);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
exportMenu.setEnabled(false);
save.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
// saveGcmAsLhpn.setEnabled(false);
viewSG.setEnabled(false);
if (tree.getFile() != null) {
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
viewModGraph.setEnabled(true);
viewModGraph.setActionCommand("graph");
viewModBrowser.setEnabled(true);
createAnal.setEnabled(true);
createAnal.setActionCommand("simulate");
createLearn.setEnabled(true);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
viewModGraph.setEnabled(true);
// viewModGraph.setActionCommand("graphDot");
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSbml.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// /saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(true);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
save.setEnabled(true); // SB should be????
// saveas too ????
// viewLog should be available ???
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(true);
viewLHPN.setEnabled(false);
save.setEnabled(true); // SB should be????
// saveas too ????
// viewLog should be available ???
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
if (new File(root + separator + "atacs.log").exists()) {
viewLog.setEnabled(true);
}
else {
viewLog.setEnabled(false);
}
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
if (new File(root + separator + "atacs.log").exists()) {
viewLog.setEnabled(true);
}
else {
viewLog.setEnabled(false);
}
// not displaying the correct log too ????? SB
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(true); // SB true ??? since lpn
save.setEnabled(true); // SB should exist ???
// saveas too???
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
if (sim || synth || ver || learn) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
else {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
}
public String getRoot() {
return root;
}
public void setGlassPane(boolean visible) {
frame.getGlassPane().setVisible(visible);
}
public boolean overwrite(String fullPath, String name) {
if (new File(fullPath).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, name + " already exists."
+ "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
String[] views = canDelete(name);
if (views.length == 0) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(name)) {
tab.remove(i);
}
}
File dir = new File(fullPath);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
return true;
}
else {
String view = "";
for (int i = 0; i < views.length; i++) {
if (i == views.length - 1) {
view += views[i];
}
else {
view += views[i] + "\n";
}
}
String message = "Unable to overwrite file."
+ "\nIt is linked to the following views:\n" + view
+ "\nDelete these views first.";
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(frame, scroll, "Unable To Overwrite File",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else {
return false;
}
}
else {
return true;
}
}
public boolean updateOpenSBML(String sbmlName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
if (sbmlName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof SBML_Editor) {
SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log,
this, null, null);
this.tab.setComponentAt(i, newSBML);
this.tab.getComponentAt(i).setName("SBML Editor");
newSBML.save(false, "", false);
return true;
}
}
}
return false;
}
public boolean updateOpenLHPN(String lhpnName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
if (lhpnName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof LHPNEditor) {
LHPNEditor newLHPN = new LHPNEditor(root, lhpnName, null, this, log);
this.tab.setComponentAt(i, newLHPN);
this.tab.getComponentAt(i).setName("LHPN Editor");
return true;
}
}
}
return false;
}
private String[] canDelete(String filename) {
ArrayList<String> views = new ArrayList<String>();
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
Scanner scan = new Scanner(new File(root + separator + s + separator + s
+ ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
scan.close();
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".ver").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".synth").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
if (check.equals(filename)) {
views.add(s);
}
}
}
String[] usingViews = views.toArray(new String[0]);
sort(usingViews);
return usingViews;
}
private void sort(String[] sort) {
int i, j;
String index;
for (i = 1; i < sort.length; i++) {
index = sort[i];
j = i;
while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) {
sort[j] = sort[j - 1];
j = j - 1;
}
sort[j] = index;
}
}
private void reassignViews(String oldName, String newName) {
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
ArrayList<String> copy = new ArrayList<String>();
Scanner scan = new Scanner(new File(root + separator + s + separator + s
+ ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
if (check.equals(oldName)) {
while (scan.hasNextLine()) {
copy.add(scan.nextLine());
}
scan.close();
FileOutputStream out = new FileOutputStream(new File(root
+ separator + s + separator + s + ".sim"));
out.write((newName + "\n").getBytes());
for (String cop : copy) {
out.write((cop + "\n").getBytes());
}
out.close();
}
else {
scan.close();
}
}
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
if (check.equals(oldName)) {
p.setProperty("genenet.file", newName);
FileOutputStream store = new FileOutputStream(new File(root
+ separator + s + separator + s + ".lrn"));
p.store(store, "Learn File Data");
store.close();
}
}
}
catch (Exception e) {
}
}
}
}
}
protected JButton makeToolButton(String imageName, String actionCommand, String toolTipText,
String altText) {
// URL imageURL = BioSim.class.getResource(imageName);
// Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
button.setIcon(new ImageIcon(imageName));
// if (imageURL != null) { //image found
// button.setIcon(new ImageIcon(imageURL, altText));
// } else { //no image found
// button.setText(altText);
// System.err.println("Resource not found: "
// + imageName);
return button;
}
public static SBMLDocument readSBML(String filename) {
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(filename);
JTextArea messageArea = new JTextArea();
messageArea.append("Conversion to SBML level " + SBML_LEVEL + " version " + SBML_VERSION
+ " produced the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n");
boolean display = false;
long numErrors = document.checkL2v4Compatibility();
if (numErrors > 0) {
display = true;
messageArea
.append("
messageArea.append(filename);
messageArea
.append("\n
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
}
if (display) {
final JFrame f = new JFrame("SBML Conversion Errors and Warnings");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
document.setLevelAndVersion(SBML_LEVEL, SBML_VERSION);
return document;
}
public static void checkModelCompleteness(SBMLDocument document) {
JTextArea messageArea = new JTextArea();
messageArea
.append("Model is incomplete. Cannot be simulated until the following information is provided.\n");
boolean display = false;
Model model = document.getModel();
ListOf list = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
Compartment compartment = (Compartment) list.get(i);
if (!compartment.isSetSize()) {
messageArea
.append("
messageArea.append("Compartment " + compartment.getId() + " needs a size.\n");
display = true;
}
}
list = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) list.get(i);
if (!(species.isSetInitialAmount()) && !(species.isSetInitialConcentration())) {
messageArea
.append("
messageArea.append("Species " + species.getId()
+ " needs an initial amount or concentration.\n");
display = true;
}
}
list = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter parameter = (Parameter) list.get(i);
if (!(parameter.isSetValue())) {
messageArea
.append("
messageArea.append("Parameter " + parameter.getId() + " needs an initial value.\n");
display = true;
}
}
list = model.getListOfReactions();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) list.get(i);
if (!(reaction.isSetKineticLaw())) {
messageArea
.append("
messageArea.append("Reaction " + reaction.getId() + " needs a kinetic law.\n");
display = true;
}
else {
ListOf params = reaction.getKineticLaw().getListOfParameters();
for (int j = 0; j < reaction.getKineticLaw().getNumParameters(); j++) {
Parameter param = (Parameter) params.get(j);
if (!(param.isSetValue())) {
messageArea
.append("
messageArea.append("Local parameter " + param.getId() + " for reaction "
+ reaction.getId() + " needs an initial value.\n");
display = true;
}
}
}
}
if (display) {
final JFrame f = new JFrame("SBML Model Completeness Errors");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
}
}
|
package org.jetel.ctl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import junit.framework.AssertionFailedError;
import org.jetel.component.CTLRecordTransform;
import org.jetel.component.RecordTransform;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.SetVal;
import org.jetel.data.lookup.LookupTable;
import org.jetel.data.lookup.LookupTableFactory;
import org.jetel.data.primitive.Decimal;
import org.jetel.data.sequence.Sequence;
import org.jetel.data.sequence.SequenceFactory;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.TransformException;
import org.jetel.graph.ContextProvider;
import org.jetel.graph.ContextProvider.Context;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataFieldContainerType;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataFieldType;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.test.CloverTestCase;
import org.jetel.util.MiscUtils;
import org.jetel.util.bytes.PackedDecimal;
import org.jetel.util.crypto.Base64;
import org.jetel.util.crypto.Digest;
import org.jetel.util.crypto.Digest.DigestType;
import org.jetel.util.primitive.TypedProperties;
import org.jetel.util.string.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Years;
import sun.misc.Cleaner;
public abstract class CompilerTestCase extends CloverTestCase {
protected static final String INPUT_1 = "firstInput";
protected static final String INPUT_2 = "secondInput";
protected static final String INPUT_3 = "thirdInput";
protected static final String INPUT_4 = "multivalueInput";
protected static final String OUTPUT_1 = "firstOutput";
protected static final String OUTPUT_2 = "secondOutput";
protected static final String OUTPUT_3 = "thirdOutput";
protected static final String OUTPUT_4 = "fourthOutput";
protected static final String OUTPUT_5 = "firstMultivalueOutput";
protected static final String OUTPUT_6 = "secondMultivalueOutput";
protected static final String OUTPUT_7 = "thirdMultivalueOutput";
protected static final String LOOKUP = "lookupMetadata";
protected static final String NAME_VALUE = " HELLO ";
protected static final Double AGE_VALUE = 20.25;
protected static final String CITY_VALUE = "Chong'La";
protected static final Date BORN_VALUE;
protected static final Long BORN_MILLISEC_VALUE;
static {
Calendar c = Calendar.getInstance();
c.set(2008, 12, 25, 13, 25, 55);
c.set(Calendar.MILLISECOND, 333);
BORN_VALUE = c.getTime();
BORN_MILLISEC_VALUE = c.getTimeInMillis();
}
protected static final Integer VALUE_VALUE = Integer.MAX_VALUE - 10;
protected static final Boolean FLAG_VALUE = true;
protected static final byte[] BYTEARRAY_VALUE = "Abeceda zedla deda".getBytes();
protected static final BigDecimal CURRENCY_VALUE = new BigDecimal("133.525");
protected static final int DECIMAL_PRECISION = 7;
protected static final int DECIMAL_SCALE = 3;
protected static final int NORMALIZE_RETURN_OK = 0;
public static final int DECIMAL_MAX_PRECISION = 32;
public static final MathContext MAX_PRECISION = new MathContext(DECIMAL_MAX_PRECISION,RoundingMode.DOWN);
/** Flag to trigger Java compilation */
private boolean compileToJava;
protected DataRecord[] inputRecords;
protected DataRecord[] outputRecords;
protected TransformationGraph graph;
public CompilerTestCase(boolean compileToJava) {
this.compileToJava = compileToJava;
}
/**
* Method to execute tested CTL code in a way specific to testing scenario.
*
* Assumes that
* {@link #graph}, {@link #inputRecords} and {@link #outputRecords}
* have already been set.
*
* @param compiler
*/
public abstract void executeCode(ITLCompiler compiler);
/**
* Method which provides access to specified global variable
*
* @param varName
* global variable to be accessed
* @return
*
*/
protected abstract Object getVariable(String varName);
protected void check(String varName, Object expectedResult) {
assertEquals(varName, expectedResult, getVariable(varName));
}
protected void checkEquals(String varName1, String varName2) {
assertEquals("Comparing " + varName1 + " and " + varName2 + " : ", getVariable(varName1), getVariable(varName2));
}
protected void checkNull(String varName) {
assertNull(getVariable(varName));
}
private void checkArray(String varName, byte[] expected) {
byte[] actual = (byte[]) getVariable(varName);
assertTrue("Arrays do not match; expected: " + byteArrayAsString(expected) + " but was " + byteArrayAsString(actual), Arrays.equals(actual, expected));
}
private static String byteArrayAsString(byte[] array) {
final StringBuilder sb = new StringBuilder("[");
for (final byte b : array) {
sb.append(b);
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
sb.append(']');
return sb.toString();
}
@Override
protected void setUp() {
// set default locale to English to prevent various parsing errors
Locale.setDefault(Locale.ENGLISH);
initEngine();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
inputRecords = null;
outputRecords = null;
graph = null;
}
protected TransformationGraph createEmptyGraph() {
return new TransformationGraph();
}
protected TransformationGraph createDefaultGraph() {
TransformationGraph g = createEmptyGraph();
// set the context URL, so that imports can be used
g.getRuntimeContext().setContextURL(CompilerTestCase.class.getResource("."));
final HashMap<String, DataRecordMetadata> metadataMap = new HashMap<String, DataRecordMetadata>();
metadataMap.put(INPUT_1, createDefaultMetadata(INPUT_1));
metadataMap.put(INPUT_2, createDefaultMetadata(INPUT_2));
metadataMap.put(INPUT_3, createDefaultMetadata(INPUT_3));
metadataMap.put(INPUT_4, createDefaultMultivalueMetadata(INPUT_4));
metadataMap.put(OUTPUT_1, createDefaultMetadata(OUTPUT_1));
metadataMap.put(OUTPUT_2, createDefaultMetadata(OUTPUT_2));
metadataMap.put(OUTPUT_3, createDefaultMetadata(OUTPUT_3));
metadataMap.put(OUTPUT_4, createDefault1Metadata(OUTPUT_4));
metadataMap.put(OUTPUT_5, createDefaultMultivalueMetadata(OUTPUT_5));
metadataMap.put(OUTPUT_6, createDefaultMultivalueMetadata(OUTPUT_6));
metadataMap.put(OUTPUT_7, createDefaultMultivalueMetadata(OUTPUT_7));
metadataMap.put(LOOKUP, createDefaultMetadata(LOOKUP));
g.addDataRecordMetadata(metadataMap);
g.addSequence(createDefaultSequence(g, "TestSequence"));
g.addLookupTable(createDefaultLookup(g, "TestLookup"));
Properties properties = new Properties();
properties.put("PROJECT", ".");
properties.put("DATAIN_DIR", "${PROJECT}/data-in");
properties.put("COUNT", "`1+2`");
properties.put("NEWLINE", "\\n");
g.setGraphProperties(properties);
initDefaultDictionary(g);
return g;
}
private void initDefaultDictionary(TransformationGraph g) {
try {
g.getDictionary().init();
g.getDictionary().setValue("s", "string", null);
g.getDictionary().setValue("i", "integer", null);
g.getDictionary().setValue("l", "long", null);
g.getDictionary().setValue("d", "decimal", null);
g.getDictionary().setValue("n", "number", null);
g.getDictionary().setValue("a", "date", null);
g.getDictionary().setValue("b", "boolean", null);
g.getDictionary().setValue("y", "byte", null);
g.getDictionary().setValue("i211", "integer", new Integer(211));
g.getDictionary().setValue("sVerdon", "string", "Verdon");
g.getDictionary().setValue("l452", "long", new Long(452));
g.getDictionary().setValue("d621", "decimal", new BigDecimal(621));
g.getDictionary().setValue("n9342", "number", new Double(934.2));
g.getDictionary().setValue("a1992", "date", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime());
g.getDictionary().setValue("bTrue", "boolean", Boolean.TRUE);
g.getDictionary().setValue("yFib", "byte", new byte[]{1,2,3,5,8,13,21,34,55,89} );
g.getDictionary().setValue("stringList", "list", Arrays.asList("aa", "bb", null, "cc"));
g.getDictionary().setContentType("stringList", "string");
g.getDictionary().setValue("dateList", "list", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000)));
g.getDictionary().setContentType("dateList", "date");
g.getDictionary().setValue("byteList", "list", Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78}));
g.getDictionary().setContentType("byteList", "byte");
} catch (ComponentNotReadyException e) {
throw new RuntimeException("Error init default dictionary", e);
}
}
protected Sequence createDefaultSequence(TransformationGraph graph, String name) {
Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE", new Object[] { "Sequence0", graph, name }, new Class[] { String.class, TransformationGraph.class, String.class });
try {
seq.checkConfig(new ConfigurationStatus());
seq.init();
} catch (ComponentNotReadyException e) {
throw new RuntimeException(e);
}
return seq;
}
/**
* Creates default lookup table of type SimpleLookupTable with 4 records using default metadata and a composite
* lookup key Name+Value. Use field City for testing response.
*
* @param graph
* @param name
* @return
*/
protected LookupTable createDefaultLookup(TransformationGraph graph, String name) {
final TypedProperties props = new TypedProperties();
props.setProperty("id", "LookupTable0");
props.setProperty("type", "simpleLookup");
props.setProperty("metadata", LOOKUP);
props.setProperty("key", "Name;Value");
props.setProperty("name", name);
props.setProperty("keyDuplicates", "true");
/*
* The test lookup table is populated from file TestLookup.dat. Alternatively uncomment the populating code
* below, however this will most probably break down test_lookup() because free() will wipe away all data and
* noone will restore them
*/
URL dataFile = getClass().getSuperclass().getResource("TestLookup.dat");
if (dataFile == null) {
throw new RuntimeException("Unable to populate testing lookup table. File 'TestLookup.dat' not found by classloader");
}
props.setProperty("fileURL", dataFile.getFile());
LookupTableFactory.init();
LookupTable lkp = LookupTableFactory.createLookupTable(props);
lkp.setGraph(graph);
try {
lkp.checkConfig(new ConfigurationStatus());
lkp.init();
lkp.preExecute();
} catch (ComponentNotReadyException ex) {
throw new RuntimeException(ex);
}
/*DataRecord lkpRecord = createEmptyRecord(createDefaultMetadata("lookupResponse"));
lkpRecord.getField("Name").setValue("Alpha");
lkpRecord.getField("Value").setValue(1);
lkpRecord.getField("City").setValue("Andorra la Vella");
lkp.put(lkpRecord);
lkpRecord.getField("Name").setValue("Bravo");
lkpRecord.getField("Value").setValue(2);
lkpRecord.getField("City").setValue("Bruxelles");
lkp.put(lkpRecord);
// duplicate entry
lkpRecord.getField("Name").setValue("Charlie");
lkpRecord.getField("Value").setValue(3);
lkpRecord.getField("City").setValue("Chamonix");
lkp.put(lkpRecord);
lkpRecord.getField("Name").setValue("Charlie");
lkpRecord.getField("Value").setValue(3);
lkpRecord.getField("City").setValue("Chomutov");
lkp.put(lkpRecord);*/
return lkp;
}
/**
* Creates records with default structure
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefaultMetadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
ret.addField(new DataFieldMetadata("Name", DataFieldType.STRING, "|"));
ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|"));
ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|"));
DataFieldMetadata dateField = new DataFieldMetadata("Born", DataFieldType.DATE, "|");
dateField.setFormatStr("yyyy-MM-dd HH:mm:ss");
ret.addField(dateField);
ret.addField(new DataFieldMetadata("BornMillisec", DataFieldType.LONG, "|"));
ret.addField(new DataFieldMetadata("Value", DataFieldType.INTEGER, "|"));
ret.addField(new DataFieldMetadata("Flag", DataFieldType.BOOLEAN, "|"));
ret.addField(new DataFieldMetadata("ByteArray", DataFieldType.BYTE, "|"));
DataFieldMetadata decimalField = new DataFieldMetadata("Currency", DataFieldType.DECIMAL, "\n");
decimalField.setProperty(DataFieldMetadata.LENGTH_ATTR, String.valueOf(DECIMAL_PRECISION));
decimalField.setProperty(DataFieldMetadata.SCALE_ATTR, String.valueOf(DECIMAL_SCALE));
ret.addField(decimalField);
return ret;
}
/**
* Creates records with default structure
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefault1Metadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
ret.addField(new DataFieldMetadata("Field1", DataFieldType.STRING, "|"));
ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|"));
ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|"));
return ret;
}
/**
* Creates records with default structure
* containing multivalue fields.
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefaultMultivalueMetadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
DataFieldMetadata stringListField = new DataFieldMetadata("stringListField", DataFieldType.STRING, "|");
stringListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(stringListField);
DataFieldMetadata dateField = new DataFieldMetadata("dateField", DataFieldType.DATE, "|");
ret.addField(dateField);
DataFieldMetadata byteField = new DataFieldMetadata("byteField", DataFieldType.BYTE, "|");
ret.addField(byteField);
DataFieldMetadata dateListField = new DataFieldMetadata("dateListField", DataFieldType.DATE, "|");
dateListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(dateListField);
DataFieldMetadata byteListField = new DataFieldMetadata("byteListField", DataFieldType.BYTE, "|");
byteListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(byteListField);
DataFieldMetadata stringField = new DataFieldMetadata("stringField", DataFieldType.STRING, "|");
ret.addField(stringField);
DataFieldMetadata integerMapField = new DataFieldMetadata("integerMapField", DataFieldType.INTEGER, "|");
integerMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(integerMapField);
DataFieldMetadata stringMapField = new DataFieldMetadata("stringMapField", DataFieldType.STRING, "|");
stringMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(stringMapField);
DataFieldMetadata dateMapField = new DataFieldMetadata("dateMapField", DataFieldType.DATE, "|");
dateMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(dateMapField);
DataFieldMetadata byteMapField = new DataFieldMetadata("byteMapField", DataFieldType.BYTE, "|");
byteMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(byteMapField);
DataFieldMetadata integerListField = new DataFieldMetadata("integerListField", DataFieldType.INTEGER, "|");
integerListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(integerListField);
DataFieldMetadata decimalListField = new DataFieldMetadata("decimalListField", DataFieldType.DECIMAL, "|");
decimalListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(decimalListField);
DataFieldMetadata decimalMapField = new DataFieldMetadata("decimalMapField", DataFieldType.DECIMAL, "|");
decimalMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(decimalMapField);
return ret;
}
protected DataRecord createDefaultMultivalueRecord(DataRecordMetadata dataRecordMetadata) {
final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata);
ret.init();
for (int i = 0; i < ret.getNumFields(); i++) {
DataField field = ret.getField(i);
DataFieldMetadata fieldMetadata = field.getMetadata();
switch (fieldMetadata.getContainerType()) {
case SINGLE:
switch (fieldMetadata.getDataType()) {
case STRING:
field.setValue("John");
break;
case DATE:
field.setValue(new Date(10000));
break;
case BYTE:
field.setValue(new byte[] { 0x12, 0x34, 0x56, 0x78 } );
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
break;
case LIST:
{
List<Object> value = new ArrayList<Object>();
switch (fieldMetadata.getDataType()) {
case STRING:
value.addAll(Arrays.asList("John", "Doe", "Jersey"));
break;
case INTEGER:
value.addAll(Arrays.asList(123, 456, 789));
break;
case DATE:
value.addAll(Arrays.asList(new Date (12000), new Date(34000)));
break;
case BYTE:
value.addAll(Arrays.asList(new byte[] {0x12, 0x34}, new byte[] {0x56, 0x78}));
break;
case DECIMAL:
value.addAll(Arrays.asList(12.34, 56.78));
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
field.setValue(value);
}
break;
case MAP:
{
Map<String, Object> value = new HashMap<String, Object>();
switch (fieldMetadata.getDataType()) {
case STRING:
value.put("firstName", "John");
value.put("lastName", "Doe");
value.put("address", "Jersey");
break;
case INTEGER:
value.put("count", 123);
value.put("max", 456);
value.put("sum", 789);
break;
case DATE:
value.put("before", new Date (12000));
value.put("after", new Date(34000));
break;
case BYTE:
value.put("hash", new byte[] {0x12, 0x34});
value.put("checksum", new byte[] {0x56, 0x78});
break;
case DECIMAL:
value.put("asset", 12.34);
value.put("liability", 56.78);
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
field.setValue(value);
}
break;
default:
throw new IllegalArgumentException(fieldMetadata.getContainerType().toString());
}
}
return ret;
}
protected DataRecord createDefaultRecord(DataRecordMetadata dataRecordMetadata) {
final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata);
ret.init();
SetVal.setString(ret, "Name", NAME_VALUE);
SetVal.setDouble(ret, "Age", AGE_VALUE);
SetVal.setString(ret, "City", CITY_VALUE);
SetVal.setDate(ret, "Born", BORN_VALUE);
SetVal.setLong(ret, "BornMillisec", BORN_MILLISEC_VALUE);
SetVal.setInt(ret, "Value", VALUE_VALUE);
SetVal.setValue(ret, "Flag", FLAG_VALUE);
SetVal.setValue(ret, "ByteArray", BYTEARRAY_VALUE);
SetVal.setValue(ret, "Currency", CURRENCY_VALUE);
return ret;
}
/**
* Allocates new records with structure prescribed by metadata and sets all its fields to <code>null</code>
*
* @param metadata
* structure to use
* @return empty record
*/
protected DataRecord createEmptyRecord(DataRecordMetadata metadata) {
DataRecord ret = DataRecordFactory.newRecord(metadata);
ret.init();
for (int i = 0; i < ret.getNumFields(); i++) {
SetVal.setNull(ret, i);
}
return ret;
}
/**
* Executes the code using the default graph and records.
*/
protected void doCompile(String expStr, String testIdentifier) {
TransformationGraph graph = createDefaultGraph();
DataRecord[] inRecords = new DataRecord[] { createDefaultRecord(graph.getDataRecordMetadata(INPUT_1)), createDefaultRecord(graph.getDataRecordMetadata(INPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(INPUT_3)), createDefaultMultivalueRecord(graph.getDataRecordMetadata(INPUT_4)) };
DataRecord[] outRecords = new DataRecord[] { createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_1)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_3)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_4)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_5)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_6)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_7)) };
doCompile(expStr, testIdentifier, graph, inRecords, outRecords);
}
/**
* This method should be used to execute a test with a custom graph and custom input and output records.
*
* To execute a test with the default graph,
* use {@link #doCompile(String)}
* or {@link #doCompile(String, String)} instead.
*
* @param expStr
* @param testIdentifier
* @param graph
* @param inRecords
* @param outRecords
*/
protected void doCompile(String expStr, String testIdentifier, TransformationGraph graph, DataRecord[] inRecords, DataRecord[] outRecords) {
this.graph = graph;
this.inputRecords = inRecords;
this.outputRecords = outRecords;
// prepend the compilation mode prefix
if (compileToJava) {
expStr = "//#CTL2:COMPILE\n" + expStr;
}
print_code(expStr);
DataRecordMetadata[] inMetadata = new DataRecordMetadata[inRecords.length];
for (int i = 0; i < inRecords.length; i++) {
inMetadata[i] = inRecords[i].getMetadata();
}
DataRecordMetadata[] outMetadata = new DataRecordMetadata[outRecords.length];
for (int i = 0; i < outRecords.length; i++) {
outMetadata[i] = outRecords[i].getMetadata();
}
ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8");
// try {
// System.out.println(compiler.convertToJava(expStr, CTLRecordTransform.class, testIdentifier));
// } catch (ErrorMessageException e) {
// System.out.println("Error parsing CTL code. Unable to output Java translation.");
List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier);
printMessages(messages);
if (compiler.errorCount() > 0) {
throw new AssertionFailedError("Error in execution. Check standard output for details.");
}
// CLVFStart parseTree = compiler.getStart();
// parseTree.dump("");
executeCode(compiler);
}
protected void doCompileExpectError(String expStr, String testIdentifier, List<String> errCodes) {
graph = createDefaultGraph();
DataRecordMetadata[] inMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(INPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_3) };
DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(OUTPUT_2), graph.getDataRecordMetadata(OUTPUT_3), graph.getDataRecordMetadata(OUTPUT_4) };
// prepend the compilation mode prefix
if (compileToJava) {
expStr = "//#CTL2:COMPILE\n" + expStr;
}
print_code(expStr);
ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8");
List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier);
printMessages(messages);
if (compiler.errorCount() == 0) {
throw new AssertionFailedError("No errors in parsing. Expected " + errCodes.size() + " errors.");
}
if (compiler.errorCount() != errCodes.size()) {
throw new AssertionFailedError(compiler.errorCount() + " errors in code, but expected " + errCodes.size() + " errors.");
}
Iterator<String> it = errCodes.iterator();
for (ErrorMessage errorMessage : compiler.getDiagnosticMessages()) {
String expectedError = it.next();
if (!expectedError.equals(errorMessage.getErrorMessage())) {
throw new AssertionFailedError("Error : \'" + compiler.getDiagnosticMessages().get(0).getErrorMessage() + "\', but expected: \'" + expectedError + "\'");
}
}
// CLVFStart parseTree = compiler.getStart();
// parseTree.dump("");
// executeCode(compiler);
}
protected void doCompileExpectError(String testIdentifier, String errCode) {
doCompileExpectErrors(testIdentifier, Arrays.asList(errCode));
}
protected void doCompileExpectErrors(String testIdentifier, List<String> errCodes) {
URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl");
if (importLoc == null) {
throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found");
}
final StringBuilder sourceCode = new StringBuilder();
String line = null;
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream()));
while ((line = rd.readLine()) != null) {
sourceCode.append(line).append("\n");
}
rd.close();
} catch (IOException e) {
throw new RuntimeException("I/O error occured when reading source file", e);
}
doCompileExpectError(sourceCode.toString(), testIdentifier, errCodes);
}
/**
* Method loads tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should
* be stored in the same directory as this class.
*
* @param Test
* identifier defining CTL file to load code from
*/
protected String loadSourceCode(String testIdentifier) {
URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl");
if (importLoc == null) {
throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found");
}
final StringBuilder sourceCode = new StringBuilder();
String line = null;
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream()));
while ((line = rd.readLine()) != null) {
sourceCode.append(line).append("\n");
}
rd.close();
} catch (IOException e) {
throw new RuntimeException("I/O error occured when reading source file", e);
}
return sourceCode.toString();
}
/**
* Method loads and compiles tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should
* be stored in the same directory as this class.
*
* The default graph and records are used for the execution.
*
* @param Test
* identifier defining CTL file to load code from
*/
protected void doCompile(String testIdentifier) {
String sourceCode = loadSourceCode(testIdentifier);
doCompile(sourceCode, testIdentifier);
}
protected void printMessages(List<ErrorMessage> diagnosticMessages) {
for (ErrorMessage e : diagnosticMessages) {
System.out.println(e);
}
}
/**
* Compares two records if they have the same number of fields and identical values in their fields. Does not
* consider (or examine) metadata.
*
* @param lhs
* @param rhs
* @return true if records have the same number of fields and the same values in them
*/
protected static boolean recordEquals(DataRecord lhs, DataRecord rhs) {
if (lhs == rhs)
return true;
if (rhs == null)
return false;
if (lhs == null) {
return false;
}
if (lhs.getNumFields() != rhs.getNumFields()) {
return false;
}
for (int i = 0; i < lhs.getNumFields(); i++) {
if (lhs.getField(i).isNull()) {
if (!rhs.getField(i).isNull()) {
return false;
}
} else if (!lhs.getField(i).equals(rhs.getField(i))) {
return false;
}
}
return true;
}
public void print_code(String text) {
String[] lines = text.split("\n");
System.out.println("\t: 1 2 3 4 5 ");
System.out.println("\t:12345678901234567890123456789012345678901234567890123456789");
for (int i = 0; i < lines.length; i++) {
System.out.println((i + 1) + "\t:" + lines[i]);
}
}
@SuppressWarnings("unchecked")
public void test_operators_unary_record_allowed() {
doCompile("test_operators_unary_record_allowed");
check("value", Arrays.asList(14, 16, 16, 65, 63, 63));
check("bornMillisec", Arrays.asList(14L, 16L, 16L, 65L, 63L, 63L));
List<Double> actualAge = (List<Double>) getVariable("age");
double[] expectedAge = {14.123, 16.123, 16.123, 65.789, 63.789, 63.789};
for (int i = 0; i < actualAge.size(); i++) {
assertEquals("age[" + i + "]", expectedAge[i], actualAge.get(i), 0.0001);
}
check("currency", Arrays.asList(
new BigDecimal(BigInteger.valueOf(12500), 3),
new BigDecimal(BigInteger.valueOf(14500), 3),
new BigDecimal(BigInteger.valueOf(14500), 3),
new BigDecimal(BigInteger.valueOf(65432), 3),
new BigDecimal(BigInteger.valueOf(63432), 3),
new BigDecimal(BigInteger.valueOf(63432), 3)
));
}
@SuppressWarnings("unchecked")
public void test_dynamic_compare() {
doCompile("test_dynamic_compare");
String varName = "compare";
List<Integer> compareResult = (List<Integer>) getVariable(varName);
for (int i = 0; i < compareResult.size(); i++) {
if ((i % 3) == 0) {
assertTrue(varName + "[" + i + "]", compareResult.get(i) > 0);
} else if ((i % 3) == 1) {
assertEquals(varName + "[" + i + "]", Integer.valueOf(0), compareResult.get(i));
} else if ((i % 3) == 2) {
assertTrue(varName + "[" + i + "]", compareResult.get(i) < 0);
}
}
varName = "compareBooleans";
compareResult = (List<Integer>) getVariable(varName);
assertEquals(varName + "[0]", Integer.valueOf(0), compareResult.get(0));
assertTrue(varName + "[1]", compareResult.get(1) > 0);
assertTrue(varName + "[2]", compareResult.get(2) < 0);
assertEquals(varName + "[3]", Integer.valueOf(0), compareResult.get(3));
}
public void test_dynamiclib_compare_expect_error(){
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = $out.0; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, 'Flagxx', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = $out.0; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, 'Flag', myRec2, 'Flagxx'); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = null; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "$out.0.Flag = true; "
+ "$out.1.Age = 11;"
+ "integer i = compare($out.0, 'Flag', $out.1, 'Age'); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = $out.0; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, -1, myRec2, -1 ); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "firstInput myRec; myRec = $out.0; "
+ "firstOutput myRec2; myRec2 = $out.1;"
+ "integer i = compare(myRec, 2, myRec2, 2 ); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "$out.0.8 = 12.4d; "
+ "$out.1.8 = 12.5d;"
+ "integer i = compare($out.0, 9, $out.1, 9 ); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "$out.0.0 = null; "
+ "$out.1.0 = null;"
+ "integer i = compare($out.0, 0, $out.1, 0 ); return 0;}","test_dynamiclib_compare_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
private void test_dynamic_get_set_loop(String testIdentifier) {
doCompile(testIdentifier);
check("recordLength", 9);
check("value", Arrays.asList(654321, 777777, 654321, 654323, 123456, 112567, 112233));
check("type", Arrays.asList("string", "number", "string", "date", "long", "integer", "boolean", "byte", "decimal"));
check("asString", Arrays.asList("1000", "1001.0", "1002", "Thu Jan 01 01:00:01 CET 1970", "1004", "1005", "true", null, "1008.000"));
check("isNull", Arrays.asList(false, false, false, false, false, false, false, true, false));
check("fieldName", Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency"));
Integer[] indices = new Integer[9];
for (int i = 0; i < indices.length; i++) {
indices[i] = i;
}
check("fieldIndex", Arrays.asList(indices));
// check dynamic write and read with all data types
check("booleanVar", true);
assertTrue("byteVar", Arrays.equals(new BigInteger("1234567890abcdef", 16).toByteArray(), (byte[]) getVariable("byteVar")));
check("decimalVar", new BigDecimal(BigInteger.valueOf(1000125), 3));
check("integerVar", 1000);
check("longVar", 1000000000000L);
check("numberVar", 1000.5);
check("stringVar", "hello");
check("dateVar", new Date(5000));
// null value
Boolean[] someValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(someValue, Boolean.FALSE);
check("someValue", Arrays.asList(someValue));
Boolean[] nullValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(nullValue, Boolean.TRUE);
check("nullValue", Arrays.asList(nullValue));
String[] asString2 = new String[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
check("asString2", Arrays.asList(asString2));
Boolean[] isNull2 = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(isNull2, Boolean.TRUE);
check("isNull2", Arrays.asList(isNull2));
}
public void test_dynamic_get_set_loop() {
test_dynamic_get_set_loop("test_dynamic_get_set_loop");
}
public void test_dynamic_get_set_loop_alternative() {
test_dynamic_get_set_loop("test_dynamic_get_set_loop_alternative");
}
public void test_dynamic_invalid() {
doCompileExpectErrors("test_dynamic_invalid", Arrays.asList(
"Input record cannot be assigned to",
"Input record cannot be assigned to"
));
}
public void test_dynamiclib_getBoolValue(){
doCompile("test_dynamiclib_getBoolValue");
check("ret1", true);
check("ret2", true);
check("ret3", false);
check("ret4", false);
check("ret5", null);
check("ret6", null);
}
public void test_dynamiclib_getBoolValue_expect_error(){
try {
doCompile("function integer transform(){boolean b = getBoolValue($in.0, 2);return 0;}","test_dynamiclib_getBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){boolean b = getBoolValue($in.0, 'Age');return 0;}","test_dynamiclib_getBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 6); return 0;}","test_dynamiclib_getBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 'Flag'); return 0;}","test_dynamiclib_getBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getByteValue(){
doCompile("test_dynamiclib_getByteValue");
checkArray("ret1",CompilerTestCase.BYTEARRAY_VALUE);
checkArray("ret2",CompilerTestCase.BYTEARRAY_VALUE);
check("ret3", null);
check("ret4", null);
}
public void test_dynamiclib_getByteValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; byte b = getByteValue(fi,7); return 0;}","test_dynamiclib_getByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; byte b = fi.getByteValue('ByteArray'); return 0;}","test_dynamiclib_getByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = $in.0.getByteValue('Age'); return 0;}","test_dynamiclib_getByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = getByteValue($in.0, 0); return 0;}","test_dynamiclib_getByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getDateValue(){
doCompile("test_dynamiclib_getDateValue");
check("ret1", CompilerTestCase.BORN_VALUE);
check("ret2", CompilerTestCase.BORN_VALUE);
check("ret3", null);
check("ret4", null);
}
public void test_dynamiclib_getDateValue_expect_error(){
try {
doCompile("function integer transform(){date d = getDateValue($in.0,1); return 0;}","test_dynamiclib_getDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = getDateValue($in.0,'Age'); return 0;}","test_dynamiclib_getDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,'Born'); return 0;}","test_dynamiclib_getDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,3); return 0;}","test_dynamiclib_getDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getDecimalValue(){
doCompile("test_dynamiclib_getDecimalValue");
check("ret1", CompilerTestCase.CURRENCY_VALUE);
check("ret2", CompilerTestCase.CURRENCY_VALUE);
check("ret3", null);
check("ret4", null);
}
public void test_dynamiclib_getDecimalValue_expect_error(){
try {
doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 1); return 0;}","test_dynamiclib_getDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 'Age'); return 0;}","test_dynamiclib_getDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,8); return 0;}","test_dynamiclib_getDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,'Currency'); return 0;}","test_dynamiclib_getDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getFieldIndex(){
doCompile("test_dynamiclib_getFieldIndex");
check("ret1", 1);
check("ret2", 1);
check("ret3", -1);
}
public void test_dynamiclib_getFieldIndex_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; integer int = fi.getFieldIndex('Age'); return 0;}","test_dynamiclib_getFieldIndex_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getFieldLabel(){
doCompile("test_dynamiclib_getFieldLabel");
check("ret1", "Age");
check("ret2","Name");
}
public void test_dynamiclib_getFieldLable_expect_error(){
try {
doCompile("function integer transform(){string name = getFieldLabel($in.0, -5);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string name = getFieldLabel($in.0, 12);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel(2);return 0;}","test_dynamiclib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getFieldName(){
doCompile("test_dynamiclib_getFieldName");
check("ret1", "Age");
check("ret2", "Name");
}
public void test_dynamiclib_getFieldName_expect_error(){
try {
doCompile("function integer transform(){string str = getFieldName($in.0, -5); return 0;}","test_dynamiclib_getFieldName_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = getFieldName($in.0, 15); return 0;}","test_dynamiclib_getFieldName_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldName(2); return 0;}","test_dynamiclib_getFieldName_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getFieldType(){
doCompile("test_dynamiclib_getFieldType");
check("ret1", "string");
check("ret2", "number");
}
public void test_dynamiclib_getFieldType_expect_error(){
try {
doCompile("function integer transform(){string str = getFieldType($in.0, -5); return 0;}","test_dynamiclib_getFieldType_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = getFieldType($in.0, 12); return 0;}","test_dynamiclib_getFieldType_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldType(5); return 0;}","test_dynamiclib_getFieldType_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getIntValue(){
doCompile("test_dynamiclib_getIntValue");
check("ret1", CompilerTestCase.VALUE_VALUE);
check("ret2", CompilerTestCase.VALUE_VALUE);
check("ret3", CompilerTestCase.VALUE_VALUE);
check("ret4", CompilerTestCase.VALUE_VALUE);
check("ret5", null);
}
public void test_dynamiclib_getIntValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; integer i = fi.getIntValue(5); return 0;}","test_dynamiclib_getIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getIntValue($in.0, 1); return 0;}","test_dynamiclib_getIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getIntValue($in.0, 'Born'); return 0;}","test_dynamiclib_getIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getLongValue(){
doCompile("test_dynamiclib_getLongValue");
check("ret1", CompilerTestCase.BORN_MILLISEC_VALUE);
check("ret2", CompilerTestCase.BORN_MILLISEC_VALUE);
check("ret3", null);
}
public void test_dynamiclib_getLongValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; long l = getLongValue(fi, 4);return 0;} ","test_dynamiclib_getLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long l = getLongValue($in.0, 7);return 0;} ","test_dynamiclib_getLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long l = getLongValue($in.0, 'Age');return 0;} ","test_dynamiclib_getLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getNumValue(){
doCompile("test_dynamiclib_getNumValue");
check("ret1", CompilerTestCase.AGE_VALUE);
check("ret2", CompilerTestCase.AGE_VALUE);
check("ret3", null);
}
public void test_dynamiclib_getNumValue_expectValue(){
try {
doCompile("function integer transform(){firstInput fi = null; number n = getNumValue(fi, 1); return 0;}","test_dynamiclib_getNumValue_expectValue");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number n = getNumValue($in.0, 4); return 0;}","test_dynamiclib_getNumValue_expectValue");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number n = $in.0.getNumValue('Name'); return 0;}","test_dynamiclib_getNumValue_expectValue");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getStringValue(){
doCompile("test_dynamiclib_getStringValue");
check("ret1", CompilerTestCase.NAME_VALUE);
check("ret2", CompilerTestCase.NAME_VALUE);
check("ret3", null);
}
public void test_dynamiclib_getStringValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; string str = getStringValue(fi, 0); return 0;}","test_dynamiclib_getStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = getStringValue($in.0, 5); return 0;}","test_dynamiclib_getStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = $in.0.getStringValue('Age'); return 0;}","test_dynamiclib_getStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_getValueAsString(){
doCompile("test_dynamiclib_getValueAsString");
check("ret1", " HELLO ");
check("ret2", "20.25");
check("ret3", "Chong'La");
check("ret4", "Sun Jan 25 13:25:55 CET 2009");
check("ret5", "1232886355333");
check("ret6", "2147483637");
check("ret7", "true");
check("ret8", "41626563656461207a65646c612064656461");
check("ret9", "133.525");
check("ret10", null);
}
public void test_dynamiclib_getValueAsString_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; string str = getValueAsString(fi, 1); return 0;}","test_dynamiclib_getValueAsString_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = getValueAsString($in.0, -1); return 0;}","test_dynamiclib_getValueAsString_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string str = $in.0.getValueAsString(10); return 0;}","test_dynamiclib_getValueAsString_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_isNull(){
doCompile("test_dynamiclib_isNull");
check("ret1", false);
check("ret2", false);
check("ret3", true);
}
public void test_dynamiclib_isNull_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; boolean b = fi.isNull(1); return 0;}","test_dynamiclib_isNull_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){boolean b = $in.0.isNull(-5); return 0;}","test_dynamiclib_isNull_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){boolean b = isNull($in.0,12); return 0;}","test_dynamiclib_isNull_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setBoolValue(){
doCompile("test_dynamiclib_setBoolValue");
check("ret1", null);
check("ret2", true);
check("ret3", false);
}
public void test_dynamiclib_setBoolValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setBoolValue(fi,6,true); return 0;}","test_dynamiclib_setBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setBoolValue($out.0,1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setBoolValue(15,true); return 0;}","test_dynamiclib_setBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setBoolValue(-1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setByteValue() throws UnsupportedEncodingException{
doCompile("test_dynamiclib_setByteValue");
checkArray("ret1", "Urgot".getBytes("UTF-8"));
check("ret2", null);
}
public void test_dynamiclib_setByteValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi =null; setByteValue(fi,7,str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setByteValue($out.0, 1, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setByteValue($out.0, 12, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setByteValue(-2, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setDateValue(){
doCompile("test_dynamiclib_setDateValue");
Calendar cal = Calendar.getInstance();
cal.set(2006,10,12,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret1", cal.getTime());
check("ret2", null);
}
public void test_dynamiclib_setDateValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setDateValue(fi,'Born', null);return 0;}","test_dynamiclib_setDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setDateValue($out.0,1, null);return 0;}","test_dynamiclib_setDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setDateValue($out.0,-2, null);return 0;}","test_dynamiclib_setDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setDateValue(12, null);return 0;}","test_dynamiclib_setDateValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setDecimalValue(){
doCompile("test_dynamiclib_setDecimalValue");
check("ret1", new BigDecimal("12.300"));
check("ret2", null);
}
public void test_dynamiclib_setDecimalValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setDecimalValue(fi, 'Currency', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setDecimalValue($out.0, 'Name', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setDecimalValue(-1, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setDecimalValue(15, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setIntValue(){
doCompile("test_dynamiclib_setIntValue");
check("ret1", 90);
check("ret2", null);
}
public void test_dynamiclib_setIntValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi =null; setIntValue(fi,5,null);return 0;}","test_dynamiclib_setIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setIntValue($out.0,4,90);return 0;}","test_dynamiclib_setIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setIntValue($out.0,-2,90);return 0;}","test_dynamiclib_setIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setIntValue(15,90);return 0;}","test_dynamiclib_setIntValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setLongValue(){
doCompile("test_dynamiclib_setLongValue");
check("ret1", 1565486L);
check("ret2", null);
}
public void test_dynamiclib_setLongValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setLongValue(fi, 4, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setLongValue($out.0, 0, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setLongValue($out.0, -1, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setLongValue(12, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setNumValue(){
doCompile("test_dynamiclib_setNumValue");
check("ret1", 12.5d);
check("ret2", null);
}
public void test_dynamiclib_setNumValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setNumValue(fi, 'Age', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setNumValue($out.0, 'Name', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setNumValue($out.0, -1, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setNumValue(11, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_dynamiclib_setStringValue(){
doCompile("test_dynamiclib_setStringValue");
check("ret1", "Zac");
check("ret2", null);
}
public void test_dynamiclib_setStringValue_expect_error(){
try {
doCompile("function integer transform(){firstInput fi = null; setStringValue(fi, 'Name', 'Draven'); return 0;}","test_dynamiclib_setStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setStringValue($out.0, 'Age', 'Soraka'); return 0;}","test_dynamiclib_setStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){setStringValue($out.0, -1, 'Rengar'); return 0;}","test_dynamiclib_setStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){$out.0.setStringValue(11, 'Vaigar'); return 0;}","test_dynamiclib_setStringValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_return_constants() {
// test case for issue 2257
System.out.println("Return constants test:");
doCompile("test_return_constants");
check("skip", RecordTransform.SKIP);
check("all", RecordTransform.ALL);
check("ok", NORMALIZE_RETURN_OK);
check("stop", RecordTransform.STOP);
}
public void test_raise_error_terminal() {
// test case for issue 2337
doCompile("test_raise_error_terminal");
}
public void test_raise_error_nonliteral() {
// test case for issue CL-2071
doCompile("test_raise_error_nonliteral");
}
public void test_case_unique_check() {
// test case for issue 2515
doCompileExpectErrors("test_case_unique_check", Arrays.asList("Duplicate case", "Duplicate case"));
}
public void test_case_unique_check2() {
// test case for issue 2515
doCompileExpectErrors("test_case_unique_check2", Arrays.asList("Duplicate case", "Duplicate case"));
}
public void test_case_unique_check3() {
doCompileExpectError("test_case_unique_check3", "Default case is already defined");
}
public void test_rvalue_for_append() {
// test case for issue 3956
doCompile("test_rvalue_for_append");
check("a", Arrays.asList("1", "2"));
check("b", Arrays.asList("a", "b", "c"));
check("c", Arrays.asList("1", "2", "a", "b", "c"));
}
public void test_rvalue_for_map_append() {
// test case for issue 3960
doCompile("test_rvalue_for_map_append");
HashMap<Integer, String> map1instance = new HashMap<Integer, String>();
map1instance.put(1, "a");
map1instance.put(2, "b");
HashMap<Integer, String> map2instance = new HashMap<Integer, String>();
map2instance.put(3, "c");
map2instance.put(4, "d");
HashMap<Integer, String> map3instance = new HashMap<Integer, String>();
map3instance.put(1, "a");
map3instance.put(2, "b");
map3instance.put(3, "c");
map3instance.put(4, "d");
check("map1", map1instance);
check("map2", map2instance);
check("map3", map3instance);
}
public void test_global_field_access() {
// test case for issue 3957
doCompileExpectError("test_global_field_access", "Unable to access record field in global scope");
}
public void test_global_scope() {
// test case for issue 5006
doCompile("test_global_scope");
check("len", "Kokon".length());
}
//TODO Implement
/*public void test_new() {
doCompile("test_new");
}*/
public void test_parser() {
System.out.println("\nParser test:");
doCompile("test_parser");
}
public void test_ref_res_import() {
System.out.println("\nSpecial character resolving (import) test:");
URL importLoc = getClass().getSuperclass().getResource("test_ref_res.ctl");
String expStr = "import '" + importLoc + "';\n";
doCompile(expStr, "test_ref_res_import");
}
public void test_ref_res_noimport() {
System.out.println("\nSpecial character resolving (no import) test:");
doCompile("test_ref_res");
}
public void test_import() {
System.out.println("\nImport test:");
URL importLoc = getClass().getSuperclass().getResource("import.ctl");
String expStr = "import '" + importLoc + "';\n";
importLoc = getClass().getSuperclass().getResource("other.ctl");
expStr += "import '" + importLoc + "';\n" +
"integer sumInt;\n" +
"function integer transform() {\n" +
" if (a == 3) {\n" +
" otherImportVar++;\n" +
" }\n" +
" sumInt = sum(a, otherImportVar);\n" +
" return 0;\n" +
"}\n";
doCompile(expStr, "test_import");
}
public void test_scope() throws ComponentNotReadyException, TransformException {
System.out.println("\nMapping test:");
// String expStr =
// "function string computeSomething(int n) {\n" +
// " string s = '';\n" +
// " do {\n" +
// " int i = n--;\n" +
// " s = s + '-' + i;\n" +
// " } while (n > 0)\n" +
// " return s;" +
// "function int transform() {\n" +
// " printErr(computeSomething(10));\n" +
// " return 0;\n" +
URL importLoc = getClass().getSuperclass().getResource("samplecode.ctl");
String expStr = "import '" + importLoc + "';\n";
// "function int getIndexOfOffsetStart(string encodedDate) {\n" +
// "int offsetStart;\n" +
// "int actualLastMinus;\n" +
// "int lastMinus = -1;\n" +
// "if ( index_of(encodedDate, '+') != -1 )\n" +
// " return index_of(encodedDate, '+');\n" +
// "do {\n" +
// " actualLastMinus = index_of(encodedDate, '-', lastMinus+1);\n" +
// " if ( actualLastMinus != -1 )\n" +
// " lastMinus = actualLastMinus;\n" +
// "} while ( actualLastMinus != -1 )\n" +
// "return lastMinus;\n" +
// "function int transform() {\n" +
// " getIndexOfOffsetStart('2009-04-24T08:00:00-05:00');\n" +
// " return 0;\n" +
doCompile(expStr, "test_scope");
}
public void test_type_void() {
doCompileExpectErrors("test_type_void", Arrays.asList("Syntax error on token 'void'",
"Variable 'voidVar' is not declared",
"Variable 'voidVar' is not declared",
"Syntax error on token 'void'"));
}
public void test_type_integer() {
doCompile("test_type_integer");
check("i", 0);
check("j", -1);
check("field", VALUE_VALUE);
checkNull("nullValue");
check("varWithInitializer", 123);
checkNull("varWithNullInitializer");
}
public void test_type_integer_edge() {
String testExpression =
"integer minInt;\n"+
"integer maxInt;\n"+
"function integer transform() {\n" +
"minInt=" + Integer.MIN_VALUE + ";\n" +
"printErr(minInt, true);\n" +
"maxInt=" + Integer.MAX_VALUE + ";\n" +
"printErr(maxInt, true);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_int_edge");
check("minInt", Integer.MIN_VALUE);
check("maxInt", Integer.MAX_VALUE);
}
public void test_type_long() {
doCompile("test_type_long");
check("i", Long.valueOf(0));
check("j", Long.valueOf(-1));
check("field", BORN_MILLISEC_VALUE);
check("def", Long.valueOf(0));
checkNull("nullValue");
check("varWithInitializer", 123L);
checkNull("varWithNullInitializer");
}
public void test_type_long_edge() {
String expStr =
"long minLong;\n"+
"long maxLong;\n"+
"function integer transform() {\n" +
"minLong=" + (Long.MIN_VALUE) + "L;\n" +
"printErr(minLong);\n" +
"maxLong=" + (Long.MAX_VALUE) + "L;\n" +
"printErr(maxLong);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr,"test_long_edge");
check("minLong", Long.MIN_VALUE);
check("maxLong", Long.MAX_VALUE);
}
public void test_type_decimal() {
doCompile("test_type_decimal");
check("i", new BigDecimal(0, MAX_PRECISION));
check("j", new BigDecimal(-1, MAX_PRECISION));
check("field", CURRENCY_VALUE);
check("def", new BigDecimal(0, MAX_PRECISION));
checkNull("nullValue");
check("varWithInitializer", new BigDecimal("123.35", MAX_PRECISION));
checkNull("varWithNullInitializer");
check("varWithInitializerNoDist", new BigDecimal(123.35, MAX_PRECISION));
}
public void test_type_decimal_edge() {
String testExpression =
"decimal minLong;\n"+
"decimal maxLong;\n"+
"decimal minLongNoDist;\n"+
"decimal maxLongNoDist;\n"+
"decimal minDouble;\n"+
"decimal maxDouble;\n"+
"decimal minDoubleNoDist;\n"+
"decimal maxDoubleNoDist;\n"+
"function integer transform() {\n" +
"minLong=" + String.valueOf(Long.MIN_VALUE) + "d;\n" +
"printErr(minLong);\n" +
"maxLong=" + String.valueOf(Long.MAX_VALUE) + "d;\n" +
"printErr(maxLong);\n" +
"minLongNoDist=" + String.valueOf(Long.MIN_VALUE) + "L;\n" +
"printErr(minLongNoDist);\n" +
"maxLongNoDist=" + String.valueOf(Long.MAX_VALUE) + "L;\n" +
"printErr(maxLongNoDist);\n" +
// distincter will cause the double-string be parsed into exact representation within BigDecimal
"minDouble=" + String.valueOf(Double.MIN_VALUE) + "D;\n" +
"printErr(minDouble);\n" +
"maxDouble=" + String.valueOf(Double.MAX_VALUE) + "D;\n" +
"printErr(maxDouble);\n" +
// no distincter will cause the double-string to be parsed into inexact representation within double
// then to be assigned into BigDecimal (which will extract only MAX_PRECISION digits)
"minDoubleNoDist=" + String.valueOf(Double.MIN_VALUE) + ";\n" +
"printErr(minDoubleNoDist);\n" +
"maxDoubleNoDist=" + String.valueOf(Double.MAX_VALUE) + ";\n" +
"printErr(maxDoubleNoDist);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_decimal_edge");
check("minLong", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION));
check("maxLong", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION));
check("minLongNoDist", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION));
check("maxLongNoDist", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION));
// distincter will cause the MIN_VALUE to be parsed into exact representation (i.e. 4.9E-324)
check("minDouble", new BigDecimal(String.valueOf(Double.MIN_VALUE), MAX_PRECISION));
check("maxDouble", new BigDecimal(String.valueOf(Double.MAX_VALUE), MAX_PRECISION));
// no distincter will cause MIN_VALUE to be parsed into double inexact representation and extraction of
// MAX_PRECISION digits (i.e. 4.94065.....E-324)
check("minDoubleNoDist", new BigDecimal(Double.MIN_VALUE, MAX_PRECISION));
check("maxDoubleNoDist", new BigDecimal(Double.MAX_VALUE, MAX_PRECISION));
}
public void test_type_number() {
doCompile("test_type_number");
check("i", Double.valueOf(0));
check("j", Double.valueOf(-1));
check("field", AGE_VALUE);
check("def", Double.valueOf(0));
checkNull("nullValue");
checkNull("varWithNullInitializer");
}
public void test_type_number_edge() {
String testExpression =
"number minDouble;\n" +
"number maxDouble;\n"+
"function integer transform() {\n" +
"minDouble=" + Double.MIN_VALUE + ";\n" +
"printErr(minDouble);\n" +
"maxDouble=" + Double.MAX_VALUE + ";\n" +
"printErr(maxDouble);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_number_edge");
check("minDouble", Double.valueOf(Double.MIN_VALUE));
check("maxDouble", Double.valueOf(Double.MAX_VALUE));
}
public void test_type_string() {
doCompile("test_type_string");
check("i","0");
check("helloEscaped", "hello\\nworld");
check("helloExpanded", "hello\nworld");
check("fieldName", NAME_VALUE);
check("fieldCity", CITY_VALUE);
check("escapeChars", "a\u0101\u0102A");
check("doubleEscapeChars", "a\\u0101\\u0102A");
check("specialChars", "špeciálne značky s mäkčeňom môžu byť");
check("dQescapeChars", "a\u0101\u0102A");
//TODO:Is next test correct?
check("dQdoubleEscapeChars", "a\\u0101\\u0102A");
check("dQspecialChars", "špeciálne značky s mäkčeňom môžu byť");
check("empty", "");
check("def", "");
checkNull("varWithNullInitializer");
}
public void test_type_string_long() {
int length = 1000;
StringBuilder tmp = new StringBuilder(length);
for (int i = 0; i < length; i++) {
tmp.append(i % 10);
}
String testExpression =
"string longString;\n" +
"function integer transform() {\n" +
"longString=\"" + tmp + "\";\n" +
"printErr(longString);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_string_long");
check("longString", String.valueOf(tmp));
}
public void test_type_date() throws Exception {
doCompile("test_type_date");
check("d3", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 1).getTime());
check("d2", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3).getTime());
check("d1", new GregorianCalendar(2006, GregorianCalendar.JANUARY, 1, 1, 2, 3).getTime());
check("field", BORN_VALUE);
checkNull("nullValue");
check("minValue", new GregorianCalendar(1970, GregorianCalendar.JANUARY, 1, 1, 0, 0).getTime());
checkNull("varWithNullInitializer");
// test with a default time zone set on the GraphRuntimeContext
Context context = null;
try {
tearDown();
setUp();
TransformationGraph graph = new TransformationGraph();
graph.getRuntimeContext().setTimeZone("GMT+8");
context = ContextProvider.registerGraph(graph);
doCompile("test_type_date");
Calendar calendar = new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3);
calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
check("d2", calendar.getTime());
calendar.set(2006, 0, 1, 1, 2, 3);
check("d1", calendar.getTime());
} finally {
ContextProvider.unregister(context);
}
}
public void test_type_boolean() {
doCompile("test_type_boolean");
check("b1", true);
check("b2", false);
check("b3", false);
checkNull("nullValue");
checkNull("varWithNullInitializer");
}
public void test_type_boolean_compare() {
doCompileExpectErrors("test_type_boolean_compare", Arrays.asList(
"Operator '>' is not defined for types 'boolean' and 'boolean'",
"Operator '>=' is not defined for types 'boolean' and 'boolean'",
"Operator '<' is not defined for types 'boolean' and 'boolean'",
"Operator '<=' is not defined for types 'boolean' and 'boolean'",
"Operator '<' is not defined for types 'boolean' and 'boolean'",
"Operator '>' is not defined for types 'boolean' and 'boolean'",
"Operator '>=' is not defined for types 'boolean' and 'boolean'",
"Operator '<=' is not defined for types 'boolean' and 'boolean'"));
}
public void test_type_list() {
doCompile("test_type_list");
check("intList", Arrays.asList(1, 2, 3, 4, 5, 6));
check("intList2", Arrays.asList(1, 2, 3));
check("stringList", Arrays.asList(
"first", "replaced", "third", "fourth",
"fifth", "sixth", "extra"));
check("stringListCopy", Arrays.asList(
"first", "second", "third", "fourth",
"fifth", "seventh"));
check("stringListCopy2", Arrays.asList(
"first", "replaced", "third", "fourth",
"fifth", "sixth", "extra"));
assertTrue(getVariable("stringList") != getVariable("stringListCopy"));
assertEquals(getVariable("stringList"), getVariable("stringListCopy2"));
assertEquals(Arrays.asList(false, null, true), getVariable("booleanList"));
assertDeepEquals(Arrays.asList(new byte[] {(byte) 0xAB}, null), getVariable("byteList"));
assertDeepEquals(Arrays.asList(null, new byte[] {(byte) 0xCD}), getVariable("cbyteList"));
assertEquals(Arrays.asList(new Date(12000), null, new Date(34000)), getVariable("dateList"));
assertEquals(Arrays.asList(null, new BigDecimal(BigInteger.valueOf(1234), 2)), getVariable("decimalList"));
assertEquals(Arrays.asList(12, null, 34), getVariable("intList3"));
assertEquals(Arrays.asList(12l, null, 98l), getVariable("longList"));
assertEquals(Arrays.asList(12.34, null, 56.78), getVariable("numberList"));
assertEquals(Arrays.asList("aa", null, "bb"), getVariable("stringList2"));
List<?> decimalList2 = (List<?>) getVariable("decimalList2");
for (Object o: decimalList2) {
assertTrue(o instanceof BigDecimal);
}
List<?> intList4 = (List<?>) getVariable("intList4");
Set<Object> intList4Set = new HashSet<Object>(intList4);
assertEquals(3, intList4Set.size());
}
public void test_type_list_field() {
doCompile("test_type_list_field");
check("copyByValueTest1", "2");
check("copyByValueTest2", "test");
}
public void test_type_map_field() {
doCompile("test_type_map_field");
Integer copyByValueTest1 = (Integer) getVariable("copyByValueTest1");
assertEquals(new Integer(2), copyByValueTest1);
Integer copyByValueTest2 = (Integer) getVariable("copyByValueTest2");
assertEquals(new Integer(100), copyByValueTest2);
}
/**
* The structure of the objects must be exactly the same!
*
* @param o1
* @param o2
*/
private static void assertDeepCopy(Object o1, Object o2) {
if (o1 instanceof DataRecord) {
assertFalse(o1 == o2);
DataRecord r1 = (DataRecord) o1;
DataRecord r2 = (DataRecord) o2;
for (int i = 0; i < r1.getNumFields(); i++) {
assertDeepCopy(r1.getField(i).getValue(), r2.getField(i).getValue());
}
} else if (o1 instanceof Map) {
assertFalse(o1 == o2);
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
for (Object key: m1.keySet()) {
assertDeepCopy(m1.get(key), m2.get(key));
}
} else if (o1 instanceof List) {
assertFalse(o1 == o2);
List<?> l1 = (List<?>) o1;
List<?> l2 = (List<?>) o2;
for (int i = 0; i < l1.size(); i++) {
assertDeepCopy(l1.get(i), l2.get(i));
}
} else if (o1 instanceof Date) {
assertFalse(o1 == o2);
// } else if (o1 instanceof byte[]) { // not required anymore
// assertFalse(o1 == o2);
}
}
/**
* The structure of the objects must be exactly the same!
*
* @param o1
* @param o2
*/
private static void assertDeepEquals(Object o1, Object o2) {
if ((o1 == null) && (o2 == null)) {
return;
}
assertTrue((o1 == null) == (o2 == null));
if (o1 instanceof DataRecord) {
DataRecord r1 = (DataRecord) o1;
DataRecord r2 = (DataRecord) o2;
assertEquals(r1.getNumFields(), r2.getNumFields());
for (int i = 0; i < r1.getNumFields(); i++) {
assertDeepEquals(r1.getField(i).getValue(), r2.getField(i).getValue());
}
} else if (o1 instanceof Map) {
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
assertTrue(m1.keySet().equals(m2.keySet()));
for (Object key: m1.keySet()) {
assertDeepEquals(m1.get(key), m2.get(key));
}
} else if (o1 instanceof List) {
List<?> l1 = (List<?>) o1;
List<?> l2 = (List<?>) o2;
assertEquals("size", l1.size(), l2.size());
for (int i = 0; i < l1.size(); i++) {
assertDeepEquals(l1.get(i), l2.get(i));
}
} else if (o1 instanceof byte[]) {
byte[] b1 = (byte[]) o1;
byte[] b2 = (byte[]) o2;
if (b1 != b2) {
if (b1 == null || b2 == null) {
assertEquals(b1, b2);
}
assertEquals("length", b1.length, b2.length);
for (int i = 0; i < b1.length; i++) {
assertEquals(String.format("[%d]", i), b1[i], b2[i]);
}
}
} else if (o1 instanceof CharSequence) {
String s1 = ((CharSequence) o1).toString();
String s2 = ((CharSequence) o2).toString();
assertEquals(s1, s2);
} else if ((o1 instanceof Decimal) || (o1 instanceof BigDecimal)) {
BigDecimal d1 = o1 instanceof Decimal ? ((Decimal) o1).getBigDecimalOutput() : (BigDecimal) o1;
BigDecimal d2 = o2 instanceof Decimal ? ((Decimal) o2).getBigDecimalOutput() : (BigDecimal) o2;
assertEquals(d1, d2);
} else {
assertEquals(o1, o2);
}
}
private void check_assignment_deepcopy_variable_declaration() {
Date testVariableDeclarationDate1 = (Date) getVariable("testVariableDeclarationDate1");
Date testVariableDeclarationDate2 = (Date) getVariable("testVariableDeclarationDate2");
byte[] testVariableDeclarationByte1 = (byte[]) getVariable("testVariableDeclarationByte1");
byte[] testVariableDeclarationByte2 = (byte[]) getVariable("testVariableDeclarationByte2");
assertDeepEquals(testVariableDeclarationDate1, testVariableDeclarationDate2);
assertDeepEquals(testVariableDeclarationByte1, testVariableDeclarationByte2);
assertDeepCopy(testVariableDeclarationDate1, testVariableDeclarationDate2);
assertDeepCopy(testVariableDeclarationByte1, testVariableDeclarationByte2);
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_array_access_expression() {
{
// JJTARRAYACCESSEXPRESSION - List
List<String> stringListField1 = (List<String>) getVariable("stringListField1");
DataRecord recordInList1 = (DataRecord) getVariable("recordInList1");
List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1");
List<DataRecord> recordList2 = (List<DataRecord>) getVariable("recordList2");
assertDeepEquals(stringListField1, recordInList1.getField("stringListField").getValue());
assertDeepEquals(recordInList1, recordList1.get(0));
assertDeepEquals(recordList1, recordList2);
assertDeepCopy(stringListField1, recordInList1.getField("stringListField").getValue());
assertDeepCopy(recordInList1, recordList1.get(0));
assertDeepCopy(recordList1, recordList2);
}
{
// map of records
Date testDate1 = (Date) getVariable("testDate1");
Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1");
DataRecord recordInMap1 = (DataRecord) getVariable("recordInMap1");
DataRecord recordInMap2 = (DataRecord) getVariable("recordInMap2");
Map<Integer, DataRecord> recordMap2 = (Map<Integer, DataRecord>) getVariable("recordMap2");
assertDeepEquals(testDate1, recordInMap1.getField("dateField").getValue());
assertDeepEquals(recordInMap1, recordMap1.get(0));
assertDeepEquals(recordInMap2, recordMap1.get(0));
assertDeepEquals(recordMap1, recordMap2);
assertDeepCopy(testDate1, recordInMap1.getField("dateField").getValue());
assertDeepCopy(recordInMap1, recordMap1.get(0));
assertDeepCopy(recordInMap2, recordMap1.get(0));
assertDeepCopy(recordMap1, recordMap2);
}
{
// map of dates
Map<Integer, Date> dateMap1 = (Map<Integer, Date>) getVariable("dateMap1");
Date date1 = (Date) getVariable("date1");
Date date2 = (Date) getVariable("date2");
assertDeepCopy(date1, dateMap1.get(0));
assertDeepCopy(date2, dateMap1.get(1));
}
{
// map of byte arrays
Map<Integer, byte[]> byteMap1 = (Map<Integer, byte[]>) getVariable("byteMap1");
byte[] byte1 = (byte[]) getVariable("byte1");
byte[] byte2 = (byte[]) getVariable("byte2");
assertDeepCopy(byte1, byteMap1.get(0));
assertDeepCopy(byte2, byteMap1.get(1));
}
{
// JJTARRAYACCESSEXPRESSION - Function call
List<String> testArrayAccessFunctionCallStringList = (List<String>) getVariable("testArrayAccessFunctionCallStringList");
DataRecord testArrayAccessFunctionCall = (DataRecord) getVariable("testArrayAccessFunctionCall");
Map<String, DataRecord> function_call_original_map = (Map<String, DataRecord>) getVariable("function_call_original_map");
Map<String, DataRecord> function_call_copied_map = (Map<String, DataRecord>) getVariable("function_call_copied_map");
List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list");
List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list");
assertDeepEquals(testArrayAccessFunctionCallStringList, testArrayAccessFunctionCall.getField("stringListField").getValue());
assertEquals(1, function_call_original_map.size());
assertEquals(2, function_call_copied_map.size());
assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall), function_call_original_list);
assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall, testArrayAccessFunctionCall), function_call_copied_list);
assertDeepEquals(testArrayAccessFunctionCall, function_call_original_map.get("1"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("1"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("2"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_original_list.get(1));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(1));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(2));
assertDeepCopy(testArrayAccessFunctionCall, function_call_original_map.get("1"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("1"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("2"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_original_list.get(1));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(1));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(2));
}
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_field_access_expression() {
// field access
Date testFieldAccessDate1 = (Date) getVariable("testFieldAccessDate1");
String testFieldAccessString1 = (String) getVariable("testFieldAccessString1");
List<Date> testFieldAccessDateList1 = (List<Date>) getVariable("testFieldAccessDateList1");
List<String> testFieldAccessStringList1 = (List<String>) getVariable("testFieldAccessStringList1");
Map<String, Date> testFieldAccessDateMap1 = (Map<String, Date>) getVariable("testFieldAccessDateMap1");
Map<String, String> testFieldAccessStringMap1 = (Map<String, String>) getVariable("testFieldAccessStringMap1");
DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
assertDeepEquals(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue());
assertDeepEquals(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0));
assertDeepEquals(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0));
assertDeepEquals(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first"));
assertDeepEquals(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first"));
assertDeepEquals(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue());
assertDeepEquals(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue());
assertDeepEquals(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue());
assertDeepEquals(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue());
assertDeepEquals(testFieldAccessRecord1, thirdMultivalueOutput);
assertDeepCopy(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue());
assertDeepCopy(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0));
assertDeepCopy(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0));
assertDeepCopy(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first"));
assertDeepCopy(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first"));
assertDeepCopy(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue());
assertDeepCopy(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue());
assertDeepCopy(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue());
assertDeepCopy(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue());
assertDeepCopy(testFieldAccessRecord1, thirdMultivalueOutput);
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_member_access_expression() {
{
// member access - record
Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1");
byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1");
List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1");
List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1");
DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1");
DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
}
{
// member access - record
Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1");
byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1");
List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1");
List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1");
DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1");
DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2");
DataRecord testMemberAccessRecord3 = (DataRecord) getVariable("testMemberAccessRecord3");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecord3, testMemberAccessRecord2);
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecord3, testMemberAccessRecord2);
// dictionary
Date dictionaryDate = (Date) graph.getDictionary().getEntry("a").getValue();
byte[] dictionaryByte = (byte[]) graph.getDictionary().getEntry("y").getValue();
List<String> testMemberAccessStringList1 = (List<String>) getVariable("testMemberAccessStringList1");
List<Date> testMemberAccessDateList2 = (List<Date>) getVariable("testMemberAccessDateList2");
List<byte[]> testMemberAccessByteList2 = (List<byte[]>) getVariable("testMemberAccessByteList2");
List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList");
List<Date> dictionaryDateList = (List<Date>) graph.getDictionary().getValue("dateList");
List<byte[]> dictionaryByteList = (List<byte[]>) graph.getDictionary().getValue("byteList");
assertDeepEquals(dictionaryDate, testMemberAccessDate1);
assertDeepEquals(dictionaryByte, testMemberAccessByte1);
assertDeepEquals(dictionaryStringList, testMemberAccessStringList1);
assertDeepEquals(dictionaryDateList, testMemberAccessDateList2);
assertDeepEquals(dictionaryByteList, testMemberAccessByteList2);
assertDeepCopy(dictionaryDate, testMemberAccessDate1);
assertDeepCopy(dictionaryByte, testMemberAccessByte1);
assertDeepCopy(dictionaryStringList, testMemberAccessStringList1);
assertDeepCopy(dictionaryDateList, testMemberAccessDateList2);
assertDeepCopy(dictionaryByteList, testMemberAccessByteList2);
// member access - array of records
List<DataRecord> testMemberAccessRecordList1 = (List<DataRecord>) getVariable("testMemberAccessRecordList1");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2));
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2));
// member access - map of records
Map<Integer, DataRecord> testMemberAccessRecordMap1 = (Map<Integer, DataRecord>) getVariable("testMemberAccessRecordMap1");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2));
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2));
}
}
@SuppressWarnings("unchecked")
public void test_assignment_deepcopy() {
doCompile("test_assignment_deepcopy");
List<DataRecord> secondRecordList = (List<DataRecord>) getVariable("secondRecordList");
assertEquals("before", secondRecordList.get(0).getField("Name").getValue().toString());
List<DataRecord> firstRecordList = (List<DataRecord>) getVariable("firstRecordList");
assertEquals("after", firstRecordList.get(0).getField("Name").getValue().toString());
check_assignment_deepcopy_variable_declaration();
check_assignment_deepcopy_array_access_expression();
check_assignment_deepcopy_field_access_expression();
check_assignment_deepcopy_member_access_expression();
}
public void test_assignment_deepcopy_field_access_expression() {
doCompile("test_assignment_deepcopy_field_access_expression");
DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
DataRecord multivalueInput = inputRecords[3];
assertDeepEquals(firstMultivalueOutput, testFieldAccessRecord1);
assertDeepEquals(secondMultivalueOutput, multivalueInput);
assertDeepEquals(thirdMultivalueOutput, secondMultivalueOutput);
assertDeepCopy(firstMultivalueOutput, testFieldAccessRecord1);
assertDeepCopy(secondMultivalueOutput, multivalueInput);
assertDeepCopy(thirdMultivalueOutput, secondMultivalueOutput);
}
public void test_assignment_array_access_function_call() {
doCompile("test_assignment_array_access_function_call");
Map<String, String> originalMap = new HashMap<String, String>();
originalMap.put("a", "b");
Map<String, String> copiedMap = new HashMap<String, String>(originalMap);
copiedMap.put("c", "d");
check("originalMap", originalMap);
check("copiedMap", copiedMap);
}
public void test_assignment_array_access_function_call_wrong_type() {
doCompileExpectErrors("test_assignment_array_access_function_call_wrong_type",
Arrays.asList(
"Expression is not a composite type but is resolved to 'string'",
"Type mismatch: cannot convert from 'integer' to 'string'",
"Cannot convert from 'integer' to string"
));
}
@SuppressWarnings("unchecked")
public void test_assignment_returnvalue() {
doCompile("test_assignment_returnvalue");
{
List<String> stringList1 = (List<String>) getVariable("stringList1");
List<String> stringList2 = (List<String>) getVariable("stringList2");
List<String> stringList3 = (List<String>) getVariable("stringList3");
List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1");
Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1");
List<String> stringList4 = (List<String>) getVariable("stringList4");
Map<String, Integer> integerMap1 = (Map<String, Integer>) getVariable("integerMap1");
DataRecord record1 = (DataRecord) getVariable("record1");
DataRecord record2 = (DataRecord) getVariable("record2");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
Date dictionaryDate1 = (Date) getVariable("dictionaryDate1");
Date dictionaryDate = (Date) graph.getDictionary().getValue("a");
Date zeroDate = new Date(0);
List<String> testReturnValueDictionary2 = (List<String>) getVariable("testReturnValueDictionary2");
List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList");
List<String> testReturnValue10 = (List<String>) getVariable("testReturnValue10");
DataRecord testReturnValue11 = (DataRecord) getVariable("testReturnValue11");
List<String> testReturnValue12 = (List<String>) getVariable("testReturnValue12");
List<String> testReturnValue13 = (List<String>) getVariable("testReturnValue13");
Map<Integer, DataRecord> function_call_original_map = (Map<Integer, DataRecord>) getVariable("function_call_original_map");
Map<Integer, DataRecord> function_call_copied_map = (Map<Integer, DataRecord>) getVariable("function_call_copied_map");
DataRecord function_call_map_newrecord = (DataRecord) getVariable("function_call_map_newrecord");
List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list");
List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list");
DataRecord function_call_list_newrecord = (DataRecord) getVariable("function_call_list_newrecord");
// identifier
assertFalse(stringList1.isEmpty());
assertTrue(stringList2.isEmpty());
assertTrue(stringList3.isEmpty());
// array access expression - list
assertDeepEquals("unmodified", recordList1.get(0).getField("stringField").getValue());
assertDeepEquals("modified", recordList1.get(1).getField("stringField").getValue());
// array access expression - map
assertDeepEquals("unmodified", recordMap1.get(0).getField("stringField").getValue());
assertDeepEquals("modified", recordMap1.get(1).getField("stringField").getValue());
// array access expression - function call
assertDeepEquals(null, function_call_original_map.get(2));
assertDeepEquals("unmodified", function_call_map_newrecord.getField("stringField"));
assertDeepEquals("modified", function_call_copied_map.get(2).getField("stringField"));
assertDeepEquals(Arrays.asList(null, function_call_list_newrecord), function_call_original_list);
assertDeepEquals("unmodified", function_call_list_newrecord.getField("stringField"));
assertDeepEquals("modified", function_call_copied_list.get(2).getField("stringField"));
// field access expression
assertFalse(stringList4.isEmpty());
assertTrue(((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).isEmpty());
assertFalse(integerMap1.isEmpty());
assertTrue(((Map<?, ?>) firstMultivalueOutput.getField("integerMapField").getValue()).isEmpty());
assertDeepEquals("unmodified", record1.getField("stringField"));
assertDeepEquals("modified", secondMultivalueOutput.getField("stringField").getValue());
assertDeepEquals("unmodified", record2.getField("stringField"));
assertDeepEquals("modified", thirdMultivalueOutput.getField("stringField").getValue());
// member access expression - dictionary
// There is no function that could modify a date
// assertEquals(zeroDate, dictionaryDate);
// assertFalse(zeroDate.equals(testReturnValueDictionary1));
assertFalse(testReturnValueDictionary2.isEmpty());
assertTrue(dictionaryStringList.isEmpty());
// member access expression - record
assertFalse(testReturnValue10.isEmpty());
assertTrue(((List<?>) testReturnValue11.getField("stringListField").getValue()).isEmpty());
// member access expression - list of records
assertFalse(testReturnValue12.isEmpty());
assertTrue(((List<?>) recordList1.get(2).getField("stringListField").getValue()).isEmpty());
// member access expression - map of records
assertFalse(testReturnValue13.isEmpty());
assertTrue(((List<?>) recordMap1.get(2).getField("stringListField").getValue()).isEmpty());
}
}
@SuppressWarnings("unchecked")
public void test_type_map() {
doCompile("test_type_map");
Map<String, Integer> testMap = (Map<String, Integer>) getVariable("testMap");
assertEquals(Integer.valueOf(1), testMap.get("zero"));
assertEquals(Integer.valueOf(2), testMap.get("one"));
assertEquals(Integer.valueOf(3), testMap.get("two"));
assertEquals(Integer.valueOf(4), testMap.get("three"));
assertEquals(4, testMap.size());
Map<Date, String> dayInWeek = (Map<Date, String>) getVariable("dayInWeek");
Calendar c = Calendar.getInstance();
c.set(2009, Calendar.MARCH, 2, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Monday", dayInWeek.get(c.getTime()));
Map<Date, String> dayInWeekCopy = (Map<Date, String>) getVariable("dayInWeekCopy");
c.set(2009, Calendar.MARCH, 3, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Tuesday", ((Map<Date, String>) getVariable("tuesday")).get(c.getTime()));
assertEquals("Tuesday", dayInWeekCopy.get(c.getTime()));
c.set(2009, Calendar.MARCH, 4, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Wednesday", ((Map<Date, String>) getVariable("wednesday")).get(c.getTime()));
assertEquals("Wednesday", dayInWeekCopy.get(c.getTime()));
assertFalse(dayInWeek.equals(dayInWeekCopy));
{
Map<?, ?> preservedOrder = (Map<?, ?>) getVariable("preservedOrder");
assertEquals(100, preservedOrder.size());
int i = 0;
for (Map.Entry<?, ?> entry: preservedOrder.entrySet()) {
assertEquals("key" + i, entry.getKey());
assertEquals("value" + i, entry.getValue());
i++;
}
}
}
public void test_type_record_list() {
doCompile("test_type_record_list");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_list_global() {
doCompile("test_type_record_list_global");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_map() {
doCompile("test_type_record_map");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_map_global() {
doCompile("test_type_record_map_global");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record() {
doCompile("test_type_record");
// expected result
DataRecord expected = createDefaultRecord(createDefaultMetadata("expected"));
// simple copy
assertTrue(recordEquals(expected, inputRecords[0]));
assertTrue(recordEquals(expected, (DataRecord) getVariable("copy")));
// copy and modify
expected.getField("Name").setValue("empty");
expected.getField("Value").setValue(321);
Calendar c = Calendar.getInstance();
c.set(1987, Calendar.NOVEMBER, 13, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
expected.getField("Born").setValue(c.getTime());
assertTrue(recordEquals(expected, (DataRecord) getVariable("modified")));
// 2x modified copy
expected.getField("Name").setValue("not empty");
assertTrue(recordEquals(expected, (DataRecord)getVariable("modified2")));
// no modification by reference is possible
assertTrue(recordEquals(expected, (DataRecord)getVariable("modified3")));
expected.getField("Value").setValue(654321);
assertTrue(recordEquals(expected, (DataRecord)getVariable("reference")));
assertTrue(getVariable("modified3") != getVariable("reference"));
// output record
assertTrue(recordEquals(expected, outputRecords[1]));
// null record
expected.setToNull();
assertTrue(recordEquals(expected, (DataRecord)getVariable("nullRecord")));
}
public void test_variables() {
doCompile("test_variables");
check("b1", true);
check("b2", true);
check("b4", "hi");
check("i", 2);
}
public void test_operator_plus() {
doCompile("test_operator_plus");
check("iplusj", 10 + 100);
check("lplusm", Long.valueOf(Integer.MAX_VALUE) + Long.valueOf(Integer.MAX_VALUE / 10));
check("mplusl", getVariable("lplusm"));
check("mplusi", Long.valueOf(Integer.MAX_VALUE) + 10);
check("iplusm", getVariable("mplusi"));
check("nplusm1", Double.valueOf(0.1D + 0.001D));
check("nplusj", Double.valueOf(100 + 0.1D));
check("jplusn", getVariable("nplusj"));
check("m1plusm", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) + 0.001d));
check("mplusm1", getVariable("m1plusm"));
check("dplusd1", new BigDecimal("0.1", MAX_PRECISION).add(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dplusj", new BigDecimal(100, MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("jplusd", getVariable("dplusj"));
check("dplusm", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("mplusd", getVariable("dplusm"));
check("dplusn", new BigDecimal("0.1").add(new BigDecimal(0.1D, MAX_PRECISION)));
check("nplusd", getVariable("dplusn"));
check("spluss1", "hello world");
check("splusj", "hello100");
check("jpluss", "100hello");
check("splusm", "hello" + Long.valueOf(Integer.MAX_VALUE));
check("mpluss", Long.valueOf(Integer.MAX_VALUE) + "hello");
check("splusm1", "hello" + Double.valueOf(0.001D));
check("m1pluss", Double.valueOf(0.001D) + "hello");
check("splusd1", "hello" + new BigDecimal("0.0001"));
check("d1pluss", new BigDecimal("0.0001", MAX_PRECISION) + "hello");
}
public void test_operator_minus() {
doCompile("test_operator_minus");
check("iminusj", 10 - 100);
check("lminusm", Long.valueOf(Integer.MAX_VALUE / 10) - Long.valueOf(Integer.MAX_VALUE));
check("mminusi", Long.valueOf(Integer.MAX_VALUE - 10));
check("iminusm", 10 - Long.valueOf(Integer.MAX_VALUE));
check("nminusm1", Double.valueOf(0.1D - 0.001D));
check("nminusj", Double.valueOf(0.1D - 100));
check("jminusn", Double.valueOf(100 - 0.1D));
check("m1minusm", Double.valueOf(0.001D - Long.valueOf(Integer.MAX_VALUE)));
check("mminusm1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) - 0.001D));
check("dminusd1", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dminusj", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jminusd", new BigDecimal(100, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dminusm", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mminusd", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dminusn", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("nminusd", new BigDecimal(0.1D, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operator_multiply() {
doCompile("test_operator_multiply");
check("itimesj", 10 * 100);
check("ltimesm", Long.valueOf(Integer.MAX_VALUE) * (Long.valueOf(Integer.MAX_VALUE / 10)));
check("mtimesl", getVariable("ltimesm"));
check("mtimesi", Long.valueOf(Integer.MAX_VALUE) * 10);
check("itimesm", getVariable("mtimesi"));
check("ntimesm1", Double.valueOf(0.1D * 0.001D));
check("ntimesj", Double.valueOf(0.1) * 100);
check("jtimesn", getVariable("ntimesj"));
check("m1timesm", Double.valueOf(0.001d * Long.valueOf(Integer.MAX_VALUE)));
check("mtimesm1", getVariable("m1timesm"));
check("dtimesd1", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dtimesj", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(100, MAX_PRECISION)));
check("jtimesd", getVariable("dtimesj"));
check("dtimesm", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mtimesd", getVariable("dtimesm"));
check("dtimesn", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(0.1, MAX_PRECISION), MAX_PRECISION));
check("ntimesd", getVariable("dtimesn"));
}
public void test_operator_divide() {
doCompile("test_operator_divide");
check("idividej", 10 / 100);
check("ldividem", Long.valueOf(Integer.MAX_VALUE / 10) / Long.valueOf(Integer.MAX_VALUE));
check("mdividei", Long.valueOf(Integer.MAX_VALUE / 10));
check("idividem", 10 / Long.valueOf(Integer.MAX_VALUE));
check("ndividem1", Double.valueOf(0.1D / 0.001D));
check("ndividej", Double.valueOf(0.1D / 100));
check("jdividen", Double.valueOf(100 / 0.1D));
check("m1dividem", Double.valueOf(0.001D / Long.valueOf(Integer.MAX_VALUE)));
check("mdividem1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) / 0.001D));
check("ddivided1", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("ddividej", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jdivided", new BigDecimal(100, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("ddividem", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mdivided", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("ddividen", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("ndivided", new BigDecimal(0.1D, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operator_modulus() {
doCompile("test_operator_modulus");
check("imoduloj", 10 % 100);
check("lmodulom", Long.valueOf(Integer.MAX_VALUE / 10) % Long.valueOf(Integer.MAX_VALUE));
check("mmoduloi", Long.valueOf(Integer.MAX_VALUE % 10));
check("imodulom", 10 % Long.valueOf(Integer.MAX_VALUE));
check("nmodulom1", Double.valueOf(0.1D % 0.001D));
check("nmoduloj", Double.valueOf(0.1D % 100));
check("jmodulon", Double.valueOf(100 % 0.1D));
check("m1modulom", Double.valueOf(0.001D % Long.valueOf(Integer.MAX_VALUE)));
check("mmodulom1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) % 0.001D));
check("dmodulod1", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dmoduloj", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jmodulod", new BigDecimal(100, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dmodulom", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mmodulod", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dmodulon", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("nmodulod", new BigDecimal(0.1D, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operators_unary() {
doCompile("test_operators_unary");
// postfix operators
// int
check("intPlusOrig", Integer.valueOf(10));
check("intPlusPlus", Integer.valueOf(10));
check("intPlus", Integer.valueOf(11));
check("intMinusOrig", Integer.valueOf(10));
check("intMinusMinus", Integer.valueOf(10));
check("intMinus", Integer.valueOf(9));
// long
check("longPlusOrig", Long.valueOf(10));
check("longPlusPlus", Long.valueOf(10));
check("longPlus", Long.valueOf(11));
check("longMinusOrig", Long.valueOf(10));
check("longMinusMinus", Long.valueOf(10));
check("longMinus", Long.valueOf(9));
// double
check("numberPlusOrig", Double.valueOf(10.1));
check("numberPlusPlus", Double.valueOf(10.1));
check("numberPlus", Double.valueOf(11.1));
check("numberMinusOrig", Double.valueOf(10.1));
check("numberMinusMinus", Double.valueOf(10.1));
check("numberMinus", Double.valueOf(9.1));
// decimal
check("decimalPlusOrig", new BigDecimal("10.1"));
check("decimalPlusPlus", new BigDecimal("10.1"));
check("decimalPlus", new BigDecimal("11.1"));
check("decimalMinusOrig", new BigDecimal("10.1"));
check("decimalMinusMinus", new BigDecimal("10.1"));
check("decimalMinus", new BigDecimal("9.1"));
// prefix operators
// integer
check("plusIntOrig", Integer.valueOf(10));
check("plusPlusInt", Integer.valueOf(11));
check("plusInt", Integer.valueOf(11));
check("minusIntOrig", Integer.valueOf(10));
check("minusMinusInt", Integer.valueOf(9));
check("minusInt", Integer.valueOf(9));
check("unaryInt", Integer.valueOf(-10));
// long
check("plusLongOrig", Long.valueOf(10));
check("plusPlusLong", Long.valueOf(11));
check("plusLong", Long.valueOf(11));
check("minusLongOrig", Long.valueOf(10));
check("minusMinusLong", Long.valueOf(9));
check("minusLong", Long.valueOf(9));
check("unaryLong", Long.valueOf(-10));
// double
check("plusNumberOrig", Double.valueOf(10.1));
check("plusPlusNumber", Double.valueOf(11.1));
check("plusNumber", Double.valueOf(11.1));
check("minusNumberOrig", Double.valueOf(10.1));
check("minusMinusNumber", Double.valueOf(9.1));
check("minusNumber", Double.valueOf(9.1));
check("unaryNumber", Double.valueOf(-10.1));
// decimal
check("plusDecimalOrig", new BigDecimal("10.1"));
check("plusPlusDecimal", new BigDecimal("11.1"));
check("plusDecimal", new BigDecimal("11.1"));
check("minusDecimalOrig", new BigDecimal("10.1"));
check("minusMinusDecimal", new BigDecimal("9.1"));
check("minusDecimal", new BigDecimal("9.1"));
check("unaryDecimal", new BigDecimal("-10.1"));
// record values
assertEquals(101, ((DataRecord) getVariable("plusPlusRecord")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("recordPlusPlus")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("modifiedPlusPlusRecord")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("modifiedRecordPlusPlus")).getField("Value").getValue());
//record as parameter
assertEquals(99, ((DataRecord) getVariable("minusMinusRecord")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("recordMinusMinus")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("modifiedMinusMinusRecord")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("modifiedRecordMinusMinus")).getField("Value").getValue());
// logical not
check("booleanValue", true);
check("negation", false);
check("doubleNegation", true);
}
public void test_operators_unary_record() {
doCompileExpectErrors("test_operators_unary_record", Arrays.asList(
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Input record cannot be assigned to",
"Input record cannot be assigned to",
"Input record cannot be assigned to",
"Input record cannot be assigned to"
));
}
public void test_operator_equal() {
doCompile("test_operator_equal");
check("eq0", true);
check("eq1", true);
check("eq1a", true);
check("eq1b", true);
check("eq1c", false);
check("eq2", true);
check("eq3", true);
check("eq4", true);
check("eq5", true);
check("eq6", false);
check("eq7", true);
check("eq8", false);
check("eq9", true);
check("eq10", false);
check("eq11", true);
check("eq12", false);
check("eq13", true);
check("eq14", false);
check("eq15", false);
check("eq16", true);
check("eq17", false);
check("eq18", false);
check("eq19", false);
// byte
check("eq20", true);
check("eq21", true);
check("eq22", false);
check("eq23", false);
check("eq24", true);
check("eq25", false);
check("eq20c", true);
check("eq21c", true);
check("eq22c", false);
check("eq23c", false);
check("eq24c", true);
check("eq25c", false);
check("eq26", true);
check("eq27", true);
}
public void test_operator_non_equal(){
doCompile("test_operator_non_equal");
check("inei", false);
check("inej", true);
check("jnei", true);
check("jnej", false);
check("lnei", false);
check("inel", false);
check("lnej", true);
check("jnel", true);
check("lnel", false);
check("dnei", false);
check("ined", false);
check("dnej", true);
check("jned", true);
check("dnel", false);
check("lned", false);
check("dned", false);
check("dned_different_scale", false);
}
public void test_operator_in() {
doCompile("test_operator_in");
check("a", Integer.valueOf(1));
check("haystack", Collections.EMPTY_LIST);
check("needle", Integer.valueOf(2));
check("b1", true);
check("b2", false);
check("h2", Arrays.asList(2.1D, 2.0D, 2.2D));
check("b3", true);
check("h3", Arrays.asList("memento", "mori", "memento mori"));
check("n3", "memento mori");
check("b4", true);
}
public void test_operator_greater_less() {
doCompile("test_operator_greater_less");
check("eq1", true);
check("eq2", true);
check("eq3", true);
check("eq4", false);
check("eq5", true);
check("eq6", false);
check("eq7", true);
check("eq8", true);
check("eq9", true);
}
public void test_operator_ternary(){
doCompile("test_operator_ternary");
// simple use
check("trueValue", true);
check("falseValue", false);
check("res1", Integer.valueOf(1));
check("res2", Integer.valueOf(2));
// nesting in positive branch
check("res3", Integer.valueOf(1));
check("res4", Integer.valueOf(2));
check("res5", Integer.valueOf(3));
// nesting in negative branch
check("res6", Integer.valueOf(2));
check("res7", Integer.valueOf(3));
// nesting in both branches
check("res8", Integer.valueOf(1));
check("res9", Integer.valueOf(1));
check("res10", Integer.valueOf(2));
check("res11", Integer.valueOf(3));
check("res12", Integer.valueOf(2));
check("res13", Integer.valueOf(4));
check("res14", Integer.valueOf(3));
check("res15", Integer.valueOf(4));
}
public void test_operators_logical(){
doCompile("test_operators_logical");
//TODO: please double check this.
check("res1", false);
check("res2", false);
check("res3", true);
check("res4", true);
check("res5", false);
check("res6", false);
check("res7", true);
check("res8", false);
}
public void test_regex(){
doCompile("test_regex");
check("eq0", false);
check("eq1", true);
check("eq2", false);
check("eq3", true);
check("eq4", false);
check("eq5", true);
}
public void test_if() {
doCompile("test_if");
// if with single statement
check("cond1", true);
check("res1", true);
// if with mutliple statements (block)
check("cond2", true);
check("res21", true);
check("res22", true);
// else with single statement
check("cond3", false);
check("res31", false);
check("res32", true);
// else with multiple statements (block)
check("cond4", false);
check("res41", false);
check("res42", true);
check("res43", true);
// if with block, else with block
check("cond5", false);
check("res51", false);
check("res52", false);
check("res53", true);
check("res54", true);
// else-if with single statement
check("cond61", false);
check("cond62", true);
check("res61", false);
check("res62", true);
// else-if with multiple statements
check("cond71", false);
check("cond72", true);
check("res71", false);
check("res72", true);
check("res73", true);
// if-elseif-else test
check("cond81", false);
check("cond82", false);
check("res81", false);
check("res82", false);
check("res83", true);
// if with single statement + inactive else
check("cond9", true);
check("res91", true);
check("res92", false);
// if with multiple statements + inactive else with block
check("cond10", true);
check("res101", true);
check("res102", true);
check("res103", false);
check("res104", false);
// if with condition
check("i", 0);
check("j", 1);
check("res11", true);
}
public void test_switch() {
doCompile("test_switch");
// simple switch
check("cond1", 1);
check("res11", false);
check("res12", true);
check("res13", false);
// switch, no break
check("cond2", 1);
check("res21", false);
check("res22", true);
check("res23", true);
// default branch
check("cond3", 3);
check("res31", false);
check("res32", false);
check("res33", true);
// no default branch => no match
check("cond4", 3);
check("res41", false);
check("res42", false);
check("res43", false);
// multiple statements in a single case-branch
check("cond5", 1);
check("res51", false);
check("res52", true);
check("res53", true);
check("res54", false);
// single statement shared by several case labels
check("cond6", 1);
check("res61", false);
check("res62", true);
check("res63", true);
check("res64", false);
}
public void test_int_switch(){
doCompile("test_int_switch");
// simple switch
check("cond1", 1);
check("res11", true);
check("res12", false);
check("res13", false);
// first case is not followed by a break
check("cond2", 1);
check("res21", true);
check("res22", true);
check("res23", false);
// first and second case have multiple labels
check("cond3", 12);
check("res31", false);
check("res32", true);
check("res33", false);
// first and second case have multiple labels and no break after first group
check("cond4", 11);
check("res41", true);
check("res42", true);
check("res43", false);
// default case intermixed with other case labels in the second group
check("cond5", 11);
check("res51", true);
check("res52", true);
check("res53", true);
// default case intermixed, with break
check("cond6", 16);
check("res61", false);
check("res62", true);
check("res63", false);
// continue test
check("res7", Arrays.asList(
false, false, false,
true, true, false,
true, true, false,
false, true, false,
false, true, false,
false, false, true));
// return test
check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3"));
}
public void test_non_int_switch(){
doCompile("test_non_int_switch");
// simple switch
check("cond1", "1");
check("res11", true);
check("res12", false);
check("res13", false);
// first case is not followed by a break
check("cond2", "1");
check("res21", true);
check("res22", true);
check("res23", false);
// first and second case have multiple labels
check("cond3", "12");
check("res31", false);
check("res32", true);
check("res33", false);
// first and second case have multiple labels and no break after first group
check("cond4", "11");
check("res41", true);
check("res42", true);
check("res43", false);
// default case intermixed with other case labels in the second group
check("cond5", "11");
check("res51", true);
check("res52", true);
check("res53", true);
// default case intermixed, with break
check("cond6", "16");
check("res61", false);
check("res62", true);
check("res63", false);
// continue test
check("res7", Arrays.asList(
false, false, false,
true, true, false,
true, true, false,
false, true, false,
false, true, false,
false, false, true));
// return test
check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3"));
}
public void test_while() {
doCompile("test_while");
// simple while
check("res1", Arrays.asList(0, 1, 2));
// continue
check("res2", Arrays.asList(0, 2));
// break
check("res3", Arrays.asList(0));
}
public void test_do_while() {
doCompile("test_do_while");
// simple while
check("res1", Arrays.asList(0, 1, 2));
// continue
check("res2", Arrays.asList(0, null, 2));
// break
check("res3", Arrays.asList(0));
}
public void test_for() {
doCompile("test_for");
// simple loop
check("res1", Arrays.asList(0,1,2));
// continue
check("res2", Arrays.asList(0,null,2));
// break
check("res3", Arrays.asList(0));
// empty init
check("res4", Arrays.asList(0,1,2));
// empty update
check("res5", Arrays.asList(0,1,2));
// empty final condition
check("res6", Arrays.asList(0,1,2));
// all conditions empty
check("res7", Arrays.asList(0,1,2));
}
public void test_for1() {
//5125: CTL2: "for" cycle is EXTREMELY memory consuming
doCompile("test_for1");
checkEquals("counter", "COUNT");
}
@SuppressWarnings("unchecked")
public void test_foreach() {
doCompile("test_foreach");
check("intRes", Arrays.asList(VALUE_VALUE));
check("longRes", Arrays.asList(BORN_MILLISEC_VALUE));
check("doubleRes", Arrays.asList(AGE_VALUE));
check("decimalRes", Arrays.asList(CURRENCY_VALUE));
check("booleanRes", Arrays.asList(FLAG_VALUE));
check("stringRes", Arrays.asList(NAME_VALUE, CITY_VALUE));
check("dateRes", Arrays.asList(BORN_VALUE));
List<?> integerStringMapResTmp = (List<?>) getVariable("integerStringMapRes");
List<String> integerStringMapRes = new ArrayList<String>(integerStringMapResTmp.size());
for (Object o: integerStringMapResTmp) {
integerStringMapRes.add(String.valueOf(o));
}
List<Integer> stringIntegerMapRes = (List<Integer>) getVariable("stringIntegerMapRes");
List<DataRecord> stringRecordMapRes = (List<DataRecord>) getVariable("stringRecordMapRes");
Collections.sort(integerStringMapRes);
Collections.sort(stringIntegerMapRes);
assertEquals(Arrays.asList("0", "1", "2", "3", "4"), integerStringMapRes);
assertEquals(Arrays.asList(0, 1, 2, 3, 4), stringIntegerMapRes);
final int N = 5;
assertEquals(N, stringRecordMapRes.size());
int equalRecords = 0;
for (int i = 0; i < N; i++) {
for (DataRecord r: stringRecordMapRes) {
if (Integer.valueOf(i).equals(r.getField("Value").getValue())
&& "A string".equals(String.valueOf(r.getField("Name").getValue()))) {
equalRecords++;
break;
}
}
}
assertEquals(N, equalRecords);
}
public void test_return(){
doCompile("test_return");
check("lhs", Integer.valueOf(1));
check("rhs", Integer.valueOf(2));
check("res", Integer.valueOf(3));
}
public void test_return_incorrect() {
doCompileExpectError("test_return_incorrect", "Can't convert from 'string' to 'integer'");
}
public void test_return_void() {
doCompile("test_return_void");
}
public void test_overloading() {
doCompile("test_overloading");
check("res1", Integer.valueOf(3));
check("res2", "Memento mori");
}
public void test_overloading_incorrect() {
doCompileExpectErrors("test_overloading_incorrect", Arrays.asList(
"Duplicate function 'integer sum(integer, integer)'",
"Duplicate function 'integer sum(integer, integer)'"));
}
//Test case for 4038
public void test_function_parameter_without_type() {
doCompileExpectError("test_function_parameter_without_type", "Syntax error on token ')'");
}
public void test_duplicate_import() {
URL importLoc = getClass().getSuperclass().getResource("test_duplicate_import.ctl");
String expStr = "import '" + importLoc + "';\n";
expStr += "import '" + importLoc + "';\n";
doCompile(expStr, "test_duplicate_import");
}
/*TODO:
* public void test_invalid_import() {
URL importLoc = getClass().getResource("test_duplicate_import.ctl");
String expStr = "import '/a/b/c/d/e/f/g/h/i/j/k/l/m';\n";
expStr += expStr;
doCompileExpectError(expStr, "test_invalid_import", Arrays.asList("TODO: Unknown error"));
//doCompileExpectError(expStr, "test_duplicate_import", Arrays.asList("TODO: Unknown error"));
} */
public void test_built_in_functions(){
doCompile("test_built_in_functions");
check("notNullValue", Integer.valueOf(1));
checkNull("nullValue");
check("isNullRes1", false);
check("isNullRes2", true);
assertEquals("nvlRes1", getVariable("notNullValue"), getVariable("nvlRes1"));
check("nvlRes2", Integer.valueOf(2));
assertEquals("nvl2Res1", getVariable("notNullValue"), getVariable("nvl2Res1"));
check("nvl2Res2", Integer.valueOf(2));
check("iifRes1", Integer.valueOf(2));
check("iifRes2", Integer.valueOf(1));
}
public void test_mapping(){
doCompile("test_mapping");
// simple mappings
assertEquals("Name", NAME_VALUE, outputRecords[0].getField("Name").getValue().toString());
assertEquals("Age", AGE_VALUE, outputRecords[0].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[0].getField("City").getValue().toString());
assertEquals("Born", BORN_VALUE, outputRecords[0].getField("Born").getValue());
// * mapping
assertTrue(recordEquals(inputRecords[1], outputRecords[1]));
check("len", 2);
}
public void test_mapping_null_values() {
doCompile("test_mapping_null_values");
assertTrue(recordEquals(inputRecords[2], outputRecords[0]));
}
public void test_copyByName() {
doCompile("test_copyByName");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString());
}
public void test_copyByName_assignment() {
doCompile("test_copyByName_assignment");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString());
}
public void test_copyByName_assignment1() {
doCompile("test_copyByName_assignment1");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", null, outputRecords[3].getField("Age").getValue());
assertEquals("City", null, outputRecords[3].getField("City").getValue());
}
public void test_sequence(){
doCompile("test_sequence");
check("intRes", Arrays.asList(0,1,2));
check("longRes", Arrays.asList(Long.valueOf(0),Long.valueOf(1),Long.valueOf(2)));
check("stringRes", Arrays.asList("0","1","2"));
check("intCurrent", Integer.valueOf(2));
check("longCurrent", Long.valueOf(2));
check("stringCurrent", "2");
}
//TODO: If this test fails please double check whether the test is correct?
public void test_lookup(){
doCompile("test_lookup");
check("alphaResult", Arrays.asList("Andorra la Vella","Andorra la Vella"));
check("bravoResult", Arrays.asList("Bruxelles","Bruxelles"));
check("charlieResult", Arrays.asList("Chamonix","Chodov","Chomutov","Chamonix","Chodov","Chomutov"));
check("countResult", Arrays.asList(3,3));
check("charlieUpdatedCount", 5);
check("charlieUpdatedResult", Arrays.asList("Chamonix", "Cheb", "Chodov", "Chomutov", "Chrudim"));
check("putResult", true);
}
public void test_containerlib_append() {
doCompile("test_containerlib_append");
check("appendElem", Integer.valueOf(10));
check("appendList", Arrays.asList(1, 2, 3, 4, 5, 10));
check("stringList", Arrays.asList("horse","is","pretty","scary"));
check("stringList2", Arrays.asList("horse", null));
check("stringList3", Arrays.asList("horse", ""));
check("integerList1", Arrays.asList(1,2,3,4));
check("integerList2", Arrays.asList(1,2,null));
check("numberList1", Arrays.asList(0.21,1.1,2.2));
check("numberList2", Arrays.asList(1.1,null));
check("longList1", Arrays.asList(1l,2l,3L));
check("longList2", Arrays.asList(9L,null));
check("decList1", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("4.5"),new BigDecimal("6.7")));
check("decList2",Arrays.asList(new BigDecimal("1.1"), null));
}
public void test_containerlib_append_expect_error(){
try {
doCompile("function integer transform(){string[] listInput = null; append(listInput,'aa'); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte[] listInput = null; append(listInput,str2byte('third', 'utf-8')); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long[] listInput = null; append(listInput,15L); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] listInput = null; append(listInput,12); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal[] listInput = null; append(listInput,12.5d); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number[] listInput = null; append(listInput,12.36); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
@SuppressWarnings("unchecked")
public void test_containerlib_clear() {
doCompile("test_containerlib_clear");
assertTrue(((List<Integer>) getVariable("integerList")).isEmpty());
assertTrue(((List<Integer>) getVariable("strList")).isEmpty());
assertTrue(((List<Integer>) getVariable("longList")).isEmpty());
assertTrue(((List<Integer>) getVariable("decList")).isEmpty());
assertTrue(((List<Integer>) getVariable("numList")).isEmpty());
assertTrue(((List<Integer>) getVariable("byteList")).isEmpty());
assertTrue(((List<Integer>) getVariable("dateList")).isEmpty());
assertTrue(((List<Integer>) getVariable("boolList")).isEmpty());
assertTrue(((List<Integer>) getVariable("emptyList")).isEmpty());
assertTrue(((Map<String,Integer>) getVariable("myMap")).isEmpty());
}
public void test_container_clear_expect_error(){
try {
doCompile("function integer transform(){boolean[] nullList = null; clear(nullList); return 0;}","test_container_clear_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[integer,string] myMap = null; clear(myMap); return 0;}","test_container_clear_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_copy() {
doCompile("test_containerlib_copy");
check("copyIntList", Arrays.asList(1, 2, 3, 4, 5));
check("returnedIntList", Arrays.asList(1, 2, 3, 4, 5));
check("copyLongList", Arrays.asList(21L,15L, null, 10L));
check("returnedLongList", Arrays.asList(21l, 15l, null, 10L));
check("copyBoolList", Arrays.asList(false,false,null,true));
check("returnedBoolList", Arrays.asList(false,false,null,true));
Calendar cal = Calendar.getInstance();
cal.set(2006, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2002, 03, 12, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
check("copyDateList",Arrays.asList(cal2.getTime(), null, cal.getTime()));
check("returnedDateList",Arrays.asList(cal2.getTime(), null, cal.getTime()));
check("copyStrList", Arrays.asList("Ashe", "Jax", null, "Rengar"));
check("returnedStrList", Arrays.asList("Ashe", "Jax", null, "Rengar"));
check("copyNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d));
check("returnedNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d));
check("copyDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3")));
check("returnedDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3")));
Map<String, String> expectedMap = new HashMap<String, String>();
expectedMap.put("a", "a");
expectedMap.put("b", "b");
expectedMap.put("c", "c");
expectedMap.put("d", "d");
check("copyStrMap", expectedMap);
check("returnedStrMap", expectedMap);
Map<Integer, Integer> intMap = new HashMap<Integer, Integer>();
intMap.put(1,12);
intMap.put(2,null);
intMap.put(3,15);
check("copyIntMap", intMap);
check("returnedIntMap", intMap);
Map<Long, Long> longMap = new HashMap<Long, Long>();
longMap.put(10L, 453L);
longMap.put(11L, null);
longMap.put(12L, 54755L);
check("copyLongMap", longMap);
check("returnedLongMap", longMap);
Map<BigDecimal, BigDecimal> decMap = new HashMap<BigDecimal, BigDecimal>();
decMap.put(new BigDecimal("2.2"), new BigDecimal("12.3"));
decMap.put(new BigDecimal("2.3"), new BigDecimal("45.6"));
check("copyDecMap", decMap);
check("returnedDecMap", decMap);
Map<Double, Double> doubleMap = new HashMap<Double, Double>();
doubleMap.put(new Double(12.3d), new Double(11.2d));
doubleMap.put(new Double(13.4d), new Double(78.9d));
check("copyNumMap",doubleMap);
check("returnedNumMap", doubleMap);
List<String> myList = new ArrayList<String>();
check("copyEmptyList", myList);
check("returnedEmptyList", myList);
assertTrue(((List<String>)(getVariable("copyEmptyList"))).isEmpty());
assertTrue(((List<String>)(getVariable("returnedEmptyList"))).isEmpty());
Map<String, String> emptyMap = new HashMap<String, String>();
check("copyEmptyMap", emptyMap);
check("returnedEmptyMap", emptyMap);
assertTrue(((HashMap<String,String>)(getVariable("copyEmptyMap"))).isEmpty());
assertTrue(((HashMap<String,String>)(getVariable("returnedEmptyMap"))).isEmpty());
}
public void test_containerlib_copy_expect_error(){
try {
doCompile("function integer transform(){string[] origList = null; string[] copyList; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] origList; string[] copyList = null; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string, string] orig = null; map[string, string] copy; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string, string] orig; map[string, string] copy = null; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_insert() {
doCompile("test_containerlib_insert");
check("copyStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV"));
check("retStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV"));
check("copyStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe"));
check("retStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe"));
Calendar cal = Calendar.getInstance();
cal.set(2009, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal1 = Calendar.getInstance();
cal1.set(2008, 2, 7, 0, 0, 0);
cal1.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2003, 01, 1, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
check("copyDateList", Arrays.asList(cal1.getTime(),cal.getTime()));
check("retDateList", Arrays.asList(cal1.getTime(),cal.getTime()));
check("copyDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime()));
check("retDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime()));
check("copyIntList", Arrays.asList(1,2,3,12,4,5,6,7));
check("retIntList", Arrays.asList(1,2,3,12,4,5,6,7));
check("copyLongList", Arrays.asList(14L,15l,16l,17l));
check("retLongList", Arrays.asList(14L,15l,16l,17l));
check("copyLongList2", Arrays.asList(20L,21L,22L,23l));
check("retLongList2", Arrays.asList(20L,21L,22L,23l));
check("copyNumList", Arrays.asList(12.3d,11.1d,15.4d));
check("retNumList", Arrays.asList(12.3d,11.1d,15.4d));
check("copyNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d));
check("retNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d));
check("copyDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3")));
check("retDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3")));
check("copyDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2")));
check("retDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2")));
check("copyEmpty", Arrays.asList(11));
check("retEmpty", Arrays.asList(11));
check("copyEmpty2", Arrays.asList(12,13));
check("retEmpty2", Arrays.asList(12,13));
check("copyEmpty3", Arrays.asList());
check("retEmpty3", Arrays.asList());
}
public void test_containerlib_insert_expect_error(){
try {
doCompile("function integer transform(){integer[] tmp = null; integer[] ret = insert(tmp,0,12); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] tmp; integer[] toAdd = null; integer[] ret = insert(tmp,0,toAdd); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,-1,12); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,10,12); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_isEmpty() {
doCompile("test_containerlib_isEmpty");
check("emptyMap", true);
check("emptyMap1", true);
check("fullMap", false);
check("fullMap1", false);
check("emptyList", true);
check("emptyList1", true);
check("fullList", false);
check("fullList1", false);
}
public void test_containerlib_isEmpty_expect_error(){
try {
doCompile("function integer transform(){integer[] i = null; boolean boo = i.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string, string] m = null; boolean boo = m.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_length(){
doCompile("test_containerlib_length");
check("lengthByte", 18);
check("lengthByte2", 18);
check("recordLength", 9);
check("recordLength2", 9);
check("listLength", 3);
check("listLength2", 3);
check("emptyListLength", 0);
check("emptyListLength2", 0);
check("emptyMapLength", 0);
check("emptyMapLength2", 0);
check("nullLength1", 0);
check("nullLength2", 0);
check("nullLength3", 0);
check("nullLength4", 0);
check("nullLength5", 0);
check("nullLength6", 0);
}
public void test_containerlib_poll() throws UnsupportedEncodingException {
doCompile("test_containerlib_poll");
check("intElem", Integer.valueOf(1));
check("intElem1", 2);
check("intList", Arrays.asList(3, 4, 5));
check("strElem", "Zyra");
check("strElem2", "Tresh");
check("strList", Arrays.asList("Janna", "Wu Kong"));
Calendar cal = Calendar.getInstance();
cal.set(2002, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem", cal.getTime());
cal.clear();
cal.set(2003,5,12,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem2", cal.getTime());
cal.clear();
cal.set(2006,9,15,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime()));
checkArray("byteElem", "Maoki".getBytes("UTF-8"));
checkArray("byteElem2", "Nasus".getBytes("UTF-8"));
check("longElem", 12L);
check("longElem2", 15L);
check("longList", Arrays.asList(16L,23L));
check("numElem", 23.6d);
check("numElem2", 15.9d);
check("numList", Arrays.asList(78.8d, 57.2d));
check("decElem", new BigDecimal("12.3"));
check("decElem2", new BigDecimal("23.4"));
check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6")));
check("emptyElem", null);
check("emptyElem2", null);
check("emptyList", Arrays.asList());
}
public void test_containerlib_poll_expect_error(){
try {
doCompile("function integer transform(){integer[] arr = null; integer i = poll(arr); return 0;}","test_containerlib_poll_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] arr = null; integer i = arr.poll(); return 0;}","test_containerlib_poll_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_pop() {
doCompile("test_containerlib_pop");
check("intElem", 5);
check("intElem2", 4);
check("intList", Arrays.asList(1, 2, 3));
check("longElem", 14L);
check("longElem2", 13L);
check("longList", Arrays.asList(11L,12L));
check("numElem", 11.5d);
check("numElem2", 11.4d);
check("numList", Arrays.asList(11.2d,11.3d));
check("decElem", new BigDecimal("22.5"));
check("decElem2", new BigDecimal("22.4"));
check("decList", Arrays.asList(new BigDecimal("22.2"), new BigDecimal("22.3")));
Calendar cal = Calendar.getInstance();
cal.set(2005, 8, 24, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem",cal.getTime());
cal.clear();
cal.set(2001, 6, 13, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem2", cal.getTime());
cal.clear();
cal.set(2010, 5, 11, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2011,3,3,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime(),cal2.getTime()));
check("strElem", "Ezrael");
check("strElem2", null);
check("strList", Arrays.asList("Kha-Zix", "Xerath"));
check("emptyElem", null);
check("emptyElem2", null);
}
public void test_containerlib_pop_expect_error(){
try {
doCompile("function integer transform(){string[] arr = null; string str = pop(arr); return 0;}","test_containerlib_pop_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] arr = null; string str = arr.pop(); return 0;}","test_containerlib_pop_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
@SuppressWarnings("unchecked")
public void test_containerlib_push() {
doCompile("test_containerlib_push");
check("intCopy", Arrays.asList(1, 2, 3));
check("intRet", Arrays.asList(1, 2, 3));
check("longCopy", Arrays.asList(12l,13l,14l));
check("longRet", Arrays.asList(12l,13l,14l));
check("numCopy", Arrays.asList(11.1d,11.2d,11.3d));
check("numRet", Arrays.asList(11.1d,11.2d,11.3d));
check("decCopy", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4")));
check("decRet", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4")));
check("strCopy", Arrays.asList("Fiora", "Nunu", "Amumu"));
check("strRet", Arrays.asList("Fiora", "Nunu", "Amumu"));
Calendar cal = Calendar.getInstance();
cal.set(2001, 5, 9, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal1 = Calendar.getInstance();
cal1.set(2005, 5, 9, 0, 0, 0);
cal1.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2011, 5, 9, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateCopy", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime()));
check("dateRet", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime()));
String str = null;
check("emptyCopy", Arrays.asList(str));
check("emptyRet", Arrays.asList(str));
// there is hardly any way to get an instance of DataRecord
// hence we just check if the list has correct size
// and if its elements have correct metadata
List<DataRecord> recordList = (List<DataRecord>) getVariable("recordList");
List<DataRecordMetadata> mdList = Arrays.asList(
graph.getDataRecordMetadata(OUTPUT_1),
graph.getDataRecordMetadata(INPUT_2),
graph.getDataRecordMetadata(INPUT_1)
);
assertEquals(mdList.size(), recordList.size());
for (int i = 0; i < mdList.size(); i++) {
assertEquals(mdList.get(i), recordList.get(i).getMetadata());
}
}
public void test_containerlib_push_expect_error(){
try {
doCompile("function integer transform(){string[] str = null; str.push('a'); return 0;}","test_containerlib_push_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] str = null; push(str, 'a'); return 0;}","test_containerlib_push_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_remove() {
doCompile("test_containerlib_remove");
check("intElem", 2);
check("intList", Arrays.asList(1, 3, 4, 5));
check("longElem", 13L);
check("longList", Arrays.asList(11l,12l,14l));
check("numElem", 11.3d);
check("numList", Arrays.asList(11.1d,11.2d,11.4d));
check("decElem", new BigDecimal("11.3"));
check("decList", Arrays.asList(new BigDecimal("11.1"),new BigDecimal("11.2"),new BigDecimal("11.4")));
Calendar cal = Calendar.getInstance();
cal.set(2002,10,13,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem", cal.getTime());
cal.clear();
cal.set(2001,10,13,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2003,10,13,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime(), cal2.getTime()));
check("strElem", "Shivana");
check("strList", Arrays.asList("Annie","Lux"));
}
public void test_containerlib_remove_expect_error(){
try {
doCompile("function integer transform(){string[] strList; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList; string str = strList.remove(0); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,5); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,-1); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = null; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_reverse_expect_error(){
try {
doCompile("function integer transform(){long[] longList = null; reverse(longList); return 0;}","test_containerlib_reverse_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long[] longList = null; long[] reversed = longList.reverse(); return 0;}","test_containerlib_reverse_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_reverse() {
doCompile("test_containerlib_reverse");
check("intList", Arrays.asList(5, 4, 3, 2, 1));
check("intList2", Arrays.asList(5, 4, 3, 2, 1));
check("longList", Arrays.asList(14l,13l,12l,11l));
check("longList2", Arrays.asList(14l,13l,12l,11l));
check("numList", Arrays.asList(1.3d,1.2d,1.1d));
check("numList2", Arrays.asList(1.3d,1.2d,1.1d));
check("decList", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1")));
check("decList2", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1")));
check("strList", Arrays.asList(null,"Lulu","Kog Maw"));
check("strList2", Arrays.asList(null,"Lulu","Kog Maw"));
Calendar cal = Calendar.getInstance();
cal.set(2001,2,1,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2002,2,1,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal2.getTime(),cal.getTime()));
check("dateList2", Arrays.asList(cal2.getTime(),cal.getTime()));
}
public void test_containerlib_sort() {
doCompile("test_containerlib_sort");
check("intList", Arrays.asList(1, 1, 2, 3, 5));
check("intList2", Arrays.asList(1, 1, 2, 3, 5));
check("longList", Arrays.asList(21l,22l,23l,24l));
check("longList2", Arrays.asList(21l,22l,23l,24l));
check("decList", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4")));
check("decList2", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4")));
check("numList", Arrays.asList(1.1d,1.2d,1.3d,1.4d));
check("numList2", Arrays.asList(1.1d,1.2d,1.3d,1.4d));
Calendar cal = Calendar.getInstance();
cal.set(2002,5,12,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2003,5,12,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
Calendar cal3 = Calendar.getInstance();
cal3.set(2004,5,12,0,0,0);
cal3.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime()));
check("dateList2", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime()));
check("strList", Arrays.asList("","Alistar", "Nocturne", "Soraka"));
check("strList2", Arrays.asList("","Alistar", "Nocturne", "Soraka"));
check("emptyList", Arrays.asList());
check("emptyList2", Arrays.asList());
}
public void test_containerlib_sort_expect_error(){
try {
doCompile("function integer transform(){string[] strList = ['Renektor', null, 'Jayce']; sort(strList); return 0;}","test_containerlib_sort_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = null; sort(strList); return 0;}","test_containerlib_sort_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_containsAll() {
doCompile("test_containerlib_containsAll");
check("results", Arrays.asList(true, false, true, false, true, true, true, false, true, true, false));
check("test1", true);
check("test2", true);
check("test3", true);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", true);
check("test8", false);
check("test9", true);
check("test10", false);
check("test11", true);
check("test12", false);
check("test13", false);
check("test14", true);
check("test15", false);
check("test16", false);
}
public void test_containerlib_containsAll_expect_error(){
try {
doCompile("function integer transform(){integer[] intList = null; boolean b =intList.containsAll([1]); return 0;}","test_containerlib_containsAll_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_containsKey() {
doCompile("test_containerlib_containsKey");
check("results", Arrays.asList(false, true, false, true, false, true));
check("test1", true);
check("test2", false);
check("test3", true);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", true);
check("test8", true);
check("test9", true);
check("test10", false);
check("test11", true);
check("test12", true);
check("test13", false);
check("test14", true);
check("test15", true);
check("test16", false);
check("test17", true);
check("test18", true);
check("test19", false);
check("test20", false);
}
public void test_containerlib_containsKey_expect_error(){
try {
doCompile("function integer transform(){map[string, integer] emptyMap = null; boolean b = emptyMap.containsKey('a'); return 0;}","test_containerlib_containsKey_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_containsValue() {
doCompile("test_containerlib_containsValue");
check("results", Arrays.asList(true, false, false, true, false, false, true, false));
check("test1", true);
check("test2", true);
check("test3", false);
check("test4", true);
check("test5", true);
check("test6", false);
check("test7", false);
check("test8", true);
check("test9", true);
check("test10", false);
check("test11", true);
check("test12", true);
check("test13", false);
check("test14", true);
check("test15", true);
check("test16", false);
check("test17", true);
check("test18", true);
check("test19", false);
check("test20", true);
check("test21", true);
check("test22", false);
check("test23", true);
check("test24", true);
check("test25", false);
check("test26", false);
}
public void test_convertlib_containsValue_expect_error(){
try {
doCompile("function integer transform(){map[integer, long] nullMap = null; boolean b = nullMap.containsValue(18L); return 0;}","test_convertlib_containsValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_getKeys() {
doCompile("test_containerlib_getKeys");
check("stringList", Arrays.asList("a","b"));
check("stringList2", Arrays.asList("a","b"));
check("integerList", Arrays.asList(5,7,2));
check("integerList2", Arrays.asList(5,7,2));
List<Date> list = new ArrayList<Date>();
Calendar cal = Calendar.getInstance();
cal.set(2008, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2001, 5, 28, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
list.add(cal.getTime());
list.add(cal2.getTime());
check("dateList", list);
check("dateList2", list);
check("longList", Arrays.asList(14L, 45L));
check("longList2", Arrays.asList(14L, 45L));
check("numList", Arrays.asList(12.3d, 13.4d));
check("numList2", Arrays.asList(12.3d, 13.4d));
check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6")));
check("decList2", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6")));
check("emptyList", Arrays.asList());
check("emptyList2", Arrays.asList());
}
public void test_containerlib_getKeys_expect_error(){
try {
doCompile("function integer transform(){map[string,string] strMap = null; string[] str = strMap.getKeys(); return 0;}","test_containerlib_getKeys_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string,string] strMap = null; string[] str = getKeys(strMap); return 0;}","test_containerlib_getKeys_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_cache() {
doCompile("test_stringlib_cache");
check("rep1", "The cat says meow. All cats say meow.");
check("rep2", "The cat says meow. All cats say meow.");
check("rep3", "The cat says meow. All cats say meow.");
check("find1", Arrays.asList("to", "to", "to", "tro", "to"));
check("find2", Arrays.asList("to", "to", "to", "tro", "to"));
check("find3", Arrays.asList("to", "to", "to", "tro", "to"));
check("split1", Arrays.asList("one", "two", "three", "four", "five"));
check("split2", Arrays.asList("one", "two", "three", "four", "five"));
check("split3", Arrays.asList("one", "two", "three", "four", "five"));
check("chop01", "ting soming choping function");
check("chop02", "ting soming choping function");
check("chop03", "ting soming choping function");
check("chop11", "testing end of lines cutting");
check("chop12", "testing end of lines cutting");
}
public void test_stringlib_charAt() {
doCompile("test_stringlib_charAt");
String input = "The QUICk !!$ broWn fox juMPS over the lazy DOG ";
String[] expected = new String[input.length()];
for (int i = 0; i < expected.length; i++) {
expected[i] = String.valueOf(input.charAt(i));
}
check("chars", Arrays.asList(expected));
}
public void test_stringlib_charAt_error(){
//test: attempt to access char at position, which is out of bounds -> upper bound
try {
doCompile("string test;function integer transform(){test = charAt('milk', 7);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: attempt to access char at position, which is out of bounds -> lower bound
try {
doCompile("string test;function integer transform(){test = charAt('milk', -1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: argument for position is null
try {
doCompile("string test; integer i = null; function integer transform(){test = charAt('milk', i);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is null
try {
doCompile("string test;function integer transform(){test = charAt(null, 1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is empty string
try {
doCompile("string test;function integer transform(){test = charAt('', 1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_concat() {
doCompile("test_stringlib_concat");
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("concat", "");
check("concat1", "ello hi ELLO 2,today is " + format.format(new Date()));
check("concat2", "");
check("concat3", "clover");
check("test_null1", "null");
check("test_null2", "null");
check("test_null3","skynullisnullblue");
}
public void test_stringlib_countChar() {
doCompile("test_stringlib_countChar");
check("charCount", 3);
check("count2", 0);
}
public void test_stringlib_countChar_emptychar() {
// test: attempt to count empty chars in string.
try {
doCompile("integer charCount;function integer transform() {charCount = countChar('aaa','');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
// test: attempt to count empty chars in empty string.
try {
doCompile("integer charCount;function integer transform() {charCount = countChar('','');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 1
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null,'a');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 2
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null,'');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 3
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null, null);return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_cut() {
doCompile("test_stringlib_cut");
check("cutInput", Arrays.asList("a", "1edf", "h3ijk"));
}
public void test_string_cut_expect_error() {
// test: Attempt to cut substring from position after the end of original string. E.g. string is 6 char long and
// user attempt to cut out after position 8.
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[28,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut substring longer then possible. E.g. string is 6 characters long and user cuts from
// position
// 4 substring 4 characters long
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,8]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut a substring with negative length
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,-3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut substring from negative position. E.g cut([-3,3]).
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[-3,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is empty string
try {
doCompile("string input;string[] cutInput;function integer transform() {input = '';cutInput = cut(input,[0,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: second arg is null
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'aaaa';cutInput = cut(input,null);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is null
try {
doCompile("string input;string[] cutInput;function integer transform() {input = null;cutInput = cut(input,[5,11]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_editDistance() {
doCompile("test_stringlib_editDistance");
check("dist", 1);
check("dist1", 1);
check("dist2", 0);
check("dist5", 1);
check("dist3", 1);
check("dist4", 0);
check("dist6", 4);
check("dist7", 5);
check("dist8", 0);
check("dist9", 0);
}
public void test_stringlib_editDistance_expect_error(){
//test: input - empty string - first arg
try {
doCompile("integer test;function integer transform() {test = editDistance('','mark');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - null - first arg
try {
doCompile("integer test;function integer transform() {test = editDistance(null,'mark');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input- empty string - second arg
try {
doCompile("integer test;function integer transform() {test = editDistance('mark','');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - null - second argument
try {
doCompile("integer test;function integer transform() {test = editDistance('mark',null);return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - both empty
try {
doCompile("integer test;function integer transform() {test = editDistance('','');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - both null
try {
doCompile("integer test;function integer transform() {test = editDistance(null,null);return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
}
public void test_stringlib_find() {
doCompile("test_stringlib_find");
check("findList", Arrays.asList("The quick br", "wn f", "x jumps ", "ver the lazy d", "g"));
check("findList2", Arrays.asList("mark.twain"));
check("findList3", Arrays.asList());
check("findList4", Arrays.asList("", "", "", "", ""));
check("findList5", Arrays.asList("twain"));
check("findList6", Arrays.asList(""));
}
public void test_stringlib_find_expect_error() {
//test: regexp group number higher then count of regexp groups
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu','(^[a-z]*).([a-z]*)',5); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: negative regexp group number
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu','(^[a-z]*).([a-z]*)',-1); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg1 null input
try {
doCompile("string[] findList;function integer transform() {findList = find(null,'(^[a-z]*).([a-z]*)'); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg2 null input - test1
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu',null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg2 null input - test2
try {
doCompile("string[] findList;function integer transform() {findList = find('',null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg1 and arg2 null input
try {
doCompile("string[] findList;function integer transform() {findList = find(null,null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_join() {
doCompile("test_stringlib_join");
//check("joinedString", "Bagr,3,3.5641,-87L,CTL2");
check("joinedString1", "80=5455.987\"-5=5455.987\"3=0.1");
check("joinedString2", "5.054.6567.0231.0");
//check("joinedString3", "554656723180=5455.987-5=5455.9873=0.1CTL242");
check("test_empty1", "abc");
check("test_empty2", "");
check("test_empty3"," ");
check("test_empty4","anullb");
check("test_empty5","80=5455.987-5=5455.9873=0.1");
check("test_empty6","80=5455.987 -5=5455.987 3=0.1");
check("test_null1","abc");
check("test_null2","");
check("test_null3","anullb");
check("test_null4","80=5455.987-5=5455.9873=0.1");
//CLO-1210
// check("test_empty7","a=xb=nullc=z");
// check("test_empty8","a=x b=null c=z");
// check("test_empty9","null=xeco=storm");
// check("test_empty10","null=x eco=storm");
// check("test_null5","a=xb=nullc=z");
// check("test_null6","null=xeco=storm");
}
public void test_stringlib_join_expect_error(){
try {
doCompile("function integer transform(){string s = join(';',null);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] tmp = null; string s = join(';',tmp);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string,string] a = null; string s = join(';',a);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_left() {
//CLO - 1193
// doCompile("test_stringlib_left");
// check("test1", "aa");
// check("test2", "aaa");
// check("test3", "");
// check("test4", null);
// check("test5", "abc");
// check("test6", "ab ");
// check("test7", " ");
// check("test8", " ");
// check("test9", "abc");
// check("test10", "abc");
// check("test11", "");
// check("test12", null);
}
public void test_stringlib_length() {
doCompile("test_stringlib_length");
check("lenght1", new BigDecimal(50));
check("stringLength", 8);
check("length_empty", 0);
check("length_null1", 0);
}
public void test_stringlib_lowerCase() {
doCompile("test_stringlib_lowerCase");
check("lower", "the quick !!$ brown fox jumps over the lazy dog bagr ");
check("lower_empty", "");
check("lower_null", null);
}
public void test_stringlib_matches() {
doCompile("test_stringlib_matches");
check("matches1", true);
check("matches2", true);
check("matches3", false);
check("matches4", true);
check("matches5", false);
check("matches6", false);
check("matches7", false);
check("matches8", false);
check("matches9", true);
check("matches10", true);
}
public void test_stringlib_matches_expect_error(){
//test: regexp param null - test 1
try {
doCompile("boolean test; function integer transform(){test = matches('aaa', null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp param null - test 2
try {
doCompile("boolean test; function integer transform(){test = matches('', null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp param null - test 3
try {
doCompile("boolean test; function integer transform(){test = matches(null, null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_matchGroups() {
doCompile("test_stringlib_matchGroups");
check("result1", null);
check("result2", Arrays.asList(
//"(([^:]*)([:])([\\(]))(.*)(\\))(((
"zip:(zip:(/path/name?.zip)#innerfolder/file.zip)#innermostfolder?/filename*.txt",
"zip:(",
"zip",
":",
"(",
"zip:(/path/name?.zip)#innerfolder/file.zip",
")",
"#innermostfolder?/filename*.txt",
"#innermostfolder?/filename*.txt",
"
"innermostfolder?/filename*.txt",
null
)
);
check("result3", null);
check("test_empty1", null);
check("test_empty2", Arrays.asList(""));
check("test_null1", null);
check("test_null2", null);
}
public void test_stringlib_matchGroups_expect_error(){
//test: regexp is null - test 1
try {
doCompile("string[] test; function integer transform(){test = matchGroups('eat all the cookies',null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
//test: regexp is null - test 2
try {
doCompile("string[] test; function integer transform(){test = matchGroups('',null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
//test: regexp is null - test 3
try {
doCompile("string[] test; function integer transform(){test = matchGroups(null,null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_matchGroups_unmodifiable() {
try {
doCompile("test_stringlib_matchGroups_unmodifiable");
fail();
} catch (RuntimeException re) {
};
}
public void test_stringlib_metaphone() {
doCompile("test_stringlib_metaphone");
check("metaphone1", "XRS");
check("metaphone2", "KWNTLN");
check("metaphone3", "KWNT");
check("metaphone4", "");
check("metaphone5", "");
check("test_empty1", "");
check("test_empty2", "");
check("test_null1", null);
check("test_null2", null);
}
public void test_stringlib_nysiis() {
doCompile("test_stringlib_nysiis");
check("nysiis1", "CAP");
check("nysiis2", "CAP");
check("nysiis3", "1234");
check("nysiis4", "C2 PRADACTAN");
check("nysiis_empty", "");
check("nysiis_null", null);
}
public void test_stringlib_replace() {
doCompile("test_stringlib_replace");
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("rep", format.format(new Date()).replaceAll("[lL]", "t"));
check("rep1", "The cat says meow. All cats say meow.");
check("rep2", "intruders must die");
check("test_empty1", "a");
check("test_empty2", "");
check("test_null", null);
check("test_null2","");
check("test_null3","bbb");
check("test_null4",null);
}
public void test_stringlib_replace_expect_error(){
//test: regexp null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b',null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test2
try {
doCompile("string test; function integer transform(){test = replace('',null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test3
try {
doCompile("string test; function integer transform(){test = replace(null,null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b','a+',null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// //test: arg3 null - test2
// try {
// doCompile("string test; function integer transform(){test = replace('','a+',null); return 0;}","test_stringlib_replace_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
// //test: arg3 null - test3
// try {
// doCompile("string test; function integer transform(){test = replace(null,'a+',null); return 0;}","test_stringlib_replace_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
//test: regexp and arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b',null,null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp and arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace(null,null,null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_right() {
doCompile("test_stringlib_right");
check("righ", "y dog");
check("rightNotPadded", "y dog");
check("rightPadded", "y dog");
check("padded", " y dog");
check("notPadded", "y dog");
check("short", "Dog");
check("shortNotPadded", "Dog");
check("shortPadded", " Dog");
check("simple", "milk");
check("test_null1", null);
check("test_null2", null);
check("test_null3", " ");
check("test_empty1", "");
check("test_empty2", "");
check("test_empty3"," ");
}
public void test_stringlib_soundex() {
doCompile("test_stringlib_soundex");
check("soundex1", "W630");
check("soundex2", "W643");
check("test_null", null);
check("test_empty", "");
}
public void test_stringlib_split() {
doCompile("test_stringlib_split");
check("split1", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g"));
check("test_empty", Arrays.asList(""));
check("test_empty2", Arrays.asList("","a","a"));
List<String> tmp = new ArrayList<String>();
tmp.add(null);
check("test_null", tmp);
}
public void test_stringlib_split_expect_error(){
//test: regexp null - test1
try {
doCompile("function integer transform(){string[] s = split('aaa',null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test2
try {
doCompile("function integer transform(){string[] s = split('',null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test3
try {
doCompile("function integer transform(){string[] s = split(null,null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_substring() {
doCompile("test_stringlib_substring");
check("subs", "UICk ");
check("test1", "");
check("test_empty", "");
}
public void test_stringlib_substring_expect_error(){
try {
doCompile("function integer transform(){string test = substring('arabela',4,19);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',15,3);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',2,-3);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',-5,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('',0,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('',7,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,0,0);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,0,4);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,1,4);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_trim() {
doCompile("test_stringlib_trim");
check("trim1", "im The QUICk !!$ broWn fox juMPS over the lazy DOG");
check("trim_empty", "");
check("trim_null", null);
}
public void test_stringlib_upperCase() {
doCompile("test_stringlib_upperCase");
check("upper", "THE QUICK !!$ BROWN FOX JUMPS OVER THE LAZY DOG BAGR ");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_isFormat() {
doCompile("test_stringlib_isFormat");
check("test", "test");
check("isBlank", Boolean.FALSE);
check("blank", "");
checkNull("nullValue");
check("isBlank1", true);
check("isBlank2", true);
check("isAscii1", true);
check("isAscii2", false);
check("isAscii3", true);
check("isAscii4", true);
check("isNumber", false);
check("isNumber1", false);
check("isNumber2", true);
check("isNumber3", true);
check("isNumber4", false);
check("isNumber5", true);
check("isNumber6", true);
check("isNumber7", false);
check("isNumber8", false);
check("isInteger", false);
check("isInteger1", false);
check("isInteger2", false);
check("isInteger3", true);
check("isInteger4", false);
check("isInteger5", false);
check("isLong", true);
check("isLong1", false);
check("isLong2", false);
check("isLong3", false);
check("isLong4", false);
check("isDate", true);
check("isDate1", false);
// "kk" allows hour to be 1-24 (as opposed to HH allowing hour to be 0-23)
check("isDate2", true);
check("isDate3", true);
check("isDate4", false);
check("isDate5", true);
check("isDate6", true);
check("isDate7", false);
check("isDate9", false);
check("isDate10", false);
check("isDate11", false);
check("isDate12", true);
check("isDate13", false);
check("isDate14", false);
// empty string: invalid
check("isDate15", false);
check("isDate16", false);
check("isDate17", true);
check("isDate18", true);
check("isDate19", false);
check("isDate20", false);
check("isDate21", false);
/* CLO-1190
check("isDate22", false);
check("isDate23", false);
check("isDate24", true);
check("isDate25", false);
*/
}
public void test_stringlib_empty_strings() {
String[] expressions = new String[] {
"isInteger(?)",
"isNumber(?)",
"isLong(?)",
"isAscii(?)",
"isBlank(?)",
"isDate(?, \"yyyy\")",
"isUrl(?)",
"string x = ?; length(x)",
"lowerCase(?)",
"matches(?, \"\")",
"NYSIIS(?)",
"removeBlankSpace(?)",
"removeDiacritic(?)",
"removeNonAscii(?)",
"removeNonPrintable(?)",
"replace(?, \"a\", \"a\")",
"translate(?, \"ab\", \"cd\")",
"trim(?)",
"upperCase(?)",
"chop(?)",
"concat(?)",
"getAlphanumericChars(?)",
};
StringBuilder sb = new StringBuilder();
for (String expr : expressions) {
String emptyString = expr.replace("?", "\"\"");
boolean crashesEmpty = test_expression_crashes(emptyString);
assertFalse("Function " + emptyString + " crashed", crashesEmpty);
String nullString = expr.replace("?", "null");
boolean crashesNull = test_expression_crashes(nullString);
sb.append(String.format("|%20s|%5s|%5s|%n", expr, crashesEmpty ? "CRASH" : "ok", crashesNull ? "CRASH" : "ok"));
}
System.out.println(sb.toString());
}
private boolean test_expression_crashes(String expr) {
String expStr = "function integer transform() { " + expr + "; return 0; }";
try {
doCompile(expStr, "test_stringlib_empty_null_strings");
return false;
} catch (RuntimeException e) {
return true;
}
}
public void test_stringlib_removeBlankSpace() {
String expStr =
"string r1;\n" +
"string str_empty;\n" +
"string str_null;\n" +
"function integer transform() {\n" +
"r1=removeBlankSpace(\"" + StringUtils.specCharToString(" a b\nc\rd e \u000Cf\r\n") + "\");\n" +
"printErr(r1);\n" +
"str_empty = removeBlankSpace('');\n" +
"str_null = removeBlankSpace(null);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr, "test_removeBlankSpace");
check("r1", "abcdef");
check("str_empty", "");
check("str_null", null);
}
public void test_stringlib_removeNonPrintable() {
doCompile("test_stringlib_removeNonPrintable");
check("nonPrintableRemoved", "AHOJ");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_getAlphanumericChars() {
String expStr =
"string an1;\n" +
"string an2;\n" +
"string an3;\n" +
"string an4;\n" +
"string an5;\n" +
"string an6;\n" +
"string an7;\n" +
"string an8;\n" +
"string an9;\n" +
"string an10;\n" +
"string an11;\n" +
"string an12;\n" +
"string an13;\n" +
"string an14;\n" +
"string an15;\n" +
"function integer transform() {\n" +
"an1=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\");\n" +
"an2=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,true);\n" +
"an3=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,false);\n" +
"an4=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,true);\n" +
"an5=getAlphanumericChars(\"\");\n" +
"an6=getAlphanumericChars(\"\",true,true);\n"+
"an7=getAlphanumericChars(\"\",true,false);\n"+
"an8=getAlphanumericChars(\"\",false,true);\n"+
"an9=getAlphanumericChars(null);\n" +
"an10=getAlphanumericChars(null,false,false);\n" +
"an11=getAlphanumericChars(null,true,false);\n" +
"an12=getAlphanumericChars(null,false,true);\n" +
"an13=getAlphanumericChars(' 0 ľeškó11');\n" +
"an14=getAlphanumericChars(' 0 ľeškó11', false, false);\n" +
//CLO-1174
"string tmp = \""+StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\";\n"+
"printErr('BEFORE DO COMPILE: '+tmp); \n"+
"an15=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,false);\n" +
"printErr('AFTER GET_ALPHA_NUMERIC_CHARS: '+ an15);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr, "test_getAlphanumericChars");
check("an1", "a1bcde2f");
check("an2", "a1bcde2f");
check("an3", "abcdef");
check("an4", "12");
check("an5", "");
check("an6", "");
check("an7", "");
check("an8", "");
check("an9", null);
check("an10", null);
check("an11", null);
check("an12", null);
check("an13", "0ľeškó11");
check("an14"," 0 ľeškó11");
//CLO-1174
String tmp = StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n");
System.out.println("FROM JAVA - AFTER DO COMPILE: "+ tmp);
//check("an15", tmp);
}
public void test_stringlib_indexOf(){
doCompile("test_stringlib_indexOf");
check("index",2);
check("index1",9);
check("index2",0);
check("index3",-1);
check("index4",6);
check("index5",-1);
check("index6",0);
check("index7",4);
check("index8",4);
check("index9", -1);
check("index10", 2);
check("index_empty1", -1);
check("index_empty2", 0);
check("index_empty3", 0);
check("index_empty4", -1);
}
public void test_stringlib_indexOf_expect_error(){
//test: second arg is null - test1
try {
doCompile("integer index;function integer transform() {index = indexOf('hello world',null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: second arg is null - test2
try {
doCompile("integer index;function integer transform() {index = indexOf('',null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: first arg is null - test1
try {
doCompile("integer index;function integer transform() {index = indexOf(null,'a'); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: first arg is null - test2
try {
doCompile("integer index;function integer transform() {index = indexOf(null,''); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: both args are null
try {
doCompile("integer index;function integer transform() {index = indexOf(null,null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_removeDiacritic(){
doCompile("test_stringlib_removeDiacritic");
check("test","tescik");
check("test1","zabicka");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_translate(){
doCompile("test_stringlib_translate");
check("trans","hippi");
check("trans1","hipp");
check("trans2","hippi");
check("trans3","");
check("trans4","y lanuaX nXXd thX lXttXr X");
check("trans5", "hello");
check("test_empty1", "");
check("test_empty2", "");
check("test_null", null);
}
public void test_stringlib_translate_expect_error(){
try {
doCompile("function integer transform(){string test = translate('bla bla',null,'o');return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate('bla bla','a',null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate('bla bla',null,null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,'a',null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,null,'a');return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,null,null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_removeNonAscii(){
doCompile("test_stringlib_removeNonAscii");
check("test1", "Sun is shining");
check("test2", "");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_chop() {
doCompile("test_stringlib_chop");
check("s1", "hello");
check("s6", "hello");
check("s5", "hello");
check("s2", "hello");
check("s7", "helloworld");
check("s3", "hello ");
check("s4", "hello");
check("s8", "hello");
check("s9", "world");
check("s10", "hello");
check("s11", "world");
check("s12", "mark.twain");
check("s13", "two words");
check("s14", "");
check("s15", "");
check("s16", "");
check("s17", "");
check("s18", "");
check("s19", "word");
check("s20", "");
check("s21", "");
check("s22", "mark.twain");
}
public void test_stringlib_chop_expect_error() {
//test: arg is null
try {
doCompile("string test;function integer transform() {test = chop(null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp pattern is null
try {
doCompile("string test;function integer transform() {test = chop('aaa', null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp pattern is null - test 2
try {
doCompile("string test;function integer transform() {test = chop('', null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null
try {
doCompile("string test;function integer transform() {test = chop(null, 'aaa');return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null - test2
try {
doCompile("string test;function integer transform() {test = chop(null, '');return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null - test3
try {
doCompile("string test;function integer transform() {test = chop(null, null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_bitSet(){
doCompile("test_bitwise_bitSet");
check("test1", 3);
check("test2", 15);
check("test3", 34);
check("test4", 3l);
check("test5", 15l);
check("test6", 34l);
}
public void test_bitwise_bitSet_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer var1 = null;"
+ "integer var2 = 3;"
+ "boolean var3 = false;"
+ "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer var1 = 512;"
+ "integer var2 = null;"
+ "boolean var3 = false;"
+ "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer var1 = 512;"
+ "integer var2 = 3;"
+ "boolean var3 = null;"
+ "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = 512l;"
+ "integer var2 = 3;"
+ "boolean var3 = null;"
+ "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = 512l;"
+ "integer var2 = null;"
+ "boolean var3 = true;"
+ "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = null;"
+ "integer var2 = 3;"
+ "boolean var3 = true;"
+ "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_bitIsSet(){
doCompile("test_bitwise_bitIsSet");
check("test1", true);
check("test2", false);
check("test3", false);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", false);
check("test8", false);
}
public void test_bitwise_bitIsSet_expect_error(){
try {
doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(11,i); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = 12l; boolean b = bitIsSet(i,null); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_or() {
doCompile("test_bitwise_or");
check("resultInt1", 1);
check("resultInt2", 1);
check("resultInt3", 3);
check("resultInt4", 3);
check("resultLong1", 1l);
check("resultLong2", 1l);
check("resultLong3", 3l);
check("resultLong4", 3l);
check("resultMix1", 15L);
check("resultMix2", 15L);
}
public void test_bitwise_or_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer input1 = 12; "
+ "integer input2 = null; "
+ "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer input1 = null; "
+ "integer input2 = 13; "
+ "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long input1 = null; "
+ "long input2 = 13l; "
+ "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long input1 = 23l; "
+ "long input2 = null; "
+ "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_and() {
doCompile("test_bitwise_and");
check("resultInt1", 0);
check("resultInt2", 1);
check("resultInt3", 0);
check("resultInt4", 1);
check("resultLong1", 0l);
check("resultLong2", 1l);
check("resultLong3", 0l);
check("resultLong4", 1l);
check("test_mixed1", 4l);
check("test_mixed2", 4l);
}
public void test_bitwise_and_expect_error(){
try {
doCompile("function integer transform(){\n"
+ "integer a = null; integer b = 16;\n"
+ "integer i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "integer a = 16; integer b = null;\n"
+ "integer i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "long a = 16l; long b = null;\n"
+ "long i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "long a = null; long b = 10l;\n"
+ "long i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_xor() {
doCompile("test_bitwise_xor");
check("resultInt1", 1);
check("resultInt2", 0);
check("resultInt3", 3);
check("resultInt4", 2);
check("resultLong1", 1l);
check("resultLong2", 0l);
check("resultLong3", 3l);
check("resultLong4", 2l);
check("test_mixed1", 15L);
check("test_mixed2", 60L);
}
public void test_bitwise_xor_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer var1 = null;"
+ "integer var2 = 123;"
+ "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer var1 = 23;"
+ "integer var2 = null;"
+ "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = null;"
+ "long var2 = 123l;"
+ "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = 2135l;"
+ "long var2 = null;"
+ "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_lshift() {
doCompile("test_bitwise_lshift");
check("resultInt1", 2);
check("resultInt2", 4);
check("resultInt3", 10);
check("resultInt4", 20);
check("resultInt5", -2147483648);
check("resultLong1", 2l);
check("resultLong2", 4l);
check("resultLong3", 10l);
check("resultLong4", 20l);
check("resultLong5",-9223372036854775808l);
}
public void test_bitwise_lshift_expect_error(){
try {
doCompile("function integer transform(){integer input = null; integer i = bitLShift(input,2); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer input = null; integer i = bitLShift(44,input); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitLShift(input,4l); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitLShift(444l,input); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_rshift() {
doCompile("test_bitwise_rshift");
check("resultInt1", 2);
check("resultInt2", 0);
check("resultInt3", 4);
check("resultInt4", 2);
check("resultLong1", 2l);
check("resultLong2", 0l);
check("resultLong3", 4l);
check("resultLong4", 2l);
check("test_neg1", 0);
check("test_neg2", 0);
check("test_neg3", 0l);
check("test_neg4", 0l);
// CLO-1399
// check("test_mix1", 2);
// check("test_mix2", 2);
}
public void test_bitwise_rshift_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer var1 = 23;"
+ "integer var2 = null;"
+ "integer i = bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){"
+ "integer var1 = null;"
+ "integer var2 = 78;"
+ "integer u = bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){"
+ "long var1 = 23l;"
+ "long var2 = null;"
+ "long l =bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){"
+ "long var1 = null;"
+ "long var2 = 84l;"
+ "long l = bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_bitwise_negate() {
doCompile("test_bitwise_negate");
check("resultInt", -59081717);
check("resultLong", -3321654987654105969L);
check("test_zero_int", -1);
check("test_zero_long", -1l);
}
public void test_bitwise_negate_expect_error(){
try {
doCompile("function integer transform(){integer input = null; integer i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_set_bit() {
doCompile("test_set_bit");
check("resultInt1", 0x2FF);
check("resultInt2", 0xFB);
check("resultLong1", 0x4000000000000l);
check("resultLong2", 0xFFDFFFFFFFFFFFFl);
check("resultBool1", true);
check("resultBool2", false);
check("resultBool3", true);
check("resultBool4", false);
}
public void test_mathlib_abs() {
doCompile("test_mathlib_abs");
check("absIntegerPlus", new Integer(10));
check("absIntegerMinus", new Integer(1));
check("absLongPlus", new Long(10));
check("absLongMinus", new Long(1));
check("absDoublePlus", new Double(10.0));
check("absDoubleMinus", new Double(1.0));
check("absDecimalPlus", new BigDecimal(5.0));
check("absDecimalMinus", new BigDecimal(5.0));
}
public void test_mathlib_abs_expect_error(){
try {
doCompile("function integer transform(){ \n "
+ "integer tmp;\n "
+ "tmp = null; \n"
+ " integer i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "long tmp;\n "
+ "tmp = null; \n"
+ "long i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "double tmp;\n "
+ "tmp = null; \n"
+ "double i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "decimal tmp;\n "
+ "tmp = null; \n"
+ "decimal i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_ceil() {
doCompile("test_mathlib_ceil");
check("ceil1", -3.0);
check("intResult", Arrays.asList(2.0, 3.0));
check("longResult", Arrays.asList(2.0, 3.0));
check("doubleResult", Arrays.asList(3.0, -3.0));
check("decimalResult", Arrays.asList(3.0, -3.0));
}
public void test_mathlib_ceil_expect_error(){
try {
doCompile("function integer transform(){integer var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_e() {
doCompile("test_mathlib_e");
check("varE", Math.E);
}
public void test_mathlib_exp() {
doCompile("test_mathlib_exp");
check("ex", Math.exp(1.123));
check("test1", Math.exp(2));
check("test2", Math.exp(22));
check("test3", Math.exp(23));
check("test4", Math.exp(94));
}
public void test_mathlib_exp_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_floor() {
doCompile("test_mathlib_floor");
check("floor1", -4.0);
check("intResult", Arrays.asList(2.0, 3.0));
check("longResult", Arrays.asList(2.0, 3.0));
check("doubleResult", Arrays.asList(2.0, -4.0));
check("decimalResult", Arrays.asList(2.0, -4.0));
}
public void test_math_lib_floor_expect_error(){
try {
doCompile("function integer transform(){integer input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input= null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_log() {
doCompile("test_mathlib_log");
check("ln", Math.log(3));
check("test_int", Math.log(32));
check("test_long", Math.log(14l));
check("test_double", Math.log(12.9));
check("test_decimal", Math.log(23.7));
}
public void test_math_log_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){long input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){decimal input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){double input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_mathlib_log10() {
doCompile("test_mathlib_log10");
check("varLog10", Math.log10(3));
check("test_int", Math.log10(5));
check("test_long", Math.log10(90L));
check("test_decimal", Math.log10(32.1));
check("test_number", Math.log10(84.12));
}
public void test_mathlib_log10_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_pi() {
doCompile("test_mathlib_pi");
check("varPi", Math.PI);
}
public void test_mathlib_pow() {
doCompile("test_mathlib_pow");
check("power1", Math.pow(3,1.2));
check("power2", Double.NaN);
check("intResult", Arrays.asList(8d, 8d, 8d, 8d));
check("longResult", Arrays.asList(8d, 8d, 8d, 8d));
check("doubleResult", Arrays.asList(8d, 8d, 8d, 8d));
check("decimalResult", Arrays.asList(8d, 8d, 8d, 8d));
}
public void test_mathlib_pow_expect_error(){
try {
doCompile("function integer transform(){integer var1 = 12; integer var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer var1 = null; integer var2 = 2; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long var1 = 12l; long var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long var1 = null; long var2 = 12L; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number var1 = 12.2; number var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number var1 = null; number var2 = 2.1; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal var1 = 12.2d; decimal var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal var1 = null; decimal var2 = 45.3d; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_round() {
doCompile("test_mathlib_round");
check("round1", -4l);
check("intResult", Arrays.asList(2l, 3l));
check("longResult", Arrays.asList(2l, 3l));
check("doubleResult", Arrays.asList(2l, 4l));
check("decimalResult", Arrays.asList(2l, 4l));
}
public void test_mathlib_round_expect_error(){
try {
doCompile("function integer transform(){number input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_sqrt() {
doCompile("test_mathlib_sqrt");
check("sqrtPi", Math.sqrt(Math.PI));
check("sqrt9", Math.sqrt(9));
check("test_int", 2.0);
check("test_long", Math.sqrt(64L));
check("test_num", Math.sqrt(86.9));
check("test_dec", Math.sqrt(34.5));
}
public void test_mathlib_sqrt_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_randomInteger(){
doCompile("test_mathlib_randomInteger");
assertNotNull(getVariable("test1"));
check("test2", 2);
}
public void test_mathlib_randomInteger_expect_error(){
try {
doCompile("function integer transform(){integer i = randomInteger(1,null); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = randomInteger(null,null); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = randomInteger(null, -3); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = randomInteger(1,-7); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_randomLong(){
doCompile("test_mathlib_randomLong");
assertNotNull(getVariable("test1"));
check("test2", 15L);
}
public void test_mathlib_randomLong_expect_error(){
try {
doCompile("function integer transform(){long lo = randomLong(15L, null); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long lo = randomLong(null, null); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long lo = randomLong(null, 15L); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long lo = randomLong(15L, 10L); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_cache() {
doCompile("test_datelib_cache");
check("b11", true);
check("b12", true);
check("b21", true);
check("b22", true);
check("b31", true);
check("b32", true);
check("b41", true);
check("b42", true);
checkEquals("date3", "date3d");
checkEquals("date4", "date4d");
checkEquals("date7", "date7d");
checkEquals("date8", "date8d");
}
public void test_datelib_trunc() {
doCompile("test_datelib_trunc");
check("truncDate", new GregorianCalendar(2004, 00, 02).getTime());
}
public void test_datelib_truncDate() {
doCompile("test_datelib_truncDate");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)};
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, portion[0]);
cal.set(Calendar.MINUTE, portion[1]);
cal.set(Calendar.SECOND, portion[2]);
cal.set(Calendar.MILLISECOND, portion[3]);
check("truncBornDate", cal.getTime());
}
public void test_datelib_today() {
doCompile("test_datelib_today");
Date expectedDate = new Date();
//the returned date does not need to be exactly the same date which is in expectedData variable
//let say 1000ms is tolerance for equality
assertTrue("todayDate", Math.abs(expectedDate.getTime() - ((Date) getVariable("todayDate")).getTime()) < 1000);
}
public void test_datelib_zeroDate() {
doCompile("test_datelib_zeroDate");
check("zeroDate", new Date(0));
}
public void test_datelib_dateDiff() {
doCompile("test_datelib_dateDiff");
long diffYears = Years.yearsBetween(new DateTime(), new DateTime(BORN_VALUE)).getYears();
check("ddiff", diffYears);
long[] results = {1, 12, 52, 365, 8760, 525600, 31536000, 31536000000L};
String[] vars = {"ddiffYears", "ddiffMonths", "ddiffWeeks", "ddiffDays", "ddiffHours", "ddiffMinutes", "ddiffSeconds", "ddiffMilliseconds"};
for (int i = 0; i < results.length; i++) {
check(vars[i], results[i]);
}
}
public void test_datelib_dateDiff_epect_error(){
try {
doCompile("function integer transform(){long i = dateDiff(null,today(),millisec);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = dateDiff(today(),null,millisec);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = dateDiff(today(),today(),null);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_dateAdd() {
doCompile("test_datelib_dateAdd");
check("datum", new Date(BORN_MILLISEC_VALUE + 100));
}
public void test_datelib_dateAdd_expect_error(){
try {
doCompile("function integer transform(){date d = dateAdd(null,120,second); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = dateAdd(today(),null,second); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = dateAdd(today(),120,null); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_extractTime() {
doCompile("test_datelib_extractTime");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)};
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, portion[0]);
cal.set(Calendar.MINUTE, portion[1]);
cal.set(Calendar.SECOND, portion[2]);
cal.set(Calendar.MILLISECOND, portion[3]);
check("bornExtractTime", cal.getTime());
check("originalDate", BORN_VALUE);
}
public void test_datelib_extractTime_expect_error(){
try {
doCompile("function integer transform(){date d = extractTime(null); return 0;}","test_datelib_extractTime_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_extractDate() {
doCompile("test_datelib_extractDate");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)};
cal.clear();
cal.set(Calendar.DAY_OF_MONTH, portion[0]);
cal.set(Calendar.MONTH, portion[1]);
cal.set(Calendar.YEAR, portion[2]);
check("bornExtractDate", cal.getTime());
check("originalDate", BORN_VALUE);
}
public void test_datelib_extractDate_expect_error(){
try {
doCompile("function integer transform(){date d = extractDate(null); return 0;}","test_datelib_extractDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_createDate() {
doCompile("test_datelib_createDate");
Calendar cal = Calendar.getInstance();
// no time zone
cal.clear();
cal.set(2013, 5, 11);
check("date1", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime1", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis1", cal.getTime());
// literal
cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
cal.clear();
cal.set(2013, 5, 11);
check("date2", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime2", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis2", cal.getTime());
// variable
cal.clear();
cal.set(2013, 5, 11);
check("date3", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime3", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis3", cal.getTime());
}
public void test_datelib_getPart() {
doCompile("test_datelib_getPart");
Calendar cal = Calendar.getInstance();
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT+1"));
cal.set(2013, 5, 11, 14, 46, 34);
cal.set(Calendar.MILLISECOND, 123);
Date date = cal.getTime();
cal = Calendar.getInstance();
cal.setTime(date);
// no time zone
check("year1", cal.get(Calendar.YEAR));
check("month1", cal.get(Calendar.MONTH) + 1);
check("day1", cal.get(Calendar.DAY_OF_MONTH));
check("hour1", cal.get(Calendar.HOUR_OF_DAY));
check("minute1", cal.get(Calendar.MINUTE));
check("second1", cal.get(Calendar.SECOND));
check("millisecond1", cal.get(Calendar.MILLISECOND));
cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
// literal
check("year2", cal.get(Calendar.YEAR));
check("month2", cal.get(Calendar.MONTH) + 1);
check("day2", cal.get(Calendar.DAY_OF_MONTH));
check("hour2", cal.get(Calendar.HOUR_OF_DAY));
check("minute2", cal.get(Calendar.MINUTE));
check("second2", cal.get(Calendar.SECOND));
check("millisecond2", cal.get(Calendar.MILLISECOND));
// variable
check("year3", cal.get(Calendar.YEAR));
check("month3", cal.get(Calendar.MONTH) + 1);
check("day3", cal.get(Calendar.DAY_OF_MONTH));
check("hour3", cal.get(Calendar.HOUR_OF_DAY));
check("minute3", cal.get(Calendar.MINUTE));
check("second3", cal.get(Calendar.SECOND));
check("millisecond3", cal.get(Calendar.MILLISECOND));
check("year_null", 2013);
check("month_null", 6);
check("day_null", 11);
check("hour_null", 15);
check("minute_null", cal.get(Calendar.MINUTE));
check("second_null", cal.get(Calendar.SECOND));
check("milli_null", cal.get(Calendar.MILLISECOND));
}
public void test_datelib_getPart_expect_error(){
try {
doCompile("function integer transform(){integer i = getYear(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getMonth(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getDay(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getHour(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getMinute(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getSecond(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getMillisecond(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_randomDate() {
doCompile("test_datelib_randomDate");
final long HOUR = 60L * 60L * 1000L;
Date BORN_VALUE_NO_MILLIS = new Date(BORN_VALUE.getTime() / 1000L * 1000L);
check("noTimeZone1", BORN_VALUE);
check("noTimeZone2", BORN_VALUE_NO_MILLIS);
check("withTimeZone1", new Date(BORN_VALUE_NO_MILLIS.getTime() + 2*HOUR)); // timezone changes from GMT+5 to GMT+3
check("withTimeZone2", new Date(BORN_VALUE_NO_MILLIS.getTime() - 2*HOUR)); // timezone changes from GMT+3 to GMT+5
assertNotNull(getVariable("patt_null"));
}
public void test_datelib_randomDate_expect_error(){
try {
doCompile("function integer transform(){date a = null; date b = today(); "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date a = today(); date b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date a = null; date b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = 843484317231l; long b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = null; long b = 12115641158l; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = null; long b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "string a = null; string b = '2006-11-12'; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "string a = '2006-11-12'; string b = null; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//wrong format
try {
doCompile("function integer transform(){"
+ "string a = '2006-10-12'; string b = '2006-11-12'; string pattern='yyyy:MM:dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//start date bigger then end date
try {
doCompile("function integer transform(){"
+ "string a = '2008-10-12'; string b = '2006-11-12'; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_cache() {
// set default locale to en.US so the date is formatted uniformly on all systems
Locale.setDefault(Locale.US);
doCompile("test_convertlib_cache");
Calendar cal = Calendar.getInstance();
cal.set(2000, 6, 20, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date checkDate = cal.getTime();
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("sdate1", format.format(new Date()));
check("sdate2", format.format(new Date()));
check("date01", checkDate);
check("date02", checkDate);
check("date03", checkDate);
check("date04", checkDate);
check("date11", checkDate);
check("date12", checkDate);
check("date13", checkDate);
}
public void test_convertlib_base64byte() {
doCompile("test_convertlib_base64byte");
assertTrue(Arrays.equals((byte[])getVariable("base64input"), Base64.decode("The quick brown fox jumps over the lazy dog")));
}
public void test_convertlib_base64byte_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){byte b = base64byte(null); return 0;}","test_convertlib_base64byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_bits2str() {
doCompile("test_convertlib_bits2str");
check("bitsAsString1", "00000000");
check("bitsAsString2", "11111111");
check("bitsAsString3", "010100000100110110100000");
}
public void test_convertlib_bits2str_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = bits2str(null); return 0;}","test_convertlib_bits2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_bool2num() {
doCompile("test_convertlib_bool2num");
check("resultTrue", 1);
check("resultFalse", 0);
}
public void test_convertlib_bool2num_expect_error(){
// CLO-1255
//this test should be expected to success in future
try {
doCompile("function integer transform(){boolean b = null; integer s = bool2num(b);return 0;}","test_convertlib_bool2num_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_byte2base64() {
doCompile("test_convertlib_byte2base64");
check("inputBase64", Base64.encodeBytes("Abeceda zedla deda".getBytes()));
}
public void test_convertlib_byte2base64_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = byte2base64(null);return 0;}","test_convertlib_byte2base64_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_byte2hex() {
doCompile("test_convertlib_byte2hex");
check("hexResult", "41626563656461207a65646c612064656461");
check("test_null", null);
}
public void test_convertlib_date2long() {
doCompile("test_convertlib_date2long");
check("bornDate", BORN_MILLISEC_VALUE);
check("zeroDate", 0l);
}
public void test_convertlib_date2long_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){long l = date2long(null);return 0;}","test_convertlib_date2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_date2num() {
doCompile("test_convertlib_date2num");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
check("yearDate", 1987);
check("monthDate", 5);
check("secondDate", 0);
check("yearBorn", cal.get(Calendar.YEAR));
check("monthBorn", cal.get(Calendar.MONTH) + 1); //Calendar enumerates months from 0, not 1;
check("secondBorn", cal.get(Calendar.SECOND));
check("yearMin", 1970);
check("monthMin", 1);
check("weekMin", 1);
check("weekMinCs", 1);
check("dayMin", 1);
check("hourMin", 1); //TODO: check!
check("minuteMin", 0);
check("secondMin", 0);
check("millisecMin", 0);
}
public void test_convertlib_date2num_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){number num = date2num(null,null); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
//this test should be expected to success in future
try {
doCompile("function integer transform(){number num = date2num(1982-09-02,null); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
//this test should be expected to success in future
try {
doCompile("function integer transform(){number num = date2num(null,year); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_date2str() {
doCompile("test_convertlib_date2str");
check("inputDate", "1987:05:12");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd");
check("bornDate", sdf.format(BORN_VALUE));
SimpleDateFormat sdfCZ = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("cs.CZ"));
check("czechBornDate", sdfCZ.format(BORN_VALUE));
SimpleDateFormat sdfEN = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("en"));
check("englishBornDate", sdfEN.format(BORN_VALUE));
{
String[] locales = {"en", "pl", null, "cs.CZ", null};
List<String> expectedDates = new ArrayList<String>();
for (String locale: locales) {
expectedDates.add(new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale(locale)).format(BORN_VALUE));
}
check("loopTest", expectedDates);
}
SimpleDateFormat sdfGMT8 = new SimpleDateFormat("yyyy:MMMM:dd z", MiscUtils.createLocale("en"));
sdfGMT8.setTimeZone(TimeZone.getTimeZone("GMT+8"));
check("timeZone", sdfGMT8.format(BORN_VALUE));
}
public void test_convertlib_date2str_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = date2str(null,'yyyy:MMMM:dd', 'cs.CZ', 'GMT+8');return 0;}","test_convertlib_date2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = date2str(1985-11-12,null, 'cs.CZ', 'GMT+8');return 0;}","test_convertlib_date2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_decimal2double() {
doCompile("test_convertlib_decimal2double");
check("toDouble", 0.007d);
}
public void test_convertlib_decimal2double_except_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){double d = decimal2double(null); return 0;}","test_convertlib_decimal2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_decimal2integer() {
doCompile("test_convertlib_decimal2integer");
check("toInteger", 0);
check("toInteger2", -500);
check("toInteger3", 1000000);
}
public void test_convertlib_decimal2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = decimal2integer(null); return 0;}","test_convertlib_decimal2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_decimal2long() {
doCompile("test_convertlib_decimal2long");
check("toLong", 0l);
check("toLong2", -500l);
check("toLong3", 10000000000l);
}
public void test_convertlib_decimal2long_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){long i = decimal2long(null); return 0;}","test_convertlib_decimal2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_double2integer() {
doCompile("test_convertlib_double2integer");
check("toInteger", 0);
check("toInteger2", -500);
check("toInteger3", 1000000);
}
public void test_convertlib_double2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = double2integer(null); return 0;}","test_convertlib_doublel2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_double2long() {
doCompile("test_convertlib_double2long");
check("toLong", 0l);
check("toLong2", -500l);
check("toLong3", 10000000000l);
}
public void test_convertlib_double2long_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){long l = double2long(null); return 0;}","test_convertlib_doublel2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_getFieldName() {
doCompile("test_convertlib_getFieldName");
check("fieldNames",Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency"));
}
public void test_convertlib_getFieldType() {
doCompile("test_convertlib_getFieldType");
check("fieldTypes",Arrays.asList(DataFieldType.STRING.getName(), DataFieldType.NUMBER.getName(), DataFieldType.STRING.getName(),
DataFieldType.DATE.getName(), DataFieldType.LONG.getName(), DataFieldType.INTEGER.getName(), DataFieldType.BOOLEAN.getName(),
DataFieldType.BYTE.getName(), DataFieldType.DECIMAL.getName()));
}
public void test_convertlib_hex2byte() {
doCompile("test_convertlib_hex2byte");
assertTrue(Arrays.equals((byte[])getVariable("fromHex"), BYTEARRAY_VALUE));
check("test_null", null);
}
public void test_convertlib_long2date() {
doCompile("test_convertlib_long2date");
check("fromLong1", new Date(0));
check("fromLong2", new Date(50000000000L));
check("fromLong3", new Date(-5000L));
}
public void test_convertlib_long2date_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){date d = long2date(null); return 0;}","test_convertlib_long2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_long2integer() {
doCompile("test_convertlib_long2integer");
check("fromLong1", 10);
check("fromLong2", -10);
}
public void test_convertlib_long2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = long2integer(null); return 0;}","test_convertlib_long2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_long2packDecimal() {
doCompile("test_convertlib_long2packDecimal");
assertTrue(Arrays.equals((byte[])getVariable("packedLong"), new byte[] {5, 0, 12}));
}
public void test_convertlib_long2packDecimal_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){byte b = long2packDecimal(null); return 0;}","test_convertlib_long2packDecimal_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_md5() {
doCompile("test_convertlib_md5");
assertTrue(Arrays.equals((byte[])getVariable("md5Hash1"), Digest.digest(DigestType.MD5, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("md5Hash2"), Digest.digest(DigestType.MD5, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.MD5, "")));
}
public void test_convertlib_md5_expect_error(){
//CLO-1254
// //this test should be expected to success in future
// try {
// doCompile("function integer transform(){byte b = md5(null); return 0;}","test_convertlib_md5_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_num2bool() {
doCompile("test_convertlib_num2bool");
check("integerTrue", true);
check("integerFalse", false);
check("longTrue", true);
check("longFalse", false);
check("doubleTrue", true);
check("doubleFalse", false);
check("decimalTrue", true);
check("decimalFalse", false);
}
public void test_convertlib_num2bool_expect_error(){
//this test should be expected to success in future
//test: integer
try {
doCompile("integer input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: long
try {
doCompile("long input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: double
try {
doCompile("double input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: decimal
try {
doCompile("decimal input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_num2str() {
System.out.println("num2str() test:");
doCompile("test_convertlib_num2str");
check("intOutput", Arrays.asList("16", "10000", "20", "10", "1.235E3", "12 350 001 Kcs"));
check("longOutput", Arrays.asList("16", "10000", "20", "10", "1.235E13", "12 350 001 Kcs"));
check("doubleOutput", Arrays.asList("16.16", "0x1.028f5c28f5c29p4", "1.23548E3", "12 350 001,1 Kcs"));
check("decimalOutput", Arrays.asList("16.16", "1235.44", "12 350 001,1 Kcs"));
check("test_null_dec", "NaN");
}
public void test_converlib_num2str_expect_error(){
//this test should be expected to success in future
//test: integer
try {
doCompile("integer input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: long
try {
doCompile("long input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: double
try {
doCompile("double input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// //this test should be expected to success in future
// //test: decimal
// try {
// doCompile("decimal input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_packdecimal2long() {
doCompile("test_convertlib_packDecimal2long");
check("unpackedLong", PackedDecimal.parse(BYTEARRAY_VALUE));
}
public void test_convertlib_packdecimal2long_expect_error(){
try {
doCompile("function integer transform(){long l =packDecimal2long(null); return 0;}","test_convertlib_packdecimal2long_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_sha() {
doCompile("test_convertlib_sha");
assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA, "")));
}
public void test_convertlib_sha_expect_error(){
// CLO-1258
// try {
// doCompile("function integer transform(){byte b = sha(null); return 0;}","test_convertlib_sha_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_sha256() {
doCompile("test_convertlib_sha256");
assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA256, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA256, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA256, "")));
}
public void test_convertlib_sha256_expect_error(){
// CLO-1258
// try {
// doCompile("function integer transform(){byte b = sha256(null); return 0;}","test_convertlib_sha256_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_str2bits() {
doCompile("test_convertlib_str2bits");
//TODO: uncomment -> test will pass, but is that correct?
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits1"), new byte[] {0/*, 0, 0, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits2"), new byte[] {-1/*, 0, 0, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits3"), new byte[] {10, -78, 5/*, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("test_empty"), new byte[] {}));
}
public void test_convertlib_str2bits_expect_error(){
try {
doCompile("function integer transform(){byte b = str2bits(null); return 0;}","test_convertlib_str2bits_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2bool() {
doCompile("test_convertlib_str2bool");
check("fromTrueString", true);
check("fromFalseString", false);
}
public void test_convertlib_str2bool_expect_error(){
try {
doCompile("function integer transform(){boolean b = str2bool('asd'); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){boolean b = str2bool(''); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){boolean b = str2bool(null); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_str2date() {
doCompile("test_convertlib_str2date");
Calendar cal = Calendar.getInstance();
cal.set(2050, 4, 19, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date checkDate = cal.getTime();
check("date1", checkDate);
check("date2", checkDate);
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
cal.set(2013, 04, 30, 17, 15, 12);
check("withTimeZone1", cal.getTime());
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT-8"));
cal.set(2013, 04, 30, 17, 15, 12);
check("withTimeZone2", cal.getTime());
assertFalse(getVariable("withTimeZone1").equals(getVariable("withTimeZone2")));
}
public void test_convertlib_str2date_expect_error(){
try {
doCompile("function integer transform(){date d = str2date('1987-11-17', null); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date(null, 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date(null, null); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('1987-11-17', 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('1987-33-17', 'yyyy-MM-dd'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('17.11.1987', null, 'cs.CZ'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2decimal() {
doCompile("test_convertlib_str2decimal");
check("parsedDecimal1", new BigDecimal("100.13"));
check("parsedDecimal2", new BigDecimal("123123123.123"));
check("parsedDecimal3", new BigDecimal("-350000.01"));
check("parsedDecimal4", new BigDecimal("1000000"));
check("parsedDecimal5", new BigDecimal("1000000.99"));
check("parsedDecimal6", new BigDecimal("123123123.123"));
check("parsedDecimal7", new BigDecimal("5.01"));
}
public void test_convertlib_str2decimal_expect_result(){
try {
doCompile("function integer transform(){decimal d = str2decimal(''); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal(null); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK','#.#CZ'); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal(null,'#.# US'); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2double() {
doCompile("test_convertlib_str2double");
check("parsedDouble1", 100.13);
check("parsedDouble2", 123123123.123);
check("parsedDouble3", -350000.01);
}
public void test_convertlib_str2double_expect_error(){
try {
doCompile("function integer transform(){double d = str2double(''); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double(null); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('text'); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('0.90c',null); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('0.90c','#.# c'); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2integer() {
doCompile("test_convertlib_str2integer");
check("parsedInteger1", 123456789);
check("parsedInteger2", 123123);
check("parsedInteger3", -350000);
check("parsedInteger4", 419);
}
public void test_convertlib_str2integer_expect_error(){
try {
doCompile("function integer transform(){integer i = str2integer('abc'); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = str2integer(''); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = str2integer(null); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2long() {
doCompile("test_convertlib_str2long");
check("parsedLong1", 1234567890123L);
check("parsedLong2", 123123123456789L);
check("parsedLong3", -350000L);
check("parsedLong4", 133L);
}
public void test_convertlib_str2long_expect_error(){
try {
doCompile("function integer transform(){long i = str2long('abc'); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long(''); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long(null); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_toString() {
doCompile("test_convertlib_toString");
check("integerString", "10");
check("longString", "110654321874");
check("doubleString", "1.547874E-14");
check("decimalString", "-6847521431.1545874");
check("listString", "[not ALI A, not ALI B, not ALI D..., but, ALI H!]");
check("mapString", "{1=Testing, 2=makes, 3=me, 4=crazy :-)}");
String byteMapString = getVariable("byteMapString").toString();
assertTrue(byteMapString.contains("1=value1"));
assertTrue(byteMapString.contains("2=value2"));
String fieldByteMapString = getVariable("fieldByteMapString").toString();
assertTrue(fieldByteMapString.contains("key1=value1"));
assertTrue(fieldByteMapString.contains("key2=value2"));
check("byteListString", "[firstElement, secondElement]");
check("fieldByteListString", "[firstElement, secondElement]");
// CLO-1262
// check("test_null_l", "null");
// check("test_null_dec", "null");
// check("test_null_d", "null");
// check("test_null_i", "null");
}
public void test_convertlib_str2byte() {
doCompile("test_convertlib_str2byte");
checkArray("utf8Hello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("utf8Horse", new byte[] { 80, -59, -103, -61, -83, 108, 105, -59, -95, 32, -59, -66, 108, 117, -59, -91, 111, 117, -60, -115, 107, -61, -67, 32, 107, -59, -81, -59, -120, 32, 112, -60, -101, 108, 32, -60, -113, -61, -95, 98, 108, 115, 107, -61, -87, 32, -61, -77, 100, 121 });
checkArray("utf8Math", new byte[] { -62, -67, 32, -30, -123, -109, 32, -62, -68, 32, -30, -123, -107, 32, -30, -123, -103, 32, -30, -123, -101, 32, -30, -123, -108, 32, -30, -123, -106, 32, -62, -66, 32, -30, -123, -105, 32, -30, -123, -100, 32, -30, -123, -104, 32, -30, -126, -84, 32, -62, -78, 32, -62, -77, 32, -30, -128, -96, 32, -61, -105, 32, -30, -122, -112, 32, -30, -122, -110, 32, -30, -122, -108, 32, -30, -121, -110, 32, -30, -128, -90, 32, -30, -128, -80, 32, -50, -111, 32, -50, -110, 32, -30, -128, -109, 32, -50, -109, 32, -50, -108, 32, -30, -126, -84, 32, -50, -107, 32, -50, -106, 32, -49, -128, 32, -49, -127, 32, -49, -126, 32, -49, -125, 32, -49, -124, 32, -49, -123, 32, -49, -122, 32, -49, -121, 32, -49, -120, 32, -49, -119 });
checkArray("utf16Hello", new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 });
checkArray("utf16Horse", new byte[] { -2, -1, 0, 80, 1, 89, 0, -19, 0, 108, 0, 105, 1, 97, 0, 32, 1, 126, 0, 108, 0, 117, 1, 101, 0, 111, 0, 117, 1, 13, 0, 107, 0, -3, 0, 32, 0, 107, 1, 111, 1, 72, 0, 32, 0, 112, 1, 27, 0, 108, 0, 32, 1, 15, 0, -31, 0, 98, 0, 108, 0, 115, 0, 107, 0, -23, 0, 32, 0, -13, 0, 100, 0, 121 });
checkArray("utf16Math", new byte[] { -2, -1, 0, -67, 0, 32, 33, 83, 0, 32, 0, -68, 0, 32, 33, 85, 0, 32, 33, 89, 0, 32, 33, 91, 0, 32, 33, 84, 0, 32, 33, 86, 0, 32, 0, -66, 0, 32, 33, 87, 0, 32, 33, 92, 0, 32, 33, 88, 0, 32, 32, -84, 0, 32, 0, -78, 0, 32, 0, -77, 0, 32, 32, 32, 0, 32, 0, -41, 0, 32, 33, -112, 0, 32, 33, -110, 0, 32, 33, -108, 0, 32, 33, -46, 0, 32, 32, 38, 0, 32, 32, 48, 0, 32, 3, -111, 0, 32, 3, -110, 0, 32, 32, 19, 0, 32, 3, -109, 0, 32, 3, -108, 0, 32, 32, -84, 0, 32, 3, -107, 0, 32, 3, -106, 0, 32, 3, -64, 0, 32, 3, -63, 0, 32, 3, -62, 0, 32, 3, -61, 0, 32, 3, -60, 0, 32, 3, -59, 0, 32, 3, -58, 0, 32, 3, -57, 0, 32, 3, -56, 0, 32, 3, -55 });
checkArray("macHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("macHorse", new byte[] { 80, -34, -110, 108, 105, -28, 32, -20, 108, 117, -23, 111, 117, -117, 107, -7, 32, 107, -13, -53, 32, 112, -98, 108, 32, -109, -121, 98, 108, 115, 107, -114, 32, -105, 100, 121 });
checkArray("asciiHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("isoHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("isoHorse", new byte[] { 80, -8, -19, 108, 105, -71, 32, -66, 108, 117, -69, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 });
checkArray("cpHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("cpHorse", new byte[] { 80, -8, -19, 108, 105, -102, 32, -98, 108, 117, -99, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 });
}
public void test_convertlib_str2byte_expect_error(){
try {
doCompile("function integer transform(){byte b = str2byte(null,'utf-8'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'utf-16'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'MacCentralEurope'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'ascii'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'iso-8859-2'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'windows-1250'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace','knock'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_byte2str() {
doCompile("test_convertlib_byte2str");
String hello = "Hello World!";
String horse = "Příliš žluťoučký kůň pěl ďáblské ódy";
String math = "½ ⅓ ¼ ⅕ ⅙ ⅛ ⅔ ⅖ ¾ ⅗ ⅜ ⅘ € ² ³ † × ← → ↔ ⇒ … ‰ Α Β – Γ Δ € Ε Ζ π ρ ς σ τ υ φ χ ψ ω";
check("utf8Hello", hello);
check("utf8Horse", horse);
check("utf8Math", math);
check("utf16Hello", hello);
check("utf16Horse", horse);
check("utf16Math", math);
check("macHello", hello);
check("macHorse", horse);
check("asciiHello", hello);
check("isoHello", hello);
check("isoHorse", horse);
check("cpHello", hello);
check("cpHorse", horse);
}
public void test_convertlib_byte2str_expect_error(){
try {
doCompile("function integer transform(){string s = byte2str(null,'utf-8'); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = byte2str(null,null); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = byte2str(str2byte('hello', 'utf-8'),null); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_conditional_fail() {
doCompile("test_conditional_fail");
check("result", 3);
}
public void test_expression_statement(){
// test case for issue 4174
doCompileExpectErrors("test_expression_statement", Arrays.asList("Syntax error, statement expected","Syntax error, statement expected"));
}
public void test_dictionary_read() {
doCompile("test_dictionary_read");
check("s", "Verdon");
check("i", Integer.valueOf(211));
check("l", Long.valueOf(226));
check("d", BigDecimal.valueOf(239483061));
check("n", Double.valueOf(934.2));
check("a", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime());
check("b", true);
byte[] y = (byte[]) getVariable("y");
assertEquals(10, y.length);
assertEquals(89, y[9]);
check("sNull", null);
check("iNull", null);
check("lNull", null);
check("dNull", null);
check("nNull", null);
check("aNull", null);
check("bNull", null);
check("yNull", null);
check("stringList", Arrays.asList("aa", "bb", null, "cc"));
check("dateList", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000)));
@SuppressWarnings("unchecked")
List<byte[]> byteList = (List<byte[]>) getVariable("byteList");
assertDeepEquals(byteList, Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78}));
}
public void test_dictionary_write() {
doCompile("test_dictionary_write");
assertEquals(832, graph.getDictionary().getValue("i") );
assertEquals("Guil", graph.getDictionary().getValue("s"));
assertEquals(Long.valueOf(540), graph.getDictionary().getValue("l"));
assertEquals(BigDecimal.valueOf(621), graph.getDictionary().getValue("d"));
assertEquals(934.2, graph.getDictionary().getValue("n"));
assertEquals(new GregorianCalendar(1992, GregorianCalendar.DECEMBER, 2).getTime(), graph.getDictionary().getValue("a"));
assertEquals(true, graph.getDictionary().getValue("b"));
byte[] y = (byte[]) graph.getDictionary().getValue("y");
assertEquals(2, y.length);
assertEquals(18, y[0]);
assertEquals(-94, y[1]);
assertEquals(Arrays.asList("xx", null), graph.getDictionary().getValue("stringList"));
assertEquals(Arrays.asList(new Date(98000), null, new Date(76000)), graph.getDictionary().getValue("dateList"));
@SuppressWarnings("unchecked")
List<byte[]> byteList = (List<byte[]>) graph.getDictionary().getValue("byteList");
assertDeepEquals(byteList, Arrays.asList(null, new byte[] {(byte) 0xAB, (byte) 0xCD}, new byte[] {(byte) 0xEF}));
check("assignmentReturnValue", "Guil");
}
public void test_dictionary_write_null() {
doCompile("test_dictionary_write_null");
assertEquals(null, graph.getDictionary().getValue("s"));
assertEquals(null, graph.getDictionary().getValue("sVerdon"));
assertEquals(null, graph.getDictionary().getValue("i") );
assertEquals(null, graph.getDictionary().getValue("i211") );
assertEquals(null, graph.getDictionary().getValue("l"));
assertEquals(null, graph.getDictionary().getValue("l452"));
assertEquals(null, graph.getDictionary().getValue("d"));
assertEquals(null, graph.getDictionary().getValue("d621"));
assertEquals(null, graph.getDictionary().getValue("n"));
assertEquals(null, graph.getDictionary().getValue("n9342"));
assertEquals(null, graph.getDictionary().getValue("a"));
assertEquals(null, graph.getDictionary().getValue("a1992"));
assertEquals(null, graph.getDictionary().getValue("b"));
assertEquals(null, graph.getDictionary().getValue("bTrue"));
assertEquals(null, graph.getDictionary().getValue("y"));
assertEquals(null, graph.getDictionary().getValue("yFib"));
}
public void test_dictionary_invalid_key(){
doCompileExpectErrors("test_dictionary_invalid_key", Arrays.asList("Dictionary entry 'invalid' does not exist"));
}
public void test_dictionary_string_to_int(){
doCompileExpectErrors("test_dictionary_string_to_int", Arrays.asList("Type mismatch: cannot convert from 'string' to 'integer'","Type mismatch: cannot convert from 'string' to 'integer'"));
}
public void test_utillib_sleep() {
long time = System.currentTimeMillis();
doCompile("test_utillib_sleep");
long tmp = System.currentTimeMillis() - time;
assertTrue("sleep() function didn't pause execution "+ tmp, tmp >= 1000);
}
public void test_utillib_random_uuid() {
doCompile("test_utillib_random_uuid");
assertNotNull(getVariable("uuid"));
}
public void test_stringlib_randomString(){
doCompile("string test; function integer transform(){test = randomString(1,3); return 0;}","test_stringlib_randomString");
assertNotNull(getVariable("test"));
}
public void test_stringlib_validUrl() {
doCompile("test_stringlib_url");
check("urlValid", Arrays.asList(true, true, false, true, false, true));
check("protocol", Arrays.asList("http", "https", null, "sandbox", null, "zip"));
check("userInfo", Arrays.asList("", "chuck:norris", null, "", null, ""));
check("host", Arrays.asList("example.com", "server.javlin.eu", null, "cloveretl.test.scenarios", null, ""));
check("port", Arrays.asList(-1, 12345, -2, -1, -2, -1));
check("path", Arrays.asList("", "/backdoor/trojan.cgi", null, "/graph/UDR_FileURL_SFTP_OneGzipFileSpecified.grf", null, "(sftp://test:test@koule/home/test/data-in/file2.zip)"));
check("query", Arrays.asList("", "hash=SHA560;god=yes", null, "", null, ""));
check("ref", Arrays.asList("", "autodestruct", null, "", null, "innerfolder2/URLIn21.txt"));
}
public void test_stringlib_escapeUrl() {
doCompile("test_stringlib_escapeUrl");
check("escaped", "http://example.com/foo%20bar%5E");
check("unescaped", "http://example.com/foo bar^");
}
public void test_stringlib_escapeUrl_unescapeUrl_expect_error(){
//test: escape - empty string
try {
doCompile("string test; function integer transform() {test = escapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: escape - null string
try {
doCompile("string test; function integer transform() {test = escapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescape - empty string
try {
doCompile("string test; function integer transform() {test = unescapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescape - null
try {
doCompile("string test; function integer transform() {test = unescapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: escape - invalid URL
try {
doCompile("string test; function integer transform() {test = escapeUrl('somewhere over the rainbow'); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescpae - invalid URL
try {
doCompile("string test; function integer transform() {test = unescapeUrl('mister%20postman'); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_resolveParams() {
doCompile("test_stringlib_resolveParams");
check("resultNoParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
check("resultFalseFalseParams", "Special character representing new line is: \\n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in");
check("resultTrueFalseParams", "Special character representing new line is: \n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in");
check("resultFalseTrueParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
check("resultTrueTrueParams", "Special character representing new line is: \n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
}
public void test_utillib_getEnvironmentVariables() {
doCompile("test_utillib_getEnvironmentVariables");
check("empty", false);
}
public void test_utillib_getJavaProperties() {
String key1 = "my.testing.property";
String key2 = "my.testing.property2";
String value = "my value";
String value2;
assertNull(System.getProperty(key1));
assertNull(System.getProperty(key2));
System.setProperty(key1, value);
try {
doCompile("test_utillib_getJavaProperties");
value2 = System.getProperty(key2);
} finally {
System.clearProperty(key1);
assertNull(System.getProperty(key1));
System.clearProperty(key2);
assertNull(System.getProperty(key2));
}
check("java_specification_name", "Java Platform API Specification");
check("my_testing_property", value);
assertEquals("my value 2", value2);
}
public void test_utillib_getParamValues() {
doCompile("test_utillib_getParamValues");
Map<String, String> params = new HashMap<String, String>();
params.put("PROJECT", ".");
params.put("DATAIN_DIR", "./data-in");
params.put("COUNT", "3");
params.put("NEWLINE", "\\n"); // special characters should NOT be resolved
check("params", params);
}
public void test_utillib_getParamValue() {
doCompile("test_utillib_getParamValue");
Map<String, String> params = new HashMap<String, String>();
params.put("PROJECT", ".");
params.put("DATAIN_DIR", "./data-in");
params.put("COUNT", "3");
params.put("NEWLINE", "\\n"); // special characters should NOT be resolved
params.put("NONEXISTING", null);
check("params", params);
}
public void test_stringlib_getUrlParts() {
doCompile("test_stringlib_getUrlParts");
List<Boolean> isUrl = Arrays.asList(true, true, true, true, false);
List<String> path = Arrays.asList(
"/users/a6/15e83578ad5cba95c442273ea20bfa/msf-183/out5.txt",
"/data-in/fileOperation/input.txt",
"/data/file.txt",
"/data/file.txt",
null);
List<String> protocol = Arrays.asList("sftp", "sandbox", "ftp", "https", null);
List<String> host = Arrays.asList(
"ava-fileManipulator1-devel.getgooddata.com",
"cloveretl.test.scenarios",
"ftp.test.com",
"www.test.com",
null);
List<Integer> port = Arrays.asList(-1, -1, 21, 80, -2);
List<String> userInfo = Arrays.asList(
"user%40gooddata.com:password",
"",
"test:test",
"test:test",
null);
List<String> ref = Arrays.asList("", "", "", "", null);
List<String> query = Arrays.asList("", "", "", "", null);
check("isUrl", isUrl);
check("path", path);
check("protocol", protocol);
check("host", host);
check("port", port);
check("userInfo", userInfo);
check("ref", ref);
check("query", query);
check("isURL_empty", false);
check("path_empty", null);
check("protocol_empty", null);
check("host_empty", null);
check("port_empty", -2);
check("userInfo_empty", null);
check("ref_empty", null);
check("query_empty", null);
check("isURL_null", false);
check("path_null", null);
check("protocol_null", null);
check("host_null", null);
check("port_null", -2);
check("userInfo_null", null);
check("ref_null", null);
check("query_empty", null);
}
public void test_utillib_iif() throws UnsupportedEncodingException{
doCompile("test_utillib_iif");
check("ret1", "Renektor");
Calendar cal = Calendar.getInstance();
cal.set(2005,10,12,0,0,0);
cal.set(Calendar.MILLISECOND,0);
check("ret2", cal.getTime());
checkArray("ret3", "Akali".getBytes("UTF-8"));
check("ret4", 236);
check("ret5", 78L);
check("ret6", 78.2d);
check("ret7", new BigDecimal("87.69"));
check("ret8", true);
}
public void test_utillib_iif_expect_error(){
try {
doCompile("function integer transform(){boolean b = null; string str = iif(b, 'Rammus', 'Sion'); return 0;}","test_utillib_iif_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_utillib_isnull(){
doCompile("test_utillib_isnull");
check("ret1", false);
check("ret2", true);
check("ret3", false);
check("ret4", true);
check("ret5", false);
check("ret6", true);
check("ret7", false);
check("ret8", true);
check("ret9", false);
check("ret10", true);
check("ret11", false);
check("ret12", true);
check("ret13", false);
check("ret14", true);
check("ret15", false);
check("ret16", true);
check("ret17", false);
check("ret18", true);
check("ret19", true);
}
public void test_utillib_nvl() throws UnsupportedEncodingException{
doCompile("test_utillib_nvl");
check("ret1", "Fiora");
check("ret2", "Olaf");
checkArray("ret3", "Elise".getBytes("UTF-8"));
checkArray("ret4", "Diana".getBytes("UTF-8"));
Calendar cal = Calendar.getInstance();
cal.set(2005,4,13,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret5", cal.getTime());
cal.clear();
cal.set(2004,2,14,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret6", cal.getTime());
check("ret7", 7);
check("ret8", 8);
check("ret9", 111l);
check("ret10", 112l);
check("ret11", 10.1d);
check("ret12", 10.2d);
check("ret13", new BigDecimal("12.2"));
check("ret14", new BigDecimal("12.3"));
// check("ret15", null);
}
public void test_utillib_nvl2() throws UnsupportedEncodingException{
doCompile("test_utillib_nvl2");
check("ret1", "Ahri");
check("ret2", "Galio");
checkArray("ret3", "Mordekaiser".getBytes("UTF-8"));
checkArray("ret4", "Zed".getBytes("UTF-8"));
Calendar cal = Calendar.getInstance();
cal.set(2010,4,18,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret5", cal.getTime());
cal.clear();
cal.set(2008,7,9,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("ret6", cal.getTime());
check("ret7", 11);
check("ret8", 18);
check("ret9", 20L);
check("ret10", 23L);
check("ret11", 15.2d);
check("ret12", 89.3d);
check("ret13", new BigDecimal("22.2"));
check("ret14", new BigDecimal("55.5"));
// check("ret15", null);
// check("ret16", null);
}
}
|
package biomodelsim;
import gcm2sbml.gui.GCM2SBMLEditor;
import gcm2sbml.network.GeneticNetwork;
import gcm2sbml.parser.CompatibilityFixer;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.parser.GCMParser;
import gcm2sbml.util.GlobalConstants;
import lhpn2sbml.parser.LHPNFile;
import lhpn2sbml.parser.Translator;
import lhpn2sbml.gui.*;
import graph.Graph;
import stategraph.StateGraph;
import java.awt.AWTError;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.Point;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener; //import java.awt.event.ComponentListener;
//import java.awt.event.ComponentEvent;
import java.awt.event.WindowFocusListener; //import java.awt.event.FocusListener;
//import java.awt.event.FocusEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Scanner;
import java.util.prefs.Preferences;
import java.util.regex.Pattern; //import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JViewport; //import javax.swing.tree.TreePath;
import tabs.CloseAndMaxTabbedPane;
import com.apple.eawt.ApplicationAdapter;
import com.apple.eawt.ApplicationEvent;
import com.apple.eawt.Application;
import learn.Learn;
import learn.LearnLHPN;
import synthesis.Synthesis;
import verification.*;
import org.sbml.libsbml.Compartment;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.SBMLReader;
import org.sbml.libsbml.SBMLWriter;
import reb2sac.Reb2Sac;
import reb2sac.Run;
import sbmleditor.SBML_Editor;
import buttons.Buttons;
import datamanager.DataManager;
import java.net.*;
import uk.ac.ebi.biomodels.*;
//import datamanager.DataManagerLHPN;
/**
* This class creates a GUI for the Tstubd program. It implements the
* ActionListener class. This allows the GUI to perform actions when menu items
* are selected.
*
* @author Curtis Madsen
*/
public class BioSim implements MouseListener, ActionListener, MouseMotionListener,
MouseWheelListener, WindowFocusListener {
private JFrame frame; // Frame where components of the GUI are displayed
private JMenuBar menuBar;
private JMenu file, edit, view, tools, help, saveAsMenu, importMenu, exportMenu, newMenu,
viewModel; // The file menu
private JMenuItem newProj; // The new menu item
private JMenuItem newModel; // The new menu item
private JMenuItem newCircuit; // The new menu item
private JMenuItem newVhdl; // The new vhdl menu item
private JMenuItem newS; // The new assembly file menu item
private JMenuItem newInst; // The new instruction file menu item
private JMenuItem newLhpn; // The new lhpn menu item
private JMenuItem newG; // The new petri net menu item
private JMenuItem newCsp; // The new csp menu item
private JMenuItem newHse; // The new handshaking extension menu item
private JMenuItem newUnc; // The new extended burst mode menu item
private JMenuItem newRsg; // The new rsg menu item
private JMenuItem newSpice; // The new spice circuit item
private JMenuItem exit; // The exit menu item
private JMenuItem importSbml; // The import sbml menu item
private JMenuItem importBioModel; // The import sbml menu item
private JMenuItem importDot; // The import dot menu item
private JMenuItem importVhdl; // The import vhdl menu item
private JMenuItem importS; // The import assembly file menu item
private JMenuItem importInst; // The import instruction file menu item
private JMenuItem importLpn; // The import lpn menu item
private JMenuItem importG; // The import .g file menu item
private JMenuItem importCsp; // The import csp menu item
private JMenuItem importHse; // The import handshaking extension menu
// item
private JMenuItem importUnc; // The import extended burst mode menu item
private JMenuItem importRsg; // The import rsg menu item
private JMenuItem importSpice; // The import spice circuit item
private JMenuItem manual; // The manual menu item
private JMenuItem about; // The about menu item
private JMenuItem openProj; // The open menu item
private JMenuItem pref; // The preferences menu item
private JMenuItem graph; // The graph menu item
private JMenuItem probGraph, exportCsv, exportDat, exportEps, exportJpg, exportPdf, exportPng,
exportSvg, exportTsd;
private String root; // The root directory
private FileTree tree; // FileTree
private CloseAndMaxTabbedPane tab; // JTabbedPane for different tools
private JToolBar toolbar; // Tool bar for common options
private JButton saveButton, runButton, refreshButton, saveasButton, checkButton, exportButton; // Tool
// Bar
// options
private JPanel mainPanel; // the main panel
public Log log; // the log
private JPopupMenu popup; // popup menu
private String separator;
private KeyEventDispatcher dispatcher;
private JMenuItem recentProjects[];
private String recentProjectPaths[];
private int numberRecentProj;
private int ShortCutKey;
public boolean checkUndeclared, checkUnits;
private JCheckBox Undeclared, Units, viewerCheck;
private JTextField viewerField;
private JLabel viewerLabel;
private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*");
private boolean async, externView, treeSelected = false, popupFlag = false, menuFlag = false;
public boolean atacs, lema;
private String viewer;
private String[] BioModelIds = null;
private JMenuItem copy, rename, delete, save, saveAs, saveAsGcm, saveAsGraph, saveAsSbml,
saveAsTemplate, saveGcmAsLhpn, saveAsLhpn, check, run, export, refresh, viewCircuit,
viewRules, viewTrace, viewLog, viewCoverage, viewVHDL, viewVerilog, viewLHPN, saveSbml,
saveTemp, saveModel, viewSG, viewModGraph, viewModBrowser, createAnal, createLearn,
createSbml, createSynth, createVer, close, closeAll;
public String ENVVAR;
public static final int SBML_LEVEL = 2;
public static final int SBML_VERSION = 4;
public static final Object[] OPTIONS = { "Yes", "No", "Yes To All", "No To All", "Cancel" };
public static final int YES_OPTION = JOptionPane.YES_OPTION;
public static final int NO_OPTION = JOptionPane.NO_OPTION;
public static final int YES_TO_ALL_OPTION = JOptionPane.CANCEL_OPTION;
public static final int NO_TO_ALL_OPTION = 3;
public static final int CANCEL_OPTION = 4;
public class MacOSAboutHandler extends Application {
public MacOSAboutHandler() {
addApplicationListener(new AboutBoxHandler());
}
class AboutBoxHandler extends ApplicationAdapter {
public void handleAbout(ApplicationEvent event) {
about();
event.setHandled(true);
}
}
}
public class MacOSPreferencesHandler extends Application {
public MacOSPreferencesHandler() {
addApplicationListener(new PreferencesHandler());
}
class PreferencesHandler extends ApplicationAdapter {
public void handlePreferences(ApplicationEvent event) {
preferences();
event.setHandled(true);
}
}
}
public class MacOSQuitHandler extends Application {
public MacOSQuitHandler() {
addApplicationListener(new QuitHandler());
}
class QuitHandler extends ApplicationAdapter {
public void handleQuit(ApplicationEvent event) {
exit();
event.setHandled(true);
}
}
}
/**
* This is the constructor for the Proj class. It initializes all the input
* fields, puts them on panels, adds the panels to the frame, and then
* displays the frame.
*
* @throws Exception
*/
public BioSim(boolean lema, boolean atacs) {
this.lema = lema;
this.atacs = atacs;
async = lema || atacs;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
if (atacs) {
ENVVAR = System.getenv("ATACSGUI");
}
else if (lema) {
ENVVAR = System.getenv("LEMA");
}
else {
ENVVAR = System.getenv("BIOSIM");
}
// Creates a new frame
if (lema) {
frame = new JFrame("LEMA");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons"
+ separator + "LEMA.png").getImage());
}
else if (atacs) {
frame = new JFrame("ATACS");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons"
+ separator + "ATACS.png").getImage());
}
else {
frame = new JFrame("iBioSim");
frame.setIconImage(new ImageIcon(ENVVAR + separator + "gui" + separator + "icons"
+ separator + "iBioSim.png").getImage());
}
// Makes it so that clicking the x in the corner closes the program
WindowListener w = new WindowListener() {
public void windowClosing(WindowEvent arg0) {
exit.doClick();
}
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) {
}
};
frame.addWindowListener(w);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowFocusListener(this);
popup = new JPopupMenu();
popup.addMouseListener(this);
// popup.addFocusListener(this);
// popup.addComponentListener(this);
// Sets up the Tool Bar
toolbar = new JToolBar();
String imgName = ENVVAR + File.separator + "gui" + File.separator + "icons"
+ File.separator + "save.png";
saveButton = makeToolButton(imgName, "save", "Save", "Save");
// toolButton = new JButton("Save");
toolbar.add(saveButton);
imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator
+ "saveas.png";
saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As");
toolbar.add(saveasButton);
imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator
+ "run-icon.jpg";
runButton = makeToolButton(imgName, "run", "Save and Run", "Run");
// toolButton = new JButton("Run");
toolbar.add(runButton);
imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator
+ "refresh.jpg";
refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh");
toolbar.add(refreshButton);
imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator
+ "savecheck.png";
checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check");
toolbar.add(checkButton);
imgName = ENVVAR + File.separator + "gui" + File.separator + "icons" + File.separator
+ "export.jpg";
exportButton = makeToolButton(imgName, "export", "Export", "Export");
toolbar.add(exportButton);
saveButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
saveasButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// Creates a menu for the frame
menuBar = new JMenuBar();
file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
help = new JMenu("Help");
help.setMnemonic(KeyEvent.VK_H);
edit = new JMenu("Edit");
edit.setMnemonic(KeyEvent.VK_E);
importMenu = new JMenu("Import");
exportMenu = new JMenu("Export");
newMenu = new JMenu("New");
saveAsMenu = new JMenu("Save As");
view = new JMenu("View");
viewModel = new JMenu("Model");
tools = new JMenu("Tools");
menuBar.add(file);
menuBar.add(edit);
menuBar.add(view);
menuBar.add(tools);
menuBar.add(help);
// menuBar.addFocusListener(this);
// menuBar.addMouseListener(this);
// file.addMouseListener(this);
// edit.addMouseListener(this);
// view.addMouseListener(this);
// tools.addMouseListener(this);
// help.addMouseListener(this);
copy = new JMenuItem("Copy");
rename = new JMenuItem("Rename");
delete = new JMenuItem("Delete");
manual = new JMenuItem("Manual");
about = new JMenuItem("About");
openProj = new JMenuItem("Open Project");
close = new JMenuItem("Close");
closeAll = new JMenuItem("Close All");
pref = new JMenuItem("Preferences");
newProj = new JMenuItem("Project");
newCircuit = new JMenuItem("Genetic Circuit Model");
newModel = new JMenuItem("SBML Model");
newSpice = new JMenuItem("Spice Circuit");
newVhdl = new JMenuItem("VHDL-AMS Model");
newS = new JMenuItem("Assembly File");
newInst = new JMenuItem("Instruction File");
newLhpn = new JMenuItem("Labeled Petri Net");
newG = new JMenuItem("Petri Net");
newCsp = new JMenuItem("CSP Model");
newHse = new JMenuItem("Handshaking Expansion");
newUnc = new JMenuItem("Extended Burst Mode Machine");
newRsg = new JMenuItem("Reduced State Graph");
graph = new JMenuItem("TSD Graph");
probGraph = new JMenuItem("Histogram");
importSbml = new JMenuItem("SBML Model");
importBioModel = new JMenuItem("BioModel");
importDot = new JMenuItem("Genetic Circuit Model");
importG = new JMenuItem("Petri Net");
importLpn = new JMenuItem("Labeled Petri Net");
importVhdl = new JMenuItem("VHDL-AMS Model");
importS = new JMenuItem("Assembly File");
importInst = new JMenuItem("Instruction File");
importSpice = new JMenuItem("Spice Circuit");
importCsp = new JMenuItem("CSP Model");
importHse = new JMenuItem("Handshaking Expansion");
importUnc = new JMenuItem("Extended Burst Mode Machine");
importRsg = new JMenuItem("Reduced State Graph");
exportCsv = new JMenuItem("Comma Separated Values (csv)");
exportDat = new JMenuItem("Tab Delimited Data (dat)");
exportEps = new JMenuItem("Encapsulated Postscript (eps)");
exportJpg = new JMenuItem("JPEG (jpg)");
exportPdf = new JMenuItem("Portable Document Format (pdf)");
exportPng = new JMenuItem("Portable Network Graphics (png)");
exportSvg = new JMenuItem("Scalable Vector Graphics (svg)");
exportTsd = new JMenuItem("Time Series Data (tsd)");
save = new JMenuItem("Save");
if (async) {
saveModel = new JMenuItem("Save Models");
}
else {
saveModel = new JMenuItem("Save GCM");
}
saveAs = new JMenuItem("Save As");
saveAsGcm = new JMenuItem("Genetic Circuit Model");
saveAsGraph = new JMenuItem("Graph");
saveAsSbml = new JMenuItem("Save SBML Model");
saveAsTemplate = new JMenuItem("Save SBML Template");
saveGcmAsLhpn = new JMenuItem("Save LHPN Model");
saveAsLhpn = new JMenuItem("LHPN");
run = new JMenuItem("Save and Run");
check = new JMenuItem("Save and Check");
saveSbml = new JMenuItem("Save as SBML");
saveTemp = new JMenuItem("Save as SBML Template");
// saveParam = new JMenuItem("Save Parameters");
refresh = new JMenuItem("Refresh");
export = new JMenuItem("Export");
viewCircuit = new JMenuItem("Circuit");
viewRules = new JMenuItem("Production Rules");
viewTrace = new JMenuItem("Error Trace");
viewLog = new JMenuItem("Log");
viewCoverage = new JMenuItem("Coverage Report");
viewVHDL = new JMenuItem("VHDL-AMS Model");
viewVerilog = new JMenuItem("Verilog-AMS Model");
viewLHPN = new JMenuItem("LHPN Model");
viewModGraph = new JMenuItem("Model");
viewModBrowser = new JMenuItem("Model in Browser");
viewSG = new JMenuItem("State Graph");
createAnal = new JMenuItem("Analysis Tool");
createLearn = new JMenuItem("Learn Tool");
createSbml = new JMenuItem("Create SBML File");
createSynth = new JMenuItem("Synthesis Tool");
createVer = new JMenuItem("Verification Tool");
exit = new JMenuItem("Exit");
copy.addActionListener(this);
rename.addActionListener(this);
delete.addActionListener(this);
openProj.addActionListener(this);
close.addActionListener(this);
closeAll.addActionListener(this);
pref.addActionListener(this);
manual.addActionListener(this);
newProj.addActionListener(this);
newCircuit.addActionListener(this);
newModel.addActionListener(this);
newVhdl.addActionListener(this);
newS.addActionListener(this);
newInst.addActionListener(this);
newLhpn.addActionListener(this);
newG.addActionListener(this);
newCsp.addActionListener(this);
newHse.addActionListener(this);
newUnc.addActionListener(this);
newRsg.addActionListener(this);
newSpice.addActionListener(this);
exit.addActionListener(this);
about.addActionListener(this);
importSbml.addActionListener(this);
importBioModel.addActionListener(this);
importDot.addActionListener(this);
importVhdl.addActionListener(this);
importS.addActionListener(this);
importInst.addActionListener(this);
importLpn.addActionListener(this);
importG.addActionListener(this);
importCsp.addActionListener(this);
importHse.addActionListener(this);
importUnc.addActionListener(this);
importRsg.addActionListener(this);
importSpice.addActionListener(this);
exportCsv.addActionListener(this);
exportDat.addActionListener(this);
exportEps.addActionListener(this);
exportJpg.addActionListener(this);
exportPdf.addActionListener(this);
exportPng.addActionListener(this);
exportSvg.addActionListener(this);
exportTsd.addActionListener(this);
graph.addActionListener(this);
probGraph.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
saveAsSbml.addActionListener(this);
saveAsTemplate.addActionListener(this);
saveGcmAsLhpn.addActionListener(this);
run.addActionListener(this);
check.addActionListener(this);
saveSbml.addActionListener(this);
saveTemp.addActionListener(this);
saveModel.addActionListener(this);
// saveParam.addActionListener(this);
export.addActionListener(this);
viewCircuit.addActionListener(this);
viewRules.addActionListener(this);
viewTrace.addActionListener(this);
viewLog.addActionListener(this);
viewCoverage.addActionListener(this);
viewVHDL.addActionListener(this);
viewVerilog.addActionListener(this);
viewLHPN.addActionListener(this);
viewModGraph.addActionListener(this);
viewModBrowser.addActionListener(this);
viewSG.addActionListener(this);
createAnal.addActionListener(this);
createLearn.addActionListener(this);
createSbml.addActionListener(this);
createSynth.addActionListener(this);
createVer.addActionListener(this);
save.setActionCommand("save");
saveAs.setActionCommand("saveas");
run.setActionCommand("run");
check.setActionCommand("check");
refresh.setActionCommand("refresh");
export.setActionCommand("export");
if (atacs) {
viewModGraph.setActionCommand("viewModel");
}
else {
viewModGraph.setActionCommand("graph");
}
viewModBrowser.setActionCommand("browse");
viewSG.setActionCommand("stateGraph");
createLearn.setActionCommand("createLearn");
createSbml.setActionCommand("createSBML");
createSynth.setActionCommand("createSynthesis");
createVer.setActionCommand("createVerify");
ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey));
rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey));
// newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
// ShortCutKey));
openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey));
close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey));
closeAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey
| KeyEvent.SHIFT_MASK));
// saveAsMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// importMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// exportMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// viewModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,
// ShortCutKey | KeyEvent.ALT_DOWN_MASK));
// newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
// ShortCutKey));
// newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
// ShortCutKey));
// newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
// ShortCutKey));
// newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
// ShortCutKey));
// about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
// ShortCutKey));
manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey));
run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey));
check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey));
pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey));
viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
if (lema) {
// viewCoverage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,
// 0)); // SB
viewVHDL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0));
viewVerilog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
viewLHPN.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
viewTrace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0));
}
else {
viewCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey));
createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey));
}
Action newAction = new NewAction();
Action saveAction = new SaveAction();
Action importAction = new ImportAction();
Action exportAction = new ExportAction();
Action modelAction = new ModelAction();
newMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "new");
newMenu.getActionMap().put("new", newAction);
saveAsMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"save");
saveAsMenu.getActionMap().put("save", saveAction);
importMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_I, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"import");
importMenu.getActionMap().put("import", importAction);
exportMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"export");
exportMenu.getActionMap().put("export", exportAction);
viewModel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.ALT_DOWN_MASK),
"model");
viewModel.getActionMap().put("model", modelAction);
// graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
// ShortCutKey));
// probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
// ShortCutKey));
// if (!lema) {
// importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
// ShortCutKey));
// else {
// importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
// ShortCutKey));
// importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B,
// ShortCutKey));
// importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
// ShortCutKey));
newMenu.setMnemonic(KeyEvent.VK_N);
saveAsMenu.setMnemonic(KeyEvent.VK_A);
importMenu.setMnemonic(KeyEvent.VK_I);
exportMenu.setMnemonic(KeyEvent.VK_E);
viewModel.setMnemonic(KeyEvent.VK_M);
copy.setMnemonic(KeyEvent.VK_C);
rename.setMnemonic(KeyEvent.VK_R);
delete.setMnemonic(KeyEvent.VK_D);
exit.setMnemonic(KeyEvent.VK_X);
newProj.setMnemonic(KeyEvent.VK_P);
openProj.setMnemonic(KeyEvent.VK_O);
close.setMnemonic(KeyEvent.VK_W);
newCircuit.setMnemonic(KeyEvent.VK_G);
newModel.setMnemonic(KeyEvent.VK_S);
newVhdl.setMnemonic(KeyEvent.VK_V);
newLhpn.setMnemonic(KeyEvent.VK_L);
newG.setMnemonic(KeyEvent.VK_N);
newSpice.setMnemonic(KeyEvent.VK_P);
about.setMnemonic(KeyEvent.VK_A);
manual.setMnemonic(KeyEvent.VK_M);
graph.setMnemonic(KeyEvent.VK_T);
probGraph.setMnemonic(KeyEvent.VK_H);
if (!async) {
importDot.setMnemonic(KeyEvent.VK_G);
}
else {
importLpn.setMnemonic(KeyEvent.VK_L);
}
importSbml.setMnemonic(KeyEvent.VK_S);
// importBioModel.setMnemonic(KeyEvent.VK_S);
importVhdl.setMnemonic(KeyEvent.VK_V);
importSpice.setMnemonic(KeyEvent.VK_P);
save.setMnemonic(KeyEvent.VK_S);
run.setMnemonic(KeyEvent.VK_R);
check.setMnemonic(KeyEvent.VK_K);
exportCsv.setMnemonic(KeyEvent.VK_C);
exportEps.setMnemonic(KeyEvent.VK_E);
exportDat.setMnemonic(KeyEvent.VK_D);
exportJpg.setMnemonic(KeyEvent.VK_J);
exportPdf.setMnemonic(KeyEvent.VK_F);
exportPng.setMnemonic(KeyEvent.VK_G);
exportSvg.setMnemonic(KeyEvent.VK_S);
exportTsd.setMnemonic(KeyEvent.VK_T);
pref.setMnemonic(KeyEvent.VK_P);
viewModGraph.setMnemonic(KeyEvent.VK_G);
viewModBrowser.setMnemonic(KeyEvent.VK_B);
createAnal.setMnemonic(KeyEvent.VK_A);
createLearn.setMnemonic(KeyEvent.VK_L);
importDot.setEnabled(false);
importSbml.setEnabled(false);
importBioModel.setEnabled(false);
importVhdl.setEnabled(false);
importS.setEnabled(false);
importInst.setEnabled(false);
importLpn.setEnabled(false);
importG.setEnabled(false);
importCsp.setEnabled(false);
importHse.setEnabled(false);
importUnc.setEnabled(false);
importRsg.setEnabled(false);
importSpice.setEnabled(false);
exportMenu.setEnabled(false);
// exportCsv.setEnabled(false);
// exportDat.setEnabled(false);
// exportEps.setEnabled(false);
// exportJpg.setEnabled(false);
// exportPdf.setEnabled(false);
// exportPng.setEnabled(false);
// exportSvg.setEnabled(false);
// exportTsd.setEnabled(false);
newCircuit.setEnabled(false);
newModel.setEnabled(false);
newVhdl.setEnabled(false);
newS.setEnabled(false);
newInst.setEnabled(false);
newLhpn.setEnabled(false);
newG.setEnabled(false);
newCsp.setEnabled(false);
newHse.setEnabled(false);
newUnc.setEnabled(false);
newRsg.setEnabled(false);
newSpice.setEnabled(false);
graph.setEnabled(false);
probGraph.setEnabled(false);
save.setEnabled(false);
saveModel.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
run.setEnabled(false);
check.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
// saveParam.setEnabled(false);
refresh.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
viewSG.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
edit.add(copy);
edit.add(rename);
// edit.add(refresh);
edit.add(delete);
// edit.addSeparator();
// edit.add(pref);
file.add(newMenu);
newMenu.add(newProj);
if (!async) {
newMenu.add(newCircuit);
newMenu.add(newLhpn);
newMenu.add(newModel);
}
else if (atacs) {
newMenu.add(newVhdl);
newMenu.add(newG);
newMenu.add(newLhpn);
newMenu.add(newCsp);
newMenu.add(newHse);
newMenu.add(newUnc);
newMenu.add(newRsg);
}
else {
newMenu.add(newVhdl);
newMenu.add(newS);
newMenu.add(newInst);
newMenu.add(newLhpn);
// newMenu.add(newSpice);
}
newMenu.add(graph);
if (!async) {
newMenu.add(probGraph);
}
file.add(openProj);
// openMenu.add(openProj);
file.addSeparator();
file.add(close);
file.add(closeAll);
file.addSeparator();
file.add(save);
// file.add(saveAsMenu);
if (!async) {
saveAsMenu.add(saveAsGcm);
saveAsMenu.add(saveAsGraph);
saveAsMenu.add(saveAsSbml);
saveAsMenu.add(saveAsTemplate);
saveAsMenu.add(saveGcmAsLhpn);
}
else {
saveAsMenu.add(saveAsLhpn);
saveAsMenu.add(saveAsGraph);
}
file.add(saveAs);
if (!async) {
file.add(saveAsSbml);
file.add(saveAsTemplate);
file.add(saveGcmAsLhpn);
}
file.add(saveModel);
// file.add(saveParam);
file.add(run);
if (!async) {
file.add(check);
}
file.addSeparator();
file.add(importMenu);
if (!async) {
importMenu.add(importDot);
importMenu.add(importLpn);
importMenu.add(importSbml);
importMenu.add(importBioModel);
}
else if (atacs) {
importMenu.add(importVhdl);
importMenu.add(importG);
importMenu.add(importLpn);
importMenu.add(importCsp);
importMenu.add(importHse);
importMenu.add(importUnc);
importMenu.add(importRsg);
}
else {
importMenu.add(importVhdl);
importMenu.add(importS);
importMenu.add(importInst);
importMenu.add(importLpn);
// importMenu.add(importSpice);
}
file.add(exportMenu);
exportMenu.add(exportCsv);
exportMenu.add(exportDat);
exportMenu.add(exportEps);
exportMenu.add(exportJpg);
exportMenu.add(exportPdf);
exportMenu.add(exportPng);
exportMenu.add(exportSvg);
exportMenu.add(exportTsd);
file.addSeparator();
// file.add(save);
// file.add(saveAs);
// file.add(run);
// file.add(check);
// if (!lema) {
// file.add(saveParam);
// file.addSeparator();
// file.add(export);
// if (!lema) {
// file.add(saveSbml);
// file.add(saveTemp);
help.add(manual);
externView = false;
viewer = "";
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
edit.addSeparator();
edit.add(pref);
file.add(exit);
file.addSeparator();
help.add(about);
}
if (lema) {
view.add(viewVHDL);
view.add(viewVerilog);
view.add(viewLHPN);
view.addSeparator();
view.add(viewCoverage);
view.add(viewLog);
view.add(viewTrace);
}
else if (atacs) {
view.add(viewModGraph);
view.add(viewCircuit);
view.add(viewRules);
view.add(viewTrace);
view.add(viewLog);
}
else {
view.add(viewModGraph);
view.add(viewModBrowser);
view.add(viewSG);
view.add(viewLog);
view.addSeparator();
view.add(refresh);
}
if (!async) {
tools.add(createAnal);
}
if (!atacs) {
tools.add(createLearn);
}
if (atacs) {
tools.add(createSynth);
}
if (async) {
tools.add(createVer);
}
// else {
// tools.add(createSbml);
root = null;
// Create recent project menu items
numberRecentProj = 0;
recentProjects = new JMenuItem[5];
recentProjectPaths = new String[5];
for (int i = 0; i < 5; i++) {
recentProjects[i] = new JMenuItem();
recentProjects[i].addActionListener(this);
recentProjects[i].setActionCommand("recent" + i);
recentProjectPaths[i] = "";
}
recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey));
recentProjects[0].setMnemonic(KeyEvent.VK_1);
recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey));
recentProjects[1].setMnemonic(KeyEvent.VK_2);
recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey));
recentProjects[2].setMnemonic(KeyEvent.VK_3);
recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey));
recentProjects[3].setMnemonic(KeyEvent.VK_4);
recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey));
recentProjects[4].setMnemonic(KeyEvent.VK_5);
Preferences biosimrc = Preferences.userRoot();
for (int i = 0; i < 5; i++) {
if (atacs) {
recentProjects[i].setText(biosimrc.get("atacs.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("atacs.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
else if (lema) {
recentProjects[i].setText(biosimrc.get("lema.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("lema.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
else {
recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, ""));
recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, "");
if (!recentProjectPaths[i].equals("")) {
file.add(recentProjects[i]);
numberRecentProj = i + 1;
}
}
}
if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
new MacOSAboutHandler();
new MacOSPreferencesHandler();
new MacOSQuitHandler();
Application application = new Application();
application.addPreferencesMenuItem();
application.setEnabledPreferencesMenu(true);
}
else {
// file.add(pref);
// file.add(exit);
help.add(about);
}
if (biosimrc.get("biosim.check.undeclared", "").equals("false")) {
checkUndeclared = false;
}
else {
checkUndeclared = true;
}
if (biosimrc.get("biosim.check.units", "").equals("false")) {
checkUnits = false;
}
else {
checkUnits = true;
}
if (biosimrc.get("biosim.general.file_browser", "").equals("")) {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KREP_VALUE", ".5");
}
if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KACT_VALUE", ".0033");
}
if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KBIO_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2");
}
if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001");
}
if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.OCR_VALUE", ".05");
}
if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075");
}
if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.RNAP_VALUE", "30");
}
if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033");
}
if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10");
}
if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2");
}
if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25");
}
if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1");
}
if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) {
biosimrc.put("biosim.gcm.INITIAL_VALUE", "0");
}
if (biosimrc.get("biosim.sim.abs", "").equals("")) {
biosimrc.put("biosim.sim.abs", "None");
}
if (biosimrc.get("biosim.sim.type", "").equals("")) {
biosimrc.put("biosim.sim.type", "ODE");
}
if (biosimrc.get("biosim.sim.sim", "").equals("")) {
biosimrc.put("biosim.sim.sim", "rkf45");
}
if (biosimrc.get("biosim.sim.limit", "").equals("")) {
biosimrc.put("biosim.sim.limit", "100.0");
}
if (biosimrc.get("biosim.sim.useInterval", "").equals("")) {
biosimrc.put("biosim.sim.useInterval", "Print Interval");
}
if (biosimrc.get("biosim.sim.interval", "").equals("")) {
biosimrc.put("biosim.sim.interval", "1.0");
}
if (biosimrc.get("biosim.sim.step", "").equals("")) {
biosimrc.put("biosim.sim.step", "inf");
}
if (biosimrc.get("biosim.sim.min.step", "").equals("")) {
biosimrc.put("biosim.sim.min.step", "0");
}
if (biosimrc.get("biosim.sim.error", "").equals("")) {
biosimrc.put("biosim.sim.error", "1.0E-9");
}
if (biosimrc.get("biosim.sim.seed", "").equals("")) {
biosimrc.put("biosim.sim.seed", "314159");
}
if (biosimrc.get("biosim.sim.runs", "").equals("")) {
biosimrc.put("biosim.sim.runs", "1");
}
if (biosimrc.get("biosim.sim.rapid1", "").equals("")) {
biosimrc.put("biosim.sim.rapid1", "0.1");
}
if (biosimrc.get("biosim.sim.rapid2", "").equals("")) {
biosimrc.put("biosim.sim.rapid2", "0.1");
}
if (biosimrc.get("biosim.sim.qssa", "").equals("")) {
biosimrc.put("biosim.sim.qssa", "0.1");
}
if (biosimrc.get("biosim.sim.concentration", "").equals("")) {
biosimrc.put("biosim.sim.concentration", "15");
}
if (biosimrc.get("biosim.learn.tn", "").equals("")) {
biosimrc.put("biosim.learn.tn", "2");
}
if (biosimrc.get("biosim.learn.tj", "").equals("")) {
biosimrc.put("biosim.learn.tj", "2");
}
if (biosimrc.get("biosim.learn.ti", "").equals("")) {
biosimrc.put("biosim.learn.ti", "0.5");
}
if (biosimrc.get("biosim.learn.bins", "").equals("")) {
biosimrc.put("biosim.learn.bins", "4");
}
if (biosimrc.get("biosim.learn.equaldata", "").equals("")) {
biosimrc.put("biosim.learn.equaldata", "Equal Data Per Bins");
}
if (biosimrc.get("biosim.learn.autolevels", "").equals("")) {
biosimrc.put("biosim.learn.autolevels", "Auto");
}
if (biosimrc.get("biosim.learn.ta", "").equals("")) {
biosimrc.put("biosim.learn.ta", "1.15");
}
if (biosimrc.get("biosim.learn.tr", "").equals("")) {
biosimrc.put("biosim.learn.tr", "0.75");
}
if (biosimrc.get("biosim.learn.tm", "").equals("")) {
biosimrc.put("biosim.learn.tm", "0.0");
}
if (biosimrc.get("biosim.learn.tt", "").equals("")) {
biosimrc.put("biosim.learn.tt", "0.025");
}
if (biosimrc.get("biosim.learn.debug", "").equals("")) {
biosimrc.put("biosim.learn.debug", "0");
}
if (biosimrc.get("biosim.learn.succpred", "").equals("")) {
biosimrc.put("biosim.learn.succpred", "Successors");
}
if (biosimrc.get("biosim.learn.findbaseprob", "").equals("")) {
biosimrc.put("biosim.learn.findbaseprob", "False");
}
// Open .biosimrc here
// Packs the frame and displays it
mainPanel = new JPanel(new BorderLayout());
tree = new FileTree(null, this, lema, atacs);
log = new Log();
tab = new CloseAndMaxTabbedPane(false, this);
tab.setPreferredSize(new Dimension(1100, 550));
tab.getPaneUI().addMouseListener(this);
mainPanel.add(tree, "West");
mainPanel.add(tab, "Center");
mainPanel.add(log, "South");
mainPanel.add(toolbar, "North");
frame.setContentPane(mainPanel);
frame.setJMenuBar(menuBar);
frame.getGlassPane().setVisible(true);
frame.getGlassPane().addMouseListener(this);
frame.getGlassPane().addMouseMotionListener(this);
frame.getGlassPane().addMouseWheelListener(this);
frame.addMouseListener(this);
menuBar.addMouseListener(this);
frame.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
frame.setSize(frameSize);
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
frame.setSize(frameSize);
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
frame.setLocation(x, y);
frame.setVisible(true);
dispatcher = new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_TYPED) {
if (e.getKeyChar() == '') {
if (tab.getTabCount() > 0) {
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.removeKeyEventDispatcher(dispatcher);
if (save(tab.getSelectedIndex(), 0) != 0) {
tab.remove(tab.getSelectedIndex());
}
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(dispatcher);
}
}
}
return false;
}
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
}
public void preferences() {
if (!async) {
Undeclared = new JCheckBox("Check for undeclared units in SBML");
if (checkUndeclared) {
Undeclared.setSelected(true);
}
else {
Undeclared.setSelected(false);
}
Units = new JCheckBox("Check units in SBML");
if (checkUnits) {
Units.setSelected(true);
}
else {
Units.setSelected(false);
}
Preferences biosimrc = Preferences.userRoot();
JCheckBox dialog = new JCheckBox("Use File Dialog");
if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) {
dialog.setSelected(true);
}
else {
dialog.setSelected(false);
}
final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.ACTIVED_VALUE", ""));
final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", ""));
final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE",
""));
final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", ""));
final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE",
""));
final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.COOPERATIVITY_VALUE", ""));
final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.KASSOCIATION_VALUE", ""));
final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", ""));
final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.PROMOTER_COUNT_VALUE", ""));
final JTextField INITIAL_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.INITIAL_VALUE", ""));
final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.MAX_DIMER_VALUE", ""));
final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", ""));
final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.RNAP_BINDING_VALUE", ""));
final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", ""));
final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get(
"biosim.gcm.STOICHIOMETRY_VALUE", ""));
JPanel labels = new JPanel(new GridLayout(15, 1));
labels
.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.COOPERATIVITY_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.KASSOCIATION_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.PROMOTER_COUNT_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING)
+ "):"));
labels
.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING)
+ " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.RNAP_BINDING_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING)
+ "):"));
labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):"));
labels.add(new JLabel(CompatibilityFixer
.getGuiName(GlobalConstants.STOICHIOMETRY_STRING)
+ " ("
+ CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING)
+ "):"));
JPanel fields = new JPanel(new GridLayout(15, 1));
fields.add(ACTIVED_VALUE);
fields.add(KACT_VALUE);
fields.add(KBASAL_VALUE);
fields.add(KBIO_VALUE);
fields.add(KDECAY_VALUE);
fields.add(COOPERATIVITY_VALUE);
fields.add(KASSOCIATION_VALUE);
fields.add(RNAP_VALUE);
fields.add(PROMOTER_COUNT_VALUE);
fields.add(INITIAL_VALUE);
fields.add(MAX_DIMER_VALUE);
fields.add(OCR_VALUE);
fields.add(RNAP_BINDING_VALUE);
fields.add(KREP_VALUE);
fields.add(STOICHIOMETRY_VALUE);
JPanel gcmPrefs = new JPanel(new GridLayout(1, 2));
gcmPrefs.add(labels);
gcmPrefs.add(fields);
String[] choices = { "None", "Abstraction", "Logical Abstraction" };
final JComboBox abs = new JComboBox(choices);
abs.setSelectedItem(biosimrc.get("biosim.sim.abs", ""));
if (abs.getSelectedItem().equals("None")) {
choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" };
}
else if (abs.getSelectedItem().equals("Abstraction")) {
choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" };
}
else {
choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser",
"LHPN" };
}
final JComboBox type = new JComboBox(choices);
type.setSelectedItem(biosimrc.get("biosim.sim.type", ""));
if (type.getSelectedItem().equals("ODE")) {
choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" };
}
else if (type.getSelectedItem().equals("Monte Carlo")) {
choices = new String[] { "gillespie", "mpde", "mp", "mp-adaptive", "mp-event",
"emc-sim", "bunker", "nmc" };
}
else if (type.getSelectedItem().equals("Markov")) {
choices = new String[] { "markov-chain-analysis", "atacs", "ctmc-transient" };
}
else {
choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" };
}
final JComboBox sim = new JComboBox(choices);
sim.setSelectedItem(biosimrc.get("biosim.sim.sim", ""));
abs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (abs.getSelectedItem().equals("None")) {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("ODE");
type.addItem("Monte Carlo");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.setSelectedItem(o);
}
else if (abs.getSelectedItem().equals("Abstraction")) {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("ODE");
type.addItem("Monte Carlo");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.setSelectedItem(o);
}
else {
Object o = type.getSelectedItem();
type.removeAllItems();
type.addItem("Monte Carlo");
type.addItem("Markov");
type.addItem("SBML");
type.addItem("Network");
type.addItem("Browser");
type.addItem("LHPN");
type.setSelectedItem(o);
}
}
});
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (type.getSelectedItem() == null) {
}
else if (type.getSelectedItem().equals("ODE")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("euler");
sim.addItem("gear1");
sim.addItem("gear2");
sim.addItem("rk4imp");
sim.addItem("rk8pd");
sim.addItem("rkf45");
sim.setSelectedIndex(5);
sim.setSelectedItem(o);
}
else if (type.getSelectedItem().equals("Monte Carlo")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("gillespie");
sim.addItem("mpde");
sim.addItem("mp");
sim.addItem("mp-adaptive");
sim.addItem("mp-event");
sim.addItem("emc-sim");
sim.addItem("bunker");
sim.addItem("nmc");
sim.setSelectedItem(o);
}
else if (type.getSelectedItem().equals("Markov")) {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("atacs");
sim.addItem("ctmc-transient");
sim.setSelectedItem(o);
}
else {
Object o = sim.getSelectedItem();
sim.removeAllItems();
sim.addItem("euler");
sim.addItem("gear1");
sim.addItem("gear2");
sim.addItem("rk4imp");
sim.addItem("rk8pd");
sim.addItem("rkf45");
sim.setSelectedIndex(5);
sim.setSelectedItem(o);
}
}
});
JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", ""));
JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", ""));
JTextField minStep = new JTextField(biosimrc.get("biosim.sim.min.step", ""));
JTextField step = new JTextField(biosimrc.get("biosim.sim.step", ""));
JTextField error = new JTextField(biosimrc.get("biosim.sim.error", ""));
JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", ""));
JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", ""));
JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", ""));
JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", ""));
JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", ""));
JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", ""));
choices = new String[] { "Print Interval", "Minimum Print Interval", "Number Of Steps" };
JComboBox useInterval = new JComboBox(choices);
useInterval.setSelectedItem(biosimrc.get("biosim.sim.useInterval", ""));
JPanel analysisLabels = new JPanel(new GridLayout(14, 1));
analysisLabels.add(new JLabel("Abstraction:"));
analysisLabels.add(new JLabel("Simulation Type:"));
analysisLabels.add(new JLabel("Possible Simulators/Analyzers:"));
analysisLabels.add(new JLabel("Time Limit:"));
analysisLabels.add(useInterval);
analysisLabels.add(new JLabel("Minimum Time Step:"));
analysisLabels.add(new JLabel("Maximum Time Step:"));
analysisLabels.add(new JLabel("Absolute Error:"));
analysisLabels.add(new JLabel("Random Seed:"));
analysisLabels.add(new JLabel("Runs:"));
analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:"));
analysisLabels.add(new JLabel("Rapid Equilibrium Cojdition 2:"));
analysisLabels.add(new JLabel("QSSA Condition:"));
analysisLabels.add(new JLabel("Max Concentration Threshold:"));
JPanel analysisFields = new JPanel(new GridLayout(14, 1));
analysisFields.add(abs);
analysisFields.add(type);
analysisFields.add(sim);
analysisFields.add(limit);
analysisFields.add(interval);
analysisFields.add(minStep);
analysisFields.add(step);
analysisFields.add(error);
analysisFields.add(seed);
analysisFields.add(runs);
analysisFields.add(rapid1);
analysisFields.add(rapid2);
analysisFields.add(qssa);
analysisFields.add(concentration);
JPanel analysisPrefs = new JPanel(new GridLayout(1, 2));
analysisPrefs.add(analysisLabels);
analysisPrefs.add(analysisFields);
final JTextField tn = new JTextField(biosimrc.get("biosim.learn.tn", ""));
final JTextField tj = new JTextField(biosimrc.get("biosim.learn.tj", ""));
final JTextField ti = new JTextField(biosimrc.get("biosim.learn.ti", ""));
choices = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
final JComboBox bins = new JComboBox(choices);
bins.setSelectedItem(biosimrc.get("biosim.learn.bins", ""));
choices = new String[] { "Equal Data Per Bins", "Equal Spacing Of Bins" };
final JComboBox equaldata = new JComboBox(choices);
equaldata.setSelectedItem(biosimrc.get("biosim.learn.equaldata", ""));
choices = new String[] { "Auto", "User" };
final JComboBox autolevels = new JComboBox(choices);
autolevels.setSelectedItem(biosimrc.get("biosim.learn.autolevels", ""));
final JTextField ta = new JTextField(biosimrc.get("biosim.learn.ta", ""));
final JTextField tr = new JTextField(biosimrc.get("biosim.learn.tr", ""));
final JTextField tm = new JTextField(biosimrc.get("biosim.learn.tm", ""));
final JTextField tt = new JTextField(biosimrc.get("biosim.learn.tt", ""));
choices = new String[] { "0", "1", "2", "3" };
final JComboBox debug = new JComboBox(choices);
debug.setSelectedItem(biosimrc.get("biosim.learn.debug", ""));
choices = new String[] { "Successors", "Predecessors", "Both" };
final JComboBox succpred = new JComboBox(choices);
succpred.setSelectedItem(biosimrc.get("biosim.learn.succpred", ""));
choices = new String[] { "True", "False" };
final JComboBox findbaseprob = new JComboBox(choices);
findbaseprob.setSelectedItem(biosimrc.get("biosim.learn.findbaseprob", ""));
JPanel learnLabels = new JPanel(new GridLayout(13, 1));
learnLabels.add(new JLabel("Minimum Number Of Initial Vectors (Tn):"));
learnLabels.add(new JLabel("Maximum Influence Vector Size (Tj):"));
learnLabels.add(new JLabel("Score For Empty Influence Vector (Ti):"));
learnLabels.add(new JLabel("Number Of Bins:"));
learnLabels.add(new JLabel("Divide Bins:"));
learnLabels.add(new JLabel("Generate Levels:"));
learnLabels.add(new JLabel("Ratio For Activation (Ta):"));
learnLabels.add(new JLabel("Ratio For Repression (Tr):"));
learnLabels.add(new JLabel("Merge Influence Vectors Delta (Tm):"));
learnLabels.add(new JLabel("Relax Thresholds Delta (Tt):"));
learnLabels.add(new JLabel("Debug Level:"));
learnLabels.add(new JLabel("Successors Or Predecessors:"));
learnLabels.add(new JLabel("Basic FindBaseProb:"));
JPanel learnFields = new JPanel(new GridLayout(13, 1));
learnFields.add(tn);
learnFields.add(tj);
learnFields.add(ti);
learnFields.add(bins);
learnFields.add(equaldata);
learnFields.add(autolevels);
learnFields.add(ta);
learnFields.add(tr);
learnFields.add(tm);
learnFields.add(tt);
learnFields.add(debug);
learnFields.add(succpred);
learnFields.add(findbaseprob);
JPanel learnPrefs = new JPanel(new GridLayout(1, 2));
learnPrefs.add(learnLabels);
learnPrefs.add(learnFields);
JPanel generalPrefs = new JPanel(new BorderLayout());
generalPrefs.add(dialog, "North");
JPanel sbmlPrefsBordered = new JPanel(new BorderLayout());
JPanel sbmlPrefs = new JPanel();
sbmlPrefsBordered.add(Undeclared, "North");
sbmlPrefsBordered.add(Units, "Center");
sbmlPrefs.add(sbmlPrefsBordered);
((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT);
JTabbedPane prefTabs = new JTabbedPane();
prefTabs.addTab("General Preferences", dialog);
prefTabs.addTab("SBML Preferences", sbmlPrefs);
prefTabs.addTab("GCM Preferences", gcmPrefs);
prefTabs.addTab("Analysis Preferences", analysisPrefs);
prefTabs.addTab("Learn Preferences", learnPrefs);
Object[] options = { "Save", "Cancel" };
int value = JOptionPane
.showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
if (dialog.isSelected()) {
biosimrc.put("biosim.general.file_browser", "FileDialog");
}
else {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
if (Undeclared.isSelected()) {
checkUndeclared = true;
biosimrc.put("biosim.check.undeclared", "true");
}
else {
checkUndeclared = false;
biosimrc.put("biosim.check.undeclared", "false");
}
if (Units.isSelected()) {
checkUnits = true;
biosimrc.put("biosim.check.units", "true");
}
else {
checkUnits = false;
biosimrc.put("biosim.check.units", "false");
}
try {
Double.parseDouble(KREP_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KACT_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KBIO_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim());
biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KASSOCIATION_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KBASAL_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(OCR_VALUE.getText().trim());
biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(KDECAY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(RNAP_VALUE.getText().trim());
biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(RNAP_BINDING_VALUE.getText().trim());
biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(COOPERATIVITY_VALUE.getText().trim());
biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText()
.trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(ACTIVED_VALUE.getText().trim());
biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(MAX_DIMER_VALUE.getText().trim());
biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(INITIAL_VALUE.getText().trim());
biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(limit.getText().trim());
biosimrc.put("biosim.sim.limit", limit.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(interval.getText().trim());
biosimrc.put("biosim.sim.interval", interval.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(minStep.getText().trim());
biosimrc.put("biosim.min.sim.step", minStep.getText().trim());
}
catch (Exception e1) {
}
try {
if (step.getText().trim().equals("inf")) {
biosimrc.put("biosim.sim.step", step.getText().trim());
}
else {
Double.parseDouble(step.getText().trim());
biosimrc.put("biosim.sim.step", step.getText().trim());
}
}
catch (Exception e1) {
}
try {
Double.parseDouble(error.getText().trim());
biosimrc.put("biosim.sim.error", error.getText().trim());
}
catch (Exception e1) {
}
try {
Long.parseLong(seed.getText().trim());
biosimrc.put("biosim.sim.seed", seed.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(runs.getText().trim());
biosimrc.put("biosim.sim.runs", runs.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(rapid1.getText().trim());
biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(rapid2.getText().trim());
biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(qssa.getText().trim());
biosimrc.put("biosim.sim.qssa", qssa.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(concentration.getText().trim());
biosimrc.put("biosim.sim.concentration", concentration.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.sim.useInterval", (String) useInterval.getSelectedItem());
biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem());
biosimrc.put("biosim.sim.type", (String) type.getSelectedItem());
biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem());
try {
Integer.parseInt(tn.getText().trim());
biosimrc.put("biosim.learn.tn", tn.getText().trim());
}
catch (Exception e1) {
}
try {
Integer.parseInt(tj.getText().trim());
biosimrc.put("biosim.learn.tj", tj.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(ti.getText().trim());
biosimrc.put("biosim.learn.ti", ti.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.learn.bins", (String) bins.getSelectedItem());
biosimrc.put("biosim.learn.equaldata", (String) equaldata.getSelectedItem());
biosimrc.put("biosim.learn.autolevels", (String) autolevels.getSelectedItem());
try {
Double.parseDouble(ta.getText().trim());
biosimrc.put("biosim.learn.ta", ta.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tr.getText().trim());
biosimrc.put("biosim.learn.tr", tr.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tm.getText().trim());
biosimrc.put("biosim.learn.tm", tm.getText().trim());
}
catch (Exception e1) {
}
try {
Double.parseDouble(tt.getText().trim());
biosimrc.put("biosim.learn.tt", tt.getText().trim());
}
catch (Exception e1) {
}
biosimrc.put("biosim.learn.debug", (String) debug.getSelectedItem());
biosimrc.put("biosim.learn.succpred", (String) succpred.getSelectedItem());
biosimrc.put("biosim.learn.findbaseprob", (String) findbaseprob.getSelectedItem());
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).contains(".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters();
((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters();
}
}
}
else {
}
}
else {
JPanel prefPanel = new JPanel(new GridLayout(0, 2));
viewerLabel = new JLabel("External Editor for non-LHPN files:");
viewerField = new JTextField("");
viewerCheck = new JCheckBox("Use External Viewer");
viewerCheck.addActionListener(this);
viewerCheck.setSelected(externView);
viewerField.setText(viewer);
viewerLabel.setEnabled(externView);
viewerField.setEnabled(externView);
prefPanel.add(viewerLabel);
prefPanel.add(viewerField);
prefPanel.add(viewerCheck);
// Preferences biosimrc = Preferences.userRoot();
// JPanel vhdlPrefs = new JPanel();
// JPanel lhpnPrefs = new JPanel();
// JTabbedPane prefTabsNoLema = new JTabbedPane();
// prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs);
// prefTabsNoLema.addTab("LHPN Preferences", lhpnPrefs);
Preferences biosimrc = Preferences.userRoot();
JCheckBox dialog = new JCheckBox("Use File Dialog");
if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) {
dialog.setSelected(true);
}
else {
dialog.setSelected(false);
}
prefPanel.add(dialog);
Object[] options = { "Save", "Cancel" };
int value = JOptionPane
.showOptionDialog(frame, prefPanel, "Preferences", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
viewer = viewerField.getText();
if (dialog.isSelected()) {
biosimrc.put("biosim.general.file_browser", "FileDialog");
}
else {
biosimrc.put("biosim.general.file_browser", "JFileChooser");
}
}
}
}
public void about() {
final JFrame f = new JFrame("About");
// frame.setIconImage(new ImageIcon(ENVVAR +
// File.separator
// + "gui"
// + File.separator + "icons" + File.separator +
// "iBioSim.png").getImage());
JLabel name;
JLabel version;
final String developers;
if (lema) {
name = new JLabel("LEMA", JLabel.CENTER);
version = new JLabel("Version 1.3", JLabel.CENTER);
developers = "Satish Batchu\nKevin Jones\nScott Little\nCurtis Madsen\nChris Myers\nNicholas Seegmiller\n"
+ "Robert Thacker\nDavid Walter";
}
else if (atacs) {
name = new JLabel("ATACS", JLabel.CENTER);
version = new JLabel("Version 6.3", JLabel.CENTER);
developers = "Wendy Belluomini\nJeff Cuthbert\nHans Jacobson\nKevin Jones\nSung-Tae Jung\n"
+ "Christopher Krieger\nScott Little\nCurtis Madsen\nEric Mercer\nChris Myers\n"
+ "Curt Nelson\nEric Peskin\nNicholas Seegmiller\nDavid Walter\nHao Zheng";
}
else {
name = new JLabel("iBioSim", JLabel.CENTER);
version = new JLabel("Version 1.3", JLabel.CENTER);
developers = "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n"
+ "Curtis Madsen\nChris Myers\nNam Nguyen";
}
Font font = name.getFont();
font = font.deriveFont(Font.BOLD, 36.0f);
name.setFont(font);
JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER);
JButton credits = new JButton("Credits");
credits.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = { "Close" };
JOptionPane.showOptionDialog(f, developers, "Credits", JOptionPane.YES_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
});
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel buttons = new JPanel();
buttons.add(credits);
buttons.add(close);
JPanel aboutPanel = new JPanel(new BorderLayout());
JPanel uOfUPanel = new JPanel(new BorderLayout());
uOfUPanel.add(name, "North");
uOfUPanel.add(version, "Center");
uOfUPanel.add(uOfU, "South");
if (lema) {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + File.separator
+ "gui" + File.separator + "icons" + File.separator + "LEMA.png")), "North");
}
else if (atacs) {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + File.separator
+ "gui" + File.separator + "icons" + File.separator + "ATACS.png")), "North");
}
else {
aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(ENVVAR + File.separator
+ "gui" + File.separator + "icons" + File.separator + "iBioSim.png")), "North");
}
// aboutPanel.add(bioSim, "North");
aboutPanel.add(uOfUPanel, "Center");
aboutPanel.add(buttons, "South");
f.setContentPane(aboutPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
public void exit() {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
Preferences biosimrc = Preferences.userRoot();
for (int i = 0; i < numberRecentProj; i++) {
if (atacs) {
biosimrc.put("atacs.recent.project." + i, recentProjects[i].getText());
biosimrc.put("atacs.recent.project.path." + i, recentProjectPaths[i]);
}
else if (lema) {
biosimrc.put("lema.recent.project." + i, recentProjects[i].getText());
biosimrc.put("lema.recent.project.path." + i, recentProjectPaths[i]);
}
else {
biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText());
biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]);
}
}
System.exit(1);
}
/**
* This method performs different functions depending on what menu items are
* selected.
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == viewerCheck) {
externView = viewerCheck.isSelected();
viewerLabel.setEnabled(viewerCheck.isSelected());
viewerField.setEnabled(viewerCheck.isSelected());
}
if (e.getSource() == viewCircuit) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewGcm();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLhpn();
}
}
else if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).viewLhpn();
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Verification) {
((Verification) array[0]).viewCircuit();
}
else if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewCircuit();
}
}
}
else if (e.getSource() == viewLog) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
if (new File(root + separator + "atacs.log").exists()) {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(frame(), "No log exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame(), "Unable to view log.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof Verification) {
((Verification) comp).viewLog();
}
else if (comp instanceof JPanel) {
Component[] array = ((JPanel) comp).getComponents();
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).viewLog();
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Learn) {
((Learn) component).viewLog();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLog();
}
}
}
else if (e.getSource() == viewCoverage) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
JOptionPane.showMessageDialog(frame(), "No Coverage report exists.", "Error",
JOptionPane.ERROR_MESSAGE);
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewCoverage();
}
}
}
else if (e.getSource() == viewVHDL) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
String vhdFile = tree.getFile();
if (new File(vhdFile).exists()) {
File vhdlAmsFile = new File(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(this.frame(), scrolls, "VHDL-AMS Model",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"VHDL-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(this.frame(), "Unable to view VHDL-AMS model.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewVHDL();
}
}
}
else if (e.getSource() == viewVerilog) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
String vamsFileName = tree.getFile();
if (new File(vamsFileName).exists()) {
File vamsFile = new File(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(this.frame(), scrolls, "Verilog-AMS Model",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"Verilog-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(this.frame(), "Unable to view Verilog-AMS model.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewVerilog();
}
}
}
else if (e.getSource() == viewLHPN) {
Component comp = tab.getSelectedComponent();
if (treeSelected) {
try {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "File cannot be read", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (InterruptedException e2) {
e2.printStackTrace();
}
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof LearnLHPN) {
((LearnLHPN) component).viewLhpn();
}
}
}
// else if (e.getSource() == saveParam) {
// Component comp = tab.getSelectedComponent();
// if (comp instanceof JTabbedPane) {
// Component component = ((JTabbedPane) comp).getSelectedComponent();
// if (component instanceof Learn) {
// ((Learn) component).save();
// else if (component instanceof LearnLHPN) {
// ((LearnLHPN) component).save();
// else {
// ((Reb2Sac) ((JTabbedPane) comp).getComponentAt(0)).save();
else if (e.getSource() == saveModel) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
for (Component component : ((JTabbedPane) comp).getComponents()) {
if (component instanceof Learn) {
((Learn) component).saveGcm();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).saveLhpn();
}
}
}
}
else if (e.getSource() == saveSbml) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("SBML");
}
else if (e.getSource() == saveTemp) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("template");
}
else if (e.getSource() == saveAsGcm) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("GCM");
}
else if (e.getSource() == saveGcmAsLhpn) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("LHPN");
}
else if (e.getSource() == saveAsLhpn) {
Component comp = tab.getSelectedComponent();
((LHPNEditor) comp).save();
}
else if (e.getSource() == saveAsGraph) {
Component comp = tab.getSelectedComponent();
((Graph) comp).save();
}
else if (e.getSource() == saveAsSbml) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("Save as SBML");
}
else if (e.getSource() == saveAsTemplate) {
Component comp = tab.getSelectedComponent();
((GCM2SBMLEditor) comp).save("Save as SBML template");
}
else if (e.getSource() == close && tab.getSelectedComponent() != null) {
Component comp = tab.getSelectedComponent();
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(),
point.x, point.y, 0, false), tab.getSelectedIndex());
}
else if (e.getSource() == closeAll) {
while (tab.getSelectedComponent() != null) {
int index = tab.getSelectedIndex();
Component comp = tab.getComponent(index);
Point point = comp.getLocation();
tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(),
e.getModifiers(), point.x, point.y, 0, false), index);
}
}
else if (e.getSource() == viewRules) {
Component comp = tab.getSelectedComponent();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).viewRules();
}
else if (e.getSource() == viewTrace) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Verification) {
((Verification) comp).viewTrace();
}
else if (comp instanceof Synthesis) {
((Synthesis) comp).viewTrace();
}
}
else if (e.getSource() == exportCsv) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(5);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(5);
}
}
else if (e.getSource() == exportDat) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(6);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export();
}
}
else if (e.getSource() == exportEps) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(3);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(3);
}
}
else if (e.getSource() == exportJpg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(0);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(0);
}
}
else if (e.getSource() == exportPdf) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(2);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(2);
}
}
else if (e.getSource() == exportPng) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(1);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(1);
}
}
else if (e.getSource() == exportSvg) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(4);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(4);
}
}
else if (e.getSource() == exportTsd) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export(7);
}
else if (comp instanceof JTabbedPane) {
((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(7);
}
}
else if (e.getSource() == about) {
about();
}
else if (e.getSource() == manual) {
try {
String directory = "";
String theFile = "";
if (!async) {
theFile = "iBioSim.html";
}
else if (atacs) {
theFile = "ATACS.html";
}
else {
theFile = "LEMA.html";
}
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
directory = ENVVAR + "/docs/";
command = "open ";
}
else {
directory = ENVVAR + "\\docs\\";
command = "cmd /c start ";
}
File work = new File(directory);
log.addText("Executing:\n" + command + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec(command + theFile, null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the exit menu item is selected
else if (e.getSource() == exit) {
exit();
}
// if the open popup menu is selected on a sim directory
else if (e.getActionCommand().equals("openSim")) {
openSim();
Translator t1 = new Translator();
t1.BuildTemplate(tree.getFile());
}
else if (e.getActionCommand().equals("openLearn")) {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
else if (e.getActionCommand().equals("openSynth")) {
openSynth();
}
else if (e.getActionCommand().equals("openVerification")) {
openVerify();
}
else if (e.getActionCommand().equals("convertToSBML")) {
new Translator().BuildTemplate(tree.getFile());
refreshTree();
}
// if the create simulation popup menu is selected on a dot file
else if (e.getActionCommand().equals("createSim")) {
try {
simulate(true);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"You must select a valid gcm file for simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the simulate popup menu is selected on an sbml file
else if (e.getActionCommand().equals("simulate")) {
try {
simulate(false);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame,
"You must select a valid sbml file for simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the synthesis popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createSynthesis")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:",
"Synthesis View ID", JOptionPane.PLAIN_MESSAGE);
if (synthName != null && !synthName.trim().equals("")) {
synthName = synthName.trim();
try {
if (overwrite(root + separator + synthName, synthName)) {
new File(root + separator + synthName).mkdir();
// new FileWriter(new File(root + separator +
// synthName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + synthName.trim() + separator
+ synthName.trim() + ".syn"));
out
.write(("synthesis.file=" + circuitFileNoPath + "\n")
.getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to save parameter file!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
}
try {
FileInputStream in = new FileInputStream(new File(root + separator
+ circuitFileNoPath));
FileOutputStream out = new FileOutputStream(new File(root
+ separator + synthName.trim() + separator
+ circuitFileNoPath));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to copy circuit file!", "Error Saving File",
JOptionPane.ERROR_MESSAGE);
}
refreshTree();
String work = root + separator + synthName;
String circuitFile = root + separator + synthName.trim() + separator
+ circuitFileNoPath;
JPanel synthPane = new JPanel();
Synthesis synth = new Synthesis(work, circuitFile, log, this);
// synth.addMouseListener(this);
synthPane.add(synth);
/*
* JLabel noData = new JLabel("No data available");
* Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn",
* noData);
* lrnTab.getComponentAt(lrnTab.getComponents
* ().length - 1).setName("Learn"); JLabel noData1 =
* new JLabel("No data available"); font =
* noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt
* (lrnTab.getComponents().length -
* 1).setName("TSD Graph");
*/
addTab(synthName, synthPane, "Synthesis");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to create Synthesis View directory.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the verify popup menu is selected on a vhdl or lhpn file
else if (e.getActionCommand().equals("createVerify")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:",
"Verification View ID", JOptionPane.PLAIN_MESSAGE);
if (verName != null && !verName.trim().equals("")) {
verName = verName.trim();
// try {
if (overwrite(root + separator + verName, verName)) {
new File(root + separator + verName).mkdir();
// new FileWriter(new File(root + separator +
// synthName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String circuitFileNoPath = getFilename[getFilename.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ verName.trim() + separator + verName.trim() + ".ver"));
out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
/*
* try { FileInputStream in = new FileInputStream(new
* File(root + separator + circuitFileNoPath));
* FileOutputStream out = new FileOutputStream(new
* File(root + separator + verName.trim() + separator +
* circuitFileNoPath)); int read = in.read(); while
* (read != -1) { out.write(read); read = in.read(); }
* in.close(); out.close(); } catch (Exception e1) {
* JOptionPane.showMessageDialog(frame, "Unable to copy
* circuit file!", "Error Saving File",
* JOptionPane.ERROR_MESSAGE); }
*/
refreshTree();
// String work = root + separator + verName;
// log.addText(circuitFile);
// JTabbedPane verTab = new JTabbedPane();
// JPanel verPane = new JPanel();
Verification verify = new Verification(root + separator + verName, verName,
circuitFileNoPath, log, this, lema, atacs);
// verify.addMouseListener(this);
verify.save();
// verPane.add(verify);
// JPanel abstPane = new JPanel();
// AbstPane abst = new AbstPane(root + separator +
// verName, verify,
// circuitFileNoPath, log, this, lema, atacs);
// abstPane.add(abst);
// verTab.addTab("verify", verPane);
// verTab.addTab("abstract", abstPane);
/*
* JLabel noData = new JLabel("No data available"); Font
* font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font); noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn",
* noData); lrnTab.getComponentAt(lrnTab.getComponents
* ().length - 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font =
* noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("TSD Graph",
* noData1); lrnTab.getComponentAt
* (lrnTab.getComponents().length -
* 1).setName("TSD Graph");
*/
addTab(verName, verify, "Verification");
}
// catch (Exception e1) {
// JOptionPane.showMessageDialog(frame,
// "Unable to create Verification View directory.", "Error",
// JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the delete popup menu is selected
else if (e.getActionCommand().contains("delete") || e.getSource() == delete) {
if (!tree.getFile().equals(root)) {
if (new File(tree.getFile()).isDirectory()) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.remove(i);
}
}
File dir = new File(tree.getFile());
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
refreshTree();
}
else {
String[] views = canDelete(tree.getFile().split(separator)[tree.getFile()
.split(separator).length - 1]);
if (views.length == 0) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.remove(i);
}
}
System.gc();
new File(tree.getFile()).delete();
refreshTree();
}
else {
String view = "";
for (int i = 0; i < views.length; i++) {
if (i == views.length - 1) {
view += views[i];
}
else {
view += views[i] + "\n";
}
}
String message = "Unable to delete the selected file."
+ "\nIt is linked to the following views:\n" + view
+ "\nDelete these views first.";
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(frame, scroll, "Unable To Delete File",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("createSBML")) {
try {
String theFile = "";
String filename = tree.getFile();
GCMFile gcm = new GCMFile(root);
gcm.load(filename);
GCMParser parser = new GCMParser(filename);
GeneticNetwork network = null;
try {
network = parser.buildNetwork();
}
catch (IllegalStateException e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
network.loadProperties(gcm);
if (filename.lastIndexOf('/') >= 0) {
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
if (new File(root + File.separator + theFile.replace(".gcm", "") + ".xml").exists()) {
String[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "")
+ ".xml already exists. Overwrite file?", "Save file",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
GeneticNetwork.setRoot(root + File.separator);
network.mergeSBML(root + File.separator + theFile.replace(".gcm", "")
+ ".xml");
log.addText("Saving GCM file as SBML file:\n" + root + File.separator
+ theFile.replace(".gcm", "") + ".xml\n");
refreshTree();
updateOpenSBML(theFile.replace(".gcm", "") + ".xml");
}
else {
// Do nothing
}
}
else {
GeneticNetwork.setRoot(root + File.separator);
network.mergeSBML(root + File.separator + theFile.replace(".gcm", "") + ".xml");
log.addText("Saving GCM file as SBML file:\n" + root + File.separator
+ theFile.replace(".gcm", "") + ".xml\n");
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("createLHPN")) {
try {
String theFile = "";
String filename = tree.getFile();
GCMFile gcm = new GCMFile(root);
gcm.load(filename);
if (filename.lastIndexOf('/') >= 0) {
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
if (new File(root + File.separator + theFile.replace(".gcm", "") + ".lpn").exists()) {
String[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, theFile.replace(".gcm", "")
+ ".lpn already exists. Overwrite file?", "Save file",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
gcm.createLogicalModel(root + File.separator + theFile.replace(".gcm", "")
+ ".lpn", log, this, theFile.replace(".gcm", "") + ".lpn");
}
else {
// Do nothing
}
}
else {
gcm.createLogicalModel(root + File.separator + theFile.replace(".gcm", "")
+ ".lpn", log, this, theFile.replace(".gcm", "") + ".lpn");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create LHPN file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the edit popup menu is selected on a dot file
else if (e.getActionCommand().equals("dotEditor")) {
try {
String directory = "";
String theFile = "";
String filename = tree.getFile();
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
File work = new File(directory);
GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this,
log, false, null, null, null);
// gcm.addMouseListener(this);
addTab(theFile, gcm, "GCM Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the edit popup menu is selected on an sbml file
else if (e.getActionCommand().equals("sbmlEditor")) {
try {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new SBML_Editor(tree.getFile(), null, log, this, null, null),
"SBML Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the graph popup menu is selected on an sbml file
else if (e.getActionCommand().equals("graph")) {
try {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
dummy.setSelected(false);
JList empty = new JList();
run.createProperties(0, "Print Interval", 1, 1, 1, 1, tree.getFile()
.substring(
0,
tree.getFile().length()
- (tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1].length())), 314159, 1,
new String[0], new String[0], "tsd.printer", "amount", tree.getFile()
.split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1,
15, dummy, "", dummy, null, empty, empty, empty);
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4
&& out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out
+ ".dot " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot "
+ theFile, null, work);
String error = "";
String output = "";
InputStream reb = graph.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = graph.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
graph.waitFor();
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + out + ".dot\n");
exec.exec("open " + out + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + out + ".dot\n");
exec.exec("dotty " + out + ".dot", null, work);
}
}
String remove;
if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) {
remove = tree.getFile().substring(0, tree.getFile().length() - 4)
+ "properties";
}
else {
remove = tree.getFile().substring(0, tree.getFile().length() - 4)
+ ".properties";
}
System.gc();
new File(remove).delete();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the browse popup menu is selected on an sbml file
else if (e.getActionCommand().equals("browse")) {
try {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
Run run = new Run(null);
JCheckBox dummy = new JCheckBox();
JList empty = new JList();
dummy.setSelected(false);
run.createProperties(0, "Print Interval", 1, 1, 1, 1, tree.getFile()
.substring(
0,
tree.getFile().length()
- (tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1].length())), 314159, 1,
new String[0], new String[0], "tsd.printer", "amount", tree.getFile()
.split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1,
15, dummy, "", dummy, null, empty, empty, empty);
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
String out = theFile;
if (out.length() > 4
&& out.substring(out.length() - 5, out.length()).equals(".sbml")) {
out = out.substring(0, out.length() - 5);
}
else if (out.length() > 3
&& out.substring(out.length() - 4, out.length()).equals(".xml")) {
out = out.substring(0, out.length() - 4);
}
log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out
+ ".xhtml " + tree.getFile() + "\n");
Runtime exec = Runtime.getRuntime();
Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out
+ ".xhtml " + theFile, null, work);
String error = "";
String output = "";
InputStream reb = browse.getErrorStream();
int read = reb.read();
while (read != -1) {
error += (char) read;
read = reb.read();
}
reb.close();
reb = browse.getInputStream();
read = reb.read();
while (read != -1) {
output += (char) read;
read = reb.read();
}
reb.close();
if (!output.equals("")) {
log.addText("Output:\n" + output + "\n");
}
if (!error.equals("")) {
log.addText("Errors:\n" + error + "\n");
}
browse.waitFor();
String command = "";
if (error.equals("")) {
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open ";
}
else {
command = "cmd /c start ";
}
log.addText("Executing:\n" + command + directory + out + ".xhtml\n");
exec.exec(command + out + ".xhtml", null, work);
}
String remove;
if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) {
remove = tree.getFile().substring(0, tree.getFile().length() - 4)
+ "properties";
}
else {
remove = tree.getFile().substring(0, tree.getFile().length() - 4)
+ ".properties";
}
System.gc();
new File(remove).delete();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the graph dot popup menu is selected
else if (e.getActionCommand().equals("graphDot")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
if (System.getProperty("os.name").contentEquals("Linux")) {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
log.addText("Executing:\nopen " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("cp " + theFile + " " + theFile + ".dot", null, work);
exec = Runtime.getRuntime();
exec.exec("open " + theFile + ".dot", null, work);
}
else {
log.addText("Executing:\ndotty " + directory + theFile + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec("dotty " + theFile, null, work);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// if the save button is pressed on the Tool Bar
else if (e.getActionCommand().equals("save")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
((LHPNEditor) comp).save();
}
else if (comp instanceof GCM2SBMLEditor) {
((GCM2SBMLEditor) comp).save("Save GCM");
}
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(false, "", true);
}
else if (comp instanceof Graph) {
((Graph) comp).save();
}
else if (comp instanceof Verification) {
((Verification) comp).save();
}
else if (comp instanceof JTabbedPane) {
for (Component component : ((JTabbedPane) comp).getComponents()) {
int index = ((JTabbedPane) comp).getSelectedIndex();
if (component instanceof Graph) {
((Graph) component).save();
}
else if (component instanceof Learn) {
((Learn) component).save();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
}
else if (component instanceof DataManager) {
((DataManager) component).saveChanges(((JTabbedPane) comp)
.getTitleAt(index));
}
else if (component instanceof SBML_Editor) {
((SBML_Editor) component).save(false, "", true);
}
else if (component instanceof GCM2SBMLEditor) {
((GCM2SBMLEditor) component).saveParams(false, "");
}
else if (component instanceof Reb2Sac) {
((Reb2Sac) component).save();
}
}
}
if (comp instanceof JPanel) {
if (comp.getName().equals("Synthesis")) {
// ((Synthesis) tab.getSelectedComponent()).save();
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).save();
}
}
else if (comp instanceof JScrollPane) {
String fileName = tab.getTitleAt(tab.getSelectedIndex());
try {
File output = new File(root + separator + fileName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + fileName);
this.updateAsyncViews(fileName);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + fileName, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the save as button is pressed on the Tool Bar
else if (e.getActionCommand().equals("saveas")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof LHPNEditor) {
String newName = JOptionPane.showInputDialog(frame(), "Enter LHPN name:",
"LHPN Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".lpn")) {
newName = newName + ".lpn";
}
((LHPNEditor) comp).saveAs(newName);
tab.setTitleAt(tab.getSelectedIndex(), newName);
}
else if (comp instanceof GCM2SBMLEditor) {
String newName = JOptionPane.showInputDialog(frame(), "Enter GCM name:",
"GCM Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (newName.contains(".gcm")) {
newName = newName.replace(".gcm", "");
}
((GCM2SBMLEditor) comp).saveAs(newName);
}
else if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).saveAs();
}
else if (comp instanceof Graph) {
((Graph) comp).saveAs();
}
else if (comp instanceof Verification) {
((Verification) comp).saveAs();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).saveAs();
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Synthesis")) {
Component[] array = ((JPanel) comp).getComponents();
((Synthesis) array[0]).saveAs();
}
}
else if (comp instanceof JScrollPane) {
String fileName = tab.getTitleAt(tab.getSelectedIndex());
String newName = "";
if (fileName.endsWith(".vhd")) {
newName = JOptionPane.showInputDialog(frame(), "Enter VHDL name:", "VHDL Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".vhd")) {
newName = newName + ".vhd";
}
}
else if (fileName.endsWith(".s")) {
newName = JOptionPane.showInputDialog(frame(), "Enter Assembly File Name:",
"Assembly File Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".s")) {
newName = newName + ".s";
}
}
else if (fileName.endsWith(".inst")) {
newName = JOptionPane.showInputDialog(frame(), "Enter Instruction File Name:",
"Instruction File Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".inst")) {
newName = newName + ".inst";
}
}
else if (fileName.endsWith(".g")) {
newName = JOptionPane.showInputDialog(frame(), "Enter Petri net name:",
"Petri net Name", JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".g")) {
newName = newName + ".g";
}
}
else if (fileName.endsWith(".csp")) {
newName = JOptionPane.showInputDialog(frame(), "Enter CSP name:", "CSP Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".csp")) {
newName = newName + ".csp";
}
}
else if (fileName.endsWith(".hse")) {
newName = JOptionPane.showInputDialog(frame(), "Enter HSE name:", "HSE Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".hse")) {
newName = newName + ".hse";
}
}
else if (fileName.endsWith(".unc")) {
newName = JOptionPane.showInputDialog(frame(), "Enter UNC name:", "UNC Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".unc")) {
newName = newName + ".unc";
}
}
else if (fileName.endsWith(".rsg")) {
newName = JOptionPane.showInputDialog(frame(), "Enter RSG name:", "RSG Name",
JOptionPane.PLAIN_MESSAGE);
if (newName == null) {
return;
}
if (!newName.endsWith(".rsg")) {
newName = newName + ".rsg";
}
}
try {
File output = new File(root + separator + newName);
output.createNewFile();
FileOutputStream outStream = new FileOutputStream(output);
Component[] array = ((JScrollPane) comp).getComponents();
array = ((JViewport) array[0]).getComponents();
if (array[0] instanceof JTextArea) {
String text = ((JTextArea) array[0]).getText();
char[] chars = text.toCharArray();
for (int j = 0; j < chars.length; j++) {
outStream.write((int) chars[j]);
}
}
outStream.close();
log.addText("Saving file:\n" + root + separator + newName);
File oldFile = new File(root + separator + fileName);
oldFile.delete();
tab.setTitleAt(tab.getSelectedIndex(), newName);
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Error saving file " + newName, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the run button is selected on the tool bar
else if (e.getActionCommand().equals("run")) {
Component comp = tab.getSelectedComponent();
// int index = tab.getSelectedIndex();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
int index = -1;
for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) {
if (((JTabbedPane) comp).getComponent(i) instanceof Reb2Sac) {
index = i;
break;
}
}
if (component instanceof Graph) {
if (index != -1) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton()
.doClick();
}
else {
((Graph) component).save();
((Graph) component).run();
}
}
else if (component instanceof Learn) {
((Learn) component).save();
new Thread((Learn) component).start();
}
else if (component instanceof LearnLHPN) {
((LearnLHPN) component).save();
((LearnLHPN) component).learn();
}
else if (component instanceof SBML_Editor) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof Reb2Sac) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof JPanel) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
else if (component instanceof JScrollPane) {
((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick();
}
}
else if (comp instanceof Verification) {
((Verification) comp).save();
new Thread((Verification) comp).start();
}
else if (comp instanceof Synthesis) {
((Synthesis) comp).save();
new Thread((Synthesis) comp).start();
}
}
else if (e.getActionCommand().equals("refresh")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).refresh();
}
}
else if (comp instanceof Graph) {
((Graph) comp).refresh();
}
}
else if (e.getActionCommand().equals("check")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof SBML_Editor) {
((SBML_Editor) comp).save(true, "", true);
((SBML_Editor) comp).check();
}
}
else if (e.getActionCommand().equals("export")) {
Component comp = tab.getSelectedComponent();
if (comp instanceof Graph) {
((Graph) comp).export();
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
if (component instanceof Graph) {
((Graph) component).export();
}
}
}
// if the new menu item is selected
else if (e.getSource() == newProj) {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.project_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.project_dir", ""));
}
String filename = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY,
"New", -1);
if (!filename.trim().equals("")) {
filename = filename.trim();
biosimrc.put("biosim.general.project_dir", filename);
File f = new File(filename);
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(filename);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
}
else {
return;
}
}
new File(filename).mkdir();
try {
if (lema) {
new FileWriter(new File(filename + separator + "LEMA.prj")).close();
}
else if (atacs) {
new FileWriter(new File(filename + separator + "ATACS.prj")).close();
}
else {
new FileWriter(new File(filename + separator + "BioSim.prj")).close();
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
root = filename;
refresh();
tab.removeAll();
addRecentProject(filename);
importDot.setEnabled(true);
importSbml.setEnabled(true);
importBioModel.setEnabled(true);
importVhdl.setEnabled(true);
importS.setEnabled(true);
importInst.setEnabled(true);
importLpn.setEnabled(true);
importG.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newCircuit.setEnabled(true);
newModel.setEnabled(true);
newVhdl.setEnabled(true);
newS.setEnabled(true);
newInst.setEnabled(true);
newLhpn.setEnabled(true);
newG.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
}
// if the open project menu item is selected
else if (e.getSource() == pref) {
preferences();
}
else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0])
|| (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2])
|| (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) {
int autosave = 0;
for (int i = 0; i < tab.getTabCount(); i++) {
int save = save(i, autosave);
if (save == 0) {
return;
}
else if (save == 2) {
autosave = 1;
}
else if (save == 3) {
autosave = 2;
}
}
Preferences biosimrc = Preferences.userRoot();
String projDir = "";
if (e.getSource() == openProj) {
File file;
if (biosimrc.get("biosim.general.project_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.project_dir", ""));
}
projDir = Buttons.browse(frame, file, null, JFileChooser.DIRECTORIES_ONLY, "Open",
-1);
if (projDir.endsWith(".prj")) {
biosimrc.put("biosim.general.project_dir", projDir);
String[] tempArray = projDir.split(separator);
projDir = "";
for (int i = 0; i < tempArray.length - 1; i++) {
projDir = projDir + tempArray[i] + separator;
}
}
}
else if (e.getSource() == recentProjects[0]) {
projDir = recentProjectPaths[0];
}
else if (e.getSource() == recentProjects[1]) {
projDir = recentProjectPaths[1];
}
else if (e.getSource() == recentProjects[2]) {
projDir = recentProjectPaths[2];
}
else if (e.getSource() == recentProjects[3]) {
projDir = recentProjectPaths[3];
}
else if (e.getSource() == recentProjects[4]) {
projDir = recentProjectPaths[4];
}
// log.addText(projDir);
if (!projDir.equals("")) {
biosimrc.put("biosim.general.project_dir", projDir);
if (new File(projDir).isDirectory()) {
boolean isProject = false;
for (String temp : new File(projDir).list()) {
if (temp.equals(".prj")) {
isProject = true;
}
if (lema && temp.equals("LEMA.prj")) {
isProject = true;
}
else if (atacs && temp.equals("ATACS.prj")) {
isProject = true;
}
else if (temp.equals("BioSim.prj")) {
isProject = true;
}
}
if (isProject) {
root = projDir;
refresh();
tab.removeAll();
addRecentProject(projDir);
importDot.setEnabled(true);
importSbml.setEnabled(true);
importBioModel.setEnabled(true);
importVhdl.setEnabled(true);
importS.setEnabled(true);
importInst.setEnabled(true);
importLpn.setEnabled(true);
importG.setEnabled(true);
importCsp.setEnabled(true);
importHse.setEnabled(true);
importUnc.setEnabled(true);
importRsg.setEnabled(true);
importSpice.setEnabled(true);
newCircuit.setEnabled(true);
newModel.setEnabled(true);
newVhdl.setEnabled(true);
newS.setEnabled(true);
newInst.setEnabled(true);
newLhpn.setEnabled(true);
newG.setEnabled(true);
newCsp.setEnabled(true);
newHse.setEnabled(true);
newUnc.setEnabled(true);
newRsg.setEnabled(true);
newSpice.setEnabled(true);
graph.setEnabled(true);
probGraph.setEnabled(true);
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must select a valid project.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new circuit model menu item is selected
else if (e.getSource() == newCircuit) {
if (root != null) {
try {
String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (simName.length() > 3) {
if (!simName.substring(simName.length() - 4).equals(".gcm")) {
simName += ".gcm";
}
}
else {
simName += ".gcm";
}
String modelID = "";
if (simName.length() > 3) {
if (simName.substring(simName.length() - 4).equals(".gcm")) {
modelID = simName.substring(0, simName.length() - 4);
}
else {
modelID = simName.substring(0, simName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + simName, simName)) {
File f = new File(root + separator + simName);
f.createNewFile();
new GCMFile(root).save(f.getAbsolutePath());
int i = getTab(f.getName());
if (i != -1) {
tab.remove(i);
}
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, f
.getName(), this, log, false, null, null, null);
// gcm.addMouseListener(this);
addTab(f.getName(), gcm, "GCM Editor");
refreshTree();
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new SBML model menu item is selected
else if (e.getSource() == newModel) {
if (root != null) {
try {
String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (simName.length() > 4) {
if (!simName.substring(simName.length() - 5).equals(".sbml")
&& !simName.substring(simName.length() - 4).equals(".xml")) {
simName += ".xml";
}
}
else {
simName += ".xml";
}
String modelID = "";
if (simName.length() > 4) {
if (simName.substring(simName.length() - 5).equals(".sbml")) {
modelID = simName.substring(0, simName.length() - 5);
}
else {
modelID = simName.substring(0, simName.length() - 4);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
if (overwrite(root + separator + simName, simName)) {
String f = new String(root + separator + simName);
SBMLDocument document = new SBMLDocument();
document.createModel();
// document.setLevel(2);
document.setLevelAndVersion(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
Compartment c = document.getModel().createCompartment();
c.setId("default");
c.setSize(1.0);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + simName);
SBML_Editor sbml = new SBML_Editor(f, null, log, this, null, null);
// sbml.addMouseListener(this);
addTab(f.split(separator)[f.split(separator).length - 1], sbml,
"SBML Editor");
refreshTree();
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new vhdl menu item is selected
else if (e.getSource() == newVhdl) {
if (root != null) {
try {
String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (vhdlName != null && !vhdlName.trim().equals("")) {
vhdlName = vhdlName.trim();
if (vhdlName.length() > 3) {
if (!vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) {
vhdlName += ".vhd";
}
}
else {
vhdlName += ".vhd";
}
String modelID = "";
if (vhdlName.length() > 3) {
if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) {
modelID = vhdlName.substring(0, vhdlName.length() - 4);
}
else {
modelID = vhdlName.substring(0, vhdlName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + vhdlName);
f.createNewFile();
refreshTree();
if (externView) {
String command = viewerField.getText() + " " + root + separator
+ vhdlName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(vhdlName, scroll, "VHDL Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new assembly menu item is selected
else if (e.getSource() == newS) {
if (root != null) {
try {
String SName = JOptionPane.showInputDialog(frame, "Enter Assembly File Name:",
"Assembly File Name", JOptionPane.PLAIN_MESSAGE);
if (SName != null && !SName.trim().equals("")) {
SName = SName.trim();
if (SName.length() > 1) {
if (!SName.substring(SName.length() - 2).equals(".s")) {
SName += ".s";
}
}
else {
SName += ".s";
}
String modelID = "";
if (SName.length() > 1) {
if (SName.substring(SName.length() - 2).equals(".s")) {
modelID = SName.substring(0, SName.length() - 2);
}
else {
modelID = SName.substring(0, SName.length() - 1);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A assembly file name can only contain letters, numbers, and underscores.",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + SName);
f.createNewFile();
refreshTree();
if (externView) {
String command = viewerField.getText() + " " + root + separator
+ SName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(SName, scroll, "Assembly File Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new assembly file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new instruction file menu item is selected
else if (e.getSource() == newInst) {
if (root != null) {
try {
String InstName = JOptionPane.showInputDialog(frame,
"Enter Instruction File Name:", "Instruction File Name",
JOptionPane.PLAIN_MESSAGE);
if (InstName != null && !InstName.trim().equals("")) {
InstName = InstName.trim();
if (InstName.length() > 4) {
if (!InstName.substring(InstName.length() - 5).equals(".inst")) {
InstName += ".inst";
}
}
else {
InstName += ".inst";
}
String modelID = "";
if (InstName.length() > 4) {
if (InstName.substring(InstName.length() - 5).equals(".inst")) {
modelID = InstName.substring(0, InstName.length() - 5);
}
else {
modelID = InstName.substring(0, InstName.length() - 4);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A instruction file name can only contain letters, numbers, and underscores.",
"Invalid File Name", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + InstName);
f.createNewFile();
refreshTree();
if (externView) {
String command = viewerField.getText() + " " + root + separator
+ InstName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(InstName, scroll, "Instruction File Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new instruction file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new petri net menu item is selected
else if (e.getSource() == newG) {
if (root != null) {
try {
String vhdlName = JOptionPane.showInputDialog(frame,
"Enter Petri Net Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE);
if (vhdlName != null && !vhdlName.trim().equals("")) {
vhdlName = vhdlName.trim();
if (vhdlName.length() > 1) {
if (!vhdlName.substring(vhdlName.length() - 2).equals(".g")) {
vhdlName += ".g";
}
}
else {
vhdlName += ".g";
}
String modelID = "";
if (vhdlName.length() > 1) {
if (vhdlName.substring(vhdlName.length() - 2).equals(".g")) {
modelID = vhdlName.substring(0, vhdlName.length() - 2);
}
else {
modelID = vhdlName.substring(0, vhdlName.length() - 1);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + vhdlName);
f.createNewFile();
refreshTree();
if (externView) {
String command = viewerField.getText() + " " + root + separator
+ vhdlName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(vhdlName, scroll, "Petri Net Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
// if the new lhpn menu item is selected
else if (e.getSource() == newLhpn) {
if (root != null) {
try {
String lhpnName = JOptionPane.showInputDialog(frame, "Enter LHPN Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (lhpnName != null && !lhpnName.trim().equals("")) {
lhpnName = lhpnName.trim();
if (lhpnName.length() > 3) {
if (!lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) {
lhpnName += ".lpn";
}
}
else {
lhpnName += ".lpn";
}
String modelID = "";
if (lhpnName.length() > 3) {
if (lhpnName.substring(lhpnName.length() - 4).equals(".lpn")) {
modelID = lhpnName.substring(0, lhpnName.length() - 4);
}
else {
modelID = lhpnName.substring(0, lhpnName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
// if (overwrite(root + separator + lhpnName,
// lhpnName)) {
// File f = new File(root + separator + lhpnName);
// f.delete();
// f.createNewFile();
// new LHPNFile(log).save(f.getAbsolutePath());
// int i = getTab(f.getName());
// if (i != -1) {
// tab.remove(i);
// addTab(f.getName(), new LHPNEditor(root +
// separator, f.getName(),
// null, this, log), "LHPN Editor");
// refreshTree();
if (overwrite(root + separator + lhpnName, lhpnName)) {
File f = new File(root + separator + lhpnName);
f.createNewFile();
new LHPNFile(log).save(f.getAbsolutePath());
int i = getTab(f.getName());
if (i != -1) {
tab.remove(i);
}
LHPNEditor lhpn = new LHPNEditor(root + separator, f.getName(),
null, this, log);
// lhpn.addMouseListener(this);
addTab(f.getName(), lhpn, "LHPN Editor");
refreshTree();
}
// File f = new File(root + separator + lhpnName);
// f.createNewFile();
// String[] command = { "emacs", f.getName() };
// Runtime.getRuntime().exec(command);
// refreshTree();
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new csp menu item is selected
else if (e.getSource() == newCsp) {
if (root != null) {
try {
String cspName = JOptionPane.showInputDialog(frame, "Enter CSP Model ID:",
"Model ID", JOptionPane.PLAIN_MESSAGE);
if (cspName != null && !cspName.trim().equals("")) {
cspName = cspName.trim();
if (cspName.length() > 3) {
if (!cspName.substring(cspName.length() - 4).equals(".csp")) {
cspName += ".csp";
}
}
else {
cspName += ".csp";
}
String modelID = "";
if (cspName.length() > 3) {
if (cspName.substring(cspName.length() - 4).equals(".csp")) {
modelID = cspName.substring(0, cspName.length() - 4);
}
else {
modelID = cspName.substring(0, cspName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + cspName);
f.createNewFile();
refreshTree();
if (externView) {
String command = viewerField.getText() + " " + root + separator
+ cspName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(cspName, scroll, "CSP Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new hse menu item is selected
else if (e.getSource() == newHse) {
if (root != null) {
try {
String hseName = JOptionPane.showInputDialog(frame,
"Enter Handshaking Expansion Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (hseName != null && !hseName.trim().equals("")) {
hseName = hseName.trim();
if (hseName.length() > 3) {
if (!hseName.substring(hseName.length() - 4).equals(".hse")) {
hseName += ".hse";
}
}
else {
hseName += ".hse";
}
String modelID = "";
if (hseName.length() > 3) {
if (hseName.substring(hseName.length() - 4).equals(".hse")) {
modelID = hseName.substring(0, hseName.length() - 4);
}
else {
modelID = hseName.substring(0, hseName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + hseName);
f.createNewFile();
refreshTree();
if (externView) {
String command = viewerField.getText() + " " + root + separator
+ hseName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(hseName, scroll, "HSE Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new unc menu item is selected
else if (e.getSource() == newUnc) {
if (root != null) {
try {
String uncName = JOptionPane.showInputDialog(frame,
"Enter Extended Burst Mode Machine ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (uncName != null && !uncName.trim().equals("")) {
uncName = uncName.trim();
if (uncName.length() > 3) {
if (!uncName.substring(uncName.length() - 4).equals(".unc")) {
uncName += ".unc";
}
}
else {
uncName += ".unc";
}
String modelID = "";
if (uncName.length() > 3) {
if (uncName.substring(uncName.length() - 4).equals(".unc")) {
modelID = uncName.substring(0, uncName.length() - 4);
}
else {
modelID = uncName.substring(0, uncName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + uncName);
f.createNewFile();
refreshTree();
if (externView) {
String command = viewerField.getText() + " " + root + separator
+ uncName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(uncName, scroll, "UNC Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new rsg menu item is selected
else if (e.getSource() == newRsg) {
if (root != null) {
try {
String rsgName = JOptionPane.showInputDialog(frame,
"Enter Reduced State Graph Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (rsgName != null && !rsgName.trim().equals("")) {
rsgName = rsgName.trim();
if (rsgName.length() > 3) {
if (!rsgName.substring(rsgName.length() - 4).equals(".rsg")) {
rsgName += ".rsg";
}
}
else {
rsgName += ".rsg";
}
String modelID = "";
if (rsgName.length() > 3) {
if (rsgName.substring(rsgName.length() - 4).equals(".rsg")) {
modelID = rsgName.substring(0, rsgName.length() - 4);
}
else {
modelID = rsgName.substring(0, rsgName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + rsgName);
f.createNewFile();
refreshTree();
if (externView) {
String command = viewerField.getText() + " " + root + separator
+ rsgName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(rsgName, scroll, "RSG Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the new rsg menu item is selected
else if (e.getSource() == newSpice) {
if (root != null) {
try {
String spiceName = JOptionPane.showInputDialog(frame,
"Enter Spice Circuit ID:", "Circuit ID", JOptionPane.PLAIN_MESSAGE);
if (spiceName != null && !spiceName.trim().equals("")) {
spiceName = spiceName.trim();
if (spiceName.length() > 3) {
if (!spiceName.substring(spiceName.length() - 4).equals(".cir")) {
spiceName += ".cir";
}
}
else {
spiceName += ".cir";
}
String modelID = "";
if (spiceName.length() > 3) {
if (spiceName.substring(spiceName.length() - 4).equals(".cir")) {
modelID = spiceName.substring(0, spiceName.length() - 4);
}
else {
modelID = spiceName.substring(0, spiceName.length() - 3);
}
}
if (!(IDpat.matcher(modelID).matches())) {
JOptionPane
.showMessageDialog(
frame,
"A model ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
}
else {
File f = new File(root + separator + spiceName);
f.createNewFile();
refreshTree();
if (externView) {
String command = viewerField.getText() + " " + root + separator
+ spiceName;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
JTextArea text = new JTextArea("");
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(spiceName, scroll, "Spice Editor");
}
}
}
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import sbml menu item is selected
else if (e.getSource() == importSbml) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null,
JFileChooser.FILES_AND_DIRECTORIES, "Import SBML", -1);
if (!filename.trim().equals("")) {
biosimrc.put("biosim.general.import_dir", filename.trim());
if (new File(filename.trim()).isDirectory()) {
JTextArea messageArea = new JTextArea();
messageArea.append("Imported SBML files contain the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n");
boolean display = false;
for (String s : new File(filename.trim()).list()) {
if (s.endsWith(".xml") || s.endsWith(".sbml")) {
try {
SBMLDocument document = readSBML(filename.trim() + separator
+ s);
if (overwrite(root + separator + s, s)) {
long numErrors = document.checkConsistency();
if (numErrors > 0) {
display = true;
messageArea
.append("
messageArea.append(s);
messageArea
.append("\n
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
}
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + s);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import files.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
refreshTree();
if (display) {
final JFrame f = new JFrame("SBML Errors and Warnings");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
}
else {
String[] file = filename.trim().split(separator);
try {
SBMLDocument document = readSBML(filename.trim());
if (overwrite(root + separator + file[file.length - 1],
file[file.length - 1])) {
long numErrors = document.checkConsistency();
if (numErrors > 0) {
final JFrame f = new JFrame("SBML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea
.append("Imported SBML file contains the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n");
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
SBMLWriter writer = new SBMLWriter();
writer
.writeSBML(document, root + separator
+ file[file.length - 1]);
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importBioModel) {
if (root != null) {
final BioModelsWSClient client = new BioModelsWSClient();
if (BioModelIds == null) {
try {
BioModelIds = client.getAllCuratedModelsId();
}
catch (BioModelsWSException e2) {
JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
JPanel BioModelsPanel = new JPanel(new BorderLayout());
final JList ListOfBioModels = new JList();
sort(BioModelIds);
ListOfBioModels.setListData(BioModelIds);
ListOfBioModels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JLabel TextBioModels = new JLabel("List of BioModels");
JScrollPane ScrollBioModels = new JScrollPane();
ScrollBioModels.setMinimumSize(new Dimension(520, 250));
ScrollBioModels.setPreferredSize(new Dimension(552, 250));
ScrollBioModels.setViewportView(ListOfBioModels);
JPanel GetButtons = new JPanel();
JButton GetNames = new JButton("Get Names");
JButton GetDescription = new JButton("Get Description");
JButton GetReference = new JButton("Get Reference");
GetNames.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < BioModelIds.length; i++) {
try {
BioModelIds[i] += " " + client.getModelNameById(BioModelIds[i]);
}
catch (BioModelsWSException e1) {
JOptionPane.showMessageDialog(frame,
"Error Contacting BioModels Database", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
ListOfBioModels.setListData(BioModelIds);
}
});
GetDescription.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String SelectedModel = ((String) ListOfBioModels.getSelectedValue())
.split(" ")[0];
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open http:
+ SelectedModel;
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
command = "open http:
+ SelectedModel;
}
else {
command = "cmd /c start http:
+ SelectedModel;
}
log.addText("Executing:\n" + command + "\n");
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open model description.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
GetReference.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String SelectedModel = ((String) ListOfBioModels.getSelectedValue())
.split(" ")[0];
try {
String Pub = (client.getSimpleModelById(SelectedModel))
.getPublicationId();
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
command = "gnome-open http:
+ Pub;
}
else if (System.getProperty("os.name").toLowerCase().startsWith(
"mac os")) {
command = "open http:
+ Pub;
}
else {
command = "cmd /c start http:
+ Pub;
}
log.addText("Executing:\n" + command + "\n");
Runtime exec = Runtime.getRuntime();
exec.exec(command);
}
catch (BioModelsWSException e2) {
JOptionPane.showMessageDialog(frame,
"Error Contacting BioModels Database", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open model description.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
GetButtons.add(GetNames);
GetButtons.add(GetDescription);
GetButtons.add(GetReference);
BioModelsPanel.add(TextBioModels, "North");
BioModelsPanel.add(ScrollBioModels, "Center");
BioModelsPanel.add(GetButtons, "South");
Object[] options = { "OK", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, BioModelsPanel,
"List of BioModels", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
/*
* String modelNumber = JOptionPane.showInputDialog(frame,
* "Enter BioModel Number:", "BioModel Number",
* JOptionPane.PLAIN_MESSAGE);
*/
// if (modelNumber != null && !modelNumber.equals("")) {
if (value == JOptionPane.YES_OPTION) {
String BMurl = "http:
String filename = ((String) ListOfBioModels.getSelectedValue()).split(" ")[0];
/*
* String filename = "BIOMD"; for (int i = 0; i < 10 -
* modelNumber.length(); i++) { filename += "0"; } filename
* += modelNumber + ".xml";
*/
filename += ".xml";
try {
URL url = new URL(BMurl + filename);
/*
* System.out.println("Opening connection to " + BMurl +
* filename + "...");
*/
URLConnection urlC = url.openConnection();
InputStream is = url.openStream();
/*
* System.out.println("Copying resource (type: " +
* urlC.getContentType() + ")..."); System.out.flush();
*/
if (overwrite(root + separator + filename, filename)) {
FileOutputStream fos = null;
fos = new FileOutputStream(root + separator + filename);
int oneChar, count = 0;
while ((oneChar = is.read()) != -1) {
fos.write(oneChar);
count++;
}
is.close();
fos.close();
// System.out.println(count + " byte(s) copied");
String[] file = filename.trim().split(separator);
SBMLDocument document = readSBML(root + separator + filename.trim());
long numErrors = document.checkConsistency();
if (numErrors > 0) {
final JFrame f = new JFrame("SBML Errors and Warnings");
JTextArea messageArea = new JTextArea();
messageArea
.append("Imported SBML file contains the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n");
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + file[file.length - 1]);
refreshTree();
}
}
catch (MalformedURLException e1) {
JOptionPane.showMessageDialog(frame, e1.toString(), "Error",
JOptionPane.ERROR_MESSAGE);
filename = "";
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, filename + " not found.", "Error",
JOptionPane.ERROR_MESSAGE);
filename = "";
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import dot menu item is selected
else if (e.getSource() == importDot) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null,
JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit", -1);
if (filename != null && !filename.trim().equals("")) {
biosimrc.put("biosim.general.import_dir", filename.trim());
}
if (new File(filename.trim()).isDirectory()) {
for (String s : new File(filename.trim()).list()) {
if (!(filename.trim() + separator + s).equals("")
&& (filename.trim() + separator + s).length() > 3
&& (filename.trim() + separator + s).substring(
(filename.trim() + separator + s).length() - 4,
(filename.trim() + separator + s).length()).equals(".gcm")) {
try {
// GCMParser parser =
new GCMParser((filename.trim() + separator + s));
if (overwrite(root + separator + s, s)) {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + s));
FileInputStream in = new FileInputStream(new File((filename
.trim()
+ separator + s)));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
if (filename.trim().length() > 3
&& !filename.trim().substring(filename.trim().length() - 4,
filename.trim().length()).equals(".gcm")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid gcm file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.trim().equals("")) {
String[] file = filename.trim().split(separator);
try {
// GCMParser parser =
new GCMParser(filename.trim());
if (overwrite(root + separator + file[file.length - 1],
file[file.length - 1])) {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename.trim()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import vhdl menu item is selected
else if (e.getSource() == importVhdl) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import VHDL Model", -1);
if (filename.length() > 3
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".vhd")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid vhdl file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importS) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Assembly File", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 2, filename.length()).equals(
".s")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid assembly file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importInst) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Instruction File", -1);
if (filename.length() > 4
&& !filename.substring(filename.length() - 5, filename.length()).equals(
".inst")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid instruction file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importLpn) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import LPN", -1);
if ((filename.length() > 1 && !filename.substring(filename.length() - 2,
filename.length()).equals(".g"))
&& (filename.length() > 3 && !filename.substring(filename.length() - 4,
filename.length()).equals(".lpn"))) {
JOptionPane.showMessageDialog(frame,
"You must select a valid lhpn file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
if (new File(filename).exists()) {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
// log.addText(filename);
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
if (filename.substring(filename.length() - 2, filename.length()).equals(
".g")) {
// log.addText(filename + file[file.length - 1]);
File work = new File(root);
String oldName = root + separator + file[file.length - 1];
// String newName = oldName.replace(".lpn",
// "_NEW.g");
Process atacs = Runtime.getRuntime().exec("atacs -lgsl " + oldName,
null, work);
atacs.waitFor();
String lpnName = oldName.replace(".g", ".lpn");
String newName = oldName.replace(".g", "_NEW.lpn");
atacs = Runtime.getRuntime().exec("atacs -llsl " + lpnName, null, work);
atacs.waitFor();
FileOutputStream out = new FileOutputStream(new File(lpnName));
FileInputStream in = new FileInputStream(new File(newName));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
new File(newName).delete();
}
refreshTree();
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == importG) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Net", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 2, filename.length()).equals(
".g")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid Petri net file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import csp menu item is selected
else if (e.getSource() == importCsp) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import CSP", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".csp")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid csp file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import hse menu item is selected
else if (e.getSource() == importHse) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import HSE", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".hse")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid handshaking expansion file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import unc menu item is selected
else if (e.getSource() == importUnc) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import UNC", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".unc")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid expanded burst mode machine file to import.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import rsg menu item is selected
else if (e.getSource() == importRsg) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import RSG", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".rsg")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid rsg file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the import spice menu item is selected
else if (e.getSource() == importSpice) {
if (root != null) {
File importFile;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.import_dir", "").equals("")) {
importFile = null;
}
else {
importFile = new File(biosimrc.get("biosim.general.import_dir", ""));
}
String filename = Buttons.browse(frame, importFile, null, JFileChooser.FILES_ONLY,
"Import Spice Circuit", -1);
if (filename.length() > 1
&& !filename.substring(filename.length() - 4, filename.length()).equals(
".cir")) {
JOptionPane.showMessageDialog(frame,
"You must select a valid spice circuit file to import.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else if (!filename.equals("")) {
biosimrc.put("biosim.general.import_dir", filename);
String[] file = filename.split(separator);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ file[file.length - 1]));
FileInputStream in = new FileInputStream(new File(filename));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
// if the Graph data menu item is clicked
else if (e.getSource() == graph) {
if (root != null) {
String graphName = JOptionPane.showInputDialog(frame,
"Enter A Name For The TSD Graph:", "TSD Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "Number of molecules", graphName.trim()
.substring(0, graphName.length() - 4), "tsd.printer", root, "Time",
this, null, log, graphName.trim(), true, false);
addTab(graphName.trim(), g, "TSD Graph");
g.save();
refreshTree();
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getSource() == probGraph) {
if (root != null) {
String graphName = JOptionPane.showInputDialog(frame,
"Enter A Name For The Probability Graph:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
if (overwrite(root + separator + graphName, graphName)) {
Graph g = new Graph(null, "Number of Molecules", graphName.trim()
.substring(0, graphName.length() - 4), "tsd.printer", root, "Time",
this, null, log, graphName.trim(), false, false);
addTab(graphName.trim(), g, "Probability Graph");
g.save();
refreshTree();
}
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("createLearn")) {
if (root != null) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:",
"Learn View ID", JOptionPane.PLAIN_MESSAGE);
if (lrnName != null && !lrnName.trim().equals("")) {
lrnName = lrnName.trim();
// try {
if (overwrite(root + separator + lrnName, lrnName)) {
new File(root + separator + lrnName).mkdir();
// new FileWriter(new File(root + separator +
// lrnName + separator
// ".lrn")).close();
String sbmlFile = tree.getFile();
String[] getFilename = sbmlFile.split(separator);
String sbmlFileNoPath = getFilename[getFilename.length - 1];
if (sbmlFileNoPath.endsWith(".vhd")) {
try {
File work = new File(root);
Runtime.getRuntime().exec("atacs -lvsl " + sbmlFileNoPath, null,
work);
sbmlFileNoPath = sbmlFileNoPath.replace(".vhd", ".lpn");
log.addText("atacs -lvsl " + sbmlFileNoPath + "\n");
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame,
"Unable to generate LHPN from VHDL file!",
"Error Generating File", JOptionPane.ERROR_MESSAGE);
}
}
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ lrnName.trim() + separator + lrnName.trim() + ".lrn"));
if (lema) {
out.write(("learn.file=" + sbmlFileNoPath + "\n").getBytes());
}
else {
out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes());
}
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
refreshTree();
JTabbedPane lrnTab = new JTabbedPane();
DataManager data = new DataManager(root + separator + lrnName, this, lema);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName(
"Data Manager");
if (lema) {
LearnLHPN learn = new LearnLHPN(root + separator + lrnName, log, this);
lrnTab.addTab("Learn", learn);
}
else {
Learn learn = new Learn(root + separator + lrnName, log, this);
lrnTab.addTab("Learn", learn);
}
// learn.addMouseListener(this);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph;
tsdGraph = new Graph(null, "Number of molecules", lrnName + " data",
"tsd.printer", root + separator + lrnName, "Time", this, null, log,
null, true, false);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName(
"TSD Graph");
/*
* JLabel noData = new JLabel("No data available"); Font
* font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font); noData.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("Learn",
* noData); lrnTab.getComponentAt(lrnTab.getComponents
* ().length - 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font =
* noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER); lrnTab.addTab("TSD Graph",
* noData1); lrnTab.getComponentAt
* (lrnTab.getComponents().length -
* 1).setName("TSD Graph");
*/
addTab(lrnName, lrnTab, null);
}
// catch (Exception e1) {
// JOptionPane.showMessageDialog(frame,
// "Unable to create Learn View directory.", "Error",
// JOptionPane.ERROR_MESSAGE);
}
}
else {
JOptionPane.showMessageDialog(frame, "You must open or create a project first.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("viewState")) {
if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
LHPNFile lhpnFile = new LHPNFile();
lhpnFile.load(tree.getFile());
log.addText("Creating state graph.");
StateGraph sg = new StateGraph(lhpnFile);
sg.outputStateGraph(tree.getFile().replace(".lpn", "_sg.dot"), false);
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
log.addText("Executing:\n" + command + root + separator
+ (file.replace(".lpn", "_sg.dot")) + "\n");
Runtime exec = Runtime.getRuntime();
File work = new File(root);
try {
exec.exec(command + (file.replace(".lpn", "_sg.dot")), null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("markov")) {
if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
LHPNFile lhpnFile = new LHPNFile();
lhpnFile.load(tree.getFile());
log.addText("Creating state graph.");
StateGraph sg = new StateGraph(lhpnFile);
log.addText("Performing Markov Chain analysis.");
sg.performMarkovianAnalysis(null);
sg.outputStateGraph(tree.getFile().replace(".lpn", "_sg.dot"), true);
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
String file = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
log.addText("Executing:\n" + command + root + separator
+ (file.replace(".lpn", "_sg.dot")) + "\n");
Runtime exec = Runtime.getRuntime();
File work = new File(root);
try {
exec.exec(command + (file.replace(".lpn", "_sg.dot")), null, work);
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to view state graph.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("viewModel")) {
try {
if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String[] findTheFile = filename.split("\\.");
String theFile = findTheFile[0] + ".dot";
File dot = new File(root + separator + theFile);
dot.delete();
String cmd = "atacs -cPlgodpe " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process ATACS = exec.exec(cmd, null, work);
ATACS.waitFor();
log.addText("Executing:\n" + cmd);
if (dot.exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + separator + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
try {
String vhdFile = tree.getFile();
if (new File(vhdFile).exists()) {
File vhdlAmsFile = new File(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(this.frame(), scrolls, "VHDL-AMS Model",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"VHDL-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(this.frame(),
"Unable to view VHDL-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
/*
* String filename =
* tree.getFile().split(separator)[tree.getFile().split(
* separator).length - 1]; String cmd = "atacs -lvslllodpl "
* + filename; File work = new File(root); Runtime exec =
* Runtime.getRuntime(); Process view = exec.exec(cmd, null,
* work); log.addText("Executing:\n" + cmd); String[]
* findTheFile = filename.split("\\."); view.waitFor(); //
* String directory = ""; String theFile = findTheFile[0] +
* ".dot"; if (new File(root + separator +
* theFile).exists()) { String command = ""; if
* (System.getProperty("os.name").contentEquals("Linux")) {
* // directory = ENVVAR + "/docs/"; command =
* "gnome-open "; } else if
* (System.getProperty("os.name").toLowerCase
* ().startsWith("mac os")) { // directory = ENVVAR +
* "/docs/"; command = "open "; } else { // directory =
* ENVVAR + "\\docs\\"; command = "dotty start "; }
* log.addText(command + root + theFile + "\n");
* exec.exec(command + theFile, null, work); } else { File
* log = new File(root + 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(frame(), scrolls, "Log",
* JOptionPane.INFORMATION_MESSAGE); }
*/
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
try {
String vamsFileName = tree.getFile();
if (new File(vamsFileName).exists()) {
File vamsFile = new File(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(this.frame(), scrolls,
"Verilog-AMS Model", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this.frame(),
"Verilog-AMS model does not exist.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(this.frame(),
"Unable to view Verilog-AMS model.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lcslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lhslllodpl " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lxodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
String filename = tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1];
String cmd = "atacs -lsodps " + filename;
File work = new File(root);
Runtime exec = Runtime.getRuntime();
Process view = exec.exec(cmd, null, work);
log.addText("Executing:\n" + cmd);
view.waitFor();
String[] findTheFile = filename.split("\\.");
// String directory = "";
String theFile = findTheFile[0] + ".dot";
if (new File(root + separator + theFile).exists()) {
String command = "";
if (System.getProperty("os.name").contentEquals("Linux")) {
// directory = ENVVAR + "/docs/";
command = "gnome-open ";
}
else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
// directory = ENVVAR + "/docs/";
command = "open ";
}
else {
// directory = ENVVAR + "\\docs\\";
command = "dotty start ";
}
log.addText(command + root + theFile + "\n");
exec.exec(command + theFile, null, work);
}
else {
File log = new File(root + 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(frame(), scrolls, "Log",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "File cannot be read", "Error",
JOptionPane.ERROR_MESSAGE);
}
catch (InterruptedException e2) {
e2.printStackTrace();
}
}
else if (e.getActionCommand().equals("copy") || e.getSource() == copy) {
if (!tree.getFile().equals(root)) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String modelID = null;
String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy",
JOptionPane.PLAIN_MESSAGE);
if (copy != null) {
copy = copy.trim();
}
else {
return;
}
try {
if (!copy.equals("")) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".xml")) {
if (copy.length() > 4) {
if (!copy.substring(copy.length() - 5).equals(".sbml")
&& !copy.substring(copy.length() - 4).equals(".xml")) {
copy += ".xml";
}
}
else {
copy += ".xml";
}
if (copy.length() > 4) {
if (copy.substring(copy.length() - 5).equals(".sbml")) {
modelID = copy.substring(0, copy.length() - 5);
}
else {
modelID = copy.substring(0, copy.length() - 4);
}
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".gcm")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".gcm")) {
copy += ".gcm";
}
}
else {
copy += ".gcm";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".vhd")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".vhd")) {
copy += ".vhd";
}
}
else {
copy += ".vhd";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".s")) {
if (copy.length() > 1) {
if (!copy.substring(copy.length() - 2).equals(".s")) {
copy += ".s";
}
}
else {
copy += ".s";
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".inst")) {
if (copy.length() > 4) {
if (!copy.substring(copy.length() - 5).equals(".inst")) {
copy += ".inst";
}
}
else {
copy += ".inst";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".g")) {
if (copy.length() > 1) {
if (!copy.substring(copy.length() - 2).equals(".g")) {
copy += ".g";
}
}
else {
copy += ".g";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".lpn")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".lpn")) {
copy += ".lpn";
}
}
else {
copy += ".lpn";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".csp")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".csp")) {
copy += ".csp";
}
}
else {
copy += ".csp";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".hse")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".hse")) {
copy += ".hse";
}
}
else {
copy += ".hse";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".unc")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".unc")) {
copy += ".unc";
}
}
else {
copy += ".unc";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".rsg")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".rsg")) {
copy += ".rsg";
}
}
else {
copy += ".rsg";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".grf")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".grf")) {
copy += ".grf";
}
}
else {
copy += ".grf";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".prb")) {
if (copy.length() > 3) {
if (!copy.substring(copy.length() - 4).equals(".prb")) {
copy += ".prb";
}
}
else {
copy += ".prb";
}
}
}
if (copy
.equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to copy file."
+ "\nNew filename must be different than old filename.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (overwrite(root + separator + copy, copy)) {
if (modelID != null) {
SBMLDocument document = readSBML(tree.getFile());
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy);
}
else if ((tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".gcm")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".grf")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".vhd")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".csp")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".hse")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".lpn")
|| tree.getFile().substring(tree.getFile().length() - 4).equals(
".unc") || tree.getFile().substring(
tree.getFile().length() - 4).equals(".rsg"))
|| (tree.getFile().length() >= 2 && tree.getFile().substring(
tree.getFile().length() - 2).equals(".s"))
|| (tree.getFile().length() >= 5 && tree.getFile().substring(
tree.getFile().length() - 5).equals(".inst"))
|| (tree.getFile().length() >= 2 && tree.getFile().substring(
tree.getFile().length() - 2).equals(".g"))) {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ copy));
FileInputStream in = new FileInputStream(new File(tree.getFile()));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else {
boolean sim = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
}
if (sim) {
new File(root + separator + copy).mkdir();
// new FileWriter(new File(root + separator +
// copy +
// separator +
// ".sim")).close();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 4
&& ss.substring(ss.length() - 5).equals(".sbml")
|| ss.length() > 3
&& ss.substring(ss.length() - 4).equals(".xml")) {
SBMLDocument document = readSBML(tree.getFile() + separator
+ ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + copy
+ separator + ss);
}
else if (ss.length() > 10
&& ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root
+ separator + copy + separator + ss));
FileInputStream in = new FileInputStream(new File(tree
.getFile()
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd")
|| ss.substring(ss.length() - 4).equals(".dat")
|| ss.substring(ss.length() - 4).equals(".sad")
|| ss.substring(ss.length() - 4).equals(".pms") || ss
.substring(ss.length() - 4).equals(".sim"))
&& !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator
+ copy + separator + copy + ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator
+ copy + separator + copy + ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator
+ copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree
.getFile()
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
else {
new File(root + separator + copy).mkdir();
String[] s = new File(tree.getFile()).list();
for (String ss : s) {
if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".tsd") || ss
.substring(ss.length() - 4).equals(".lrn"))) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".lrn")) {
out = new FileOutputStream(new File(root + separator
+ copy + separator + copy + ".lrn"));
}
else {
out = new FileOutputStream(new File(root + separator
+ copy + separator + ss));
}
FileInputStream in = new FileInputStream(new File(tree
.getFile()
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
}
}
}
}
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("rename") || e.getSource() == rename) {
if (!tree.getFile().equals(root)) {
try {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) != 1) {
return;
}
break;
}
}
String modelID = null;
String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:",
"Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".xml")) {
if (rename.length() > 4) {
if (!rename.substring(rename.length() - 5).equals(".sbml")
&& !rename.substring(rename.length() - 4).equals(".xml")) {
rename += ".xml";
}
}
else {
rename += ".xml";
}
if (rename.length() > 4) {
if (rename.substring(rename.length() - 5).equals(".sbml")) {
modelID = rename.substring(0, rename.length() - 5);
}
else {
modelID = rename.substring(0, rename.length() - 4);
}
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".gcm")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".gcm")) {
rename += ".gcm";
}
}
else {
rename += ".gcm";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".vhd")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".vhd")) {
rename += ".vhd";
}
}
else {
rename += ".vhd";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".g")) {
if (rename.length() > 1) {
if (!rename.substring(rename.length() - 2).equals(".g")) {
rename += ".g";
}
}
else {
rename += ".g";
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(
".s")) {
if (rename.length() > 1) {
if (!rename.substring(rename.length() - 2).equals(".s")) {
rename += ".s";
}
}
else {
rename += ".s";
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5).equals(
".inst")) {
if (rename.length() > 4) {
if (!rename.substring(rename.length() - 5).equals(".inst")) {
rename += ".inst";
}
}
else {
rename += ".inst";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".lpn")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".lpn")) {
rename += ".lpn";
}
}
else {
rename += ".lpn";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".csp")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".csp")) {
rename += ".csp";
}
}
else {
rename += ".csp";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".hse")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".hse")) {
rename += ".hse";
}
}
else {
rename += ".hse";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".unc")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".unc")) {
rename += ".unc";
}
}
else {
rename += ".unc";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".rsg")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".rsg")) {
rename += ".rsg";
}
}
else {
rename += ".rsg";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".grf")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".grf")) {
rename += ".grf";
}
}
else {
rename += ".grf";
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(
".prb")) {
if (rename.length() > 3) {
if (!rename.substring(rename.length() - 4).equals(".prb")) {
rename += ".prb";
}
}
else {
rename += ".prb";
}
}
if (rename.equals(tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
JOptionPane.showMessageDialog(frame, "Unable to rename file."
+ "\nNew filename must be different than old filename.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (overwrite(root + separator + rename, rename)) {
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".sbml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".xml")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".gcm")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".lpn")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".vhd")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".csp")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".hse")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".unc")
|| tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4)
.equals(".rsg")) {
String oldName = tree.getFile().split(separator)[tree.getFile()
.split(separator).length - 1];
reassignViews(oldName, rename);
}
new File(tree.getFile()).renameTo(new File(root + separator + rename));
if (modelID != null) {
SBMLDocument document = readSBML(root + separator + rename);
document.getModel().setId(modelID);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + rename);
}
if (rename.length() >= 5
&& rename.substring(rename.length() - 5).equals(".sbml")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".xml")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".gcm")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".lpn")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".vhd")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".csp")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".hse")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".unc")
|| rename.length() >= 4
&& rename.substring(rename.length() - 4).equals(".rsg")) {
updateAsyncViews(rename);
}
if (new File(root + separator + rename).isDirectory()) {
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".sim").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".sim")
.renameTo(new File(root + separator + rename
+ separator + rename + ".sim"));
}
else if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".pms").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".pms")
.renameTo(new File(root + separator + rename
+ separator + rename + ".sim"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".lrn").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".lrn")
.renameTo(new File(root + separator + rename
+ separator + rename + ".lrn"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".ver").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".ver")
.renameTo(new File(root + separator + rename
+ separator + rename + ".ver"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".grf").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".grf")
.renameTo(new File(root + separator + rename
+ separator + rename + ".grf"));
}
if (new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".prb").exists()) {
new File(root
+ separator
+ rename
+ separator
+ tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1] + ".prb")
.renameTo(new File(root + separator + rename
+ separator + rename + ".prb"));
}
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
if (tree.getFile().length() > 4
&& tree.getFile()
.substring(tree.getFile().length() - 5).equals(
".sbml")
|| tree.getFile().length() > 3
&& tree.getFile()
.substring(tree.getFile().length() - 4).equals(
".xml")) {
((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID);
((SBML_Editor) tab.getComponentAt(i)).setFile(root
+ separator + rename);
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3
&& (tree.getFile().substring(
tree.getFile().length() - 4).equals(".grf") || tree
.getFile().substring(
tree.getFile().length() - 4).equals(
".prb"))) {
((Graph) tab.getComponentAt(i)).setGraphName(rename);
tab.setTitleAt(i, rename);
}
else if (tree.getFile().length() > 3
&& tree.getFile()
.substring(tree.getFile().length() - 4).equals(
".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename
.substring(0, rename.length() - 4));
}
else if (tree.getFile().length() > 3
&& tree.getFile()
.substring(tree.getFile().length() - 4).equals(
".lpn")) {
((LHPNEditor) tab.getComponentAt(i)).reload(rename
.substring(0, rename.length() - 4));
tab.setTitleAt(i, rename);
}
else if (tab.getComponentAt(i) instanceof JTabbedPane) {
JTabbedPane t = new JTabbedPane();
int selected = ((JTabbedPane) tab.getComponentAt(i))
.getSelectedIndex();
boolean analysis = false;
ArrayList<Component> comps = new ArrayList<Component>();
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i))
.getTabCount(); j++) {
Component c = ((JTabbedPane) tab.getComponentAt(i))
.getComponent(j);
comps.add(c);
}
for (Component c : comps) {
if (c instanceof Reb2Sac) {
((Reb2Sac) c).setSim(rename);
analysis = true;
}
else if (c instanceof SBML_Editor) {
String properties = root + separator + rename
+ separator + rename + ".sim";
new File(properties).renameTo(new File(properties
.replace(".sim", ".temp")));
boolean dirty = ((SBML_Editor) c).isDirty();
((SBML_Editor) c).setParamFileAndSimDir(properties,
root + separator + rename);
((SBML_Editor) c).save(false, "", true);
((SBML_Editor) c).updateSBML(i, 0);
((SBML_Editor) c).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp"))
.renameTo(new File(properties));
}
else if (c instanceof Graph) {
// c.addMouseListener(this);
Graph g = ((Graph) c);
g.setDirectory(root + separator + rename);
if (g.isTSDGraph()) {
g.setGraphName(rename + ".grf");
}
else {
g.setGraphName(rename + ".prb");
}
}
else if (c instanceof Learn) {
Learn l = ((Learn) c);
l.setDirectory(root + separator + rename);
}
else if (c instanceof DataManager) {
DataManager d = ((DataManager) c);
d.setDirectory(root + separator + rename);
}
if (analysis) {
if (c instanceof Reb2Sac) {
t.addTab("Simulation Options", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("Simulate");
}
else if (c instanceof SBML_Editor) {
t.addTab("Parameter Editor", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("SBML Editor");
}
else if (c instanceof GCM2SBMLEditor) {
t.addTab("Parameter Editor", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("GCM Editor");
}
else if (c instanceof Graph) {
if (((Graph) c).isTSDGraph()) {
t.addTab("TSD Graph", c);
t.getComponentAt(
t.getComponents().length - 1)
.setName("TSD Graph");
}
else {
t.addTab("Probability Graph", c);
t.getComponentAt(
t.getComponents().length - 1)
.setName("ProbGraph");
}
}
else {
t.addTab("Abstraction Options", c);
t.getComponentAt(t.getComponents().length - 1)
.setName("");
}
}
}
if (analysis) {
t.setSelectedIndex(selected);
tab.setComponentAt(i, t);
}
tab.setTitleAt(i, rename);
tab.getComponentAt(i).setName(rename);
}
else {
tab.setTitleAt(i, rename);
tab.getComponentAt(i).setName(rename);
}
}
}
refreshTree();
// updateAsyncViews(rename);
updateViewNames(tree.getFile(), rename);
}
}
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to rename selected file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else if (e.getActionCommand().equals("openGraph")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
.contains(".grf")) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Number of molecules", "title", "tsd.printer", root,
"Time", this, tree.getFile(), log, tree.getFile().split(
separator)[tree.getFile().split(separator).length - 1],
true, false), "TSD Graph");
}
else {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Percent", "title", "tsd.printer", root, "Time", this,
tree.getFile(), log, tree.getFile().split(separator)[tree
.getFile().split(separator).length - 1], false, false),
"Probability Graph");
}
}
}
}
public int getTab(String name) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(name)) {
return i;
}
}
return -1;
}
public void deleteDir(File dir) {
int count = 0;
do {
File[] list = dir.listFiles();
System.gc();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
deleteDir(list[i]);
}
else {
list[i].delete();
}
}
count++;
}
while (!dir.delete() && count != 100);
if (count == 100) {
JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* This method adds a new project to recent list
*/
public void addRecentProject(String projDir) {
// boolean newOne = true;
for (int i = 0; i < numberRecentProj; i++) {
if (recentProjectPaths[i].equals(projDir)) {
for (int j = 0; j <= i; j++) {
String save = recentProjectPaths[j];
recentProjects[j]
.setText(projDir.split(separator)[projDir.split(separator).length - 1]);
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[j]);
}
recentProjectPaths[j] = projDir;
projDir = save;
}
for (int j = i + 1; j < numberRecentProj; j++) {
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[j]);
}
}
return;
}
}
if (numberRecentProj < 5) {
numberRecentProj++;
}
for (int i = 0; i < numberRecentProj; i++) {
String save = recentProjectPaths[i];
recentProjects[i]
.setText(projDir.split(separator)[projDir.split(separator).length - 1]);
if (file.getItem(file.getItemCount() - 1) == exit) {
file.insert(recentProjects[i], file.getItemCount() - 3 - numberRecentProj);
}
else {
file.add(recentProjects[i]);
}
recentProjectPaths[i] = projDir;
projDir = save;
}
}
/**
* This method refreshes the menu.
*/
public void refresh() {
mainPanel.remove(tree);
tree = new FileTree(new File(root), this, lema, atacs);
mainPanel.add(tree, "West");
mainPanel.validate();
}
/**
* This method refreshes the tree.
*/
public void refreshTree() {
tree.fixTree();
mainPanel.validate();
updateGCM();
}
/**
* This method adds the given Component to a tab.
*/
public void addTab(String name, Component panel, String tabName) {
tab.addTab(name, panel);
// panel.addMouseListener(this);
if (tabName != null) {
tab.getComponentAt(tab.getTabCount() - 1).setName(tabName);
}
else {
tab.getComponentAt(tab.getTabCount() - 1).setName(name);
}
tab.setSelectedIndex(tab.getTabCount() - 1);
}
/**
* This method removes the given component from the tabs.
*/
public void removeTab(Component component) {
tab.remove(component);
}
public JTabbedPane getTab() {
return tab;
}
/**
* Prompts the user to save work that has been done.
*/
public int save(int index, int autosave) {
if (tab.getComponentAt(index).getName().contains(("GCM"))
|| tab.getComponentAt(index).getName().contains("LHPN")) {
if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) {
GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
editor.save("gcm");
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
editor.save("gcm");
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
editor.save("gcm");
return 2;
}
else {
return 3;
}
}
}
else if (tab.getComponentAt(index) instanceof LHPNEditor) {
LHPNEditor editor = (LHPNEditor) tab.getComponentAt(index);
if (editor.isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
editor.save();
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
editor.save();
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
editor.save();
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else if (tab.getComponentAt(index).getName().equals("SBML Editor")) {
if (tab.getComponentAt(index) instanceof SBML_Editor) {
if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
((SBML_Editor) tab.getComponentAt(index)).save(false, "", true);
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else if (tab.getComponentAt(index).getName().contains("Graph")) {
if (tab.getComponentAt(index) instanceof Graph) {
if (((Graph) tab.getComponentAt(index)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save changes to " + tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Graph) tab.getComponentAt(index)).save();
return 1;
}
else if (value == NO_OPTION) {
return 1;
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Graph) tab.getComponentAt(index)).save();
return 2;
}
else if (value == NO_TO_ALL_OPTION) {
return 3;
}
}
else if (autosave == 1) {
((Graph) tab.getComponentAt(index)).save();
return 2;
}
else {
return 3;
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
else {
if (tab.getComponentAt(index) instanceof JTabbedPane) {
for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() != null) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName()
.equals("Simulate")) {
if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save simulation option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("SBML Editor")) {
if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save(false, "", true);
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save(false, "", true);
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save(false, "", true);
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("GCM Editor")) {
if (((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).isDirty()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save parameter changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveParams(false, "");
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveParams(false, "");
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((GCM2SBMLEditor) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveParams(false, "");
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("Learn")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) {
if (((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for "
+ tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Learn) {
((Learn) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
}
}
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) {
if (((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save learn option changes for "
+ tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i))
.save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i))
.save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof LearnLHPN) {
((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).save();
}
}
}
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().equals("Data Manager")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) {
((DataManager) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).saveChanges(tab.getTitleAt(index));
}
}
else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i)
.getName().contains("Graph")) {
if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) {
if (((Graph) ((JTabbedPane) tab.getComponentAt(index))
.getComponent(i)).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save graph changes for "
+ tab.getTitleAt(index) + "?",
"Save Changes", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS,
OPTIONS[0]);
if (value == YES_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i));
g.save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i));
g.save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (((JTabbedPane) tab.getComponentAt(index))
.getComponent(i) instanceof Graph) {
Graph g = ((Graph) ((JTabbedPane) tab
.getComponentAt(index)).getComponent(i));
g.save();
}
}
}
}
}
}
}
}
else if (tab.getComponentAt(index) instanceof JPanel) {
if ((tab.getComponentAt(index)).getName().equals("Synthesis")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Synthesis) {
if (((Synthesis) array[0]).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save synthesis option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
if (array[0] instanceof Synthesis) {
((Synthesis) array[0]).save();
}
}
}
}
}
else if (tab.getComponentAt(index).getName().equals("Verification")) {
Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents();
if (array[0] instanceof Verification) {
if (((Verification) array[0]).hasChanged()) {
if (autosave == 0) {
int value = JOptionPane.showOptionDialog(frame,
"Do you want to save verification option changes for "
+ tab.getTitleAt(index) + "?", "Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, OPTIONS, OPTIONS[0]);
if (value == YES_OPTION) {
((Verification) array[0]).save();
}
else if (value == CANCEL_OPTION) {
return 0;
}
else if (value == YES_TO_ALL_OPTION) {
((Verification) array[0]).save();
autosave = 1;
}
else if (value == NO_TO_ALL_OPTION) {
autosave = 2;
}
}
else if (autosave == 1) {
((Verification) array[0]).save();
}
}
}
}
}
if (autosave == 0) {
return 1;
}
else if (autosave == 1) {
return 2;
}
else {
return 3;
}
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveGcm(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
FileOutputStream out = new FileOutputStream(new File(root + separator + filename));
FileInputStream in = new FileInputStream(new File(path));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Saves a circuit from a learn view to the project view
*/
public void saveLhpn(String filename, String path) {
try {
if (overwrite(root + separator + filename, filename)) {
BufferedWriter out = new BufferedWriter(new FileWriter(root + separator + filename));
BufferedReader in = new BufferedReader(new FileReader(path));
String str;
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
out = new BufferedWriter(new FileWriter(root + separator
+ filename.replace(".lpn", ".vhd")));
in = new BufferedReader(new FileReader(path.replace(".lpn", ".vhd")));
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
out = new BufferedWriter(new FileWriter(root + separator
+ filename.replace(".lpn", ".vams")));
in = new BufferedReader(new FileReader(path.replace(".lpn", ".vams")));
while ((str = in.readLine()) != null) {
out.write(str + "\n");
}
in.close();
out.close();
out = new BufferedWriter(new FileWriter(root + separator
+ filename.replace(".lpn", "_top.vams")));
String[] learnPath = path.split(separator);
String topVFile = path.replace(learnPath[learnPath.length - 1], "top.vams");
String[] cktPath = filename.split(separator);
in = new BufferedReader(new FileReader(topVFile));
while ((str = in.readLine()) != null) {
str = str.replace("module top", "module "
+ cktPath[cktPath.length - 1].replace(".lpn", "_top"));
out.write(str + "\n");
}
in.close();
out.close();
refreshTree();
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to save LHPN.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void updateMenu(boolean logEnabled, boolean othersEnabled) {
viewVHDL.setEnabled(othersEnabled);
viewVerilog.setEnabled(othersEnabled);
viewLHPN.setEnabled(othersEnabled);
viewCoverage.setEnabled(othersEnabled);
save.setEnabled(othersEnabled);
viewLog.setEnabled(logEnabled);
// Do saveas & save button too
}
/**
* Returns the frame.
*/
public JFrame frame() {
return frame;
}
public void mousePressed(MouseEvent e) {
// log.addText(e.getSource().toString());
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(),
e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
}
else {
if (e.isPopupTrigger() && tree.getFile() != null) {
frame.getGlassPane().setVisible(false);
popup.removeAll();
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("sbmlEditor");
JMenuItem graph = new JMenuItem("View Network");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem browse = new JMenuItem("View in Browser");
browse.addActionListener(this);
browse.addMouseListener(this);
browse.setActionCommand("browse");
JMenuItem simulate = new JMenuItem("Create Analysis View");
simulate.addActionListener(this);
simulate.addMouseListener(this);
simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(simulate);
popup.add(createLearn);
popup.addSeparator();
popup.add(graph);
popup.add(browse);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createSBML = new JMenuItem("Create SBML File");
createSBML.addActionListener(this);
createSBML.addMouseListener(this);
createSBML.setActionCommand("createSBML");
JMenuItem createLHPN = new JMenuItem("Create LHPN File");
createLHPN.addActionListener(this);
createLHPN.addMouseListener(this);
createLHPN.setActionCommand("createLHPN");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem graph = new JMenuItem("View Genetic Circuit");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graphDot");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.add(createSBML);
popup.add(createLHPN);
popup.addSeparator();
popup.add(graph);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (lema) {
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
// if (lema) {
// popup.add(createLearn);
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem convertToSBML = new JMenuItem("Convert To SBML");
convertToSBML.addActionListener(this);
convertToSBML.addMouseListener(this);
convertToSBML.setActionCommand("convertToSBML");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem viewStateGraph = new JMenuItem("View State Graph");
viewStateGraph.addActionListener(this);
viewStateGraph.addMouseListener(this);
viewStateGraph.setActionCommand("viewState");
JMenuItem markovAnalysis = new JMenuItem("Perform Markovian Analysis");
markovAnalysis.addActionListener(this);
markovAnalysis.addMouseListener(this);
markovAnalysis.setActionCommand("markov");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
if (atacs || lema) {
popup.add(createVerification);
popup.addSeparator();
}
popup.add(convertToSBML);
popup.add(viewModel);
popup.add(viewStateGraph);
popup.add(markovAnalysis);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) {
// JMenuItem createAnalysis = new
// JMenuItem("Create Analysis View");
// createAnalysis.addActionListener(this);
// createAnalysis.addMouseListener(this);
// createAnalysis.setActionCommand("createSim");
// JMenuItem createVerification = new
// JMenuItem("Create Verification View");
// createVerification.addActionListener(this);
// createVerification.addMouseListener(this);
// createVerification.setActionCommand("createVerify");
// JMenuItem viewModel = new JMenuItem("View Model");
// viewModel.addActionListener(this);
// viewModel.addMouseListener(this);
// viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
// popup.add(createVerification);
// popup.addSeparator();
// popup.add(viewModel);
// popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".inst")) {
// JMenuItem createAnalysis = new
// JMenuItem("Create Analysis View");
// createAnalysis.addActionListener(this);
// createAnalysis.addMouseListener(this);
// createAnalysis.setActionCommand("createSim");
// JMenuItem createVerification = new
// JMenuItem("Create Verification View");
// createVerification.addActionListener(this);
// createVerification.addMouseListener(this);
// createVerification.setActionCommand("createVerify");
// JMenuItem viewModel = new JMenuItem("View Model");
// viewModel.addActionListener(this);
// viewModel.addMouseListener(this);
// viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
// popup.add(createVerification);
// popup.addSeparator();
// popup.add(viewModel);
// popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
JMenuItem open;
if (sim) {
open = new JMenuItem("Open Analysis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSim");
popup.add(open);
}
else if (synth) {
open = new JMenuItem("Open Synthesis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSynth");
popup.add(open);
}
else if (ver) {
open = new JMenuItem("Open Verification View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openVerification");
popup.add(open);
}
else if (learn) {
open = new JMenuItem("Open Learn View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openLearn");
popup.add(open);
}
if (sim || ver || synth || learn) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("deleteSim");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (tree.getFile() != null) {
int index = tab.getSelectedIndex();
enableTabMenu(index);
if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".sbml") || tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
try {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
SBML_Editor sbml = new SBML_Editor(tree.getFile(), null, log, this,
null, null);
// sbml.addMouseListener(this);
addTab(tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1], sbml, "SBML Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"You must select a valid sbml file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(),
theFile, this, log, false, null, null, null);
// gcm.addMouseListener(this);
addTab(theFile, gcm, "GCM Editor");
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "VHDL Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Assembly File Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to view this assembly file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".inst")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Instruction File Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to view this instruction file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 5
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".vams")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "VHDL Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to view this Verilog-AMS file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 2
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Petri Net Editor");
}
}
// String[] command = { "emacs", filename };
// Runtime.getRuntime().exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this .g file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
LHPNFile lhpn = new LHPNFile(log);
if (new File(directory + theFile).length() > 0) {
// log.addText("here");
lhpn.load(directory + theFile);
// log.addText("there");
}
// log.addText("load completed");
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
// log.addText("make Editor");
LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile,
lhpn, this, log);
// editor.addMouseListener(this);
addTab(theFile, editor, "LHPN Editor");
// log.addText("Editor made");
}
// String[] cmd = { "emacs", filename };
// Runtime.getRuntime().exec(cmd);
}
catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to view this LHPN file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "CSP Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this csp file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "HSE Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this hse file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "UNC Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this unc file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "RSG Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this rsg file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) {
try {
String filename = tree.getFile();
String directory = "";
String theFile = "";
if (filename.lastIndexOf('/') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('/') + 1);
theFile = filename.substring(filename.lastIndexOf('/') + 1);
}
if (filename.lastIndexOf('\\') >= 0) {
directory = filename.substring(0, filename.lastIndexOf('\\') + 1);
theFile = filename.substring(filename.lastIndexOf('\\') + 1);
}
File work = new File(directory);
int i = getTab(theFile);
if (i != -1) {
tab.setSelectedIndex(i);
}
else {
if (externView) {
String command = viewerField.getText() + " " + directory
+ separator + theFile;
Runtime exec = Runtime.getRuntime();
try {
exec.exec(command);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame,
"Unable to open external editor.",
"Error Opening Editor", JOptionPane.ERROR_MESSAGE);
}
}
else {
File file = new File(work + separator + theFile);
String input = "";
FileReader in = new FileReader(file);
int read = in.read();
while (read != -1) {
input += (char) read;
read = in.read();
}
in.close();
JTextArea text = new JTextArea(input);
text.setEditable(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
// gcm.addMouseListener(this);
addTab(theFile, scroll, "Spice Editor");
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(frame, "Unable to view this spice file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Number of molecules", "title", "tsd.printer",
root, "Time", this, tree.getFile(), log, tree.getFile()
.split(separator)[tree.getFile().split(
separator).length - 1], true, false),
"TSD Graph");
}
}
else if (tree.getFile().length() >= 4
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(
separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
addTab(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
new Graph(null, "Percent", "title", "tsd.printer", root,
"Time", this, tree.getFile(), log, tree.getFile()
.split(separator)[tree.getFile().split(
separator).length - 1], false, false),
"Probability Graph");
}
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
if (sim) {
openSim();
}
else if (synth) {
openSynth();
}
else if (ver) {
openVerify();
}
else if (learn) {
if (lema) {
openLearnLHPN();
}
else {
openLearn();
}
}
}
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities
.convertPoint(glassPane, glassPanePoint, container);
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(),
e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
try {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
if (e != null) {
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e
.getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e
.getClickCount(), e.isPopupTrigger()));
}
if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) {
enableTreeMenu();
}
else {
enableTabMenu(tab.getSelectedIndex());
}
}
catch (Exception e1) {
e1.printStackTrace();
}
}
}
else {
if (tree.getFile() != null) {
if (e.isPopupTrigger() && tree.getFile() != null) {
frame.getGlassPane().setVisible(false);
popup.removeAll();
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5)
.equals(".sbml") || tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("sbmlEditor");
JMenuItem graph = new JMenuItem("View Network");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graph");
JMenuItem browse = new JMenuItem("View in Browser");
browse.addActionListener(this);
browse.addMouseListener(this);
browse.setActionCommand("browse");
JMenuItem simulate = new JMenuItem("Create Analysis View");
simulate.addActionListener(this);
simulate.addMouseListener(this);
simulate.setActionCommand("simulate");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(simulate);
popup.add(createLearn);
popup.addSeparator();
popup.add(graph);
popup.add(browse);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
JMenuItem create = new JMenuItem("Create Analysis View");
create.addActionListener(this);
create.addMouseListener(this);
create.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createSBML = new JMenuItem("Create SBML File");
createSBML.addActionListener(this);
createSBML.addMouseListener(this);
createSBML.setActionCommand("createSBML");
JMenuItem createLHPN = new JMenuItem("Create LHPN File");
createLHPN.addActionListener(this);
createLHPN.addMouseListener(this);
createLHPN.setActionCommand("createLHPN");
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("dotEditor");
JMenuItem graph = new JMenuItem("View Genetic Circuit");
graph.addActionListener(this);
graph.addMouseListener(this);
graph.setActionCommand("graphDot");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(create);
popup.add(createLearn);
popup.add(createSBML);
popup.add(createLHPN);
popup.addSeparator();
popup.add(graph);
popup.addSeparator();
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
JMenuItem edit = new JMenuItem("View/Edit");
edit.addActionListener(this);
edit.addMouseListener(this);
edit.setActionCommand("openGraph");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(edit);
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
// if (lema) {
// popup.add(createLearn);
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem viewStateGraph = new JMenuItem("View State Graph");
viewStateGraph.addActionListener(this);
viewStateGraph.addMouseListener(this);
viewStateGraph.setActionCommand("viewState");
JMenuItem markovAnalysis = new JMenuItem("Perform Markovian Analysis");
markovAnalysis.addActionListener(this);
markovAnalysis.addMouseListener(this);
markovAnalysis.setActionCommand("markov");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
if (atacs || lema) {
popup.add(createVerification);
popup.addSeparator();
}
popup.add(viewModel);
popup.add(viewStateGraph);
popup.add(markovAnalysis);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem createAnalysis = new JMenuItem("Create Analysis View");
createAnalysis.addActionListener(this);
createAnalysis.addMouseListener(this);
createAnalysis.setActionCommand("createSim");
JMenuItem createLearn = new JMenuItem("Create Learn View");
createLearn.addActionListener(this);
createLearn.addMouseListener(this);
createLearn.setActionCommand("createLearn");
JMenuItem createVerification = new JMenuItem("Create Verification View");
createVerification.addActionListener(this);
createVerification.addMouseListener(this);
createVerification.setActionCommand("createVerify");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
if (atacs) {
popup.add(createSynthesis);
}
// popup.add(createAnalysis);
if (lema) {
popup.add(createLearn);
}
popup.add(createVerification);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
JMenuItem createSynthesis = new JMenuItem("Create Synthesis View");
createSynthesis.addActionListener(this);
createSynthesis.addMouseListener(this);
createSynthesis.setActionCommand("createSynthesis");
JMenuItem viewModel = new JMenuItem("View Model");
viewModel.addActionListener(this);
viewModel.addMouseListener(this);
viewModel.setActionCommand("viewModel");
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("delete");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.add(createSynthesis);
popup.addSeparator();
popup.add(viewModel);
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
JMenuItem open;
if (sim) {
open = new JMenuItem("Open Analysis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSim");
popup.add(open);
}
else if (synth) {
open = new JMenuItem("Open Synthesis View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openSynth");
popup.add(open);
}
else if (ver) {
open = new JMenuItem("Open Verification View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openVerification");
popup.add(open);
}
else if (learn) {
open = new JMenuItem("Open Learn View");
open.addActionListener(this);
open.addMouseListener(this);
open.setActionCommand("openLearn");
popup.add(open);
}
if (sim || ver | learn | synth) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.addMouseListener(this);
delete.setActionCommand("deleteSim");
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(this);
copy.addMouseListener(this);
copy.setActionCommand("copy");
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.addMouseListener(this);
rename.setActionCommand("rename");
popup.addSeparator();
popup.add(copy);
popup.add(rename);
popup.add(delete);
}
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
else if (!popup.isVisible()) {
frame.getGlassPane().setVisible(true);
}
}
}
}
public void mouseMoved(MouseEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
}
public void mouseWheelMoved(MouseWheelEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseWheelEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e
.getWheelRotation()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseWheelEvent(deepComponent, e.getID(), e.getWhen(),
e.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e
.getWheelRotation()));
}
}
public void windowGainedFocus(WindowEvent e) {
setGlassPane(true);
}
private void simulate(boolean isDot) throws Exception {
if (isDot) {
String simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:",
"Analysis ID", JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (overwrite(root + separator + simName, simName)) {
new File(root + separator + simName).mkdir();
// new FileWriter(new File(root + separator + simName +
// separator +
// ".sim")).close();
String[] dot = tree.getFile().split(separator);
String sbmlFile = /*
* root + separator + simName + separator +
*/(dot[dot.length - 1].substring(0, dot[dot.length - 1]
.length() - 3) + "sbml");
GCMParser parser = new GCMParser(tree.getFile());
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + File.separator);
network.mergeSBML(root + separator + simName + separator + sbmlFile);
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ simName.trim() + separator + simName.trim() + ".sim"));
out.write((dot[dot.length - 1] + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
// network.outputSBML(root + separator + sbmlFile);
refreshTree();
sbmlFile = root
+ separator
+ simName
+ separator
+ (dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml");
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, simName.trim(),
log, simTab, null, dot[dot.length - 1]);
// reb2sac.addMouseListener(this);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
JPanel abstraction = reb2sac.getAdvanced();
// abstraction.addMouseListener(this);
simTab.addTab("Abstraction Options", abstraction);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (dot[dot.length - 1].contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator,
dot[dot.length - 1], this, log, true, simName.trim(), root
+ separator + simName.trim() + separator + simName.trim()
+ ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(
root + separator + gcm.getSBMLFile(), reb2sac, log, this, root
+ separator + simName.trim(), root + separator
+ simName.trim() + separator + simName.trim() + ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(null);
}
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root
+ separator + simName.trim(), root + separator + simName.trim()
+ separator + simName.trim() + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font
* font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No
* data available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
addTab(simName, simTab, null);
}
}
}
else {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab
.getTitleAt(i)
.equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
SBMLDocument document = readSBML(tree.getFile());
String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:",
"Analysis ID", JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.trim().equals("")) {
simName = simName.trim();
if (overwrite(root + separator + simName, simName)) {
new File(root + separator + simName).mkdir();
// new FileWriter(new File(root + separator + simName +
// separator +
// ".sim")).close();
String sbmlFile = tree.getFile();
String[] sbml1 = tree.getFile().split(separator);
String sbmlFileProp = root + separator + simName + separator
+ sbml1[sbml1.length - 1];
try {
FileOutputStream out = new FileOutputStream(new File(root + separator
+ simName.trim() + separator + simName.trim() + ".sim"));
out.write((sbml1[sbml1.length - 1] + "\n").getBytes());
out.close();
}
catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Unable to save parameter file!",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
new FileOutputStream(new File(sbmlFileProp)).close();
/*
* try { FileOutputStream out = new FileOutputStream(new
* File(sbmlFile)); SBMLWriter writer = new SBMLWriter();
* String doc = writer.writeToString(document); byte[]
* output = doc.getBytes(); out.write(output); out.close();
* } catch (Exception e1) {
* JOptionPane.showMessageDialog(frame, "Unable to copy sbml
* file to output location.", "Error",
* JOptionPane.ERROR_MESSAGE); }
*/
refreshTree();
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName
.trim(), log, simTab, null, sbml1[sbml1.length - 1]);
// reb2sac.addMouseListener(this);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
JPanel abstraction = reb2sac.getAdvanced();
// abstraction.addMouseListener(this);
simTab.addTab("Abstraction Options", abstraction);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (sbml1[sbml1.length - 1].contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator,
sbml1[sbml1.length - 1], this, log, true, simName.trim(), root
+ separator + simName.trim() + separator + simName.trim()
+ ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(
root + separator + gcm.getSBMLFile(), reb2sac, log, this, root
+ separator + simName.trim(), root + separator
+ simName.trim() + separator + simName.trim() + ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(null);
}
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root
+ separator + simName.trim(), root + separator + simName.trim()
+ separator + simName.trim() + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font
* font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No
* data available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
addTab(simName, simTab, null);
}
}
}
}
private void openLearn() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
DataManager data = new DataManager(tree.getFile(), this, lema);
// data.addMouseListener(this);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
Learn learn = new Learn(tree.getFile(), log, this);
// learn.addMouseListener(this);
lrnTab.addTab("Learn", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph = new Graph(null, "Number of molecules",
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "Time", this, open, log,
null, true, true);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
/*
* else { lrnTab.addTab("Data Manager", new
* DataManager(tree.getFile(), this));
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Data Manager"); JLabel noData = new JLabel("No data
* available"); Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font = noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
lrnTab, null);
}
}
private void openLearnLHPN() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JTabbedPane lrnTab = new JTabbedPane();
// String graphFile = "";
String open = null;
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
else if (end.equals(".grf")) {
open = tree.getFile() + separator + list[i];
}
}
}
}
String lrnFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".lrn";
String lrnFile2 = tree.getFile() + separator + ".lrn";
Properties load = new Properties();
String learnFile = "";
try {
if (new File(lrnFile2).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile2));
load.load(in);
in.close();
new File(lrnFile2).delete();
}
if (new File(lrnFile).exists()) {
FileInputStream in = new FileInputStream(new File(lrnFile));
load.load(in);
in.close();
if (load.containsKey("genenet.file")) {
learnFile = load.getProperty("genenet.file");
learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(lrnFile));
load.store(out, learnFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + learnFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
DataManager data = new DataManager(tree.getFile(), this, lema);
// data.addMouseListener(this);
lrnTab.addTab("Data Manager", data);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager");
LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this);
// learn.addMouseListener(this);
lrnTab.addTab("Learn", learn);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn");
Graph tsdGraph = new Graph(null, "Number of molecules",
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ " data", "tsd.printer", tree.getFile(), "Time", this, open, log,
null, true, true);
// tsdGraph.addMouseListener(this);
lrnTab.addTab("TSD Graph", tsdGraph);
lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph");
/*
* else { lrnTab.addTab("Data Manager", new
* DataManager(tree.getFile(), this));
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Data Manager"); JLabel noData = new JLabel("No data
* available"); Font font = noData.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("Learn", noData);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("Learn"); JLabel noData1 = new
* JLabel("No data available"); font = noData1.getFont(); font =
* font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* lrnTab.addTab("TSD Graph", noData1);
* lrnTab.getComponentAt(lrnTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
lrnTab, null);
}
}
private void openSynth() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
JPanel synthPanel = new JPanel();
// String graphFile = "";
if (new File(tree.getFile()).isDirectory()) {
String[] list = new File(tree.getFile()).list();
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = tree.getFile() + separator +
// list[i];
}
}
}
}
}
}
String synthFile = tree.getFile() + separator
+ tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]
+ ".syn";
String synthFile2 = tree.getFile() + separator + ".syn";
Properties load = new Properties();
String synthesisFile = "";
try {
if (new File(synthFile2).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile2));
load.load(in);
in.close();
new File(synthFile2).delete();
}
if (new File(synthFile).exists()) {
FileInputStream in = new FileInputStream(new File(synthFile));
load.load(in);
in.close();
if (load.containsKey("synthesis.file")) {
synthesisFile = load.getProperty("synthesis.file");
synthesisFile = synthesisFile.split(separator)[synthesisFile
.split(separator).length - 1];
}
}
FileOutputStream out = new FileOutputStream(new File(synthesisFile));
load.store(out, synthesisFile);
out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(synthesisFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(root + separator + synthesisFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Synthesis synth = new Synthesis(tree.getFile(), "flag", log, this);
// synth.addMouseListener(this);
synthPanel.add(synth);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
synthPanel, "Synthesis");
}
}
private void openVerify() {
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
// JPanel verPanel = new JPanel();
// JPanel abstPanel = new JPanel();
// JPanel verTab = new JTabbedPane();
// String graphFile = "";
/*
* if (new File(tree.getFile()).isDirectory()) { String[] list = new
* File(tree.getFile()).list(); int run = 0; for (int i = 0; i <
* list.length; i++) { if (!(new File(list[i]).isDirectory()) &&
* list[i].length() > 4) { String end = ""; for (int j = 1; j < 5;
* j++) { end = list[i].charAt(list[i].length() - j) + end; } if
* (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv"))
* { if (list[i].contains("run-")) { int tempNum =
* Integer.parseInt(list[i].substring(4, list[i] .length() -
* end.length())); if (tempNum > run) { run = tempNum; // graphFile
* = tree.getFile() + separator + // list[i]; } } } } } }
*/
String verName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1];
String verFile = tree.getFile() + separator + verName + ".ver";
Properties load = new Properties();
String verifyFile = "";
try {
if (new File(verFile).exists()) {
FileInputStream in = new FileInputStream(new File(verFile));
load.load(in);
in.close();
if (load.containsKey("verification.file")) {
verifyFile = load.getProperty("verification.file");
verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1];
}
}
// FileOutputStream out = new FileOutputStream(new
// File(verifyFile));
// load.store(out, verifyFile);
// out.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame(), "Unable to load properties file!",
"Error Loading Properties", JOptionPane.ERROR_MESSAGE);
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(verifyFile)) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
if (!(new File(verFile).exists())) {
JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile
+ " is missing.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// if (!graphFile.equals("")) {
Verification ver = new Verification(root + separator + verName, verName, "flag", log,
this, lema, atacs);
// ver.addMouseListener(this);
// verPanel.add(ver);
// AbstPane abst = new AbstPane(root + separator + verName, ver,
// "flag", log, this, lema,
// atacs);
// abstPanel.add(abst);
// verTab.add("verify", verPanel);
// verTab.add("abstract", abstPanel);
addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1],
ver, "Verification");
}
}
private void openSim() {
String filename = tree.getFile();
boolean done = false;
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(
filename.split(separator)[filename.split(separator).length - 1])) {
tab.setSelectedIndex(i);
done = true;
}
}
if (!done) {
if (filename != null && !filename.equals("")) {
if (new File(filename).isDirectory()) {
if (new File(filename + separator + ".sim").exists()) {
new File(filename + separator + ".sim").delete();
}
String[] list = new File(filename).list();
String getAFile = "";
// String probFile = "";
String openFile = "";
// String graphFile = "";
String open = null;
String openProb = null;
int run = 0;
for (int i = 0; i < list.length; i++) {
if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = list[i].charAt(list[i].length() - j) + end;
}
if (end.equals("sbml")) {
getAFile = filename + separator + list[i];
}
else if (end.equals(".xml") && getAFile.equals("")) {
getAFile = filename + separator + list[i];
}
else if (end.equals(".txt") && list[i].contains("sim-rep")) {
// probFile = filename + separator + list[i];
}
else if (end.equals("ties") && list[i].contains("properties")
&& !(list[i].equals("species.properties"))) {
openFile = filename + separator + list[i];
}
else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")
|| end.contains("=")) {
if (list[i].contains("run-")) {
int tempNum = Integer.parseInt(list[i].substring(4, list[i]
.length()
- end.length()));
if (tempNum > run) {
run = tempNum;
// graphFile = filename + separator +
// list[i];
}
}
else if (list[i].contains("euler-run.")
|| list[i].contains("gear1-run.")
|| list[i].contains("gear2-run.")
|| list[i].contains("rk4imp-run.")
|| list[i].contains("rk8pd-run.")
|| list[i].contains("rkf45-run.")) {
// graphFile = filename + separator +
// list[i];
}
else if (end.contains("=")) {
// graphFile = filename + separator +
// list[i];
}
}
else if (end.equals(".grf")) {
open = filename + separator + list[i];
}
else if (end.equals(".prb")) {
openProb = filename + separator + list[i];
}
}
else if (new File(filename + separator + list[i]).isDirectory()) {
String[] s = new File(filename + separator + list[i]).list();
for (int j = 0; j < s.length; j++) {
if (s[j].contains("sim-rep")) {
// probFile = filename + separator + list[i]
// + separator +
}
else if (s[j].contains(".tsd")) {
// graphFile = filename + separator +
// list[i] + separator +
}
}
}
}
if (!getAFile.equals("")) {
String[] split = filename.split(separator);
String simFile = root + separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim";
String pmsFile = root + separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".pms";
if (new File(pmsFile).exists()) {
if (new File(simFile).exists()) {
new File(pmsFile).delete();
}
else {
new File(pmsFile).renameTo(new File(simFile));
}
}
String sbmlLoadFile = "";
String gcmFile = "";
if (new File(simFile).exists()) {
try {
Scanner s = new Scanner(new File(simFile));
if (s.hasNextLine()) {
sbmlLoadFile = s.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1];
if (sbmlLoadFile.equals("")) {
JOptionPane
.showMessageDialog(
frame,
"Unable to open view because "
+ "the sbml linked to this view is missing.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
else if (!(new File(root + separator + sbmlLoadFile).exists())) {
JOptionPane.showMessageDialog(frame,
"Unable to open view because " + sbmlLoadFile
+ " is missing.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator
+ sbmlLoadFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + File.separator);
sbmlLoadFile = root + separator
+ split[split.length - 1].trim() + separator
+ sbmlLoadFile.replace(".gcm", ".sbml");
network.mergeSBML(sbmlLoadFile);
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (s.hasNextLine()) {
s.nextLine();
}
s.close();
File f = new File(sbmlLoadFile);
if (!f.exists()) {
sbmlLoadFile = root + separator + f.getName();
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
else {
sbmlLoadFile = root
+ separator
+ getAFile.split(separator)[getAFile.split(separator).length - 1];
if (!new File(sbmlLoadFile).exists()) {
sbmlLoadFile = getAFile;
/*
* JOptionPane.showMessageDialog(frame, "Unable
* to load sbml file.", "Error",
* JOptionPane.ERROR_MESSAGE); return;
*/
}
}
if (!new File(sbmlLoadFile).exists()) {
JOptionPane.showMessageDialog(frame,
"Unable to open view because "
+ sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1] + " is missing.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i)
.equals(
sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1])) {
tab.setSelectedIndex(i);
if (save(i, 0) == 0) {
return;
}
break;
}
}
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this,
split[split.length - 1].trim(), log, simTab, openFile, gcmFile);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1)
.setName("Simulate");
simTab.addTab("Abstraction Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options",
// reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile,
this, log, true, split[split.length - 1].trim(), root
+ separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim",
reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(root + separator
+ gcm.getSBMLFile(), reb2sac, log, this, root + separator
+ split[split.length - 1].trim(), root + separator
+ split[split.length - 1].trim() + separator
+ split[split.length - 1].trim() + ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1)
.setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1)
.setName("");
gcm.setSBMLParamFile(null);
}
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this,
root + separator + split[split.length - 1].trim(), root
+ separator + split[split.length - 1].trim()
+ separator + split[split.length - 1].trim() + ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
// if (open != null) {
Graph tsdGraph = reb2sac.createGraph(open);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"TSD Graph");
/*
* } else if (!graphFile.equals("")) {
* simTab.addTab("TSD Graph",
* reb2sac.createGraph(open));
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); } / else { JLabel noData =
* new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); }
*/
// if (openProb != null) {
Graph probGraph = reb2sac.createProbGraph(openProb);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName(
"ProbGraph");
/*
* } else if (!probFile.equals("")) {
* simTab.addTab("Probability Graph",
* reb2sac.createProbGraph(openProb));
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); } else { JLabel noData1 =
* new JLabel("No data available"); Font font1 =
* noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f);
* noData1.setFont(font1);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph"); }
*/
addTab(split[split.length - 1], simTab, null);
}
}
}
}
}
private class NewAction extends AbstractAction {
NewAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(newProj);
if (!async) {
popup.add(newCircuit);
popup.add(newModel);
}
else if (atacs) {
popup.add(newVhdl);
popup.add(newLhpn);
popup.add(newCsp);
popup.add(newHse);
popup.add(newUnc);
popup.add(newRsg);
}
else {
popup.add(newVhdl);
popup.add(newLhpn);
popup.add(newSpice);
}
popup.add(graph);
popup.add(probGraph);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class SaveAction extends AbstractAction {
SaveAction() {
super();
}
public void actionPerformed(ActionEvent e) {
if (!lema) {
popup.add(saveAsGcm);
}
else {
popup.add(saveAsLhpn);
}
popup.add(saveAsGraph);
if (!lema) {
popup.add(saveAsSbml);
popup.add(saveAsTemplate);
}
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class ImportAction extends AbstractAction {
ImportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
if (!lema) {
popup.add(importDot);
popup.add(importSbml);
popup.add(importBioModel);
}
else if (atacs) {
popup.add(importVhdl);
popup.add(importLpn);
popup.add(importCsp);
popup.add(importHse);
popup.add(importUnc);
popup.add(importRsg);
}
else {
popup.add(importVhdl);
popup.add(importS);
popup.add(importInst);
popup.add(importLpn);
popup.add(importSpice);
}
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class ExportAction extends AbstractAction {
ExportAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(exportCsv);
popup.add(exportDat);
popup.add(exportEps);
popup.add(exportJpg);
popup.add(exportPdf);
popup.add(exportPng);
popup.add(exportSvg);
popup.add(exportTsd);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
private class ModelAction extends AbstractAction {
ModelAction() {
super();
}
public void actionPerformed(ActionEvent e) {
popup.add(viewModGraph);
popup.add(viewModBrowser);
if (popup.getComponentCount() != 0) {
popup.show(mainPanel, mainPanel.getMousePosition().x,
mainPanel.getMousePosition().y);
}
}
}
public void mouseClicked(MouseEvent e) {
if (e.getSource() == frame.getGlassPane()) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(),
e.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) {
enableTreeMenu();
}
else {
enableTabMenu(tab.getSelectedIndex());
}
}
}
}
public void mouseEntered(MouseEvent e) {
if (e.getSource() == tree.tree) {
setGlassPane(false);
}
else if (e.getSource() == popup) {
popupFlag = true;
setGlassPane(false);
}
else if (e.getSource() instanceof JMenuItem) {
menuFlag = true;
setGlassPane(false);
}
}
public void mouseExited(MouseEvent e) {
if (e.getSource() == tree.tree && !popupFlag && !menuFlag) {
setGlassPane(true);
}
else if (e.getSource() == popup) {
popupFlag = false;
if (!menuFlag) {
setGlassPane(true);
}
}
else if (e.getSource() instanceof JMenuItem) {
menuFlag = false;
if (!popupFlag) {
setGlassPane(true);
}
}
}
public void mouseDragged(MouseEvent e) {
Component glassPane = frame.getGlassPane();
Point glassPanePoint = e.getPoint();
// Component component = e.getComponent();
Container container = frame.getContentPane();
Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame
.getContentPane());
if (containerPoint.y < 0) { // we're not in the content pane
if (containerPoint.y + menuBar.getHeight() >= 0) {
Component component = menuBar.getComponentAt(glassPanePoint);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
component);
component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
frame.getGlassPane().setVisible(false);
}
}
else {
try {
Component deepComponent = SwingUtilities.getDeepestComponentAt(container,
containerPoint.x, containerPoint.y);
Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint,
deepComponent);
// if (deepComponent instanceof ScrollableTabPanel) {
// deepComponent = tab.findComponentAt(componentPoint);
deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e
.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e
.isPopupTrigger()));
}
catch (Exception e1) {
}
}
}
// public void componentHidden(ComponentEvent e) {
// log.addText("hidden");
// setGlassPane(true);
// public void componentResized(ComponentEvent e) {
// log.addText("resized");
// public void componentMoved(ComponentEvent e) {
// log.addText("moved");
// public void componentShown(ComponentEvent e) {
// log.addText("shown");
public void windowLostFocus(WindowEvent e) {
}
// public void focusGained(FocusEvent e) {
// public void focusLost(FocusEvent e) {
// log.addText("focus lost");
public JMenuItem getExitButton() {
return exit;
}
/**
* This is the main method. It excecutes the BioSim GUI FrontEnd program.
*/
public static void main(String args[]) {
boolean lemaFlag = false, atacsFlag = false;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-lema")) {
lemaFlag = true;
}
else if (args[i].equals("-atacs")) {
atacsFlag = true;
}
}
}
if (!lemaFlag && !atacsFlag) {
String varname;
if (System.getProperty("mrj.version") != null)
varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
else
varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
try {
System.loadLibrary("sbmlj");
// For extra safety, check that the jar file is in the
// classpath.
Class.forName("org.sbml.libsbml.libsbml");
}
catch (UnsatisfiedLinkError e) {
System.err.println("Error: could not link with the libSBML library."
+ " It is likely\nyour " + varname
+ " environment variable does not include\nthe"
+ " directory containing the libsbml library file.");
System.exit(1);
}
catch (ClassNotFoundException e) {
System.err.println("Error: unable to load the file libsbmlj.jar."
+ " It is likely\nyour " + varname + " environment"
+ " variable or CLASSPATH variable\ndoes not include"
+ " the directory containing the libsbmlj.jar file.");
System.exit(1);
}
catch (SecurityException e) {
System.err.println("Could not load the libSBML library files due to a"
+ " security exception.");
System.exit(1);
}
}
new BioSim(lemaFlag, atacsFlag);
}
public void copySim(String newSim) {
try {
new File(root + separator + newSim).mkdir();
// new FileWriter(new File(root + separator + newSim + separator +
// ".sim")).close();
String oldSim = tab.getTitleAt(tab.getSelectedIndex());
String[] s = new File(root + separator + oldSim).list();
String sbmlFile = "";
String propertiesFile = "";
String sbmlLoadFile = null;
String gcmFile = null;
for (String ss : s) {
if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml")
|| ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) {
SBMLDocument document = readSBML(root + separator + oldSim + separator + ss);
SBMLWriter writer = new SBMLWriter();
writer.writeSBML(document, root + separator + newSim + separator + ss);
sbmlFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) {
FileOutputStream out = new FileOutputStream(new File(root + separator + newSim
+ separator + ss));
FileInputStream in = new FileInputStream(new File(root + separator + oldSim
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
propertiesFile = root + separator + newSim + separator + ss;
}
else if (ss.length() > 3
&& (ss.substring(ss.length() - 4).equals(".dat")
|| ss.substring(ss.length() - 4).equals(".sad")
|| ss.substring(ss.length() - 4).equals(".pms") || ss.substring(
ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) {
FileOutputStream out;
if (ss.substring(ss.length() - 4).equals(".pms")) {
out = new FileOutputStream(new File(root + separator + newSim + separator
+ newSim + ".sim"));
}
else if (ss.substring(ss.length() - 4).equals(".sim")) {
out = new FileOutputStream(new File(root + separator + newSim + separator
+ newSim + ".sim"));
}
else {
out = new FileOutputStream(new File(root + separator + newSim + separator
+ ss));
}
FileInputStream in = new FileInputStream(new File(root + separator + oldSim
+ separator + ss));
int read = in.read();
while (read != -1) {
out.write(read);
read = in.read();
}
in.close();
out.close();
if (ss.substring(ss.length() - 4).equals(".pms")) {
if (new File(root + separator + newSim + separator
+ ss.substring(0, ss.length() - 4) + ".sim").exists()) {
new File(root + separator + newSim + separator + ss).delete();
}
else {
new File(root + separator + newSim + separator + ss).renameTo(new File(
root + separator + newSim + separator
+ ss.substring(0, ss.length() - 4) + ".sim"));
}
ss = ss.substring(0, ss.length() - 4) + ".sim";
}
if (ss.substring(ss.length() - 4).equals(".sim")) {
try {
Scanner scan = new Scanner(new File(root + separator + newSim
+ separator + ss));
if (scan.hasNextLine()) {
sbmlLoadFile = scan.nextLine();
sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile
.split(separator).length - 1];
gcmFile = sbmlLoadFile;
if (sbmlLoadFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator
+ sbmlLoadFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + File.separator);
sbmlLoadFile = root + separator + newSim + separator
+ sbmlLoadFile.replace(".gcm", ".sbml");
network.mergeSBML(sbmlLoadFile);
}
else {
sbmlLoadFile = root + separator + sbmlLoadFile;
}
}
while (scan.hasNextLine()) {
scan.nextLine();
}
scan.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load sbml file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
refreshTree();
JTabbedPane simTab = new JTabbedPane();
Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab,
propertiesFile, gcmFile);
simTab.addTab("Simulation Options", reb2sac);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate");
simTab.addTab("Abstraction Options", reb2sac.getAdvanced());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
// simTab.addTab("Advanced Options", reb2sac.getProperties());
// simTab.getComponentAt(simTab.getComponents().length -
// 1).setName("");
if (gcmFile.contains(".gcm")) {
GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true,
newSim, root + separator + newSim + separator + newSim + ".sim", reb2sac);
reb2sac.setGcm(gcm);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", gcm);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor");
if (!gcm.getSBMLFile().equals("--none
SBML_Editor sbml = new SBML_Editor(root + separator + gcm.getSBMLFile(),
reb2sac, log, this, root + separator + newSim, root + separator
+ newSim + separator + newSim + ".sim");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
simTab.addTab("SBML Elements", scroll);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
gcm.setSBMLParamFile(null);
}
}
else {
SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root
+ separator + newSim, root + separator + newSim + separator + newSim
+ ".sim");
reb2sac.setSbml(sbml);
// sbml.addMouseListener(this);
simTab.addTab("Parameter Editor", sbml);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor");
simTab.addTab("SBML Elements", sbml.getElementsPanel());
simTab.getComponentAt(simTab.getComponents().length - 1).setName("");
}
Graph tsdGraph = reb2sac.createGraph(null);
// tsdGraph.addMouseListener(this);
simTab.addTab("TSD Graph", tsdGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph");
Graph probGraph = reb2sac.createProbGraph(null);
// probGraph.addMouseListener(this);
simTab.addTab("Probability Graph", probGraph);
simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph");
/*
* JLabel noData = new JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f);
* noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("TSD Graph", noData);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data
* available"); Font font1 = noData1.getFont(); font1 =
* font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1);
* noData1.setHorizontalAlignment(SwingConstants.CENTER);
* simTab.addTab("Probability Graph", noData1);
* simTab.getComponentAt(simTab.getComponents().length -
* 1).setName("ProbGraph");
*/
tab.setComponentAt(tab.getSelectedIndex(), simTab);
tab.setTitleAt(tab.getSelectedIndex(), newSim);
tab.getComponentAt(tab.getSelectedIndex()).setName(newSim);
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void refreshLearn(String learnName, boolean data) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(learnName)) {
for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals(
"TSD Graph")) {
// if (data) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) {
((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j))
.refresh();
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Graph(null,
"Number of molecules", learnName + " data", "tsd.printer", root
+ separator + learnName, "Time", this, null, log, null,
true, true));
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName(
"TSD Graph");
}
/*
* } else { JLabel noData1 = new
* JLabel("No data available"); Font font =
* noData1.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData1.setFont(font);
* noData1.setHorizontalAlignment
* (SwingConstants.CENTER); ((JTabbedPane)
* tab.getComponentAt(i)).setComponentAt(j, noData1);
* ((JTabbedPane)
* tab.getComponentAt(i)).getComponentAt(j
* ).setName("TSD Graph"); }
*/
}
else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName()
.equals("Learn")) {
// if (data) {
if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) {
}
else {
if (lema) {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j,
new LearnLHPN(root + separator + learnName, log, this));
}
else {
((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn(
root + separator + learnName, log, this));
}
((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)
.setName("Learn");
}
/*
* } else { JLabel noData = new
* JLabel("No data available"); Font font =
* noData.getFont(); font = font.deriveFont(Font.BOLD,
* 42.0f); noData.setFont(font);
* noData.setHorizontalAlignment(SwingConstants.CENTER);
* ((JTabbedPane)
* tab.getComponentAt(i)).setComponentAt(j, noData);
* ((JTabbedPane)
* tab.getComponentAt(i)).getComponentAt(j
* ).setName("Learn"); }
*/
}
}
}
}
}
private void updateGCM() {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).contains(".gcm")) {
((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles();
tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename());
}
}
}
public void updateAsyncViews(String updatedFile) {
// log.addText(updatedFile);
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
String properties = root + separator + tab + separator + tab + ".ver";
String properties1 = root + separator + tab + separator + tab + ".synth";
String properties2 = root + separator + tab + separator + tab + ".lrn";
// log.addText(properties + "\n" + properties1 + "\n" + properties2
if (new File(properties).exists()) {
// String check = "";
// try {
// Scanner s = new Scanner(new File(properties));
// if (s.hasNextLine()) {
// check = s.nextLine();
// check = check.split(separator)[check.split(separator).length
// s.close();
// catch (Exception e) {
// if (check.equals(updatedFile)) {
Verification verify = ((Verification) (this.tab.getComponentAt(i)));
verify.reload(updatedFile);
}
if (new File(properties1).exists()) {
// String check = "";
// try {
// Scanner s = new Scanner(new File(properties1));
// if (s.hasNextLine()) {
// check = s.nextLine();
// check = check.split(separator)[check.split(separator).length
// s.close();
// catch (Exception e) {
// if (check.equals(updatedFile)) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
if (sim.getComponentAt(j).getName().equals("Synthesis")) {
// new File(properties).renameTo(new
// File(properties.replace(".synth",
// ".temp")));
// boolean dirty = ((SBML_Editor)
// (sim.getComponentAt(j))).isDirty();
((Synthesis) (sim.getComponentAt(j))).reload(updatedFile);
// if (updatedFile.contains(".g")) {
// GCMParser parser = new GCMParser(root + separator +
// updatedFile);
// GeneticNetwork network = parser.buildNetwork();
// GeneticNetwork.setRoot(root + File.separator);
// network.mergeSBML(root + separator + tab + separator
// + updatedFile.replace(".g", ".vhd"));
// ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i,
// j, root
// + separator + tab + separator
// + updatedFile.replace(".g", ".vhd"));
// else {
// ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i,
// j, root
// + separator + updatedFile);
// ((SBML_Editor)
// (sim.getComponentAt(j))).setDirty(dirty);
// new File(properties).delete();
// new File(properties.replace(".synth",
// ".temp")).renameTo(new
// File(
// properties));
// sim.setComponentAt(j + 1, ((SBML_Editor)
// (sim.getComponentAt(j)))
// .getElementsPanel());
// sim.getComponentAt(j + 1).setName("");
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn")) {
((LearnLHPN) (learn.getComponentAt(j))).updateSpecies(root + separator
+ updatedFile);
((LearnLHPN) (learn.getComponentAt(j))).reload(updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
}
}
public void updateViews(String updatedFile) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
String properties = root + separator + tab + separator + tab + ".sim";
String properties2 = root + separator + tab + separator + tab + ".lrn";
if (new File(properties).exists()) {
String check = "";
try {
Scanner s = new Scanner(new File(properties));
if (s.hasNextLine()) {
check = s.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
s.close();
}
catch (Exception e) {
}
if (check.equals(updatedFile)) {
JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < sim.getTabCount(); j++) {
if (sim.getComponentAt(j).getName().equals("SBML Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim",
".temp")));
boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty();
((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true);
if (updatedFile.contains(".gcm")) {
GCMParser parser = new GCMParser(root + separator + updatedFile);
GeneticNetwork network = parser.buildNetwork();
GeneticNetwork.setRoot(root + File.separator);
network.mergeSBML(root + separator + tab + separator
+ updatedFile.replace(".gcm", ".sbml"));
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root
+ separator + tab + separator
+ updatedFile.replace(".gcm", ".sbml"));
}
else {
((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root
+ separator + updatedFile);
}
((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(
properties));
sim.setComponentAt(j + 1, ((SBML_Editor) (sim.getComponentAt(j)))
.getElementsPanel());
sim.getComponentAt(j + 1).setName("");
}
else if (sim.getComponentAt(j).getName().equals("GCM Editor")) {
new File(properties).renameTo(new File(properties.replace(".sim",
".temp")));
boolean dirty = ((GCM2SBMLEditor) (sim.getComponentAt(j))).isDirty();
((GCM2SBMLEditor) (sim.getComponentAt(j))).saveParams(false, "");
((GCM2SBMLEditor) (sim.getComponentAt(j))).reload(check.replace(".gcm",
""));
((GCM2SBMLEditor) (sim.getComponentAt(j))).refresh();
((GCM2SBMLEditor) (sim.getComponentAt(j))).loadParams();
((GCM2SBMLEditor) (sim.getComponentAt(j))).setDirty(dirty);
new File(properties).delete();
new File(properties.replace(".sim", ".temp")).renameTo(new File(
properties));
if (!((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile().equals(
"--none
SBML_Editor sbml = new SBML_Editor(root + separator
+ ((GCM2SBMLEditor) (sim.getComponentAt(j))).getSBMLFile(),
((Reb2Sac) sim.getComponentAt(0)), log, this, root
+ separator + tab, root + separator + tab
+ separator + tab + ".sim");
sim.setComponentAt(j + 1, sbml.getElementsPanel());
sim.getComponentAt(j + 1).setName("");
((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(sbml);
}
else {
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(new JPanel());
sim.setComponentAt(j + 1, scroll);
sim.getComponentAt(j + 1).setName("");
((GCM2SBMLEditor) (sim.getComponentAt(j))).setSBMLParamFile(null);
}
}
}
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
if (check.equals(updatedFile)) {
JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i)));
for (int j = 0; j < learn.getTabCount(); j++) {
if (learn.getComponentAt(j).getName().equals("Data Manager")) {
((DataManager) (learn.getComponentAt(j))).updateSpecies();
}
else if (learn.getComponentAt(j).getName().equals("Learn")) {
((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator
+ updatedFile);
}
else if (learn.getComponentAt(j).getName().contains("Graph")) {
((Graph) (learn.getComponentAt(j))).refresh();
}
}
}
}
ArrayList<String> saved = new ArrayList<String>();
if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) {
saved.add(this.tab.getTitleAt(i));
GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i);
if (gcm.getSBMLFile().equals(updatedFile)) {
gcm.save("save");
}
}
String[] files = new File(root).list();
for (String s : files) {
if (s.contains(".gcm") && !saved.contains(s)) {
GCMFile gcm = new GCMFile(root);
gcm.load(root + separator + s);
if (gcm.getSBMLFile().equals(updatedFile)) {
updateViews(s);
}
}
}
}
}
private void updateViewNames(String oldname, String newname) {
File work = new File(root);
String[] fileList = work.list();
String[] temp = oldname.split(separator);
oldname = temp[temp.length - 1];
for (int i = 0; i < fileList.length; i++) {
String tabTitle = fileList[i];
String properties = root + separator + tabTitle + separator + tabTitle + ".ver";
String properties1 = root + separator + tabTitle + separator + tabTitle + ".synth";
String properties2 = root + separator + tabTitle + separator + tabTitle + ".lrn";
if (new File(properties).exists()) {
String check;
Properties p = new Properties();
try {
FileInputStream load = new FileInputStream(new File(properties));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("verification.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties));
p.store(out, properties);
}
}
catch (Exception e) {
// log.addText("verification");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties1).exists()) {
String check;
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties1));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("synthesis.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties1));
p.store(out, properties1);
}
}
catch (Exception e) {
// log.addText("synthesis");
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
if (new File(properties2).exists()) {
String check = "";
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(properties2));
p.load(load);
load.close();
if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
if (check.equals(oldname)) {
p.setProperty("learn.file", newname);
FileOutputStream out = new FileOutputStream(new File(properties2));
p.store(out, properties2);
}
}
catch (Exception e) {
// e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Unable to load background file.",
"Error", JOptionPane.ERROR_MESSAGE);
check = "";
}
}
}
updateAsyncViews(newname);
}
private void enableTabMenu(int selectedTab) {
treeSelected = false;
// log.addText("tab menu");
if (selectedTab != -1) {
tab.setSelectedIndex(selectedTab);
}
Component comp = tab.getSelectedComponent();
// if (comp != null) {
// log.addText(comp.toString());
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
viewSG.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
if (comp instanceof GCM2SBMLEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(true);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(true);
saveAsTemplate.setEnabled(true);
saveGcmAsLhpn.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(true);
saveTemp.setEnabled(true);
viewModGraph.setEnabled(true);
}
else if (comp instanceof LHPNEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(true);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(true);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
viewModGraph.setEnabled(true);
}
else if (comp instanceof SBML_Editor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(true);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(true);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(true);
saveTemp.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(true);
}
else if (comp instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(true);
checkButton.setEnabled(false);
exportButton.setEnabled(true);
save.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(true);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(true);
refresh.setEnabled(true);
check.setEnabled(false);
export.setEnabled(true);
exportMenu.setEnabled(true);
if (((Graph) comp).isTSDGraph()) {
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
else {
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportTsd.setEnabled(false);
}
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (comp instanceof JTabbedPane) {
Component component = ((JTabbedPane) comp).getSelectedComponent();
Boolean learn = false;
for (Component c : ((JTabbedPane) comp).getComponents()) {
if (c instanceof Learn) {
learn = true;
}
else if (c instanceof GCM2SBMLEditor) {
viewSG.setEnabled(true);
}
}
// int index = tab.getSelectedIndex();
if (component instanceof Graph) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
if (learn) {
runButton.setEnabled(false);
}
else {
runButton.setEnabled(true);
}
refreshButton.setEnabled(true);
checkButton.setEnabled(false);
exportButton.setEnabled(true);
save.setEnabled(true);
if (learn) {
run.setEnabled(false);
saveModel.setEnabled(true);
}
else {
run.setEnabled(true);
saveModel.setEnabled(false);
}
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(true);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(true);
check.setEnabled(false);
export.setEnabled(true);
exportMenu.setEnabled(true);
if (((Graph) component).isTSDGraph()) {
exportCsv.setEnabled(true);
exportDat.setEnabled(true);
exportTsd.setEnabled(true);
}
else {
exportCsv.setEnabled(false);
exportDat.setEnabled(false);
exportTsd.setEnabled(false);
}
exportEps.setEnabled(true);
exportJpg.setEnabled(true);
exportPdf.setEnabled(true);
exportPng.setEnabled(true);
exportSvg.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof Reb2Sac) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof SBML_Editor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof GCM2SBMLEditor) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof Learn) {
if (((Learn) component).isComboSelected()) {
frame.getGlassPane().setVisible(false);
}
// saveButton.setEnabled(((Learn)
// component).getSaveGcmEnabled());
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// save.setEnabled(((Learn) component).getSaveGcmEnabled());
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled());
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(((Learn) component).getViewLogEnabled());
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// viewCoverage.setEnabled(((Learn)
// component).getViewCoverageEnabled()); // SB
// saveParam.setEnabled(true);
saveModel.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof LearnLHPN) {
if (((LearnLHPN) component).isComboSelected()) {
frame.getGlassPane().setVisible(false);
}
// saveButton.setEnabled(((LearnLHPN)
// component).getSaveLhpnEnabled());
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
// save.setEnabled(((LearnLHPN)
// component).getSaveLhpnEnabled());
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled());
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled());
viewCoverage.setEnabled(((LearnLHPN) component).getViewCoverageEnabled());
viewVHDL.setEnabled(((LearnLHPN) component).getViewVHDLEnabled());
viewVerilog.setEnabled(((LearnLHPN) component).getViewVerilogEnabled());
viewLHPN.setEnabled(((LearnLHPN) component).getViewLhpnEnabled());
// saveParam.setEnabled(true);
saveModel.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof DataManager) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(true);
saveAsGcm.setEnabled(true);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(true);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof JPanel) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (component instanceof JScrollPane) {
saveButton.setEnabled(true);
saveasButton.setEnabled(false);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
else if (comp instanceof JPanel) {
if (comp.getName().equals("Verification")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(true);
viewRules.setEnabled(false); // always false??
// viewTrace.setEnabled(((Verification)
// comp).getViewTraceEnabled());
viewTrace.setEnabled(((Verification) comp).getViewTraceEnabled()); // Should
// true
// only
// verification
// Result
// available???
viewCircuit.setEnabled(false); // always true???
// viewLog.setEnabled(((Verification)
// comp).getViewLogEnabled());
viewLog.setEnabled(((Verification) comp).getViewLogEnabled()); // Should
// true
// only
// log
// available???
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
}
else if (comp.getName().equals("Synthesis")) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(true);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(true);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewModel.setEnabled(true); // always true??
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(true);
// viewRules.setEnabled(((Synthesis)
// comp).getViewRulesEnabled());
// viewTrace.setEnabled(((Synthesis)
// comp).getViewTraceEnabled());
// viewCircuit.setEnabled(((Synthesis)
// comp).getViewCircuitEnabled());
// viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled());
viewRules.setEnabled(((Synthesis) comp).getViewRulesEnabled());
viewTrace.setEnabled(((Synthesis) comp).getViewTraceEnabled()); // Always
viewCircuit.setEnabled(((Synthesis) comp).getViewCircuitEnabled()); // Always
viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled());
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
}
}
else if (comp instanceof JScrollPane) {
saveButton.setEnabled(true);
saveasButton.setEnabled(true);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(true);
run.setEnabled(false);
saveAs.setEnabled(true);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(true);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else {
saveButton.setEnabled(false);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
save.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
exportMenu.setEnabled(false);
viewCircuit.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
}
private void enableTreeMenu() {
treeSelected = true;
// log.addText(tree.getFile());
saveButton.setEnabled(false);
saveasButton.setEnabled(false);
runButton.setEnabled(false);
refreshButton.setEnabled(false);
checkButton.setEnabled(false);
exportButton.setEnabled(false);
exportMenu.setEnabled(false);
save.setEnabled(false);
run.setEnabled(false);
saveAs.setEnabled(false);
saveAsMenu.setEnabled(false);
saveAsGcm.setEnabled(false);
saveAsLhpn.setEnabled(false);
saveAsGraph.setEnabled(false);
saveAsSbml.setEnabled(false);
saveAsTemplate.setEnabled(false);
saveGcmAsLhpn.setEnabled(false);
viewSG.setEnabled(false);
if (tree.getFile() != null) {
if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml")
|| tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) {
viewModGraph.setEnabled(true);
viewModGraph.setActionCommand("graph");
viewModBrowser.setEnabled(true);
createAnal.setEnabled(true);
createAnal.setActionCommand("simulate");
createLearn.setEnabled(true);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) {
viewModGraph.setEnabled(true);
viewModGraph.setActionCommand("graphDot");
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSbml.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewModel.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// /saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) {
viewModel.setEnabled(false);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(true);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
save.setEnabled(true); // SB should be????
// saveas too ????
// viewLog should be available ???
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 4
&& tree.getFile().substring(tree.getFile().length() - 5).equals(".vams")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(true);
viewLHPN.setEnabled(false);
save.setEnabled(true); // SB should be????
// saveas too ????
// viewLog should be available ???
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 1
&& tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
if (new File(root + separator + "atacs.log").exists()) {
viewLog.setEnabled(true);
}
else {
viewLog.setEnabled(false);
}
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".lpn")) {
viewModel.setEnabled(true);
viewModGraph.setEnabled(true);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(true);
createAnal.setActionCommand("createSim");
createLearn.setEnabled(true);
createSynth.setEnabled(true);
createVer.setEnabled(true);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
if (new File(root + separator + "atacs.log").exists()) {
viewLog.setEnabled(true);
}
else {
viewLog.setEnabled(false);
}
// not displaying the correct log too ????? SB
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(true); // SB true ??? since lpn
save.setEnabled(true); // SB should exist ???
// saveas too???
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (tree.getFile().length() > 3
&& tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSynth.setEnabled(false);
createVer.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) {
boolean sim = false;
boolean synth = false;
boolean ver = false;
boolean learn = false;
for (String s : new File(tree.getFile()).list()) {
if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) {
sim = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) {
synth = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) {
ver = true;
}
else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) {
learn = true;
}
}
if (sim || synth || ver || learn) {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(true);
rename.setEnabled(true);
delete.setEnabled(true);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
else {
viewModGraph.setEnabled(false);
viewModBrowser.setEnabled(false);
createAnal.setEnabled(false);
createLearn.setEnabled(false);
createSbml.setEnabled(false);
refresh.setEnabled(false);
check.setEnabled(false);
export.setEnabled(false);
copy.setEnabled(false);
rename.setEnabled(false);
delete.setEnabled(false);
viewRules.setEnabled(false);
viewTrace.setEnabled(false);
viewCircuit.setEnabled(false);
viewLog.setEnabled(false);
viewCoverage.setEnabled(false);
viewVHDL.setEnabled(false);
viewVerilog.setEnabled(false);
viewLHPN.setEnabled(false);
// saveParam.setEnabled(false);
saveModel.setEnabled(false);
saveSbml.setEnabled(false);
saveTemp.setEnabled(false);
}
}
}
public String getRoot() {
return root;
}
public void setGlassPane(boolean visible) {
frame.getGlassPane().setVisible(visible);
}
public boolean overwrite(String fullPath, String name) {
if (new File(fullPath).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(frame, name + " already exists."
+ "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
String[] views = canDelete(name);
if (views.length == 0) {
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(name)) {
tab.remove(i);
}
}
File dir = new File(fullPath);
if (dir.isDirectory()) {
deleteDir(dir);
}
else {
System.gc();
dir.delete();
}
return true;
}
else {
String view = "";
for (int i = 0; i < views.length; i++) {
if (i == views.length - 1) {
view += views[i];
}
else {
view += views[i] + "\n";
}
}
String message = "Unable to overwrite file."
+ "\nIt is linked to the following views:\n" + view
+ "\nDelete these views first.";
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(frame, scroll, "Unable To Overwrite File",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
else {
return false;
}
}
else {
return true;
}
}
public void updateOpenSBML(String sbmlName) {
for (int i = 0; i < tab.getTabCount(); i++) {
String tab = this.tab.getTitleAt(i);
if (sbmlName.equals(tab)) {
if (this.tab.getComponentAt(i) instanceof SBML_Editor) {
SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log,
this, null, null);
this.tab.setComponentAt(i, newSBML);
this.tab.getComponentAt(i).setName("SBML Editor");
newSBML.save(false, "", false);
}
}
}
}
private String[] canDelete(String filename) {
ArrayList<String> views = new ArrayList<String>();
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
Scanner scan = new Scanner(new File(root + separator + s + separator + s
+ ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
}
scan.close();
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".ver").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("verification.file")) {
String[] getProp = p.getProperty("verification.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
else if (new File(root + separator + s + separator + s + ".synth").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("synthesis.file")) {
String[] getProp = p.getProperty("synthesis.file").split(separator);
check = getProp[getProp.length - 1];
}
else {
check = "";
}
}
catch (Exception e) {
check = "";
}
}
if (check.equals(filename)) {
views.add(s);
}
}
}
String[] usingViews = views.toArray(new String[0]);
sort(usingViews);
return usingViews;
}
private void sort(String[] sort) {
int i, j;
String index;
for (i = 1; i < sort.length; i++) {
index = sort[i];
j = i;
while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) {
sort[j] = sort[j - 1];
j = j - 1;
}
sort[j] = index;
}
}
private void reassignViews(String oldName, String newName) {
String[] files = new File(root).list();
for (String s : files) {
if (new File(root + separator + s).isDirectory()) {
String check = "";
if (new File(root + separator + s + separator + s + ".sim").exists()) {
try {
ArrayList<String> copy = new ArrayList<String>();
Scanner scan = new Scanner(new File(root + separator + s + separator + s
+ ".sim"));
if (scan.hasNextLine()) {
check = scan.nextLine();
check = check.split(separator)[check.split(separator).length - 1];
if (check.equals(oldName)) {
while (scan.hasNextLine()) {
copy.add(scan.nextLine());
}
scan.close();
FileOutputStream out = new FileOutputStream(new File(root
+ separator + s + separator + s + ".sim"));
out.write((newName + "\n").getBytes());
for (String cop : copy) {
out.write((cop + "\n").getBytes());
}
out.close();
}
else {
scan.close();
}
}
}
catch (Exception e) {
}
}
else if (new File(root + separator + s + separator + s + ".lrn").exists()) {
try {
Properties p = new Properties();
FileInputStream load = new FileInputStream(new File(root + separator + s
+ separator + s + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
check = getProp[getProp.length - 1];
if (check.equals(oldName)) {
p.setProperty("genenet.file", newName);
FileOutputStream store = new FileOutputStream(new File(root
+ separator + s + separator + s + ".lrn"));
p.store(store, "Learn File Data");
store.close();
}
}
}
catch (Exception e) {
}
}
}
}
}
protected JButton makeToolButton(String imageName, String actionCommand, String toolTipText,
String altText) {
// URL imageURL = BioSim.class.getResource(imageName);
// Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
button.setIcon(new ImageIcon(imageName));
// if (imageURL != null) { //image found
// button.setIcon(new ImageIcon(imageURL, altText));
// } else { //no image found
// button.setText(altText);
// System.err.println("Resource not found: "
// + imageName);
return button;
}
public static SBMLDocument readSBML(String filename) {
SBMLReader reader = new SBMLReader();
SBMLDocument document = reader.readSBML(filename);
JTextArea messageArea = new JTextArea();
messageArea.append("Conversion to SBML level " + SBML_LEVEL + " version " + SBML_VERSION
+ " produced the errors listed below. ");
messageArea
.append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n");
boolean display = false;
long numErrors = document.checkL2v4Compatibility();
if (numErrors > 0) {
display = true;
messageArea
.append("
messageArea.append(filename);
messageArea
.append("\n
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage();
messageArea.append(i + ":" + error + "\n");
}
}
if (display) {
final JFrame f = new JFrame("SBML Conversion Errors and Warnings");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.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;
f.setLocation(x, y);
f.setVisible(true);
}
document.setLevelAndVersion(SBML_LEVEL, SBML_VERSION);
return document;
}
}
|
package net.qbar.common.grid;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import java.util.EnumMap;
public interface ITileCable<T extends CableGrid> extends ITileNode<T>
{
EnumMap<EnumFacing, ITileCable<T>> getConnectionsMap();
default void adjacentConnect()
{
for (final EnumFacing facing : EnumFacing.VALUES)
{
final TileEntity adjacent = this.getBlockWorld().getTileEntity(this.getAdjacentPos(facing));
if (adjacent != null && adjacent instanceof ITileCable && this.canConnect((ITileCable<?>) adjacent)
&& ((ITileCable<?>) adjacent).canConnect(this))
{
this.connect(facing, (ITileCable<T>) adjacent);
((ITileCable<T>) adjacent).connect(facing.getOpposite(), this);
}
}
}
default BlockPos getAdjacentPos(final EnumFacing facing)
{
return this.getBlockPos().offset(facing);
}
default int[] getConnections()
{
return this.getConnectionsMap().keySet().stream().mapToInt(EnumFacing::ordinal).toArray();
}
default ITileCable<T> getConnected(int edge)
{
return this.getConnected(EnumFacing.VALUES[edge]);
}
default ITileCable<T> getConnected(EnumFacing facing)
{
return this.getConnectionsMap().get(facing);
}
default void connect(EnumFacing facing, ITileCable<T> to)
{
this.getConnectionsMap().put(facing, to);
}
default void disconnect(EnumFacing facing)
{
this.getConnectionsMap().remove(facing);
}
@Override
default void disconnect(int edge)
{
this.disconnect(EnumFacing.VALUES[edge]);
}
@Override
default int invertEdge(int edge)
{
return EnumFacing.VALUES[edge].getOpposite().ordinal();
}
}
|
package org.openrtb.common.model;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
@JsonSerialize(include = Inclusion.NON_DEFAULT)
@JsonPropertyOrder( { "requestToken", "statusCode", "statusMessage" })
public class Status {
@JsonProperty("requestToken")
private String requestToken;
@JsonProperty("statusCode")
private int statusCode;
@JsonProperty("statusMessage")
private String statusMessage;
public Status() {
this(null, 0, null);
}
public Status(String requestToken, int statusCode, String statusMessage) {
this.requestToken = requestToken;
this.statusCode = statusCode;
this.statusMessage = statusMessage;
}
public String getRequestToken() {
return requestToken;
}
public void setRequestToken(String requestToken) {
this.requestToken = requestToken;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
}
|
package roart.common.util;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InetUtil {
private Logger log = LoggerFactory.getLogger(this.getClass());
public boolean checkMe(String host, int port, int timeout) {
int exitStatus = 1 ;
Socket s = null;
String reason = null ;
try {
s = new Socket();
s.setReuseAddress(true);
SocketAddress sa = new InetSocketAddress(host, port);
s.connect(sa, timeout);
} catch (IOException e) {
if ( e.getMessage().equals("Connection refused")) {
reason = "port " + port + " on " + host + " is closed.";
};
if ( e instanceof UnknownHostException ) {
reason = "node " + host + " is unresolved.";
}
if ( e instanceof SocketTimeoutException ) {
reason = "timeout while attempting to reach node " + host + " on port " + port;
}
} finally {
if (s != null) {
if ( s.isConnected()) {
log.info("Port " + port + " on " + host + " is reachable!");
exitStatus = 0;
} else {
log.info("Port " + port + " on " + host + " is not reachable; reason: " + reason );
}
try {
s.close();
} catch (IOException e) {
}
return s.isConnected();
}
return false;
}
}
public String handleServer(String serverurl) {
String server = serverurl.substring(7);
String[] serversplit = server.split(":");
String host = serversplit[0];
Integer port = Integer.valueOf(serversplit[1]);
boolean up = checkMe(host, port, 500);
if (up) {
return serverurl;
}
return null;
}
public List<String> getServers(String serverString) {
String[] servers = serverString.split(",");
// not parallelStream yet, pri list
return Arrays.asList(servers).stream().map(server -> handleServer(server)).filter(server -> server != null).collect(Collectors.toList());
}
}
|
// LIFReader.java
package loci.formats.in;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.common.xml.XMLTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.ImageTools;
import loci.formats.MetadataTools;
import loci.formats.meta.IMetadata;
import loci.formats.meta.MetadataStore;
import ome.xml.model.primitives.PositiveFloat;
import loci.formats.services.OMEXMLService;
import ome.xml.model.enums.DetectorType;
import ome.xml.model.enums.LaserMedium;
import ome.xml.model.enums.LaserType;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PercentFraction;
import ome.xml.model.primitives.PositiveInteger;
import org.xml.sax.SAXException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class LIFReader extends FormatReader {
// -- Constants --
public static final byte LIF_MAGIC_BYTE = 0x70;
public static final byte LIF_MEMORY_BYTE = 0x2a;
private static final HashMap<String, Integer> CHANNEL_PRIORITIES =
createChannelPriorities();
private static HashMap<String, Integer> createChannelPriorities() {
HashMap<String, Integer> h = new HashMap<String, Integer>();
h.put("red", new Integer(0));
h.put("green", new Integer(1));
h.put("blue", new Integer(2));
h.put("cyan", new Integer(3));
h.put("magenta", new Integer(4));
h.put("yellow", new Integer(5));
h.put("black", new Integer(6));
h.put("gray", new Integer(7));
h.put("", new Integer(8));
return h;
}
private static final byte[][][] BYTE_LUTS = createByteLUTs();
private static byte[][][] createByteLUTs() {
byte[][][] lut = new byte[9][3][256];
for (int i=0; i<256; i++) {
// red
lut[0][0][i] = (byte) (i & 0xff);
// green
lut[1][1][i] = (byte) (i & 0xff);
// blue
lut[2][2][i] = (byte) (i & 0xff);
// cyan
lut[3][1][i] = (byte) (i & 0xff);
lut[3][2][i] = (byte) (i & 0xff);
// magenta
lut[4][0][i] = (byte) (i & 0xff);
lut[4][2][i] = (byte) (i & 0xff);
// yellow
lut[5][0][i] = (byte) (i & 0xff);
lut[5][1][i] = (byte) (i & 0xff);
// gray
lut[6][0][i] = (byte) (i & 0xff);
lut[6][1][i] = (byte) (i & 0xff);
lut[6][2][i] = (byte) (i & 0xff);
lut[7][0][i] = (byte) (i & 0xff);
lut[7][1][i] = (byte) (i & 0xff);
lut[7][2][i] = (byte) (i & 0xff);
lut[8][0][i] = (byte) (i & 0xff);
lut[8][1][i] = (byte) (i & 0xff);
lut[8][2][i] = (byte) (i & 0xff);
}
return lut;
}
private static final short[][][] SHORT_LUTS = createShortLUTs();
private static short[][][] createShortLUTs() {
short[][][] lut = new short[9][3][65536];
for (int i=0; i<65536; i++) {
// red
lut[0][0][i] = (short) (i & 0xffff);
// green
lut[1][1][i] = (short) (i & 0xffff);
// blue
lut[2][2][i] = (short) (i & 0xffff);
// cyan
lut[3][1][i] = (short) (i & 0xffff);
lut[3][2][i] = (short) (i & 0xffff);
// magenta
lut[4][0][i] = (short) (i & 0xffff);
lut[4][2][i] = (short) (i & 0xffff);
// yellow
lut[5][0][i] = (short) (i & 0xffff);
lut[5][1][i] = (short) (i & 0xffff);
// gray
lut[6][0][i] = (short) (i & 0xffff);
lut[6][1][i] = (short) (i & 0xffff);
lut[6][2][i] = (short) (i & 0xffff);
lut[7][0][i] = (short) (i & 0xffff);
lut[7][1][i] = (short) (i & 0xffff);
lut[7][2][i] = (short) (i & 0xffff);
lut[8][0][i] = (short) (i & 0xffff);
lut[8][1][i] = (short) (i & 0xffff);
lut[8][2][i] = (short) (i & 0xffff);
}
return lut;
}
// -- Fields --
/** Offsets to memory blocks, paired with their corresponding description. */
private Vector<Long> offsets;
private int[][] realChannel;
private int lastChannel = 0;
private Vector<String> lutNames = new Vector<String>();
private Vector<Double> physicalSizeXs = new Vector<Double>();
private Vector<Double> physicalSizeYs = new Vector<Double>();
private String[] descriptions, microscopeModels, serialNumber;
private Double[] pinholes, zooms, zSteps, tSteps, lensNA;
private Double[][] expTimes, gains;
private Vector[] detectorOffsets;
private String[][] channelNames;
private Vector[] detectorModels, voltages;
private Integer[][] exWaves;
private Vector[] activeDetector;
private HashMap[] detectorIndexes;
private String[] immersions, corrections, objectiveModels;
private Integer[] magnification;
private Double[] posX, posY, posZ;
private Double[] refractiveIndex;
private Vector[] cutIns, cutOuts, filterModels;
private double[][] timestamps;
private Vector[] laserWavelength, laserIntensity;
private ROI[][] imageROIs;
private boolean alternateCenter = false;
private String[] imageNames;
private double[] acquiredDate;
// -- Constructor --
/** Constructs a new Leica LIF reader. */
public LIFReader() {
super("Leica Image File Format", "lif");
domains = new String[] {FormatTools.LM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
return getSizeY();
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 1;
if (!FormatTools.validStream(stream, blockLen, true)) return false;
return stream.read() == LIF_MAGIC_BYTE;
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() {
FormatTools.assertId(currentId, true, 1);
if (getPixelType() != FormatTools.UINT8 || !isIndexed()) return null;
return lastChannel < BYTE_LUTS.length ? BYTE_LUTS[lastChannel] : null;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() {
FormatTools.assertId(currentId, true, 1);
if (getPixelType() != FormatTools.UINT16 || !isIndexed()) return null;
return lastChannel < SHORT_LUTS.length ? SHORT_LUTS[lastChannel] : null;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
if (!isRGB()) {
int[] pos = getZCTCoords(no);
lastChannel = realChannel[series][pos[1]];
}
if (series >= offsets.size()) {
// truncated file; imitate LAS AF and return black planes
Arrays.fill(buf, (byte) 0);
return buf;
}
long offset = offsets.get(series).longValue();
int bytes = FormatTools.getBytesPerPixel(getPixelType());
int bpp = bytes * getRGBChannelCount();
long planeSize = (long) getSizeX() * getSizeY() * bpp;
long nextOffset = series + 1 < offsets.size() ?
offsets.get(series + 1).longValue() : in.length();
int bytesToSkip = (int) (nextOffset - offset - planeSize * getImageCount());
bytesToSkip /= getSizeY();
if ((getSizeX() % 4) == 0) bytesToSkip = 0;
if (offset + (planeSize + bytesToSkip * getSizeY()) * no >= in.length()) {
// truncated file; imitate LAS AF and return black planes
Arrays.fill(buf, (byte) 0);
return buf;
}
in.seek(offset + planeSize * no);
in.skipBytes(bytesToSkip * getSizeY() * no);
if (bytesToSkip == 0) {
readPlane(in, x, y, w, h, buf);
}
else {
in.skipBytes(y * (getSizeX() * bpp + bytesToSkip));
for (int row=0; row<h; row++) {
in.skipBytes(x * bpp);
in.read(buf, row * w * bpp, w * bpp);
in.skipBytes(bpp * (getSizeX() - w - x) + bytesToSkip);
}
}
// color planes are stored in BGR order
if (getRGBChannelCount() == 3) {
ImageTools.bgrToRgb(buf, isInterleaved(), bytes, getRGBChannelCount());
}
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
offsets = null;
realChannel = null;
lastChannel = 0;
lutNames.clear();
physicalSizeXs.clear();
physicalSizeYs.clear();
descriptions = microscopeModels = serialNumber = null;
pinholes = zooms = lensNA = null;
zSteps = tSteps = null;
expTimes = gains = null;
detectorOffsets = null;
channelNames = null;
detectorModels = voltages = null;
exWaves = null;
activeDetector = null;
immersions = corrections = null;
magnification = null;
objectiveModels = null;
posX = posY = posZ = null;
refractiveIndex = null;
cutIns = cutOuts = filterModels = null;
timestamps = null;
laserWavelength = laserIntensity = null;
imageROIs = null;
alternateCenter = false;
imageNames = null;
acquiredDate = null;
detectorIndexes = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
offsets = new Vector<Long>();
in.order(true);
// read the header
LOGGER.info("Reading header");
byte checkOne = in.readByte();
in.skipBytes(2);
byte checkTwo = in.readByte();
if (checkOne != LIF_MAGIC_BYTE && checkTwo != LIF_MAGIC_BYTE) {
throw new FormatException(id + " is not a valid Leica LIF file");
}
in.skipBytes(4);
// read and parse the XML description
if (in.read() != LIF_MEMORY_BYTE) {
throw new FormatException("Invalid XML description");
}
// number of Unicode characters in the XML block
int nc = in.readInt();
String xml = DataTools.stripString(in.readString(nc * 2));
LOGGER.info("Finding image offsets");
while (in.getFilePointer() < in.length()) {
LOGGER.debug("Looking for a block at {}; {} blocks read",
in.getFilePointer(), offsets.size());
int check = in.readInt();
if (check != LIF_MAGIC_BYTE) {
throw new FormatException("Invalid Memory Block: found magic bytes " +
check + ", expected " + LIF_MAGIC_BYTE);
}
in.skipBytes(4);
check = in.read();
if (check != LIF_MEMORY_BYTE) {
throw new FormatException("Invalid Memory Description: found magic " +
"byte " + check + ", expected " + LIF_MEMORY_BYTE);
}
long blockLength = in.readInt();
if (in.read() != LIF_MEMORY_BYTE) {
in.seek(in.getFilePointer() - 5);
blockLength = in.readLong();
check = in.read();
if (check != LIF_MEMORY_BYTE) {
throw new FormatException("Invalid Memory Description: found magic " +
"byte " + check + ", expected " + LIF_MEMORY_BYTE);
}
}
int descrLength = in.readInt() * 2;
if (blockLength > 0) {
offsets.add(new Long(in.getFilePointer() + descrLength));
}
in.seek(in.getFilePointer() + descrLength + blockLength);
}
initMetadata(xml);
xml = null;
// correct offsets, if necessary
if (offsets.size() > getSeriesCount()) {
Long[] storedOffsets = offsets.toArray(new Long[offsets.size()]);
offsets.clear();
int index = 0;
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
long nBytes = (long) FormatTools.getPlaneSize(this) * getImageCount();
long start = storedOffsets[index];
long end = index == storedOffsets.length - 1 ? in.length() :
storedOffsets[index + 1];
while (end - start < nBytes && ((end - start) / nBytes) != 1) {
index++;
start = storedOffsets[index];
end = index == storedOffsets.length - 1 ? in.length() :
storedOffsets[index + 1];
}
offsets.add(storedOffsets[index]);
index++;
}
setSeries(0);
}
}
// -- Helper methods --
/** Parses a string of XML and puts the values in a Hashtable. */
private void initMetadata(String xml) throws FormatException, IOException {
IMetadata omexml = null;
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
omexml = service.createOMEXMLMetadata();
}
catch (DependencyException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
}
catch (ServiceException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
}
MetadataStore store = makeFilterMetadata();
MetadataLevel level = getMetadataOptions().getMetadataLevel();
// the XML blocks stored in a LIF file are invalid,
// because they don't have a root node
xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>" + xml +
"</LEICA>";
xml = XMLTools.sanitizeXML(xml);
translateMetadata(getMetadataRoot(xml));
for (int i=0; i<imageNames.length; i++) {
setSeries(i);
addSeriesMeta("Image name", imageNames[i]);
}
setSeries(0);
// set up mapping to rearrange channels
// for instance, the green channel may be #0, and the red channel may be #1
realChannel = new int[getSeriesCount()][];
int nextLut = 0;
for (int i=0; i<getSeriesCount(); i++) {
realChannel[i] = new int[core[i].sizeC];
for (int q=0; q<core[i].sizeC; q++) {
String lut = lutNames.get(nextLut++).toLowerCase();
if (!CHANNEL_PRIORITIES.containsKey(lut)) lut = "";
realChannel[i][q] = CHANNEL_PRIORITIES.get(lut).intValue();
}
int[] sorted = new int[core[i].sizeC];
Arrays.fill(sorted, -1);
for (int q=0; q<sorted.length; q++) {
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int n=0; n<core[i].sizeC; n++) {
if (realChannel[i][n] < min && !DataTools.containsValue(sorted, n)) {
min = realChannel[i][n];
minIndex = n;
}
}
sorted[q] = minIndex;
}
}
MetadataTools.populatePixels(store, this, true, false);
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
store.setMicroscopeModel(microscopeModels[i], i);
store.setMicroscopeType(getMicroscopeType("Unknown"), i);
String objectiveID = MetadataTools.createLSID("Objective", i, 0);
store.setObjectiveID(objectiveID, i, 0);
store.setObjectiveLensNA(lensNA[i], i, 0);
store.setObjectiveSerialNumber(serialNumber[i], i, 0);
if (magnification[i] != null && magnification[i] > 0) {
store.setObjectiveNominalMagnification(
new PositiveInteger(magnification[i]), i, 0);
}
store.setObjectiveImmersion(getImmersion(immersions[i]), i, 0);
store.setObjectiveCorrection(getCorrection(corrections[i]), i, 0);
store.setObjectiveModel(objectiveModels[i], i, 0);
if (cutIns[i] != null) {
for (int filter=0; filter<cutIns[i].size(); filter++) {
String filterID = MetadataTools.createLSID("Filter", i, filter);
store.setFilterID(filterID, i, filter);
if (filter < filterModels[i].size()) {
store.setFilterModel(
(String) filterModels[i].get(filter), i, filter);
}
int channel = filter - (cutIns[i].size() - getEffectiveSizeC());
if (channel >= 0 && channel < getEffectiveSizeC()) {
store.setLightPathEmissionFilterRef(filterID, i, channel, 0);
}
store.setTransmittanceRangeCutIn(
(PositiveInteger) cutIns[i].get(filter), i, filter);
store.setTransmittanceRangeCutOut(
(PositiveInteger) cutOuts[i].get(filter), i, filter);
}
}
Vector lasers = laserWavelength[i];
Vector laserIntensities = laserIntensity[i];
int nextChannel = 0;
if (lasers != null) {
int laserIndex = 0;
while (laserIndex < lasers.size()) {
if ((Integer) lasers.get(laserIndex) == 0) {
lasers.removeElementAt(laserIndex);
}
else {
laserIndex++;
}
}
for (int laser=0; laser<lasers.size(); laser++) {
String id = MetadataTools.createLSID("LightSource", i, laser);
store.setLaserID(id, i, laser);
store.setLaserType(LaserType.OTHER, i, laser);
store.setLaserLaserMedium(LaserMedium.OTHER, i, laser);
Integer wavelength = (Integer) lasers.get(laser);
if (wavelength > 0) {
store.setLaserWavelength(new PositiveInteger(wavelength), i, laser);
}
}
Vector<Integer> validIntensities = new Vector<Integer>();
for (int laser=0; laser<laserIntensities.size(); laser++) {
double intensity = (Double) laserIntensities.get(laser);
if (intensity < 100) {
validIntensities.add(laser);
}
}
int start = validIntensities.size() - getEffectiveSizeC();
if (start < 0) {
start = 0;
}
boolean noNames = true;
for (String name : channelNames[i]) {
if (!name.equals("")) {
noNames = false;
break;
}
}
for (int k=start; k<validIntensities.size(); k++, nextChannel++) {
int index = validIntensities.get(k);
double intensity = (Double) laserIntensities.get(index);
int laser = index % lasers.size();
Integer wavelength = (Integer) lasers.get(laser);
if (wavelength != 0) {
while (channelNames != null && nextChannel < getEffectiveSizeC() &&
(channelNames[i][nextChannel].equals("") && !noNames))
{
nextChannel++;
}
if (nextChannel < getEffectiveSizeC()) {
String id = MetadataTools.createLSID("LightSource", i, laser);
store.setChannelLightSourceSettingsID(id, i, nextChannel);
store.setChannelLightSourceSettingsAttenuation(
new PercentFraction((float) intensity / 100f), i, nextChannel);
store.setChannelExcitationWavelength(
new PositiveInteger(wavelength), i, nextChannel);
}
}
}
}
store.setImageInstrumentRef(instrumentID, i);
store.setImageObjectiveSettingsID(objectiveID, i);
store.setImageObjectiveSettingsRefractiveIndex(refractiveIndex[i], i);
store.setImageDescription(descriptions[i], i);
if (acquiredDate[i] > 0) {
store.setImageAcquiredDate(DateTools.convertDate(
(long) (acquiredDate[i] * 1000), DateTools.COBOL), i);
}
store.setImageName(imageNames[i].trim(), i);
if (physicalSizeXs.get(i) > 0) {
store.setPixelsPhysicalSizeX(
new PositiveFloat(physicalSizeXs.get(i)), i);
}
if (physicalSizeYs.get(i) > 0) {
store.setPixelsPhysicalSizeY(
new PositiveFloat(physicalSizeYs.get(i)), i);
}
if (zSteps[i] != null && zSteps[i] > 0) {
store.setPixelsPhysicalSizeZ(new PositiveFloat(zSteps[i]), i);
}
store.setPixelsTimeIncrement(tSteps[i], i);
Vector detectors = detectorModels[i];
if (detectors != null) {
nextChannel = 0;
for (int detector=0; detector<detectors.size(); detector++) {
String detectorID = MetadataTools.createLSID("Detector", i, detector);
store.setDetectorID(detectorID, i, detector);
store.setDetectorModel((String) detectors.get(detector), i, detector);
store.setDetectorZoom(zooms[i], i, detector);
store.setDetectorType(DetectorType.PMT, i, detector);
if (voltages[i] != null && detector < voltages[i].size()) {
store.setDetectorVoltage(
(Double) voltages[i].get(detector), i, detector);
}
if (activeDetector[i] != null) {
if (detector < activeDetector[i].size() &&
(Boolean) activeDetector[i].get(detector) &&
detectorOffsets[i] != null &&
nextChannel < detectorOffsets[i].size())
{
store.setDetectorOffset(
(Double) detectorOffsets[i].get(nextChannel++), i, detector);
}
}
}
}
Vector activeDetectors = activeDetector[i];
int firstDetector = activeDetectors == null ? 0 :
activeDetectors.size() - getEffectiveSizeC();
int nextDetector = firstDetector;
for (int c=0; c<getEffectiveSizeC(); c++) {
if (activeDetectors != null) {
while (nextDetector < activeDetectors.size() &&
!(Boolean) activeDetectors.get(nextDetector))
{
nextDetector++;
}
if (nextDetector < activeDetectors.size()) {
String detectorID = MetadataTools.createLSID(
"Detector", i, nextDetector - firstDetector);
store.setDetectorSettingsID(detectorID, i, c);
nextDetector++;
if (detectorOffsets[i] != null && c < detectorOffsets[i].size()) {
store.setDetectorSettingsOffset(
(Double) detectorOffsets[i].get(c), i, c);
}
if (gains[i] != null) {
store.setDetectorSettingsGain(gains[i][c], i, c);
}
}
}
if (channelNames[i] != null) {
store.setChannelName(channelNames[i][c], i, c);
}
store.setChannelPinholeSize(pinholes[i], i, c);
if (exWaves[i] != null && exWaves[i][c] != null && exWaves[i][c] > 1) {
store.setChannelExcitationWavelength(
new PositiveInteger(exWaves[i][c]), i, c);
}
if (expTimes[i] != null) {
store.setPlaneExposureTime(expTimes[i][c], i, c);
}
}
for (int image=0; image<getImageCount(); image++) {
store.setPlanePositionX(posX[i], i, image);
store.setPlanePositionY(posY[i], i, image);
store.setPlanePositionZ(posZ[i], i, image);
if (timestamps[i] != null) {
double timestamp = timestamps[i][image];
if (timestamps[i][0] == acquiredDate[i]) {
timestamp -= acquiredDate[i];
}
store.setPlaneDeltaT(timestamp, i, image);
}
}
if (imageROIs[i] != null) {
for (int roi=0; roi<imageROIs[i].length; roi++) {
if (imageROIs[i][roi] != null) {
imageROIs[i][roi].storeROI(store, i, roi);
}
}
}
}
}
private Element getMetadataRoot(String xml)
throws FormatException, IOException
{
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
ByteArrayInputStream s = new ByteArrayInputStream(xml.getBytes());
Element root = parser.parse(s).getDocumentElement();
s.close();
return root;
}
catch (ParserConfigurationException e) {
throw new FormatException(e);
}
catch (SAXException e) {
throw new FormatException(e);
}
}
private void translateMetadata(Element root) throws FormatException {
Element realRoot = (Element) root.getChildNodes().item(0);
NodeList toPrune = getNodes(realRoot, "LDM_Block_Sequential_Master");
if (toPrune != null) {
for (int i=0; i<toPrune.getLength(); i++) {
Element prune = (Element) toPrune.item(i);
Element parent = (Element) prune.getParentNode();
parent.removeChild(prune);
}
}
NodeList imageNodes = getNodes(realRoot, "Image");
core = new CoreMetadata[imageNodes.getLength()];
acquiredDate = new double[imageNodes.getLength()];
descriptions = new String[imageNodes.getLength()];
laserWavelength = new Vector[imageNodes.getLength()];
laserIntensity = new Vector[imageNodes.getLength()];
timestamps = new double[imageNodes.getLength()][];
activeDetector = new Vector[imageNodes.getLength()];
voltages = new Vector[imageNodes.getLength()];
detectorOffsets = new Vector[imageNodes.getLength()];
serialNumber = new String[imageNodes.getLength()];
lensNA = new Double[imageNodes.getLength()];
magnification = new Integer[imageNodes.getLength()];
immersions = new String[imageNodes.getLength()];
corrections = new String[imageNodes.getLength()];
objectiveModels = new String[imageNodes.getLength()];
posX = new Double[imageNodes.getLength()];
posY = new Double[imageNodes.getLength()];
posZ = new Double[imageNodes.getLength()];
refractiveIndex = new Double[imageNodes.getLength()];
cutIns = new Vector[imageNodes.getLength()];
cutOuts = new Vector[imageNodes.getLength()];
filterModels = new Vector[imageNodes.getLength()];
microscopeModels = new String[imageNodes.getLength()];
detectorModels = new Vector[imageNodes.getLength()];
detectorIndexes = new HashMap[imageNodes.getLength()];
zSteps = new Double[imageNodes.getLength()];
tSteps = new Double[imageNodes.getLength()];
pinholes = new Double[imageNodes.getLength()];
zooms = new Double[imageNodes.getLength()];
expTimes = new Double[imageNodes.getLength()][];
gains = new Double[imageNodes.getLength()][];
channelNames = new String[imageNodes.getLength()][];
exWaves = new Integer[imageNodes.getLength()][];
imageROIs = new ROI[imageNodes.getLength()][];
imageNames = new String[imageNodes.getLength()];
for (int i=0; i<imageNodes.getLength(); i++) {
Element image = (Element) imageNodes.item(i);
setSeries(i);
translateImageNames(image, i);
translateImageNodes(image, i);
translateAttachmentNodes(image, i);
translateScannerSettings(image, i);
translateFilterSettings(image, i);
translateTimestamps(image, i);
translateLaserLines(image, i);
translateROIs(image, i);
translateSingleROIs(image, i);
translateDetectors(image, i);
Stack<String> nameStack = new Stack<String>();
HashMap<String, Integer> indexes = new HashMap<String, Integer>();
populateOriginalMetadata(image, nameStack, indexes);
indexes.clear();
}
setSeries(0);
}
private void populateOriginalMetadata(Element root, Stack<String> nameStack,
HashMap<String, Integer> indexes)
{
String name = root.getNodeName();
if (root.hasAttributes() && !name.equals("Element") &&
!name.equals("Attachment") && !name.equals("LMSDataContainerHeader"))
{
nameStack.push(name);
String suffix = root.getAttribute("Identifier");
String value = root.getAttribute("Variant");
if (suffix == null || suffix.trim().length() == 0) {
suffix = root.getAttribute("Description");
}
StringBuffer key = new StringBuffer();
for (String k : nameStack) {
key.append(k);
key.append("|");
}
if (suffix != null && value != null && suffix.length() > 0 &&
value.length() > 0 && !suffix.equals("HighInteger") &&
!suffix.equals("LowInteger"))
{
Integer i = indexes.get(key.toString() + suffix);
String storedKey = key.toString() + suffix + " " + (i == null ? 0 : i);
indexes.put(key.toString() + suffix, i == null ? 1 : i + 1);
addSeriesMeta(storedKey, value);
}
else {
NamedNodeMap attributes = root.getAttributes();
for (int i=0; i<attributes.getLength(); i++) {
Attr attr = (Attr) attributes.item(i);
if (!attr.getName().equals("HighInteger") &&
!attr.getName().equals("LowInteger"))
{
Integer index = indexes.get(key.toString() + attr.getName());
if (index == null) {
index = 0;
}
String storedKey = key.toString() + attr.getName() + " " + index;
indexes.put(key.toString() + attr.getName(), index + 1);
addSeriesMeta(storedKey, attr.getValue());
}
}
}
}
NodeList children = root.getChildNodes();
for (int i=0; i<children.getLength(); i++) {
Object child = children.item(i);
if (child instanceof Element) {
populateOriginalMetadata((Element) child, nameStack, indexes);
}
}
if (root.hasAttributes() && !name.equals("Element") &&
!name.equals("Attachment") && !name.equals("LMSDataContainerHeader"))
{
nameStack.pop();
}
}
private void translateImageNames(Element imageNode, int image) {
Vector<String> names = new Vector<String>();
Element parent = imageNode;
while (true) {
parent = (Element) parent.getParentNode();
if (parent == null || parent.getNodeName().equals("LEICA")) {
break;
}
if (parent.getNodeName().equals("Element")) {
names.add(parent.getAttribute("Name"));
}
}
imageNames[image] = "";
for (int i=names.size() - 2; i>=0; i
imageNames[image] += names.get(i);
if (i > 0) imageNames[image] += "/";
}
}
private void translateDetectors(Element imageNode, int image)
throws FormatException
{
NodeList definitions = getNodes(imageNode, "ATLConfocalSettingDefinition");
if (definitions == null) return;
Vector<String> channels = new Vector<String>();
int nextChannel = 0;
for (int definition=0; definition<definitions.getLength(); definition++) {
Element definitionNode = (Element) definitions.item(definition);
NodeList detectors = getNodes(definitionNode, "Detector");
if (detectors == null) return;
for (int d=0; d<detectors.getLength(); d++) {
Element detector = (Element) detectors.item(d);
NodeList multibands = getNodes(definitionNode, "MultiBand");
String v = detector.getAttribute("Gain");
Double gain =
v == null || v.trim().length() == 0 ? null : new Double(v);
v = detector.getAttribute("Offset");
Double offset =
v == null || v.trim().length() == 0 ? null : new Double(v);
boolean active = "1".equals(detector.getAttribute("IsActive"));
if (active) {
String c = detector.getAttribute("Channel");
int channel = c == null ? 0 : Integer.parseInt(c);
detectorModels[image].add(detectorIndexes[image].get(channel));
Element multiband = null;
if (multibands != null) {
for (int i=0; i<multibands.getLength(); i++) {
Element mb = (Element) multibands.item(i);
if (channel == Integer.parseInt(mb.getAttribute("Channel"))) {
multiband = mb;
break;
}
}
}
if (multiband != null) {
channels.add(multiband.getAttribute("DyeName"));
double cutIn = new Double(multiband.getAttribute("LeftWorld"));
double cutOut = new Double(multiband.getAttribute("RightWorld"));
cutIns[image].add(new PositiveInteger((int) Math.round(cutIn)));
cutOuts[image].add(new PositiveInteger((int) Math.round(cutOut)));
}
else {
channels.add("");
}
if (nextChannel < getEffectiveSizeC()) {
gains[image][nextChannel] = gain;
detectorOffsets[image].add(offset);
}
nextChannel++;
}
if (active) {
activeDetector[image].add(active);
}
}
}
for (int i=0; i<getEffectiveSizeC(); i++) {
int index = i + channels.size() - getEffectiveSizeC();
if (index >= 0 && index < channels.size()) {
channelNames[image][i] = channels.get(index);
}
}
}
private void translateROIs(Element imageNode, int image)
throws FormatException
{
NodeList rois = getNodes(imageNode, "Annotation");
if (rois == null) return;
imageROIs[image] = new ROI[rois.getLength()];
for (int r=0; r<rois.getLength(); r++) {
Element roiNode = (Element) rois.item(r);
ROI roi = new ROI();
String type = roiNode.getAttribute("type");
if (type != null) {
roi.type = Integer.parseInt(type);
}
String color = roiNode.getAttribute("color");
if (color != null) {
roi.color = Long.parseLong(color);
}
roi.name = roiNode.getAttribute("name");
roi.fontName = roiNode.getAttribute("fontName");
roi.fontSize = roiNode.getAttribute("fontSize");
roi.transX = parseDouble(roiNode.getAttribute("transTransX"));
roi.transY = parseDouble(roiNode.getAttribute("transTransY"));
roi.scaleX = parseDouble(roiNode.getAttribute("transScalingX"));
roi.scaleY = parseDouble(roiNode.getAttribute("transScalingY"));
roi.rotation = parseDouble(roiNode.getAttribute("transRotation"));
String linewidth = roiNode.getAttribute("linewidth");
if (linewidth != null) {
try {
roi.linewidth = Integer.parseInt(linewidth);
}
catch (NumberFormatException e) { }
}
roi.text = roiNode.getAttribute("text");
NodeList vertices = getNodes(roiNode, "Vertex");
if (vertices == null) {
continue;
}
for (int v=0; v<vertices.getLength(); v++) {
Element vertex = (Element) vertices.item(v);
String xx = vertex.getAttribute("x");
String yy = vertex.getAttribute("y");
if (xx != null) {
roi.x.add(parseDouble(xx));
}
if (yy != null) {
roi.y.add(parseDouble(yy));
}
}
imageROIs[image][r] = roi;
if (getNodes(imageNode, "ROI") != null) {
alternateCenter = true;
}
}
}
private void translateSingleROIs(Element imageNode, int image)
throws FormatException
{
if (imageROIs[image] != null) return;
NodeList children = getNodes(imageNode, "ROI");
if (children == null) return;
children = getNodes((Element) children.item(0), "Children");
if (children == null) return;
children = getNodes((Element) children.item(0), "Element");
if (children == null) return;
imageROIs[image] = new ROI[children.getLength()];
for (int r=0; r<children.getLength(); r++) {
NodeList rois = getNodes((Element) children.item(r), "ROISingle");
Element roiNode = (Element) rois.item(0);
ROI roi = new ROI();
String type = roiNode.getAttribute("RoiType");
if (type != null) {
roi.type = Integer.parseInt(type);
}
String color = roiNode.getAttribute("Color");
if (color != null) {
roi.color = Long.parseLong(color);
}
Element parent = (Element) roiNode.getParentNode();
parent = (Element) parent.getParentNode();
roi.name = parent.getAttribute("Name");
NodeList vertices = getNodes(roiNode, "P");
double sizeX = physicalSizeXs.get(image);
double sizeY = physicalSizeYs.get(image);
for (int v=0; v<vertices.getLength(); v++) {
Element vertex = (Element) vertices.item(v);
String xx = vertex.getAttribute("X");
String yy = vertex.getAttribute("Y");
if (xx != null) {
roi.x.add(parseDouble(xx) / sizeX);
}
if (yy != null) {
roi.y.add(parseDouble(yy) / sizeY);
}
}
Element transform = (Element) getNodes(roiNode, "Transformation").item(0);
roi.rotation = parseDouble(transform.getAttribute("Rotation"));
Element scaling = (Element) getNodes(transform, "Scaling").item(0);
roi.scaleX = parseDouble(scaling.getAttribute("XScale"));
roi.scaleY = parseDouble(scaling.getAttribute("YScale"));
Element translation =
(Element) getNodes(transform, "Translation").item(0);
roi.transX = parseDouble(translation.getAttribute("X")) / sizeX;
roi.transY = parseDouble(translation.getAttribute("Y")) / sizeY;
imageROIs[image][r] = roi;
}
}
private void translateLaserLines(Element imageNode, int image)
throws FormatException
{
NodeList aotfLists = getNodes(imageNode, "AotfList");
if (aotfLists == null) return;
laserWavelength[image] = new Vector<Integer>();
laserIntensity[image] = new Vector<Double>();
int baseIntensityIndex = 0;
for (int channel=0; channel<aotfLists.getLength(); channel++) {
Element aotf = (Element) aotfLists.item(channel);
NodeList laserLines = getNodes(aotf, "LaserLineSetting");
if (laserLines == null) return;
for (int laser=0; laser<laserLines.getLength(); laser++) {
Element laserLine = (Element) laserLines.item(laser);
String lineIndex = laserLine.getAttribute("LineIndex");
String qual = laserLine.getAttribute("Qualifier");
int index = lineIndex == null ? 0 : Integer.parseInt(lineIndex);
int qualifier = qual == null ? 0: Integer.parseInt(qual);
index += (2 - (qualifier / 10));
if (index < 0) index = 0;
Integer wavelength = new Integer(laserLine.getAttribute("LaserLine"));
if (index < laserWavelength[image].size()) {
laserWavelength[image].setElementAt(wavelength, index);
}
else {
for (int i=laserWavelength[image].size(); i<index; i++) {
laserWavelength[image].add(new Integer(0));
}
laserWavelength[image].add(wavelength);
}
String intensity = laserLine.getAttribute("IntensityDev");
double realIntensity = intensity == null ? 0d : new Double(intensity);
realIntensity = 100d - realIntensity;
int realIndex = baseIntensityIndex + index;
if (realIndex < laserIntensity[image].size()) {
laserIntensity[image].setElementAt(realIntensity, realIndex);
}
else {
while (realIndex < laserIntensity[image].size()) {
laserIntensity[image].add(100d);
}
laserIntensity[image].add(realIntensity);
}
}
baseIntensityIndex += laserWavelength[image].size();
}
}
private void translateTimestamps(Element imageNode, int image)
throws FormatException
{
NodeList timestampNodes = getNodes(imageNode, "TimeStamp");
if (timestampNodes == null) return;
timestamps[image] = new double[getImageCount()];
if (timestampNodes != null) {
for (int stamp=0; stamp<timestampNodes.getLength(); stamp++) {
if (stamp < getImageCount()) {
Element timestamp = (Element) timestampNodes.item(stamp);
String stampHigh = timestamp.getAttribute("HighInteger");
String stampLow = timestamp.getAttribute("LowInteger");
long high = stampHigh == null ? 0 : Long.parseLong(stampHigh);
long low = stampLow == null ? 0 : Long.parseLong(stampLow);
long ms = DateTools.getMillisFromTicks(high, low);
timestamps[image][stamp] = ms / 1000.0;
}
}
}
acquiredDate[image] = timestamps[image][0];
NodeList relTimestampNodes = getNodes(imageNode, "RelTimeStamp");
if (relTimestampNodes != null) {
for (int stamp=0; stamp<relTimestampNodes.getLength(); stamp++) {
if (stamp < getImageCount()) {
Element timestamp = (Element) relTimestampNodes.item(stamp);
timestamps[image][stamp] =
new Double(timestamp.getAttribute("Time"));
}
}
}
}
private void translateFilterSettings(Element imageNode, int image)
throws FormatException
{
NodeList filterSettings = getNodes(imageNode, "FilterSettingRecord");
if (filterSettings == null) return;
activeDetector[image] = new Vector<Boolean>();
voltages[image] = new Vector<Double>();
detectorOffsets[image] = new Vector<Double>();
cutIns[image] = new Vector<PositiveInteger>();
cutOuts[image] = new Vector<PositiveInteger>();
filterModels[image] = new Vector<String>();
detectorIndexes[image] = new HashMap<Integer, String>();
for (int i=0; i<filterSettings.getLength(); i++) {
Element filterSetting = (Element) filterSettings.item(i);
String object = filterSetting.getAttribute("ObjectName");
String attribute = filterSetting.getAttribute("Attribute");
String objectClass = filterSetting.getAttribute("ClassName");
String variant = filterSetting.getAttribute("Variant");
String data = filterSetting.getAttribute("Data");
if (attribute.equals("NumericalAperture")) {
lensNA[image] = new Double(variant);
}
else if (attribute.equals("OrderNumber")) {
serialNumber[image] = variant;
}
else if (objectClass.equals("CDetectionUnit")) {
if (attribute.equals("State")) {
int channel = getChannelIndex(filterSetting);
if (channel < 0) continue;
detectorIndexes[image].put(new Integer(data), object);
activeDetector[image].add(variant.equals("Active"));
}
else if (attribute.equals("HighVoltage")) {
int channel = getChannelIndex(filterSetting);
if (channel < 0) continue;
if (channel < voltages[image].size()) {
voltages[image].setElementAt(new Double(variant), channel);
}
else {
while (channel > voltages[image].size()) {
voltages[image].add(new Double(0));
}
voltages[image].add(new Double(variant));
}
}
else if (attribute.equals("VideoOffset")) {
int channel = getChannelIndex(filterSetting);
if (channel < 0) continue;
detectorOffsets[image].add(new Double(variant));
}
}
else if (attribute.equals("Objective")) {
StringTokenizer tokens = new StringTokenizer(variant, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
int x = token.indexOf("x");
if (x != -1) {
foundMag = true;
int mag = (int) Double.parseDouble(token.substring(0, x));
String na = token.substring(x + 1);
magnification[image] = mag;
lensNA[image] = new Double(na);
}
else {
model.append(token);
model.append(" ");
}
}
String immersion = "Other";
if (tokens.hasMoreTokens()) {
immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Other";
}
}
immersions[image] = immersion;
String correction = "Other";
if (tokens.hasMoreTokens()) {
correction = tokens.nextToken();
if (correction == null || correction.trim().equals("")) {
correction = "Other";
}
}
corrections[image] = correction;
objectiveModels[image] = model.toString().trim();
}
else if (attribute.equals("RefractionIndex")) {
refractiveIndex[image] = new Double(variant);
}
else if (attribute.equals("XPos")) {
posX[image] = new Double(variant);
}
else if (attribute.equals("YPos")) {
posY[image] = new Double(variant);
}
else if (attribute.equals("ZPos")) {
posZ[image] = new Double(variant);
}
else if (objectClass.equals("CSpectrophotometerUnit")) {
Integer v = null;
try {
v = new Integer((int) Double.parseDouble(variant));
}
catch (NumberFormatException e) { }
String description = filterSetting.getAttribute("Description");
if (description.endsWith("(left)")) {
filterModels[image].add(object);
if (v != null) {
cutIns[image].add(new PositiveInteger(v));
}
}
else if (description.endsWith("(right)")) {
if (v != null) {
cutOuts[image].add(new PositiveInteger(v));
}
}
}
}
}
private void translateScannerSettings(Element imageNode, int image)
throws FormatException
{
NodeList scannerSettings = getNodes(imageNode, "ScannerSettingRecord");
if (scannerSettings == null) return;
expTimes[image] = new Double[getEffectiveSizeC()];
gains[image] = new Double[getEffectiveSizeC()];
channelNames[image] = new String[getEffectiveSizeC()];
exWaves[image] = new Integer[getEffectiveSizeC()];
detectorModels[image] = new Vector<String>();
for (int i=0; i<scannerSettings.getLength(); i++) {
Element scannerSetting = (Element) scannerSettings.item(i);
String id = scannerSetting.getAttribute("Identifier");
if (id == null) id = "";
String suffix = scannerSetting.getAttribute("Identifier");
String value = scannerSetting.getAttribute("Variant");
if (id.equals("SystemType")) {
microscopeModels[image] = value;
}
else if (id.equals("dblPinhole")) {
pinholes[image] = Double.parseDouble(value) * 1000000;
}
else if (id.equals("dblZoom")) {
zooms[image] = new Double(value);
}
else if (id.equals("dblStepSize")) {
zSteps[image] = Double.parseDouble(value) * 1000000;
}
else if (id.equals("nDelayTime_s")) {
tSteps[image] = new Double(value);
}
else if (id.equals("CameraName")) {
detectorModels[image].add(value);
}
else if (id.equals("eDirectional")) {
addSeriesMeta("Reverse X orientation", value.equals("1"));
}
else if (id.equals("eDirectionalY")) {
addSeriesMeta("Reverse Y orientation", value.equals("1"));
}
else if (id.indexOf("WFC") == 1) {
int c = 0;
try {
c = Integer.parseInt(id.replaceAll("\\D", ""));
}
catch (NumberFormatException e) { }
if (c < 0 || c >= getEffectiveSizeC()) {
continue;
}
if (id.endsWith("ExposureTime")) {
expTimes[image][c] = new Double(value);
}
else if (id.endsWith("Gain")) {
gains[image][c] = new Double(value);
}
else if (id.endsWith("WaveLength")) {
Integer exWave = new Integer(value);
if (exWave > 0) {
exWaves[image][c] = exWave;
}
}
// NB: "UesrDefName" is not a typo.
else if (id.endsWith("UesrDefName") && !value.equals("None")) {
channelNames[image][c] = value;
}
}
}
}
private void translateAttachmentNodes(Element imageNode, int image)
throws FormatException
{
NodeList attachmentNodes = getNodes(imageNode, "Attachment");
if (attachmentNodes == null) return;
for (int i=0; i<attachmentNodes.getLength(); i++) {
Element attachment = (Element) attachmentNodes.item(i);
if ("ContextDescription".equals(attachment.getAttribute("Name"))) {
descriptions[image] = attachment.getAttribute("Content");
}
}
}
private void translateImageNodes(Element imageNode, int i)
throws FormatException
{
core[i] = new CoreMetadata();
core[i].orderCertain = true;
core[i].metadataComplete = true;
core[i].littleEndian = true;
core[i].falseColor = true;
NodeList channels = getChannelDescriptionNodes(imageNode);
NodeList dimensions = getDimensionDescriptionNodes(imageNode);
HashMap<Long, String> bytesPerAxis = new HashMap<Long, String>();
Double physicalSizeX = null;
Double physicalSizeY = null;
core[i].sizeC = channels.getLength();
for (int ch=0; ch<channels.getLength(); ch++) {
Element channel = (Element) channels.item(ch);
lutNames.add(channel.getAttribute("LUTName"));
String bytesInc = channel.getAttribute("BytesInc");
long bytes = bytesInc == null ? 0 : Long.parseLong(bytesInc);
if (bytes > 0) {
bytesPerAxis.put(bytes, "C");
}
}
int extras = 1;
for (int dim=0; dim<dimensions.getLength(); dim++) {
Element dimension = (Element) dimensions.item(dim);
int id = Integer.parseInt(dimension.getAttribute("DimID"));
int len = Integer.parseInt(dimension.getAttribute("NumberOfElements"));
long nBytes = Long.parseLong(dimension.getAttribute("BytesInc"));
Double physicalLen = new Double(dimension.getAttribute("Length"));
String unit = dimension.getAttribute("Unit");
physicalLen /= len;
if (unit.equals("Ks")) {
physicalLen /= 1000;
}
else if (unit.equals("m")) {
physicalLen *= 1000000;
}
switch (id) {
case 1: // X axis
core[i].sizeX = len;
core[i].rgb = (nBytes % 3) == 0;
if (core[i].rgb) nBytes /= 3;
core[i].pixelType =
FormatTools.pixelTypeFromBytes((int) nBytes, false, true);
physicalSizeX = physicalLen;
break;
case 2: // Y axis
if (core[i].sizeY != 0) {
if (core[i].sizeZ == 1) {
core[i].sizeZ = len;
bytesPerAxis.put(nBytes, "Z");
}
else if (core[i].sizeT == 1) {
core[i].sizeT = len;
bytesPerAxis.put(nBytes, "T");
}
}
else {
core[i].sizeY = len;
physicalSizeY = physicalLen;
}
break;
case 3: // Z axis
if (core[i].sizeY == 0) {
// XZ scan - swap Y and Z
core[i].sizeY = len;
core[i].sizeZ = 1;
bytesPerAxis.put(nBytes, "Y");
physicalSizeY = physicalLen;
}
else {
core[i].sizeZ = len;
bytesPerAxis.put(nBytes, "Z");
}
break;
case 4: // T axis
if (core[i].sizeY == 0) {
// XT scan - swap Y and T
core[i].sizeY = len;
core[i].sizeT = 1;
bytesPerAxis.put(nBytes, "Y");
physicalSizeY = physicalLen;
}
else {
core[i].sizeT = len;
bytesPerAxis.put(nBytes, "T");
}
break;
default:
extras *= len;
}
}
physicalSizeXs.add(physicalSizeX);
physicalSizeYs.add(physicalSizeY);
if (extras > 1) {
if (core[i].sizeZ == 1) core[i].sizeZ = extras;
else {
if (core[i].sizeT == 0) core[i].sizeT = extras;
else core[i].sizeT *= extras;
}
}
if (core[i].sizeC == 0) core[i].sizeC = 1;
if (core[i].sizeZ == 0) core[i].sizeZ = 1;
if (core[i].sizeT == 0) core[i].sizeT = 1;
core[i].interleaved = core[i].rgb;
core[i].indexed = !core[i].rgb;
core[i].imageCount = core[i].sizeZ * core[i].sizeT;
if (!core[i].rgb) core[i].imageCount *= core[i].sizeC;
Long[] bytes = bytesPerAxis.keySet().toArray(new Long[0]);
Arrays.sort(bytes);
core[i].dimensionOrder = "XY";
for (Long nBytes : bytes) {
String axis = bytesPerAxis.get(nBytes);
if (core[i].dimensionOrder.indexOf(axis) == -1) {
core[i].dimensionOrder += axis;
}
}
if (core[i].dimensionOrder.indexOf("Z") == -1) {
core[i].dimensionOrder += "Z";
}
if (core[i].dimensionOrder.indexOf("C") == -1) {
core[i].dimensionOrder += "C";
}
if (core[i].dimensionOrder.indexOf("T") == -1) {
core[i].dimensionOrder += "T";
}
}
private NodeList getNodes(Element root, String nodeName) {
NodeList nodes = root.getElementsByTagName(nodeName);
if (nodes.getLength() == 0) {
NodeList children = root.getChildNodes();
for (int i=0; i<children.getLength(); i++) {
Object child = children.item(i);
if (child instanceof Element) {
NodeList childNodes = getNodes((Element) child, nodeName);
if (childNodes != null) {
return childNodes;
}
}
}
return null;
}
else return nodes;
}
private Element getImageDescription(Element root) {
return (Element) root.getElementsByTagName("ImageDescription").item(0);
}
private NodeList getChannelDescriptionNodes(Element root) {
Element imageDescription = getImageDescription(root);
Element channels =
(Element) imageDescription.getElementsByTagName("Channels").item(0);
return channels.getElementsByTagName("ChannelDescription");
}
private NodeList getDimensionDescriptionNodes(Element root) {
Element imageDescription = getImageDescription(root);
Element channels =
(Element) imageDescription.getElementsByTagName("Dimensions").item(0);
return channels.getElementsByTagName("DimensionDescription");
}
private int getChannelIndex(Element filterSetting) {
String data = filterSetting.getAttribute("data");
if (data == null || data.equals("")) {
data = filterSetting.getAttribute("Data");
}
int channel = data == null || data.equals("") ? 0 : Integer.parseInt(data);
if (channel < 0) return -1;
return channel - 1;
}
// -- Helper class --
class ROI {
// -- Constants --
public static final int TEXT = 512;
public static final int SCALE_BAR = 8192;
public static final int POLYGON = 32;
public static final int RECTANGLE = 16;
public static final int LINE = 256;
public static final int ARROW = 2;
// -- Fields --
public int type;
public Vector<Double> x = new Vector<Double>();
public Vector<Double> y = new Vector<Double>();
// center point of the ROI
public double transX, transY;
// transformation parameters
public double scaleX, scaleY;
public double rotation;
public long color;
public int linewidth;
public String text;
public String fontName;
public String fontSize;
public String name;
private boolean normalized = false;
// -- ROI API methods --
public void storeROI(MetadataStore store, int series, int roi) {
MetadataLevel level = getMetadataOptions().getMetadataLevel();
if (level == MetadataLevel.NO_OVERLAYS || level == MetadataLevel.MINIMUM)
{
return;
}
// keep in mind that vertices are given relative to the center
// point of the ROI and the transX/transY values are relative to
// the center point of the image
store.setROIID(MetadataTools.createLSID("ROI", roi), roi);
store.setTextID(MetadataTools.createLSID("Shape", roi, 0), roi, 0);
if (text == null) {
text = name;
}
store.setTextValue(text, roi, 0);
if (fontSize != null) {
try {
int size = (int) Double.parseDouble(fontSize);
store.setTextFontSize(new NonNegativeInteger(size), roi, 0);
}
catch (NumberFormatException e) { }
}
store.setTextStrokeWidth(new Double(linewidth), roi, 0);
if (!normalized) normalize();
double cornerX = x.get(0).doubleValue();
double cornerY = y.get(0).doubleValue();
store.setTextX(cornerX, roi, 0);
store.setTextY(cornerY, roi, 0);
int centerX = (core[series].sizeX / 2) - 1;
int centerY = (core[series].sizeY / 2) - 1;
double roiX = centerX + transX;
double roiY = centerY + transY;
if (alternateCenter) {
roiX = transX - 2 * cornerX;
roiY = transY - 2 * cornerY;
}
// TODO : rotation/scaling not populated
String shapeID = MetadataTools.createLSID("Shape", roi, 1);
switch (type) {
case POLYGON:
StringBuffer points = new StringBuffer();
for (int i=0; i<x.size(); i++) {
points.append(x.get(i).doubleValue() + roiX);
points.append(",");
points.append(y.get(i).doubleValue() + roiY);
if (i < x.size() - 1) points.append(" ");
}
store.setPolylineID(shapeID, roi, 1);
store.setPolylinePoints(points.toString(), roi, 1);
store.setPolylineClosed(Boolean.TRUE, roi, 1);
break;
case TEXT:
case RECTANGLE:
store.setRectangleID(shapeID, roi, 1);
store.setRectangleX(roiX - Math.abs(cornerX), roi, 1);
store.setRectangleY(roiY - Math.abs(cornerY), roi, 1);
double width = 2 * Math.abs(cornerX);
double height = 2 * Math.abs(cornerY);
store.setRectangleWidth(width, roi, 1);
store.setRectangleHeight(height, roi, 1);
break;
case SCALE_BAR:
case ARROW:
case LINE:
store.setLineID(shapeID, roi, 1);
store.setLineX1(roiX + x.get(0), roi, 1);
store.setLineY1(roiY + y.get(0), roi, 1);
store.setLineX2(roiX + x.get(1), roi, 1);
store.setLineY2(roiY + y.get(1), roi, 1);
break;
}
}
// -- Helper methods --
/**
* Vertices and transformation values are not stored in pixel coordinates.
* We need to convert them from physical coordinates to pixel coordinates
* so that they can be stored in a MetadataStore.
*/
private void normalize() {
if (normalized) return;
// coordinates are in meters
transX *= 1000000;
transY *= 1000000;
transX *= 1;
transY *= 1;
for (int i=0; i<x.size(); i++) {
double coordinate = x.get(i).doubleValue() * 1000000;
coordinate *= 1;
x.setElementAt(coordinate, i);
}
for (int i=0; i<y.size(); i++) {
double coordinate = y.get(i).doubleValue() * 1000000;
coordinate *= 1;
y.setElementAt(coordinate, i);
}
normalized = true;
}
}
private double parseDouble(String number) {
if (number != null) {
number = number.replaceAll(",", ".");
return Double.parseDouble(number);
}
return 0;
}
}
|
package hackerRank;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
public class Down_To_Zero_II {
private static final int UPPER = 1000000;
private static Set<Integer> known = null;
private static Map<Integer, List<Integer>> factors;
// static {
//// // implementing Sieve of Eratosthenes to
//// // pre-compute set of primes till 'UPPER'
//// known = new HashSet<Integer>();
//// for(int i = 2 ; i < UPPER ; i++)
//// known.add(i);
//// // every time, we need to get the smallest number in
//// // our set of 'known', that is greater than 'p'; say,
//// // when p = 2, we store 2 in a temporary variable and then
//// // reset p to 3. When we need to repeat this process for p=3,
//// // we will need to remove both 2 and 3. Instead of taking this
//// // later we simply put these values in a list and add them in later.
//// List<Integer> smallPrimes = new ArrayList<Integer>();
//// int p = Collections.min(known);
//// while(p != Collections.max(known)) {
//// for(int multiplier = 2 ; multiplier <= UPPER/p ; multiplier++)
//// known.remove(multiplier*p);
//// if(Collections.min(known) == p) {
//// smallPrimes.add(p);
//// known.remove(p);
//// p = Collections.min(known);
//// known.addAll(smallPrimes);
//// System.out.println(known);
// // REF: http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
// known = new HashSet<Integer>();
// int n = UPPER;
// boolean correction = (n % 6) > 1;
// // closest number to calculate primes till
// switch(n%6) {
// case 0:
// break;
// case 1:
// n = n-1;
// break;
// case 2:
// n = n+4;
// break;
// case 3:
// n = n+3;
// break;
// case 4:
// n = n+2;
// break;
// case 5:
// n = n+1;
// break;
// boolean[] sieve = new boolean[n/3];
// for(int i = 1 ; i < sieve.length ; i++)
// sieve[i] = true;
// for(int i = 0 ; i < (int)(Math.abs(Math.sqrt(n)) + 1) ; i++) {
// if(sieve[i]) {
// int k = (3*i + 1) | 1;
// // sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)
// int offset = (k*k)/3;
// int stride = 2*k;
// for(int indx = offset ; indx < sieve.length ; indx+=stride)
// sieve[indx] = false;
// // sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1)
// offset = (k * k + 4 * k - 2 * k * (i & 1) ) / 3;
// for(int indx = offset ; indx < sieve.length ; indx+=stride)
// sieve[indx] = false;
// known.add(2);
// known.add(3);
// for(int i = 0 ; i < n/3 - (correction ? 1: 0) ; i++)
// if(sieve[i])
// known.add((3*i + 1) | 1);
// factors = new HashMap<Integer, List<Integer>>();
// for(int i = 2 ; i <= n ; i++) {
// if(known.contains(n))
// continue;
// List<Integer> factorsOfN = new ArrayList<Integer>();
// for(int factor = 2 ; factor < Math.sqrt(i) ; factor++)
// if(i % factor == 0)
// factorsOfN.add( Math.max(factor, i/factor) );
// factors.put(i, factorsOfN);
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int q = scan.nextInt();
while(q > 0) {
int n = scan.nextInt();
preCompute(Math.max(10,n));
System.out.println( takeToZero(n) );
q
}
scan.close();
}
private static void preCompute(int n) {
// REF: http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
known = new HashSet<Integer>();
boolean correction = (n % 6) > 1;
// closest number to calculate primes till
switch(n%6) {
case 0:
break;
case 1:
n = n-1;
break;
case 2:
n = n+4;
break;
case 3:
n = n+3;
break;
case 4:
n = n+2;
break;
case 5:
n = n+1;
break;
}
boolean[] sieve = new boolean[n/3];
for(int i = 1 ; i < sieve.length ; i++)
sieve[i] = true;
for(int i = 0 ; i < (int)(Math.abs(Math.sqrt(n)) + 1) ; i++) {
if(sieve[i]) {
int k = (3*i + 1) | 1;
// sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)
int offset = (k*k)/3;
int stride = 2*k;
for(int indx = offset ; indx < sieve.length ; indx+=stride)
sieve[indx] = false;
// sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1)
offset = (k * k + 4 * k - 2 * k * (i & 1) ) / 3;
for(int indx = offset ; indx < sieve.length ; indx+=stride)
sieve[indx] = false;
}
}
known.add(2);
known.add(3);
for(int i = 0 ; i < n/3 - (correction ? 1: 0) ; i++)
if(sieve[i])
known.add((3*i + 1) | 1);
factors = new HashMap<Integer, List<Integer>>();
for(int i = 2 ; i <= n ; i++) {
if(known.contains(n))
continue;
List<Integer> factorsOfN = new ArrayList<Integer>();
for(int factor = 2 ; factor < Math.sqrt(i) ; factor++)
if(i % factor == 0)
factorsOfN.add( Math.max(factor, i/factor) );
factors.put(i, factorsOfN);
}
}
private static Map<Integer, Integer> cache = new HashMap<Integer, Integer>();
private static int takeToZero(int n) {
if(cache.containsKey(n))
return cache.get(n);
if(n == 0)
return 0;
if(n == 1)
return (1);
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add( 1 + takeToZero(n-1) );
// if number is not prime
if(!known.contains(n)) {
if(!factors.containsKey(n)) {
// add number of steps for each of the factors
for(int i = 2 ; i <= Math.sqrt(n) ; i++)
if(n % i == 0)
pq.add( 1 + takeToZero( Math.max(i, n/i)) );
} else {
for(int factor: factors.get(n) )
pq.add( 1 + takeToZero(factor) );
}
}
cache.put(n, pq.poll());
return cache.get(n);
}
}
|
import com.sun.star.awt.XMessageBox;
import com.sun.star.awt.XWindowPeer;
import com.sun.star.frame.XDesktop;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.lang.*;
import com.sun.star.frame.XModel;
import com.sun.star.frame.XController;
// application specific classes
import com.sun.star.chart.*;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.XInterface;
import com.sun.star.view.XSelectionChangeListener;
import com.sun.star.view.XSelectionSupplier;
import com.sun.star.table.CellRangeAddress;
import com.sun.star.table.XCellRange;
import com.sun.star.sheet.XCellRangeAddressable;
import com.sun.star.awt.Point;
import com.sun.star.awt.Rectangle;
import com.sun.star.awt.Size;
import com.sun.star.awt.XMessageBoxFactory;
import com.sun.star.awt.XWindow;
/** Create a spreadsheet add some data.
* Create a presentation and add a chart.
* Connect the chart to a calc range via a listener
*
* Note: This example does not work in StarOffice 6.0. It will be available
* in the StarOffice Accessibility release.
*
* @author Björn Milcke
*/
public class SelectionChangeListener implements XSelectionChangeListener {
public static void main( String args[] ) {
SelectionChangeListener aMySelf = new SelectionChangeListener( args );
aMySelf.run();
}
public SelectionChangeListener( String args[] ) {
Helper aHelper = new Helper( args );
maContext = aHelper.getComponentContext();
CalcHelper aCalcHelper = new CalcHelper( aHelper.createSpreadsheetDocument() );
// insert a cell range with 4 columns and 12 rows filled with random numbers
XCellRange aRange = aCalcHelper.insertRandomRange( 4, 12 );
CellRangeAddress aRangeAddress = ((XCellRangeAddressable) UnoRuntime.queryInterface(
XCellRangeAddressable.class, aRange)).getRangeAddress();
// change view to sheet containing the chart
aCalcHelper.raiseChartSheet();
// the unit for measures is 1/100th of a millimeter
// position at (1cm, 1cm)
Point aPos = new Point( 1000, 1000 );
// size of the chart is 15cm x 9.271cm
Size aExtent = new Size( 15000, 9271 );
// insert a new chart into the "Chart" sheet of the
// spreadsheet document
maChartDocument = aCalcHelper.insertChart(
"SampleChart",
aRangeAddress,
aPos,
aExtent,
"com.sun.star.chart.XYDiagram" );
}
public void run() {
boolean bTrying = true;
while( bTrying ) {
// start listening for selection changes
XSelectionSupplier aSelSupp = (XSelectionSupplier) UnoRuntime.queryInterface(
XSelectionSupplier.class,
(((XModel) UnoRuntime.queryInterface(
XModel.class, maChartDocument )).getCurrentController()) );
if( aSelSupp != null ) {
aSelSupp.addSelectionChangeListener( this );
System.out.println( "Successfully attached as selection change listener" );
bTrying = false;
}
// start listening for death of Controller
XComponent aComp = (XComponent) UnoRuntime.queryInterface( XComponent.class, aSelSupp );
if( aComp != null ) {
aComp.addEventListener( this );
System.out.println( "Successfully attached as dispose listener" );
}
try {
Thread.currentThread().sleep( 500 );
} catch( InterruptedException ex ) {
}
}
}
// XEventListener (base of XSelectionChangeListener)
public void disposing( EventObject aSourceObj ) {
System.out.println( "disposing called. detaching as listener" );
// stop listening for selection changes
XSelectionSupplier aCtrl = (XSelectionSupplier) UnoRuntime.queryInterface(
XSelectionSupplier.class, aSourceObj );
if( aCtrl != null )
aCtrl.removeSelectionChangeListener( this );
// remove as dispose listener
XComponent aComp = (XComponent) UnoRuntime.queryInterface( XComponent.class, aSourceObj );
if( aComp != null )
aComp.removeEventListener( this );
// bail out
System.exit( 0 );
}
// XSelectionChangeListener
public void selectionChanged( EventObject aEvent ) {
XController aCtrl = (XController) UnoRuntime.queryInterface( XController.class, aEvent.Source );
if( aCtrl != null ) {
XMultiComponentFactory mMCF = maContext.getServiceManager();
MyMessageBox aMsgBox = new MyMessageBox(mMCF);
aMsgBox.start();
System.out.println("Listener finished");
}
}
private class MyMessageBox extends Thread{
private XMultiComponentFactory mMCF;
public MyMessageBox(XMultiComponentFactory xMCF){
mMCF = xMCF;
}
public void run() {
XDesktop aDesktop = null;
XInterface aToolKit = null;
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
try {
Object oDesktop = mMCF.createInstanceWithContext("com.sun.star.frame.Desktop", maContext);
Object oToolKit = mMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", maContext);
aDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, oDesktop);
aToolKit = (XInterface) UnoRuntime.queryInterface(XInterface.class, oToolKit);
} catch (Exception ex) {
ex.printStackTrace();
}
XWindow xWin = aDesktop.getCurrentFrame().getContainerWindow();
XWindowPeer aWinPeer = (XWindowPeer) UnoRuntime.queryInterface(XWindowPeer.class, xWin);
Rectangle aRect = new Rectangle();
int button = com.sun.star.awt.MessageBoxButtons.BUTTONS_OK;
XMessageBoxFactory aMBF = (XMessageBoxFactory) UnoRuntime.queryInterface(XMessageBoxFactory.class, aToolKit);
XMessageBox xMB = aMBF.createMessageBox(aWinPeer, aRect, "infobox" , button, "Event-Notify", "Listener was called, selcetion has changed");
xMB.execute();
}
}
private XChartDocument maChartDocument;
private XComponentContext maContext;
}
|
package org.voltdb.compiler;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.voltdb.BackendTarget;
import org.voltdb.ProcInfoData;
import org.voltdb.compiler.deploymentfile.AdminModeType;
import org.voltdb.compiler.deploymentfile.ClusterType;
import org.voltdb.compiler.deploymentfile.CommandLogType;
import org.voltdb.compiler.deploymentfile.DeploymentType;
import org.voltdb.compiler.deploymentfile.ExportConfigurationType;
import org.voltdb.compiler.deploymentfile.ExportType;
import org.voltdb.compiler.deploymentfile.HeartbeatType;
import org.voltdb.compiler.deploymentfile.HttpdType;
import org.voltdb.compiler.deploymentfile.HttpdType.Jsonapi;
import org.voltdb.compiler.deploymentfile.PartitionDetectionType;
import org.voltdb.compiler.deploymentfile.PartitionDetectionType.Snapshot;
import org.voltdb.compiler.deploymentfile.PathEntry;
import org.voltdb.compiler.deploymentfile.PathsType;
import org.voltdb.compiler.deploymentfile.PathsType.Voltdbroot;
import org.voltdb.compiler.deploymentfile.PropertyType;
import org.voltdb.compiler.deploymentfile.SchemaType;
import org.voltdb.compiler.deploymentfile.SecurityProviderString;
import org.voltdb.compiler.deploymentfile.SecurityType;
import org.voltdb.compiler.deploymentfile.ServerExportEnum;
import org.voltdb.compiler.deploymentfile.SnapshotType;
import org.voltdb.compiler.deploymentfile.SystemSettingsType;
import org.voltdb.compiler.deploymentfile.SystemSettingsType.Temptables;
import org.voltdb.compiler.deploymentfile.UsersType;
import org.voltdb.compiler.deploymentfile.UsersType.User;
import org.voltdb.utils.NotImplementedException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import com.google_voltpatches.common.collect.ImmutableMap;
/**
* Alternate (programmatic) interface to VoltCompiler. Give the class all of
* the information a user would put in a VoltDB project file and it will go
* and build the project file and run the compiler on it.
*
* It will also create a deployment.xml file and apply its changes to the catalog.
*/
public class VoltProjectBuilder {
final LinkedHashSet<String> m_schemas = new LinkedHashSet<String>();
public static final class ProcedureInfo {
private final String groups[];
private final Class<?> cls;
private final String name;
private final String sql;
private final String partitionInfo;
private final String joinOrder;
public ProcedureInfo(final String groups[], final Class<?> cls) {
this.groups = groups;
this.cls = cls;
this.name = cls.getSimpleName();
this.sql = null;
this.joinOrder = null;
this.partitionInfo = null;
assert(this.name != null);
}
public ProcedureInfo(
final String groups[],
final String name,
final String sql,
final String partitionInfo) {
this(groups, name, sql, partitionInfo, null);
}
public ProcedureInfo(
final String groups[],
final String name,
final String sql,
final String partitionInfo,
final String joinOrder) {
assert(name != null);
this.groups = groups;
this.cls = null;
this.name = name;
this.sql = sql;
this.partitionInfo = partitionInfo;
this.joinOrder = joinOrder;
assert(this.name != null);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(final Object o) {
if (o instanceof ProcedureInfo) {
final ProcedureInfo oInfo = (ProcedureInfo)o;
return name.equals(oInfo.name);
}
return false;
}
}
public static final class UserInfo {
public final String name;
public String password;
private final String groups[];
public UserInfo (final String name, final String password, final String groups[]){
this.name = name;
this.password = password;
this.groups = groups;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(final Object o) {
if (o instanceof UserInfo) {
final UserInfo oInfo = (UserInfo)o;
return name.equals(oInfo.name);
}
return false;
}
}
public static final class GroupInfo {
private final String name;
private final boolean adhoc;
private final boolean sysproc;
private final boolean defaultproc;
public GroupInfo(final String name, final boolean adhoc, final boolean sysproc, final boolean defaultproc){
this.name = name;
this.adhoc = adhoc;
this.sysproc = sysproc;
this.defaultproc = defaultproc;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(final Object o) {
if (o instanceof GroupInfo) {
final GroupInfo oInfo = (GroupInfo)o;
return name.equals(oInfo.name);
}
return false;
}
}
private static final class DeploymentInfo {
final int hostCount;
final int sitesPerHost;
final int replication;
final boolean useCustomAdmin;
final int adminPort;
final boolean adminOnStartup;
public DeploymentInfo(int hostCount, int sitesPerHost, int replication,
boolean useCustomAdmin, int adminPort, boolean adminOnStartup) {
this.hostCount = hostCount;
this.sitesPerHost = sitesPerHost;
this.replication = replication;
this.useCustomAdmin = useCustomAdmin;
this.adminPort = adminPort;
this.adminOnStartup = adminOnStartup;
}
}
final ArrayList<String> m_exportTables = new ArrayList<String>();
final LinkedHashSet<UserInfo> m_users = new LinkedHashSet<UserInfo>();
final LinkedHashSet<GroupInfo> m_groups = new LinkedHashSet<GroupInfo>();
final LinkedHashSet<ProcedureInfo> m_procedures = new LinkedHashSet<ProcedureInfo>();
final LinkedHashSet<Class<?>> m_supplementals = new LinkedHashSet<Class<?>>();
final LinkedHashMap<String, String> m_partitionInfos = new LinkedHashMap<String, String>();
String m_elloader = null; // loader package.Classname
private boolean m_elenabled; // true if enabled; false if disabled
// zero defaults to first open port >= 8080.
// negative one means disabled in the deployment file.
int m_httpdPortNo = -1;
boolean m_jsonApiEnabled = true;
BackendTarget m_target = BackendTarget.NATIVE_EE_JNI;
PrintStream m_compilerDebugPrintStream = null;
boolean m_securityEnabled = false;
String m_securityProvider = SecurityProviderString.HASH.value();
final Map<String, ProcInfoData> m_procInfoOverrides = new HashMap<String, ProcInfoData>();
private String m_snapshotPath = null;
private int m_snapshotRetain = 0;
private String m_snapshotPrefix = null;
private String m_snapshotFrequency = null;
private String m_pathToDeployment = null;
private String m_voltRootPath = null;
private boolean m_ppdEnabled = false;
private String m_ppdPrefix = "none";
private String m_internalSnapshotPath;
private String m_commandLogPath;
private Boolean m_commandLogSync;
private boolean m_commandLogEnabled = false;
private Integer m_commandLogSize;
private Integer m_commandLogFsyncInterval;
private Integer m_commandLogMaxTxnsBeforeFsync;
private Integer m_snapshotPriority;
private Integer m_maxTempTableMemory = 100;
private List<String> m_diagnostics;
private Properties m_elConfig;
private String m_elExportTarget = "file";
private Integer m_deadHostTimeout = null;
private Integer m_elasticTargetThroughput = null;
private Integer m_elasticTargetPauseTime = null;
private boolean m_useAdhocSchema = false;
public VoltProjectBuilder setElasticTargetThroughput(int target) {
m_elasticTargetThroughput = target;
return this;
}
public VoltProjectBuilder setElasticTargetPauseTime(int target) {
m_elasticTargetPauseTime = target;
return this;
}
public void setDeadHostTimeout(Integer deadHostTimeout) {
m_deadHostTimeout = deadHostTimeout;
}
public void setUseAdhocSchema(boolean useIt)
{
m_useAdhocSchema = useIt;
}
public void configureLogging(String internalSnapshotPath, String commandLogPath, Boolean commandLogSync,
Boolean commandLogEnabled, Integer fsyncInterval, Integer maxTxnsBeforeFsync, Integer logSize) {
m_internalSnapshotPath = internalSnapshotPath;
m_commandLogPath = commandLogPath;
m_commandLogSync = commandLogSync;
m_commandLogEnabled = commandLogEnabled;
m_commandLogFsyncInterval = fsyncInterval;
m_commandLogMaxTxnsBeforeFsync = maxTxnsBeforeFsync;
m_commandLogSize = logSize;
}
/**
* Produce all catalogs this project builder knows how to produce.
* Written to allow BenchmarkController to cause compilation of multiple
* catalogs for benchmarks that need to update running appplications and
* consequently need multiple benchmark controlled catalog jars.
* @param sitesPerHost
* @param length
* @param kFactor
* @param voltRoot where to put the compiled catalogs
* @return a list of jar filenames that were compiled. The benchmark will
* be started using the filename at index 0.
*/
public String[] compileAllCatalogs(
int sitesPerHost, int length,
int kFactor, String voltRoot)
{
throw new NotImplementedException("This project builder does not support compileAllCatalogs");
}
public void setSnapshotPriority(int priority) {
m_snapshotPriority = priority;
}
public void addAllDefaults() {
// does nothing in the base class
}
public void addUsers(final UserInfo users[]) {
for (final UserInfo info : users) {
final boolean added = m_users.add(info);
if (!added) {
assert(added);
}
}
}
public void addGroups(final GroupInfo groups[]) {
for (final GroupInfo info : groups) {
final boolean added = m_groups.add(info);
if (!added) {
assert(added);
}
}
}
public void addSchema(final URL schemaURL) {
assert(schemaURL != null);
addSchema(schemaURL.getPath());
}
/**
* This is test code written by Ryan, even though it was
* committed by John.
*/
public void addLiteralSchema(String ddlText) throws IOException {
File temp = File.createTempFile("literalschema", "sql");
temp.deleteOnExit();
FileWriter out = new FileWriter(temp);
out.write(ddlText);
out.close();
addSchema(URLEncoder.encode(temp.getAbsolutePath(), "UTF-8"));
}
/**
* Add a schema based on a URL.
* @param schemaURL Schema file URL
*/
public void addSchema(String schemaURL) {
try {
schemaURL = URLDecoder.decode(schemaURL, "UTF-8");
} catch (final UnsupportedEncodingException e) {
e.printStackTrace();
System.exit(-1);
}
assert(m_schemas.contains(schemaURL) == false);
final File schemaFile = new File(schemaURL);
assert(schemaFile != null);
assert(schemaFile.isDirectory() == false);
// this check below fails in some valid cases (like when the file is in a jar)
//assert schemaFile.canRead()
// : "can't read file: " + schemaPath;
m_schemas.add(schemaURL);
}
public void addStmtProcedure(String name, String sql) {
addStmtProcedure(name, sql, null, null);
}
public void addStmtProcedure(String name, String sql, String partitionInfo) {
addStmtProcedure( name, sql, partitionInfo, null);
}
public void addStmtProcedure(String name, String sql, String partitionInfo, String joinOrder) {
addProcedures(new ProcedureInfo(new String[0], name, sql, partitionInfo, joinOrder));
}
public void addProcedures(final Class<?>... procedures) {
final ArrayList<ProcedureInfo> procArray = new ArrayList<ProcedureInfo>();
for (final Class<?> procedure : procedures)
procArray.add(new ProcedureInfo(new String[0], procedure));
addProcedures(procArray);
}
/*
* List of groups permitted to invoke the procedure
*/
public void addProcedures(final ProcedureInfo... procedures) {
final ArrayList<ProcedureInfo> procArray = new ArrayList<ProcedureInfo>();
for (final ProcedureInfo procedure : procedures)
procArray.add(procedure);
addProcedures(procArray);
}
public void addProcedures(final Iterable<ProcedureInfo> procedures) {
// check for duplicates and existings
final HashSet<ProcedureInfo> newProcs = new HashSet<ProcedureInfo>();
for (final ProcedureInfo procedure : procedures) {
assert(newProcs.contains(procedure) == false);
assert(m_procedures.contains(procedure) == false);
newProcs.add(procedure);
}
// add the procs
for (final ProcedureInfo procedure : procedures) {
m_procedures.add(procedure);
}
}
public void addSupplementalClasses(final Class<?>... supplementals) {
final ArrayList<Class<?>> suppArray = new ArrayList<Class<?>>();
for (final Class<?> supplemental : supplementals)
suppArray.add(supplemental);
addSupplementalClasses(suppArray);
}
public void addSupplementalClasses(final Iterable<Class<?>> supplementals) {
// check for duplicates and existings
final HashSet<Class<?>> newSupps = new HashSet<Class<?>>();
for (final Class<?> supplemental : supplementals) {
assert(newSupps.contains(supplemental) == false);
assert(m_supplementals.contains(supplemental) == false);
newSupps.add(supplemental);
}
// add the supplemental classes
for (final Class<?> supplemental : supplementals)
m_supplementals.add(supplemental);
}
public void addPartitionInfo(final String tableName, final String partitionColumnName) {
assert(m_partitionInfos.containsKey(tableName) == false);
m_partitionInfos.put(tableName, partitionColumnName);
}
public void setHTTPDPort(int port) {
m_httpdPortNo = port;
}
public void setJSONAPIEnabled(final boolean enabled) {
m_jsonApiEnabled = enabled;
}
public void setSecurityEnabled(final boolean enabled) {
m_securityEnabled = enabled;
}
public void setSecurityProvider(final String provider) {
if (provider != null && !provider.trim().isEmpty()) {
SecurityProviderString.fromValue(provider);
m_securityProvider = provider;
}
}
public void setSnapshotSettings(
String frequency,
int retain,
String path,
String prefix) {
assert(frequency != null);
assert(prefix != null);
m_snapshotFrequency = frequency;
m_snapshotRetain = retain;
m_snapshotPrefix = prefix;
m_snapshotPath = path;
}
public void setPartitionDetectionSettings(final String snapshotPath, final String ppdPrefix)
{
m_ppdEnabled = true;
m_snapshotPath = snapshotPath;
m_ppdPrefix = ppdPrefix;
}
public void addExport(boolean enabled, String exportTarget, Properties config) {
m_elloader = "org.voltdb.export.processors.GuestProcessor";
m_elenabled = enabled;
if (config == null) {
config = new Properties();
config.putAll(ImmutableMap.<String, String>of(
"type","tsv", "batched","true", "with-schema","true", "nonce","zorag", "outdir","exportdata"
));
}
m_elConfig = config;
if ((exportTarget != null) && !exportTarget.trim().isEmpty()) {
m_elExportTarget = exportTarget;
}
}
public void addExport(boolean enabled) {
addExport(enabled, null, null);
}
public void setTableAsExportOnly(String name) {
assert(name != null);
m_exportTables.add(name);
}
public void setCompilerDebugPrintStream(final PrintStream out) {
m_compilerDebugPrintStream = out;
}
public void setMaxTempTableMemory(int max)
{
m_maxTempTableMemory = max;
}
/**
* Override the procedure annotation with the specified values for a
* specified procedure.
*
* @param procName The name of the procedure to override the annotation.
* @param info The values to use instead of the annotation.
*/
public void overrideProcInfoForProcedure(final String procName, final ProcInfoData info) {
assert(procName != null);
assert(info != null);
m_procInfoOverrides.put(procName, info);
}
public boolean compile(final String jarPath) {
return compile(jarPath, 1, 1, 0, null);
}
public boolean compile(final String jarPath,
final int sitesPerHost,
final int replication) {
return compile(jarPath, sitesPerHost, 1,
replication, null);
}
public boolean compile(final String jarPath,
final int sitesPerHost,
final int hostCount,
final int replication) {
return compile(jarPath, sitesPerHost, hostCount,
replication, null);
}
public boolean compile(final String jarPath,
final int sitesPerHost,
final int hostCount,
final int replication,
final String voltRoot) {
VoltCompiler compiler = new VoltCompiler();
return compile(compiler, jarPath, voltRoot,
new DeploymentInfo(hostCount, sitesPerHost, replication, false, 0, false),
m_ppdEnabled, m_snapshotPath, m_ppdPrefix);
}
public boolean compile(
final String jarPath, final int sitesPerHost,
final int hostCount, final int replication,
final String voltRoot, final boolean ppdEnabled, final String snapshotPath, final String ppdPrefix)
{
VoltCompiler compiler = new VoltCompiler();
return compile(compiler, jarPath, voltRoot,
new DeploymentInfo(hostCount, sitesPerHost, replication, false, 0, false),
ppdEnabled, snapshotPath, ppdPrefix);
}
public boolean compile(final String jarPath, final int sitesPerHost,
final int hostCount, final int replication,
final int adminPort, final boolean adminOnStartup)
{
VoltCompiler compiler = new VoltCompiler();
return compile(compiler, jarPath, null,
new DeploymentInfo(hostCount, sitesPerHost, replication, true, adminPort, adminOnStartup),
m_ppdEnabled, m_snapshotPath, m_ppdPrefix);
}
public boolean compile(final VoltCompiler compiler,
final String jarPath,
final String voltRoot,
final DeploymentInfo deployment,
final boolean ppdEnabled,
final String snapshotPath,
final String ppdPrefix)
{
assert(jarPath != null);
assert(deployment == null || deployment.sitesPerHost >= 1);
assert(deployment == null || deployment.hostCount >= 1);
String deploymentVoltRoot = voltRoot;
if (deployment != null) {
if (voltRoot == null) {
String voltRootPath = "/tmp/" + System.getProperty("user.name");
java.io.File voltRootFile = new java.io.File(voltRootPath);
if (!voltRootFile.exists()) {
if (!voltRootFile.mkdir()) {
throw new RuntimeException("Unable to create voltdbroot \"" + voltRootPath + "\" for test");
}
}
if (!voltRootFile.isDirectory()) {
throw new RuntimeException("voltdbroot \"" + voltRootPath + "\" for test exists but is not a directory");
}
if (!voltRootFile.canRead()) {
throw new RuntimeException("voltdbroot \"" + voltRootPath + "\" for test exists but is not readable");
}
if (!voltRootFile.canWrite()) {
throw new RuntimeException("voltdbroot \"" + voltRootPath + "\" for test exists but is not writable");
}
if (!voltRootFile.canExecute()) {
throw new RuntimeException("voltdbroot \"" + voltRootPath + "\" for test exists but is not writable");
}
deploymentVoltRoot = voltRootPath;
}
}
m_voltRootPath = deploymentVoltRoot;
compiler.setProcInfoOverrides(m_procInfoOverrides);
if (m_diagnostics != null) {
compiler.enableDetailedCapture();
}
int index = 0;
String[] schemaPath = new String[m_schemas.size()];
Iterator<String> ite = m_schemas.iterator();
while(ite.hasNext())
{
schemaPath[index] = ite.next();
index++;
}
// we don't use projectPath any more, but keep it here for compatibility
final String projectPath = null;
boolean success = compiler.compileWithProjectXML(projectPath, jarPath, schemaPath);
m_diagnostics = compiler.harvestCapturedDetail();
if (m_compilerDebugPrintStream != null) {
if (success) {
compiler.summarizeSuccess(m_compilerDebugPrintStream, m_compilerDebugPrintStream, jarPath);
} else {
compiler.summarizeErrors(m_compilerDebugPrintStream, m_compilerDebugPrintStream);
}
}
if (deployment != null) {
try {
m_pathToDeployment = writeDeploymentFile(deploymentVoltRoot, deployment);
} catch (Exception e) {
System.out.println("Failed to create deployment file in testcase.");
e.printStackTrace();
System.out.println("hostcount: " + deployment.hostCount);
System.out.println("sitesPerHost: " + deployment.sitesPerHost);
System.out.println("replication: " + deployment.replication);
System.out.println("voltRoot: " + deploymentVoltRoot);
System.out.println("ppdEnabled: " + ppdEnabled);
System.out.println("snapshotPath: " + snapshotPath);
System.out.println("ppdPrefix: " + ppdPrefix);
System.out.println("adminEnabled: " + deployment.useCustomAdmin);
System.out.println("adminPort: " + deployment.adminPort);
System.out.println("adminOnStartup: " + deployment.adminOnStartup);
// sufficient to escape and fail test cases?
throw new RuntimeException(e);
}
}
return success;
}
/**
* Compile catalog with no deployment file generated so that the
* internally-generated default gets used.
*
* @param jarPath path to output jar
* @return true if successful
*/
public boolean compileWithDefaultDeployment(final String jarPath) {
VoltCompiler compiler = new VoltCompiler();
return compile(compiler, jarPath, null, null, m_ppdEnabled, m_snapshotPath, m_ppdPrefix);
}
/**
* After compile() has been called, a deployment file will be written. This method exposes its location so it can be
* passed to org.voltdb.VoltDB on startup.
* @return Returns the deployment file location.
*/
public String getPathToDeployment() {
if (m_pathToDeployment == null) {
System.err.println("ERROR: Call compile() before trying to get the deployment path.");
return null;
} else {
System.out.println("path to deployment is " + m_pathToDeployment);
return m_pathToDeployment;
}
}
private void buildDatabaseElement(Document doc, final Element database) {
// /project/database/groups
final Element groups = doc.createElement("groups");
database.appendChild(groups);
// groups/group
if (m_groups.isEmpty()) {
final Element group = doc.createElement("group");
group.setAttribute("name", "default");
group.setAttribute("sysproc", "true");
group.setAttribute("defaultproc", "true");
group.setAttribute("adhoc", "true");
groups.appendChild(group);
}
else {
for (final GroupInfo info : m_groups) {
final Element group = doc.createElement("group");
group.setAttribute("name", info.name);
group.setAttribute("sysproc", info.sysproc ? "true" : "false");
group.setAttribute("defaultproc", info.defaultproc ? "true" : "false");
group.setAttribute("adhoc", info.adhoc ? "true" : "false");
groups.appendChild(group);
}
}
// /project/database/schemas
final Element schemas = doc.createElement("schemas");
database.appendChild(schemas);
// schemas/schema
for (final String schemaPath : m_schemas) {
final Element schema = doc.createElement("schema");
schema.setAttribute("path", schemaPath);
schemas.appendChild(schema);
}
// /project/database/procedures
final Element procedures = doc.createElement("procedures");
database.appendChild(procedures);
// procedures/procedure
for (final ProcedureInfo procedure : m_procedures) {
if (procedure.cls == null)
continue;
assert(procedure.sql == null);
final Element proc = doc.createElement("procedure");
proc.setAttribute("class", procedure.cls.getName());
// build up @groups. This attribute should be redesigned
if (procedure.groups.length > 0) {
final StringBuilder groupattr = new StringBuilder();
for (final String group : procedure.groups) {
if (groupattr.length() > 0)
groupattr.append(",");
groupattr.append(group);
}
proc.setAttribute("groups", groupattr.toString());
}
procedures.appendChild(proc);
}
// procedures/procedures (that are stmtprocedures)
for (final ProcedureInfo procedure : m_procedures) {
if (procedure.sql == null)
continue;
assert(procedure.cls == null);
final Element proc = doc.createElement("procedure");
proc.setAttribute("class", procedure.name);
if (procedure.partitionInfo != null);
proc.setAttribute("partitioninfo", procedure.partitionInfo);
// build up @groups. This attribute should be redesigned
if (procedure.groups.length > 0) {
final StringBuilder groupattr = new StringBuilder();
for (final String group : procedure.groups) {
if (groupattr.length() > 0)
groupattr.append(",");
groupattr.append(group);
}
proc.setAttribute("groups", groupattr.toString());
}
final Element sql = doc.createElement("sql");
if (procedure.joinOrder != null) {
sql.setAttribute("joinorder", procedure.joinOrder);
}
proc.appendChild(sql);
final Text sqltext = doc.createTextNode(procedure.sql);
sql.appendChild(sqltext);
procedures.appendChild(proc);
}
if (m_partitionInfos.size() > 0) {
// /project/database/partitions
final Element partitions = doc.createElement("partitions");
database.appendChild(partitions);
// partitions/table
for (final Entry<String, String> partitionInfo : m_partitionInfos.entrySet()) {
final Element table = doc.createElement("partition");
table.setAttribute("table", partitionInfo.getKey());
table.setAttribute("column", partitionInfo.getValue());
partitions.appendChild(table);
}
}
// /project/database/classdependencies
final Element classdeps = doc.createElement("classdependencies");
database.appendChild(classdeps);
// classdependency
for (final Class<?> supplemental : m_supplementals) {
final Element supp= doc.createElement("classdependency");
supp.setAttribute("class", supplemental.getName());
classdeps.appendChild(supp);
}
// project/database/export
if (m_elloader != null) {
final Element export = doc.createElement("export");
database.appendChild(export);
if (m_exportTables.size() > 0) {
final Element tables = doc.createElement("tables");
export.appendChild(tables);
for (String exportTableName : m_exportTables) {
final Element table = doc.createElement("table");
table.setAttribute("name", exportTableName);
tables.appendChild(table);
}
}
}
}
/**
* Utility method to take a string and put it in a file. This is used by
* this class to write the project file to a temp file, but it also used
* by some other tests.
*
* @param content The content of the file to create.
* @return A reference to the file created or null on failure.
*/
public static File writeStringToTempFile(final String content) {
File tempFile;
try {
tempFile = File.createTempFile("myApp", ".tmp");
// tempFile.deleteOnExit();
final FileWriter writer = new FileWriter(tempFile);
writer.write(content);
writer.flush();
writer.close();
return tempFile;
} catch (final IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Writes deployment.xml file to a temporary file. It is constructed from the passed parameters and the m_users
* field.
*
* @param voltRoot
* @param dinfo an instance {@link DeploymentInfo}
* @return deployment path
* @throws IOException
* @throws JAXBException
*/
private String writeDeploymentFile(
String voltRoot, DeploymentInfo dinfo) throws IOException, JAXBException
{
org.voltdb.compiler.deploymentfile.ObjectFactory factory =
new org.voltdb.compiler.deploymentfile.ObjectFactory();
// <deployment>
DeploymentType deployment = factory.createDeploymentType();
JAXBElement<DeploymentType> doc = factory.createDeployment(deployment);
// <cluster>
ClusterType cluster = factory.createClusterType();
deployment.setCluster(cluster);
cluster.setHostcount(dinfo.hostCount);
cluster.setSitesperhost(dinfo.sitesPerHost);
cluster.setKfactor(dinfo.replication);
cluster.setSchema(m_useAdhocSchema ? SchemaType.ADHOC : SchemaType.CATALOG);
// <paths>
PathsType paths = factory.createPathsType();
deployment.setPaths(paths);
Voltdbroot voltdbroot = factory.createPathsTypeVoltdbroot();
paths.setVoltdbroot(voltdbroot);
voltdbroot.setPath(voltRoot);
if (m_snapshotPath != null) {
PathEntry snapshotPathElement = factory.createPathEntry();
snapshotPathElement.setPath(m_snapshotPath);
paths.setSnapshots(snapshotPathElement);
}
if (m_deadHostTimeout != null) {
HeartbeatType heartbeat = factory.createHeartbeatType();
heartbeat.setTimeout(m_deadHostTimeout);
deployment.setHeartbeat(heartbeat);
}
if (m_commandLogPath != null) {
PathEntry commandLogPathElement = factory.createPathEntry();
commandLogPathElement.setPath(m_commandLogPath);
paths.setCommandlog(commandLogPathElement);
}
if (m_internalSnapshotPath != null) {
PathEntry commandLogSnapshotPathElement = factory.createPathEntry();
commandLogSnapshotPathElement.setPath(m_internalSnapshotPath);
paths.setCommandlogsnapshot(commandLogSnapshotPathElement);
}
if (m_snapshotPrefix != null) {
SnapshotType snapshot = factory.createSnapshotType();
deployment.setSnapshot(snapshot);
snapshot.setFrequency(m_snapshotFrequency);
snapshot.setPrefix(m_snapshotPrefix);
snapshot.setRetain(m_snapshotRetain);
}
SecurityType security = factory.createSecurityType();
deployment.setSecurity(security);
security.setEnabled(m_securityEnabled);
SecurityProviderString provider = SecurityProviderString.HASH;
if (m_securityEnabled) try {
provider = SecurityProviderString.fromValue(m_securityProvider);
} catch (IllegalArgumentException shouldNotHappenSeeSetter) {
}
security.setProvider(provider);
// set the command log (which defaults to off)
CommandLogType commandLogType = factory.createCommandLogType();
commandLogType.setEnabled(m_commandLogEnabled);
if (m_commandLogSync != null) {
commandLogType.setSynchronous(m_commandLogSync.booleanValue());
}
if (m_commandLogSize != null) {
commandLogType.setLogsize(m_commandLogSize);
}
if (m_commandLogFsyncInterval != null || m_commandLogMaxTxnsBeforeFsync != null) {
CommandLogType.Frequency frequency = factory.createCommandLogTypeFrequency();
if (m_commandLogFsyncInterval != null) {
frequency.setTime(m_commandLogFsyncInterval);
}
if (m_commandLogMaxTxnsBeforeFsync != null) {
frequency.setTransactions(m_commandLogMaxTxnsBeforeFsync);
}
commandLogType.setFrequency(frequency);
}
deployment.setCommandlog(commandLogType);
// <partition-detection>/<snapshot>
PartitionDetectionType ppd = factory.createPartitionDetectionType();
deployment.setPartitionDetection(ppd);
ppd.setEnabled(m_ppdEnabled);
Snapshot ppdsnapshot = factory.createPartitionDetectionTypeSnapshot();
ppd.setSnapshot(ppdsnapshot);
ppdsnapshot.setPrefix(m_ppdPrefix);
// <admin-mode>
// can't be disabled, but only write out the non-default config if
// requested by a test. otherwise, take the implied defaults (or
// whatever local cluster overrides on the command line).
if (dinfo.useCustomAdmin) {
AdminModeType admin = factory.createAdminModeType();
deployment.setAdminMode(admin);
admin.setPort(dinfo.adminPort);
admin.setAdminstartup(dinfo.adminOnStartup);
}
// <systemsettings>
SystemSettingsType systemSettingType = factory.createSystemSettingsType();
Temptables temptables = factory.createSystemSettingsTypeTemptables();
temptables.setMaxsize(m_maxTempTableMemory);
systemSettingType.setTemptables(temptables);
if (m_snapshotPriority != null) {
SystemSettingsType.Snapshot snapshot = factory.createSystemSettingsTypeSnapshot();
snapshot.setPriority(m_snapshotPriority);
systemSettingType.setSnapshot(snapshot);
}
if (m_elasticTargetThroughput != null || m_elasticTargetPauseTime != null) {
SystemSettingsType.Elastic elastic = factory.createSystemSettingsTypeElastic();
if (m_elasticTargetThroughput != null) elastic.setThroughput(m_elasticTargetThroughput);
if (m_elasticTargetPauseTime != null) elastic.setDuration(m_elasticTargetPauseTime);
systemSettingType.setElastic(elastic);
}
deployment.setSystemsettings(systemSettingType);
// <users>
if (m_users.size() > 0) {
UsersType users = factory.createUsersType();
deployment.setUsers(users);
// <user>
for (final UserInfo info : m_users) {
User user = factory.createUsersTypeUser();
users.getUser().add(user);
user.setName(info.name);
user.setPassword(info.password);
// build up user/@groups.
if (info.groups.length > 0) {
final StringBuilder groups = new StringBuilder();
for (final String group : info.groups) {
if (groups.length() > 0)
groups.append(",");
groups.append(group);
}
user.setGroups(groups.toString());
}
}
}
// <httpd>. Disabled unless port # is configured by a testcase
HttpdType httpd = factory.createHttpdType();
deployment.setHttpd(httpd);
httpd.setEnabled(m_httpdPortNo != -1);
httpd.setPort(m_httpdPortNo);
Jsonapi json = factory.createHttpdTypeJsonapi();
httpd.setJsonapi(json);
json.setEnabled(m_jsonApiEnabled);
// <export>
ExportType export = factory.createExportType();
deployment.setExport(export);
// this is for old generation export test suite backward compatibility
export.setEnabled(m_elenabled && m_elloader != null && !m_elloader.trim().isEmpty());
ServerExportEnum exportTarget = ServerExportEnum.fromValue(m_elExportTarget.toLowerCase());
export.setTarget(exportTarget);
if((m_elConfig != null) && (m_elConfig.size() > 0)) {
ExportConfigurationType exportConfig = factory.createExportConfigurationType();
List<PropertyType> configProperties = exportConfig.getProperty();
for( Object nameObj: m_elConfig.keySet()) {
String name = String.class.cast(nameObj);
PropertyType prop = factory.createPropertyType();
prop.setName(name);
prop.setValue(m_elConfig.getProperty(name));
configProperties.add(prop);
}
export.setConfiguration(exportConfig);
}
// Have some yummy boilerplate!
File file = File.createTempFile("myAppDeployment", ".tmp");
JAXBContext context = JAXBContext.newInstance(DeploymentType.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
marshaller.marshal(doc, file);
final String deploymentPath = file.getPath();
return deploymentPath;
}
public File getPathToVoltRoot() {
return new File(m_voltRootPath);
}
/** Provide a feedback path to monitor the VoltCompiler's plan output via harvestDiagnostics */
public void enableDiagnostics() {
// This empty dummy value enables the feature and provides a default fallback return value,
// but gets replaced in the normal code path.
m_diagnostics = new ArrayList<String>();
}
/** Access the VoltCompiler's recent plan output, for diagnostic purposes */
public List<String> harvestDiagnostics() {
List<String> result = m_diagnostics;
m_diagnostics = null;
return result;
}
}
|
package com.auth0.android.lock.utils;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.view.View;
import android.view.ViewGroup;
import com.auth0.android.lock.views.ValidatedInputView;
import com.auth0.android.lock.views.ValidatedInputView.DataType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import static com.auth0.android.lock.utils.CustomField.FieldType.TYPE_EMAIL;
import static com.auth0.android.lock.utils.CustomField.FieldType.TYPE_NAME;
import static com.auth0.android.lock.utils.CustomField.FieldType.TYPE_NUMBER;
import static com.auth0.android.lock.utils.CustomField.FieldType.TYPE_PHONE_NUMBER;
import static com.auth0.android.lock.utils.CustomField.Storage.PROFILE_ROOT;
import static com.auth0.android.lock.utils.CustomField.Storage.USER_METADATA;
public class CustomField implements Parcelable {
@IntDef({TYPE_NAME, TYPE_NUMBER, TYPE_PHONE_NUMBER, TYPE_EMAIL})
@Retention(RetentionPolicy.SOURCE)
public @interface FieldType {
int TYPE_NAME = 0;
int TYPE_NUMBER = 1;
int TYPE_PHONE_NUMBER = 2;
int TYPE_EMAIL = 3;
}
/**
* Location to store the field into.
*/
@IntDef({PROFILE_ROOT, USER_METADATA})
@Retention(RetentionPolicy.SOURCE)
public @interface Storage {
int PROFILE_ROOT = 0;
/**
* Store the field into the user_metadata object.
*/
int USER_METADATA = 1;
}
@DrawableRes
private final int icon;
@FieldType
private final int type;
private final String key;
@StringRes
private final int hint;
@Storage
private final int storage;
/**
* Constructor for CustomField instance
* When this constructor is used the field will be stored under the {@link Storage#USER_METADATA} attribute.
* If you want to change the storage location use the constructor that accepts a {@link Storage} value.
*
* @param icon the icon resource to display next to the field.
* @param type the type of input this field will receive. Used to determine the applied validation.
* @param key the key to store this field as.
* @param hint the placeholder to display when this field is empty.
*/
public CustomField(@DrawableRes int icon, @FieldType int type, @NonNull String key, @StringRes int hint) {
this(icon, type, key, hint, USER_METADATA);
}
/**
* Constructor for CustomField instance
*
* @param icon the icon resource to display next to the field.
* @param type the type of input this field will receive. Used to determine the applied validation.
* @param key the key to store this field as.
* @param hint the placeholder to display when this field is empty.
* @param storage the location to store this value into.
*/
public CustomField(@DrawableRes int icon, @FieldType int type, @NonNull String key, @StringRes int hint, @Storage int storage) {
if (key.isEmpty()) {
throw new IllegalArgumentException("The key cannot be empty!");
}
if (key.equalsIgnoreCase("user_metadata") && storage == PROFILE_ROOT){
throw new IllegalArgumentException("Update the user_metadata root profile attributes by using Storage.USER_METADATA as storage location.");
}
this.icon = icon;
this.type = type;
this.key = key;
this.hint = hint;
this.storage = storage;
}
public void configureField(@NonNull ValidatedInputView field) {
switch (type) {
case TYPE_NAME:
field.setDataType(DataType.TEXT_NAME);
break;
case TYPE_NUMBER:
field.setDataType(DataType.NUMBER);
break;
case TYPE_PHONE_NUMBER:
field.setDataType(DataType.PHONE_NUMBER);
break;
case TYPE_EMAIL:
field.setDataType(DataType.EMAIL);
break;
}
field.setHint(hint);
field.setIcon(icon);
field.setTag(key);
}
@Nullable
public String findValue(@NonNull ViewGroup container) {
String value = null;
View view = container.findViewWithTag(key);
if (view != null) {
value = ((ValidatedInputView) view).getText();
}
return value;
}
public String getKey() {
return key;
}
@StringRes
int getHint() {
return hint;
}
@DrawableRes
int getIcon() {
return icon;
}
@FieldType
int getType() {
return type;
}
@Storage
public int getStorage() {
return storage;
}
protected CustomField(Parcel in) {
icon = in.readInt();
type = in.readInt();
key = in.readString();
hint = in.readInt();
storage = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(icon);
dest.writeInt(type);
dest.writeString(key);
dest.writeInt(hint);
dest.writeInt(storage);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<CustomField> CREATOR = new Parcelable.Creator<CustomField>() {
@Override
public CustomField createFromParcel(Parcel in) {
return new CustomField(in);
}
@Override
public CustomField[] newArray(int size) {
return new CustomField[size];
}
};
}
|
package com.github.kevinsawicki.http;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_CREATED;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.Proxy.Type.HTTP;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivilegedAction;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* A fluid interface for making HTTP requests using an underlying
* {@link HttpURLConnection} (or sub-class).
* <p>
* Each instance supports making a single request and cannot be reused for
* further requests.
*/
public class HttpRequest {
/**
* 'UTF-8' charset name
*/
public static final String CHARSET_UTF8 = "UTF-8";
/**
* 'application/x-www-form-urlencoded' content type header value
*/
public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
/**
* 'application/json' content type header value
*/
public static final String CONTENT_TYPE_JSON = "application/json";
/**
* 'gzip' encoding header value
*/
public static final String ENCODING_GZIP = "gzip";
/**
* 'Accept' header name
*/
public static final String HEADER_ACCEPT = "Accept";
/**
* 'Accept-Charset' header name
*/
public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset";
/**
* 'Accept-Encoding' header name
*/
public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
/**
* 'Authorization' header name
*/
public static final String HEADER_AUTHORIZATION = "Authorization";
/**
* 'Cache-Control' header name
*/
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
/**
* 'Content-Encoding' header name
*/
public static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
/**
* 'Content-Length' header name
*/
public static final String HEADER_CONTENT_LENGTH = "Content-Length";
/**
* 'Content-Type' header name
*/
public static final String HEADER_CONTENT_TYPE = "Content-Type";
/**
* 'Date' header name
*/
public static final String HEADER_DATE = "Date";
/**
* 'ETag' header name
*/
public static final String HEADER_ETAG = "ETag";
/**
* 'Expires' header name
*/
public static final String HEADER_EXPIRES = "Expires";
/**
* 'If-None-Match' header name
*/
public static final String HEADER_IF_NONE_MATCH = "If-None-Match";
/**
* 'Last-Modified' header name
*/
public static final String HEADER_LAST_MODIFIED = "Last-Modified";
/**
* 'Location' header name
*/
public static final String HEADER_LOCATION = "Location";
/**
* 'Proxy-Authorization' header name
*/
public static final String HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization";
/**
* 'Referer' header name
*/
public static final String HEADER_REFERER = "Referer";
/**
* 'Server' header name
*/
public static final String HEADER_SERVER = "Server";
/**
* 'User-Agent' header name
*/
public static final String HEADER_USER_AGENT = "User-Agent";
/**
* 'DELETE' request method
*/
public static final String METHOD_DELETE = "DELETE";
/**
* 'GET' request method
*/
public static final String METHOD_GET = "GET";
/**
* 'HEAD' request method
*/
public static final String METHOD_HEAD = "HEAD";
/**
* 'OPTIONS' options method
*/
public static final String METHOD_OPTIONS = "OPTIONS";
/**
* 'POST' request method
*/
public static final String METHOD_POST = "POST";
/**
* 'PUT' request method
*/
public static final String METHOD_PUT = "PUT";
/**
* 'TRACE' request method
*/
public static final String METHOD_TRACE = "TRACE";
/**
* 'charset' header value parameter
*/
public static final String PARAM_CHARSET = "charset";
private static final String BOUNDARY = "00content0boundary00";
private static final String CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary="
+ BOUNDARY;
private static final String CRLF = "\r\n";
private static final String[] EMPTY_STRINGS = new String[0];
private static SSLSocketFactory PINNED_FACTORY;
private static SSLSocketFactory TRUSTED_FACTORY;
private static ArrayList<Certificate> PINNED_CERTS;
private static HostnameVerifier TRUSTED_VERIFIER;
private static String getValidCharset(final String charset) {
if (charset != null && charset.length() > 0)
return charset;
else
return CHARSET_UTF8;
}
private static SSLSocketFactory getPinnedFactory()
throws HttpRequestException {
if (PINNED_FACTORY != null) {
return PINNED_FACTORY;
} else {
IOException e = new IOException("You must add at least 1 certificate in order to pin to certificates");
throw new HttpRequestException(e);
}
}
private static SSLSocketFactory getTrustedFactory()
throws HttpRequestException {
if (TRUSTED_FACTORY == null) {
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
// Intentionally left blank
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
// Intentionally left blank
}
} };
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustAllCerts, new SecureRandom());
TRUSTED_FACTORY = context.getSocketFactory();
} catch (GeneralSecurityException e) {
IOException ioException = new IOException(
"Security exception configuring SSL context");
ioException.initCause(e);
throw new HttpRequestException(ioException);
}
}
return TRUSTED_FACTORY;
}
private static HostnameVerifier getTrustedVerifier() {
if (TRUSTED_VERIFIER == null)
TRUSTED_VERIFIER = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
return TRUSTED_VERIFIER;
}
private static StringBuilder addPathSeparator(final String baseUrl,
final StringBuilder result) {
// Add trailing slash if the base URL doesn't have any path segments.
// The following test is checking for the last slash not being part of
// the protocol to host separator: '://'.
if (baseUrl.indexOf(':') + 2 == baseUrl.lastIndexOf('/'))
result.append('/');
return result;
}
private static StringBuilder addParamPrefix(final String baseUrl,
final StringBuilder result) {
// Add '?' if missing and add '&' if params already exist in base url
final int queryStart = baseUrl.indexOf('?');
final int lastChar = result.length() - 1;
if (queryStart == -1)
result.append('?');
else if (queryStart < lastChar && baseUrl.charAt(lastChar) != '&')
result.append('&');
return result;
}
/**
* Creates {@link HttpURLConnection HTTP connections} for
* {@link URL urls}.
*/
public interface ConnectionFactory {
/**
* Open an {@link HttpURLConnection} for the specified {@link URL}.
*
* @throws IOException
*/
HttpURLConnection create(URL url) throws IOException;
/**
* Open an {@link HttpURLConnection} for the specified {@link URL}
* and {@link Proxy}.
*
* @throws IOException
*/
HttpURLConnection create(URL url, Proxy proxy) throws IOException;
/**
* A {@link ConnectionFactory} which uses the built-in
* {@link URL#openConnection()}
*/
ConnectionFactory DEFAULT = new ConnectionFactory() {
public HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
public HttpURLConnection create(URL url, Proxy proxy) throws IOException {
return (HttpURLConnection) url.openConnection(proxy);
}
};
}
private static ConnectionFactory CONNECTION_FACTORY = ConnectionFactory.DEFAULT;
/**
* Specify the {@link ConnectionFactory} used to create new requests.
*/
public static void setConnectionFactory(final ConnectionFactory connectionFactory) {
if (connectionFactory == null)
CONNECTION_FACTORY = ConnectionFactory.DEFAULT;
else
CONNECTION_FACTORY = connectionFactory;
}
/**
* Add a certificate to test against when using ssl pinning.
*
* @param ca
* The Certificate to add
* @throws GeneralSecurityException
* @throws IOException
*/
public static void addCert(Certificate ca) throws GeneralSecurityException, IOException {
if (PINNED_CERTS == null) {
PINNED_CERTS = new ArrayList<Certificate>();
}
PINNED_CERTS.add(ca);
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
for (int i = 0; i < PINNED_CERTS.size(); i++) {
keyStore.setCertificateEntry("CA" + i, PINNED_CERTS[i]);
}
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
PINNED_FACTORY = sslContext.getSocketFactory();
}
/**
* Add a certificate to test against when using ssl pinning.
*
* @param in
* An InputStream to read a certificate from
* @throws GeneralSecurityException
* @throws IOException
*/
public static void addCert(InputStream in) throws GeneralSecurityException, IOException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca;
try {
ca = cf.generateCertificate(in);
addCert(ca);
} finally {
in.close();
}
}
/**
* Callback interface for reporting upload progress for a request.
*/
public interface UploadProgress {
/**
* Callback invoked as data is uploaded by the request.
*
* @param uploaded The number of bytes already uploaded
* @param total The total number of bytes that will be uploaded or -1 if
* the length is unknown.
*/
void onUpload(long uploaded, long total);
UploadProgress DEFAULT = new UploadProgress() {
public void onUpload(long uploaded, long total) {
}
};
}
public static class Base64 {
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte) '=';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
/** The 64 valid Base64 values. */
private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B',
(byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H',
(byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
(byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T',
(byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l',
(byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r',
(byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x',
(byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
(byte) '+', (byte) '/' };
/** Defeats instantiation. */
private Base64() {
}
/**
* <p>
* Encodes up to three bytes of the array <var>source</var> and writes the
* resulting four Base64 bytes to <var>destination</var>. The source and
* destination arrays can be manipulated anywhere along their length by
* specifying <var>srcOffset</var> and <var>destOffset</var>. This method
* does not check to make sure your arrays are large enough to accomodate
* <var>srcOffset</var> + 3 for the <var>source</var> array or
* <var>destOffset</var> + 4 for the <var>destination</var> array. The
* actual number of significant bytes in your array is given by
* <var>numSigBytes</var>.
* </p>
* <p>
* This is the lowest level of the encoding methods with all possible
* parameters.
* </p>
*
* @param source
* the array to convert
* @param srcOffset
* the index where conversion begins
* @param numSigBytes
* the number of significant bytes in your array
* @param destination
* the array to hold the conversion
* @param destOffset
* the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(byte[] source, int srcOffset,
int numSigBytes, byte[] destination, int destOffset) {
byte[] ALPHABET = _STANDARD_ALPHABET;
int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
}
}
/**
* Encode string as a byte array in Base64 annotation.
*
* @param string
* @return The Base64-encoded data as a string
*/
public static String encode(String string) {
byte[] bytes;
try {
bytes = string.getBytes(PREFERRED_ENCODING);
} catch (UnsupportedEncodingException e) {
bytes = string.getBytes();
}
return encodeBytes(bytes);
}
public static String encodeBytes(byte[] source) {
return encodeBytes(source, 0, source.length);
}
public static String encodeBytes(byte[] source, int off, int len) {
byte[] encoded = encodeBytesToBytes(source, off, len);
try {
return new String(encoded, PREFERRED_ENCODING);
} catch (UnsupportedEncodingException uue) {
return new String(encoded);
}
}
public static byte[] encodeBytesToBytes(byte[] source, int off, int len) {
if (source == null)
throw new NullPointerException("Cannot serialize a null array.");
if (off < 0)
throw new IllegalArgumentException("Cannot have negative offset: "
+ off);
if (len < 0)
throw new IllegalArgumentException("Cannot have length offset: " + len);
if (off + len > source.length)
throw new IllegalArgumentException(
String
.format(
"Cannot have offset of %d and length of %d with array of length %d",
off, len, source.length));
// Bytes needed for actual encoding
int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0);
byte[] outBuff = new byte[encLen];
int d = 0;
int e = 0;
int len2 = len - 2;
for (; d < len2; d += 3, e += 4)
encode3to4(source, d + off, 3, outBuff, e);
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e);
e += 4;
}
if (e <= outBuff.length - 1) {
byte[] finalOut = new byte[e];
System.arraycopy(outBuff, 0, finalOut, 0, e);
return finalOut;
} else
return outBuff;
}
}
/**
* HTTP request exception whose cause is always an {@link IOException}
*/
public static class HttpRequestException extends RuntimeException {
private static final long serialVersionUID = -1170466989781746231L;
/**
* Create a new HttpRequestException with the given cause
*
* @param cause
*/
public HttpRequestException(final IOException cause) {
super(cause);
}
/**
* Get {@link IOException} that triggered this request exception
*
* @return {@link IOException} cause
*/
@Override
public IOException getCause() {
return (IOException) super.getCause();
}
}
/**
* Operation that handles executing a callback once complete and handling
* nested exceptions
*
* @param <V>
*/
protected static abstract class Operation<V> implements Callable<V> {
/**
* Run operation
*
* @return result
* @throws HttpRequestException
* @throws IOException
*/
protected abstract V run() throws HttpRequestException, IOException;
/**
* Operation complete callback
*
* @throws IOException
*/
protected abstract void done() throws IOException;
public V call() throws HttpRequestException {
boolean thrown = false;
try {
return run();
} catch (HttpRequestException e) {
thrown = true;
throw e;
} catch (IOException e) {
thrown = true;
throw new HttpRequestException(e);
} finally {
try {
done();
} catch (IOException e) {
if (!thrown)
throw new HttpRequestException(e);
}
}
}
}
/**
* Class that ensures a {@link Closeable} gets closed with proper exception
* handling.
*
* @param <V>
*/
protected static abstract class CloseOperation<V> extends Operation<V> {
private final Closeable closeable;
private final boolean ignoreCloseExceptions;
/**
* Create closer for operation
*
* @param closeable
* @param ignoreCloseExceptions
*/
protected CloseOperation(final Closeable closeable,
final boolean ignoreCloseExceptions) {
this.closeable = closeable;
this.ignoreCloseExceptions = ignoreCloseExceptions;
}
@Override
protected void done() throws IOException {
if (closeable instanceof Flushable)
((Flushable) closeable).flush();
if (ignoreCloseExceptions)
try {
closeable.close();
} catch (IOException e) {
// Ignored
}
else
closeable.close();
}
}
/**
* Class that and ensures a {@link Flushable} gets flushed with proper
* exception handling.
*
* @param <V>
*/
protected static abstract class FlushOperation<V> extends Operation<V> {
private final Flushable flushable;
/**
* Create flush operation
*
* @param flushable
*/
protected FlushOperation(final Flushable flushable) {
this.flushable = flushable;
}
@Override
protected void done() throws IOException {
flushable.flush();
}
}
/**
* Request output stream
*/
public static class RequestOutputStream extends BufferedOutputStream {
private final CharsetEncoder encoder;
/**
* Create request output stream
*
* @param stream
* @param charset
* @param bufferSize
*/
public RequestOutputStream(final OutputStream stream, final String charset,
final int bufferSize) {
super(stream, bufferSize);
encoder = Charset.forName(getValidCharset(charset)).newEncoder();
}
/**
* Write string to stream
*
* @param value
* @return this stream
* @throws IOException
*/
public RequestOutputStream write(final String value) throws IOException {
final ByteBuffer bytes = encoder.encode(CharBuffer.wrap(value));
super.write(bytes.array(), 0, bytes.limit());
return this;
}
}
/**
* Encode the given URL as an ASCII {@link String}
* <p>
* This method ensures the path and query segments of the URL are properly
* encoded such as ' ' characters being encoded to '%20' or any UTF-8
* characters that are non-ASCII. No encoding of URLs is done by default by
* the {@link HttpRequest} constructors and so if URL encoding is needed this
* method should be called before calling the {@link HttpRequest} constructor.
*
* @param url
* @return encoded URL
* @throws HttpRequestException
*/
public static String encode(final CharSequence url)
throws HttpRequestException {
URL parsed;
try {
parsed = new URL(url.toString());
} catch (IOException e) {
throw new HttpRequestException(e);
}
String host = parsed.getHost();
int port = parsed.getPort();
if (port != -1)
host = host + ':' + Integer.toString(port);
try {
String encoded = new URI(parsed.getProtocol(), host, parsed.getPath(),
parsed.getQuery(), null).toASCIIString();
int paramsStart = encoded.indexOf('?');
if (paramsStart > 0 && paramsStart + 1 < encoded.length())
encoded = encoded.substring(0, paramsStart + 1)
+ encoded.substring(paramsStart + 1).replace("+", "%2B");
return encoded;
} catch (URISyntaxException e) {
IOException io = new IOException("Parsing URI failed");
io.initCause(e);
throw new HttpRequestException(io);
}
}
/**
* Append given map as query parameters to the base URL
* <p>
* Each map entry's key will be a parameter name and the value's
* {@link Object#toString()} will be the parameter value.
*
* @param url
* @param params
* @return URL with appended query params
*/
public static String append(final CharSequence url, final Map<?, ?> params) {
final String baseUrl = url.toString();
if (params == null || params.isEmpty())
return baseUrl;
final StringBuilder result = new StringBuilder(baseUrl);
addPathSeparator(baseUrl, result);
addParamPrefix(baseUrl, result);
Entry<?, ?> entry;
Object value;
Iterator<?> iterator = params.entrySet().iterator();
entry = (Entry<?, ?>) iterator.next();
result.append(entry.getKey().toString());
result.append('=');
value = entry.getValue();
if (value != null)
result.append(value);
while (iterator.hasNext()) {
result.append('&');
entry = (Entry<?, ?>) iterator.next();
result.append(entry.getKey().toString());
result.append('=');
value = entry.getValue();
if (value != null)
result.append(value);
}
return result.toString();
}
/**
* Append given name/value pairs as query parameters to the base URL
* <p>
* The params argument is interpreted as a sequence of name/value pairs so the
* given number of params must be divisible by 2.
*
* @param url
* @param params
* name/value pairs
* @return URL with appended query params
*/
public static String append(final CharSequence url, final Object... params) {
final String baseUrl = url.toString();
if (params == null || params.length == 0)
return baseUrl;
if (params.length % 2 != 0)
throw new IllegalArgumentException(
"Must specify an even number of parameter names/values");
final StringBuilder result = new StringBuilder(baseUrl);
addPathSeparator(baseUrl, result);
addParamPrefix(baseUrl, result);
Object value;
result.append(params[0]);
result.append('=');
value = params[1];
if (value != null)
result.append(value);
for (int i = 2; i < params.length; i += 2) {
result.append('&');
result.append(params[i]);
result.append('=');
value = params[i + 1];
if (value != null)
result.append(value);
}
return result.toString();
}
/**
* Start a 'GET' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest get(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_GET);
}
/**
* Start a 'GET' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest get(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_GET);
}
/**
* Start a 'GET' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* The query parameters to include as part of the baseUrl
* @param encode
* true to encode the full URL
*
* @see #append(CharSequence, Map)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest get(final CharSequence baseUrl,
final Map<?, ?> params, final boolean encode) {
String url = append(baseUrl, params);
return get(encode ? encode(url) : url);
}
/**
* Start a 'GET' request to the given URL along with the query params
*
* @param baseUrl
* @param encode
* true to encode the full URL
* @param params
* the name/value query parameter pairs to include as part of the
* baseUrl
*
* @see #append(CharSequence, String...)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest get(final CharSequence baseUrl,
final boolean encode, final Object... params) {
String url = append(baseUrl, params);
return get(encode ? encode(url) : url);
}
/**
* Start a 'POST' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest post(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_POST);
}
/**
* Start a 'POST' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest post(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_POST);
}
/**
* Start a 'POST' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* the query parameters to include as part of the baseUrl
* @param encode
* true to encode the full URL
*
* @see #append(CharSequence, Map)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest post(final CharSequence baseUrl,
final Map<?, ?> params, final boolean encode) {
String url = append(baseUrl, params);
return post(encode ? encode(url) : url);
}
/**
* Start a 'POST' request to the given URL along with the query params
*
* @param baseUrl
* @param encode
* true to encode the full URL
* @param params
* the name/value query parameter pairs to include as part of the
* baseUrl
*
* @see #append(CharSequence, String...)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest post(final CharSequence baseUrl,
final boolean encode, final Object... params) {
String url = append(baseUrl, params);
return post(encode ? encode(url) : url);
}
/**
* Start a 'PUT' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest put(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_PUT);
}
/**
* Start a 'PUT' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest put(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_PUT);
}
/**
* Start a 'PUT' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* the query parameters to include as part of the baseUrl
* @param encode
* true to encode the full URL
*
* @see #append(CharSequence, Map)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest put(final CharSequence baseUrl,
final Map<?, ?> params, final boolean encode) {
String url = append(baseUrl, params);
return put(encode ? encode(url) : url);
}
/**
* Start a 'PUT' request to the given URL along with the query params
*
* @param baseUrl
* @param encode
* true to encode the full URL
* @param params
* the name/value query parameter pairs to include as part of the
* baseUrl
*
* @see #append(CharSequence, String...)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest put(final CharSequence baseUrl,
final boolean encode, final Object... params) {
String url = append(baseUrl, params);
return put(encode ? encode(url) : url);
}
/**
* Start a 'DELETE' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest delete(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_DELETE);
}
/**
* Start a 'DELETE' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest delete(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_DELETE);
}
/**
* Start a 'DELETE' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* The query parameters to include as part of the baseUrl
* @param encode
* true to encode the full URL
*
* @see #append(CharSequence, Map)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest delete(final CharSequence baseUrl,
final Map<?, ?> params, final boolean encode) {
String url = append(baseUrl, params);
return delete(encode ? encode(url) : url);
}
/**
* Start a 'DELETE' request to the given URL along with the query params
*
* @param baseUrl
* @param encode
* true to encode the full URL
* @param params
* the name/value query parameter pairs to include as part of the
* baseUrl
*
* @see #append(CharSequence, String...)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest delete(final CharSequence baseUrl,
final boolean encode, final Object... params) {
String url = append(baseUrl, params);
return delete(encode ? encode(url) : url);
}
/**
* Start a 'HEAD' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest head(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_HEAD);
}
/**
* Start a 'HEAD' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest head(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_HEAD);
}
/**
* Start a 'HEAD' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* The query parameters to include as part of the baseUrl
* @param encode
* true to encode the full URL
*
* @see #append(CharSequence, Map)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest head(final CharSequence baseUrl,
final Map<?, ?> params, final boolean encode) {
String url = append(baseUrl, params);
return head(encode ? encode(url) : url);
}
/**
* Start a 'GET' request to the given URL along with the query params
*
* @param baseUrl
* @param encode
* true to encode the full URL
* @param params
* the name/value query parameter pairs to include as part of the
* baseUrl
*
* @see #append(CharSequence, String...)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest head(final CharSequence baseUrl,
final boolean encode, final Object... params) {
String url = append(baseUrl, params);
return head(encode ? encode(url) : url);
}
/**
* Start an 'OPTIONS' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest options(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_OPTIONS);
}
/**
* Start an 'OPTIONS' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest options(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_OPTIONS);
}
/**
* Start a 'TRACE' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest trace(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_TRACE);
}
/**
* Start a 'TRACE' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest trace(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_TRACE);
}
/**
* Set the 'http.keepAlive' property to the given value.
* <p>
* This setting will apply to all requests.
*
* @param keepAlive
*/
public static void keepAlive(final boolean keepAlive) {
setProperty("http.keepAlive", Boolean.toString(keepAlive));
}
/**
* Set the 'http.maxConnections' property to the given value.
* <p>
* This setting will apply to all requests.
*
* @param maxConnections
*/
public static void maxConnections(final int maxConnections) {
setProperty("http.maxConnections", Integer.toString(maxConnections));
}
/**
* Set the 'http.proxyHost' & 'https.proxyHost' properties to the given host
* value.
* <p>
* This setting will apply to all requests.
*
* @param host
*/
public static void proxyHost(final String host) {
setProperty("http.proxyHost", host);
setProperty("https.proxyHost", host);
}
/**
* Set the 'http.proxyPort' & 'https.proxyPort' properties to the given port
* number.
* <p>
* This setting will apply to all requests.
*
* @param port
*/
public static void proxyPort(final int port) {
final String portValue = Integer.toString(port);
setProperty("http.proxyPort", portValue);
setProperty("https.proxyPort", portValue);
}
/**
* Set the 'http.nonProxyHosts' property to the given host values.
* <p>
* Hosts will be separated by a '|' character.
* <p>
* This setting will apply to all requests.
*
* @param hosts
*/
public static void nonProxyHosts(final String... hosts) {
if (hosts != null && hosts.length > 0) {
StringBuilder separated = new StringBuilder();
int last = hosts.length - 1;
for (int i = 0; i < last; i++)
separated.append(hosts[i]).append('|');
separated.append(hosts[last]);
setProperty("http.nonProxyHosts", separated.toString());
} else
setProperty("http.nonProxyHosts", null);
}
/**
* Set property to given value.
* <p>
* Specifying a null value will cause the property to be cleared
*
* @param name
* @param value
* @return previous value
*/
private static String setProperty(final String name, final String value) {
final PrivilegedAction<String> action;
if (value != null)
action = new PrivilegedAction<String>() {
public String run() {
return System.setProperty(name, value);
}
};
else
action = new PrivilegedAction<String>() {
public String run() {
return System.clearProperty(name);
}
};
return AccessController.doPrivileged(action);
}
private HttpURLConnection connection = null;
private final URL url;
private final String requestMethod;
private RequestOutputStream output;
private boolean multipart;
private boolean form;
private boolean ignoreCloseExceptions = true;
private boolean uncompress = false;
private int bufferSize = 8192;
private long totalSize = -1;
private long totalWritten = 0;
private String httpProxyHost;
private int httpProxyPort;
private UploadProgress progress = UploadProgress.DEFAULT;
/**
* Create HTTP connection wrapper
*
* @param url Remote resource URL.
* @param method HTTP request method (e.g., "GET", "POST").
* @throws HttpRequestException
*/
public HttpRequest(final CharSequence url, final String method)
throws HttpRequestException {
try {
this.url = new URL(url.toString());
} catch (MalformedURLException e) {
throw new HttpRequestException(e);
}
this.requestMethod = method;
}
/**
* Create HTTP connection wrapper
*
* @param url Remote resource URL.
* @param method HTTP request method (e.g., "GET", "POST").
* @throws HttpRequestException
*/
public HttpRequest(final URL url, final String method)
throws HttpRequestException {
this.url = url;
this.requestMethod = method;
}
private Proxy createProxy() {
return new Proxy(HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));
}
private HttpURLConnection createConnection() {
try {
final HttpURLConnection connection;
if (httpProxyHost != null)
connection = CONNECTION_FACTORY.create(url, createProxy());
else
connection = CONNECTION_FACTORY.create(url);
connection.setRequestMethod(requestMethod);
return connection;
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
@Override
public String toString() {
return method() + ' ' + url();
}
/**
* Get underlying connection
*
* @return connection
*/
public HttpURLConnection getConnection() {
if (connection == null)
connection = createConnection();
return connection;
}
/**
* Set whether or not to ignore exceptions that occur from calling
* {@link Closeable#close()}
* <p>
* The default value of this setting is <code>true</code>
*
* @param ignore
* @return this request
*/
public HttpRequest ignoreCloseExceptions(final boolean ignore) {
ignoreCloseExceptions = ignore;
return this;
}
/**
* Get whether or not exceptions thrown by {@link Closeable#close()} are
* ignored
*
* @return true if ignoring, false if throwing
*/
public boolean ignoreCloseExceptions() {
return ignoreCloseExceptions;
}
/**
* Get the status code of the response
*
* @return the response code
* @throws HttpRequestException
*/
public int code() throws HttpRequestException {
try {
closeOutput();
return getConnection().getResponseCode();
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Set the value of the given {@link AtomicInteger} to the status code of the
* response
*
* @param output
* @return this request
* @throws HttpRequestException
*/
public HttpRequest code(final AtomicInteger output)
throws HttpRequestException {
output.set(code());
return this;
}
/**
* Is the response code a 200 OK?
*
* @return true if 200, false otherwise
* @throws HttpRequestException
*/
public boolean ok() throws HttpRequestException {
return HTTP_OK == code();
}
/**
* Is the response code a 201 Created?
*
* @return true if 201, false otherwise
* @throws HttpRequestException
*/
public boolean created() throws HttpRequestException {
return HTTP_CREATED == code();
}
/**
* Is the response code a 204 No Content?
*
* @return true if 204, false otherwise
* @throws HttpRequestException
*/
public boolean noContent() throws HttpRequestException {
return HTTP_NO_CONTENT == code();
}
/**
* Is the response code a 500 Internal Server Error?
*
* @return true if 500, false otherwise
* @throws HttpRequestException
*/
public boolean serverError() throws HttpRequestException {
return HTTP_INTERNAL_ERROR == code();
}
/**
* Is the response code a 400 Bad Request?
*
* @return true if 400, false otherwise
* @throws HttpRequestException
*/
public boolean badRequest() throws HttpRequestException {
return HTTP_BAD_REQUEST == code();
}
/**
* Is the response code a 404 Not Found?
*
* @return true if 404, false otherwise
* @throws HttpRequestException
*/
public boolean notFound() throws HttpRequestException {
return HTTP_NOT_FOUND == code();
}
/**
* Is the response code a 304 Not Modified?
*
* @return true if 304, false otherwise
* @throws HttpRequestException
*/
public boolean notModified() throws HttpRequestException {
return HTTP_NOT_MODIFIED == code();
}
/**
* Get status message of the response
*
* @return message
* @throws HttpRequestException
*/
public String message() throws HttpRequestException {
try {
closeOutput();
return getConnection().getResponseMessage();
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Disconnect the connection
*
* @return this request
*/
public HttpRequest disconnect() {
getConnection().disconnect();
return this;
}
/**
* Set chunked streaming mode to the given size
*
* @param size
* @return this request
*/
public HttpRequest chunk(final int size) {
getConnection().setChunkedStreamingMode(size);
return this;
}
/**
* Set the size used when buffering and copying between streams
* <p>
* This size is also used for send and receive buffers created for both char
* and byte arrays
* <p>
* The default buffer size is 8,192 bytes
*
* @param size
* @return this request
*/
public HttpRequest bufferSize(final int size) {
if (size < 1)
throw new IllegalArgumentException("Size must be greater than zero");
bufferSize = size;
return this;
}
/**
* Get the configured buffer size
* <p>
* The default buffer size is 8,192 bytes
*
* @return buffer size
*/
public int bufferSize() {
return bufferSize;
}
/**
* Set whether or not the response body should be automatically uncompressed
* when read from.
* <p>
* This will only affect requests that have the 'Content-Encoding' response
* header set to 'gzip'.
* <p>
* This causes all receive methods to use a {@link GZIPInputStream} when
* applicable so that higher level streams and readers can read the data
* uncompressed.
* <p>
* Setting this option does not cause any request headers to be set
* automatically so {@link #acceptGzipEncoding()} should be used in
* conjunction with this setting to tell the server to gzip the response.
*
* @param uncompress
* @return this request
*/
public HttpRequest uncompress(final boolean uncompress) {
this.uncompress = uncompress;
return this;
}
/**
* Create byte array output stream
*
* @return stream
*/
protected ByteArrayOutputStream byteStream() {
final int size = contentLength();
if (size > 0)
return new ByteArrayOutputStream(size);
else
return new ByteArrayOutputStream();
}
/**
* Get response as {@link String} in given character set
* <p>
* This will fall back to using the UTF-8 character set if the given charset
* is null
*
* @param charset
* @return string
* @throws HttpRequestException
*/
public String body(final String charset) throws HttpRequestException {
final ByteArrayOutputStream output = byteStream();
try {
copy(buffer(), output);
return output.toString(getValidCharset(charset));
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Get response as {@link String} using character set returned from
* {@link #charset()}
*
* @return string
* @throws HttpRequestException
*/
public String body() throws HttpRequestException {
return body(charset());
}
/**
* Get the response body as a {@link String} and set it as the value of the
* given reference.
*
* @param output
* @return this request
* @throws HttpRequestException
*/
public HttpRequest body(final AtomicReference<String> output) throws HttpRequestException {
output.set(body());
return this;
}
/**
* Get the response body as a {@link String} and set it as the value of the
* given reference.
*
* @param output
* @param charset
* @return this request
* @throws HttpRequestException
*/
public HttpRequest body(final AtomicReference<String> output, final String charset) throws HttpRequestException {
output.set(body(charset));
return this;
}
/**
* Is the response body empty?
*
* @return true if the Content-Length response header is 0, false otherwise
* @throws HttpRequestException
*/
public boolean isBodyEmpty() throws HttpRequestException {
return contentLength() == 0;
}
/**
* Get response as byte array
*
* @return byte array
* @throws HttpRequestException
*/
public byte[] bytes() throws HttpRequestException {
final ByteArrayOutputStream output = byteStream();
try {
copy(buffer(), output);
} catch (IOException e) {
throw new HttpRequestException(e);
}
return output.toByteArray();
}
/**
* Get response in a buffered stream
*
* @see #bufferSize(int)
* @return stream
* @throws HttpRequestException
*/
public BufferedInputStream buffer() throws HttpRequestException {
return new BufferedInputStream(stream(), bufferSize);
}
/**
* Get stream to response body
*
* @return stream
* @throws HttpRequestException
*/
public InputStream stream() throws HttpRequestException {
InputStream stream;
if (code() < HTTP_BAD_REQUEST)
try {
stream = getConnection().getInputStream();
} catch (IOException e) {
throw new HttpRequestException(e);
}
else {
stream = getConnection().getErrorStream();
if (stream == null)
try {
stream = getConnection().getInputStream();
} catch (IOException e) {
if (contentLength() > 0)
throw new HttpRequestException(e);
else
stream = new ByteArrayInputStream(new byte[0]);
}
}
if (!uncompress || !ENCODING_GZIP.equals(contentEncoding()))
return stream;
else
try {
return new GZIPInputStream(stream);
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Get reader to response body using given character set.
* <p>
* This will fall back to using the UTF-8 character set if the given charset
* is null
*
* @param charset
* @return reader
* @throws HttpRequestException
*/
public InputStreamReader reader(final String charset)
throws HttpRequestException {
try {
return new InputStreamReader(stream(), getValidCharset(charset));
} catch (UnsupportedEncodingException e) {
throw new HttpRequestException(e);
}
}
/**
* Get reader to response body using the character set returned from
* {@link #charset()}
*
* @return reader
* @throws HttpRequestException
*/
public InputStreamReader reader() throws HttpRequestException {
return reader(charset());
}
/**
* Get buffered reader to response body using the given character set r and
* the configured buffer size
*
*
* @see #bufferSize(int)
* @param charset
* @return reader
* @throws HttpRequestException
*/
public BufferedReader bufferedReader(final String charset)
throws HttpRequestException {
return new BufferedReader(reader(charset), bufferSize);
}
/**
* Get buffered reader to response body using the character set returned from
* {@link #charset()} and the configured buffer size
*
* @see #bufferSize(int)
* @return reader
* @throws HttpRequestException
*/
public BufferedReader bufferedReader() throws HttpRequestException {
return bufferedReader(charset());
}
/**
* Stream response body to file
*
* @param file
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final File file) throws HttpRequestException {
final OutputStream output;
try {
output = new BufferedOutputStream(new FileOutputStream(file), bufferSize);
} catch (FileNotFoundException e) {
throw new HttpRequestException(e);
}
return new CloseOperation<HttpRequest>(output, ignoreCloseExceptions) {
@Override
protected HttpRequest run() throws HttpRequestException, IOException {
return receive(output);
}
}.call();
}
/**
* Stream response to given output stream
*
* @param output
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final OutputStream output)
throws HttpRequestException {
try {
return copy(buffer(), output);
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Stream response to given print stream
*
* @param output
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final PrintStream output)
throws HttpRequestException {
return receive((OutputStream) output);
}
/**
* Receive response into the given appendable
*
* @param appendable
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final Appendable appendable)
throws HttpRequestException {
final BufferedReader reader = bufferedReader();
return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) {
@Override
public HttpRequest run() throws IOException {
final CharBuffer buffer = CharBuffer.allocate(bufferSize);
int read;
while ((read = reader.read(buffer)) != -1) {
buffer.rewind();
appendable.append(buffer, 0, read);
buffer.rewind();
}
return HttpRequest.this;
}
}.call();
}
/**
* Receive response into the given writer
*
* @param writer
* @return this request
* @throws HttpRequestException
*/
public HttpRequest receive(final Writer writer) throws HttpRequestException {
final BufferedReader reader = bufferedReader();
return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) {
@Override
public HttpRequest run() throws IOException {
return copy(reader, writer);
}
}.call();
}
/**
* Set read timeout on connection to given value
*
* @param timeout
* @return this request
*/
public HttpRequest readTimeout(final int timeout) {
getConnection().setReadTimeout(timeout);
return this;
}
/**
* Set connect timeout on connection to given value
*
* @param timeout
* @return this request
*/
public HttpRequest connectTimeout(final int timeout) {
getConnection().setConnectTimeout(timeout);
return this;
}
/**
* Set header name to given value
*
* @param name
* @param value
* @return this request
*/
public HttpRequest header(final String name, final String value) {
getConnection().setRequestProperty(name, value);
return this;
}
/**
* Set header name to given value
*
* @param name
* @param value
* @return this request
*/
public HttpRequest header(final String name, final Number value) {
return header(name, value != null ? value.toString() : null);
}
/**
* Set all headers found in given map where the keys are the header names and
* the values are the header values
*
* @param headers
* @return this request
*/
public HttpRequest headers(final Map<String, String> headers) {
if (!headers.isEmpty())
for (Entry<String, String> header : headers.entrySet())
header(header);
return this;
}
/**
* Set header to have given entry's key as the name and value as the value
*
* @param header
* @return this request
*/
public HttpRequest header(final Entry<String, String> header) {
return header(header.getKey(), header.getValue());
}
/**
* Get a response header
*
* @param name
* @return response header
* @throws HttpRequestException
*/
public String header(final String name) throws HttpRequestException {
closeOutputQuietly();
return getConnection().getHeaderField(name);
}
/**
* Get all the response headers
*
* @return map of response header names to their value(s)
* @throws HttpRequestException
*/
public Map<String, List<String>> headers() throws HttpRequestException {
closeOutputQuietly();
return getConnection().getHeaderFields();
}
/**
* Get a date header from the response falling back to returning -1 if the
* header is missing or parsing fails
*
* @param name
* @return date, -1 on failures
* @throws HttpRequestException
*/
public long dateHeader(final String name) throws HttpRequestException {
return dateHeader(name, -1L);
}
/**
* Get a date header from the response falling back to returning the given
* default value if the header is missing or parsing fails
*
* @param name
* @param defaultValue
* @return date, default value on failures
* @throws HttpRequestException
*/
public long dateHeader(final String name, final long defaultValue)
throws HttpRequestException {
closeOutputQuietly();
return getConnection().getHeaderFieldDate(name, defaultValue);
}
/**
* Get an integer header from the response falling back to returning -1 if the
* header is missing or parsing fails
*
* @param name
* @return header value as an integer, -1 when missing or parsing fails
* @throws HttpRequestException
*/
public int intHeader(final String name) throws HttpRequestException {
return intHeader(name, -1);
}
/**
* Get an integer header value from the response falling back to the given
* default value if the header is missing or if parsing fails
*
* @param name
* @param defaultValue
* @return header value as an integer, default value when missing or parsing
* fails
* @throws HttpRequestException
*/
public int intHeader(final String name, final int defaultValue)
throws HttpRequestException {
closeOutputQuietly();
return getConnection().getHeaderFieldInt(name, defaultValue);
}
/**
* Get all values of the given header from the response
*
* @param name
* @return non-null but possibly empty array of {@link String} header values
*/
public String[] headers(final String name) {
final Map<String, List<String>> headers = headers();
if (headers == null || headers.isEmpty())
return EMPTY_STRINGS;
final List<String> values = headers.get(name);
if (values != null && !values.isEmpty())
return values.toArray(new String[values.size()]);
else
return EMPTY_STRINGS;
}
/**
* Get parameter with given name from header value in response
*
* @param headerName
* @param paramName
* @return parameter value or null if missing
*/
public String parameter(final String headerName, final String paramName) {
return getParam(header(headerName), paramName);
}
/**
* Get all parameters from header value in response
* <p>
* This will be all key=value pairs after the first ';' that are separated by
* a ';'
*
* @param headerName
* @return non-null but possibly empty map of parameter headers
*/
public Map<String, String> parameters(final String headerName) {
return getParams(header(headerName));
}
/**
* Get parameter values from header value
*
* @param header
* @return parameter value or null if none
*/
protected Map<String, String> getParams(final String header) {
if (header == null || header.length() == 0)
return Collections.emptyMap();
final int headerLength = header.length();
int start = header.indexOf(';') + 1;
if (start == 0 || start == headerLength)
return Collections.emptyMap();
int end = header.indexOf(';', start);
if (end == -1)
end = headerLength;
Map<String, String> params = new LinkedHashMap<String, String>();
while (start < end) {
int nameEnd = header.indexOf('=', start);
if (nameEnd != -1 && nameEnd < end) {
String name = header.substring(start, nameEnd).trim();
if (name.length() > 0) {
String value = header.substring(nameEnd + 1, end).trim();
int length = value.length();
if (length != 0)
if (length > 2 && '"' == value.charAt(0)
&& '"' == value.charAt(length - 1))
params.put(name, value.substring(1, length - 1));
else
params.put(name, value);
}
}
start = end + 1;
end = header.indexOf(';', start);
if (end == -1)
end = headerLength;
}
return params;
}
/**
* Get parameter value from header value
*
* @param value
* @param paramName
* @return parameter value or null if none
*/
protected String getParam(final String value, final String paramName) {
if (value == null || value.length() == 0)
return null;
final int length = value.length();
int start = value.indexOf(';') + 1;
if (start == 0 || start == length)
return null;
int end = value.indexOf(';', start);
if (end == -1)
end = length;
while (start < end) {
int nameEnd = value.indexOf('=', start);
if (nameEnd != -1 && nameEnd < end
&& paramName.equals(value.substring(start, nameEnd).trim())) {
String paramValue = value.substring(nameEnd + 1, end).trim();
int valueLength = paramValue.length();
if (valueLength != 0)
if (valueLength > 2 && '"' == paramValue.charAt(0)
&& '"' == paramValue.charAt(valueLength - 1))
return paramValue.substring(1, valueLength - 1);
else
return paramValue;
}
start = end + 1;
end = value.indexOf(';', start);
if (end == -1)
end = length;
}
return null;
}
/**
* Get 'charset' parameter from 'Content-Type' response header
*
* @return charset or null if none
*/
public String charset() {
return parameter(HEADER_CONTENT_TYPE, PARAM_CHARSET);
}
/**
* Set the 'User-Agent' header to given value
*
* @param userAgent
* @return this request
*/
public HttpRequest userAgent(final String userAgent) {
return header(HEADER_USER_AGENT, userAgent);
}
/**
* Set the 'Referer' header to given value
*
* @param referer
* @return this request
*/
public HttpRequest referer(final String referer) {
return header(HEADER_REFERER, referer);
}
/**
* Set value of {@link HttpURLConnection#setUseCaches(boolean)}
*
* @param useCaches
* @return this request
*/
public HttpRequest useCaches(final boolean useCaches) {
getConnection().setUseCaches(useCaches);
return this;
}
/**
* Set the 'Accept-Encoding' header to given value
*
* @param acceptEncoding
* @return this request
*/
public HttpRequest acceptEncoding(final String acceptEncoding) {
return header(HEADER_ACCEPT_ENCODING, acceptEncoding);
}
/**
* Set the 'Accept-Encoding' header to 'gzip'
*
* @see #uncompress(boolean)
* @return this request
*/
public HttpRequest acceptGzipEncoding() {
return acceptEncoding(ENCODING_GZIP);
}
/**
* Set the 'Accept-Charset' header to given value
*
* @param acceptCharset
* @return this request
*/
public HttpRequest acceptCharset(final String acceptCharset) {
return header(HEADER_ACCEPT_CHARSET, acceptCharset);
}
/**
* Get the 'Content-Encoding' header from the response
*
* @return this request
*/
public String contentEncoding() {
return header(HEADER_CONTENT_ENCODING);
}
/**
* Get the 'Server' header from the response
*
* @return server
*/
public String server() {
return header(HEADER_SERVER);
}
/**
* Get the 'Date' header from the response
*
* @return date value, -1 on failures
*/
public long date() {
return dateHeader(HEADER_DATE);
}
/**
* Get the 'Cache-Control' header from the response
*
* @return cache control
*/
public String cacheControl() {
return header(HEADER_CACHE_CONTROL);
}
/**
* Get the 'ETag' header from the response
*
* @return entity tag
*/
public String eTag() {
return header(HEADER_ETAG);
}
/**
* Get the 'Expires' header from the response
*
* @return expires value, -1 on failures
*/
public long expires() {
return dateHeader(HEADER_EXPIRES);
}
/**
* Get the 'Last-Modified' header from the response
*
* @return last modified value, -1 on failures
*/
public long lastModified() {
return dateHeader(HEADER_LAST_MODIFIED);
}
/**
* Get the 'Location' header from the response
*
* @return location
*/
public String location() {
return header(HEADER_LOCATION);
}
/**
* Set the 'Authorization' header to given value
*
* @param authorization
* @return this request
*/
public HttpRequest authorization(final String authorization) {
return header(HEADER_AUTHORIZATION, authorization);
}
/**
* Set the 'Proxy-Authorization' header to given value
*
* @param proxyAuthorization
* @return this request
*/
public HttpRequest proxyAuthorization(final String proxyAuthorization) {
return header(HEADER_PROXY_AUTHORIZATION, proxyAuthorization);
}
/**
* Set the 'Authorization' header to given values in Basic authentication
* format
*
* @param name
* @param password
* @return this request
*/
public HttpRequest basic(final String name, final String password) {
return authorization("Basic " + Base64.encode(name + ':' + password));
}
/**
* Set the 'Proxy-Authorization' header to given values in Basic authentication
* format
*
* @param name
* @param password
* @return this request
*/
public HttpRequest proxyBasic(final String name, final String password) {
return proxyAuthorization("Basic " + Base64.encode(name + ':' + password));
}
/**
* Set the 'If-Modified-Since' request header to the given value
*
* @param ifModifiedSince
* @return this request
*/
public HttpRequest ifModifiedSince(final long ifModifiedSince) {
getConnection().setIfModifiedSince(ifModifiedSince);
return this;
}
/**
* Set the 'If-None-Match' request header to the given value
*
* @param ifNoneMatch
* @return this request
*/
public HttpRequest ifNoneMatch(final String ifNoneMatch) {
return header(HEADER_IF_NONE_MATCH, ifNoneMatch);
}
/**
* Set the 'Content-Type' request header to the given value
*
* @param contentType
* @return this request
*/
public HttpRequest contentType(final String contentType) {
return contentType(contentType, null);
}
/**
* Set the 'Content-Type' request header to the given value and charset
*
* @param contentType
* @param charset
* @return this request
*/
public HttpRequest contentType(final String contentType, final String charset) {
if (charset != null && charset.length() > 0) {
final String separator = "; " + PARAM_CHARSET + '=';
return header(HEADER_CONTENT_TYPE, contentType + separator + charset);
} else
return header(HEADER_CONTENT_TYPE, contentType);
}
/**
* Get the 'Content-Type' header from the response
*
* @return response header value
*/
public String contentType() {
return header(HEADER_CONTENT_TYPE);
}
/**
* Get the 'Content-Length' header from the response
*
* @return response header value
*/
public int contentLength() {
return intHeader(HEADER_CONTENT_LENGTH);
}
/**
* Set the 'Content-Length' request header to the given value
*
* @param contentLength
* @return this request
*/
public HttpRequest contentLength(final String contentLength) {
return contentLength(Integer.parseInt(contentLength));
}
/**
* Set the 'Content-Length' request header to the given value
*
* @param contentLength
* @return this request
*/
public HttpRequest contentLength(final int contentLength) {
getConnection().setFixedLengthStreamingMode(contentLength);
return this;
}
/**
* Set the 'Accept' header to given value
*
* @param accept
* @return this request
*/
public HttpRequest accept(final String accept) {
return header(HEADER_ACCEPT, accept);
}
/**
* Set the 'Accept' header to 'application/json'
*
* @return this request
*/
public HttpRequest acceptJson() {
return accept(CONTENT_TYPE_JSON);
}
/**
* Copy from input stream to output stream
*
* @param input
* @param output
* @return this request
* @throws IOException
*/
protected HttpRequest copy(final InputStream input, final OutputStream output)
throws IOException {
return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) {
@Override
public HttpRequest run() throws IOException {
final byte[] buffer = new byte[bufferSize];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
totalWritten += read;
progress.onUpload(totalWritten, totalSize);
}
return HttpRequest.this;
}
}.call();
}
/**
* Copy from reader to writer
*
* @param input
* @param output
* @return this request
* @throws IOException
*/
protected HttpRequest copy(final Reader input, final Writer output)
throws IOException {
return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) {
@Override
public HttpRequest run() throws IOException {
final char[] buffer = new char[bufferSize];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
totalWritten += read;
progress.onUpload(totalWritten, -1);
}
return HttpRequest.this;
}
}.call();
}
/**
* Set the UploadProgress callback for this request
*
* @param callback
* @return this request
*/
public HttpRequest progress(final UploadProgress callback) {
if (callback == null)
progress = UploadProgress.DEFAULT;
else
progress = callback;
return this;
}
private HttpRequest incrementTotalSize(final long size) {
if (totalSize == -1)
totalSize = 0;
totalSize += size;
return this;
}
/**
* Close output stream
*
* @return this request
* @throws HttpRequestException
* @throws IOException
*/
protected HttpRequest closeOutput() throws IOException {
progress(null);
if (output == null)
return this;
if (multipart)
output.write(CRLF + "--" + BOUNDARY + "--" + CRLF);
if (ignoreCloseExceptions)
try {
output.close();
} catch (IOException ignored) {
// Ignored
}
else
output.close();
output = null;
return this;
}
/**
* Call {@link #closeOutput()} and re-throw a caught {@link IOException}s as
* an {@link HttpRequestException}
*
* @return this request
* @throws HttpRequestException
*/
protected HttpRequest closeOutputQuietly() throws HttpRequestException {
try {
return closeOutput();
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Open output stream
*
* @return this request
* @throws IOException
*/
protected HttpRequest openOutput() throws IOException {
if (output != null)
return this;
getConnection().setDoOutput(true);
final String charset = getParam(
getConnection().getRequestProperty(HEADER_CONTENT_TYPE), PARAM_CHARSET);
output = new RequestOutputStream(getConnection().getOutputStream(), charset,
bufferSize);
return this;
}
/**
* Start part of a multipart
*
* @return this request
* @throws IOException
*/
protected HttpRequest startPart() throws IOException {
if (!multipart) {
multipart = true;
contentType(CONTENT_TYPE_MULTIPART).openOutput();
output.write("--" + BOUNDARY + CRLF);
} else
output.write(CRLF + "--" + BOUNDARY + CRLF);
return this;
}
/**
* Write part header
*
* @param name
* @param filename
* @return this request
* @throws IOException
*/
protected HttpRequest writePartHeader(final String name, final String filename)
throws IOException {
return writePartHeader(name, filename, null);
}
/**
* Write part header
*
* @param name
* @param filename
* @param contentType
* @return this request
* @throws IOException
*/
protected HttpRequest writePartHeader(final String name,
final String filename, final String contentType) throws IOException {
final StringBuilder partBuffer = new StringBuilder();
partBuffer.append("form-data; name=\"").append(name);
if (filename != null)
partBuffer.append("\"; filename=\"").append(filename);
partBuffer.append('"');
partHeader("Content-Disposition", partBuffer.toString());
if (contentType != null)
partHeader(HEADER_CONTENT_TYPE, contentType);
return send(CRLF);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param part
* @return this request
*/
public HttpRequest part(final String name, final String part) {
return part(name, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final String part) throws HttpRequestException {
return part(name, filename, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param contentType
* value of the Content-Type part header
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final String contentType, final String part) throws HttpRequestException {
try {
startPart();
writePartHeader(name, filename, contentType);
output.write(part);
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final Number part)
throws HttpRequestException {
return part(name, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final Number part) throws HttpRequestException {
return part(name, filename, part != null ? part.toString() : null);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final File part)
throws HttpRequestException {
return part(name, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final File part) throws HttpRequestException {
return part(name, filename, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param contentType
* value of the Content-Type part header
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final String contentType, final File part) throws HttpRequestException {
final InputStream stream;
try {
stream = new BufferedInputStream(new FileInputStream(part));
incrementTotalSize(part.length());
} catch (IOException e) {
throw new HttpRequestException(e);
}
return part(name, filename, contentType, stream);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final InputStream part)
throws HttpRequestException {
return part(name, null, null, part);
}
/**
* Write part of a multipart request to the request body
*
* @param name
* @param filename
* @param contentType
* value of the Content-Type part header
* @param part
* @return this request
* @throws HttpRequestException
*/
public HttpRequest part(final String name, final String filename,
final String contentType, final InputStream part)
throws HttpRequestException {
try {
startPart();
writePartHeader(name, filename, contentType);
copy(part, output);
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Write a multipart header to the response body
*
* @param name
* @param value
* @return this request
* @throws HttpRequestException
*/
public HttpRequest partHeader(final String name, final String value)
throws HttpRequestException {
return send(name).send(": ").send(value).send(CRLF);
}
/**
* Write contents of file to request body
*
* @param input
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final File input) throws HttpRequestException {
final InputStream stream;
try {
stream = new BufferedInputStream(new FileInputStream(input));
incrementTotalSize(input.length());
} catch (FileNotFoundException e) {
throw new HttpRequestException(e);
}
return send(stream);
}
/**
* Write byte array to request body
*
* @param input
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final byte[] input) throws HttpRequestException {
if (input != null)
incrementTotalSize(input.length);
return send(new ByteArrayInputStream(input));
}
/**
* Write stream to request body
* <p>
* The given stream will be closed once sending completes
*
* @param input
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final InputStream input) throws HttpRequestException {
try {
openOutput();
copy(input, output);
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Write reader to request body
* <p>
* The given reader will be closed once sending completes
*
* @param input
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final Reader input) throws HttpRequestException {
try {
openOutput();
} catch (IOException e) {
throw new HttpRequestException(e);
}
final Writer writer = new OutputStreamWriter(output,
output.encoder.charset());
return new FlushOperation<HttpRequest>(writer) {
@Override
protected HttpRequest run() throws IOException {
return copy(input, writer);
}
}.call();
}
/**
* Write char sequence to request body
* <p>
* The charset configured via {@link #contentType(String)} will be used and
* UTF-8 will be used if it is unset.
*
* @param value
* @return this request
* @throws HttpRequestException
*/
public HttpRequest send(final CharSequence value) throws HttpRequestException {
try {
openOutput();
output.write(value.toString());
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Create writer to request output stream
*
* @return writer
* @throws HttpRequestException
*/
public OutputStreamWriter writer() throws HttpRequestException {
try {
openOutput();
return new OutputStreamWriter(output, output.encoder.charset());
} catch (IOException e) {
throw new HttpRequestException(e);
}
}
/**
* Write the values in the map as form data to the request body
* <p>
* The pairs specified will be URL-encoded in UTF-8 and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param values
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Map<?, ?> values) throws HttpRequestException {
return form(values, CHARSET_UTF8);
}
/**
* Write the key and value in the entry as form data to the request body
* <p>
* The pair specified will be URL-encoded in UTF-8 and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param entry
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Entry<?, ?> entry) throws HttpRequestException {
return form(entry, CHARSET_UTF8);
}
/**
* Write the key and value in the entry as form data to the request body
* <p>
* The pair specified will be URL-encoded and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param entry
* @param charset
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Entry<?, ?> entry, final String charset)
throws HttpRequestException {
return form(entry.getKey(), entry.getValue(), charset);
}
/**
* Write the name/value pair as form data to the request body
* <p>
* The pair specified will be URL-encoded in UTF-8 and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param name
* @param value
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Object name, final Object value)
throws HttpRequestException {
return form(name, value, CHARSET_UTF8);
}
/**
* Write the name/value pair as form data to the request body
* <p>
* The values specified will be URL-encoded and sent with the
* 'application/x-www-form-urlencoded' content-type
*
* @param name
* @param value
* @param charset
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Object name, final Object value, String charset)
throws HttpRequestException {
final boolean first = !form;
if (first) {
contentType(CONTENT_TYPE_FORM, charset);
form = true;
}
charset = getValidCharset(charset);
try {
openOutput();
if (!first)
output.write('&');
output.write(URLEncoder.encode(name.toString(), charset));
output.write('=');
if (value != null)
output.write(URLEncoder.encode(value.toString(), charset));
} catch (IOException e) {
throw new HttpRequestException(e);
}
return this;
}
/**
* Write the values in the map as encoded form data to the request body
*
* @param values
* @param charset
* @return this request
* @throws HttpRequestException
*/
public HttpRequest form(final Map<?, ?> values, final String charset)
throws HttpRequestException {
if (!values.isEmpty())
for (Entry<?, ?> entry : values.entrySet())
form(entry, charset);
return this;
}
/**
* Configure HTTPS connection to trust only certain certificates
* <p>
* This method throws an exception if the current request is not a HTTPS request
*
* @return this request
* @throws HttpRequestException
*/
public HttpRequest pinToCerts() throws HttpRequestException {
final HttpURLConnection connection = getConnection();
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setSSLSocketFactory(getPinnedFactory());
} else {
IOException e = new IOException("You must use a https url to use ssl pinning");
throw new HttpRequestException(e);
}
return this;
}
/**
* Configure HTTPS connection to trust all certificates
* <p>
* This method does nothing if the current request is not a HTTPS request
*
* @return this request
* @throws HttpRequestException
*/
public HttpRequest trustAllCerts() throws HttpRequestException {
final HttpURLConnection connection = getConnection();
if (connection instanceof HttpsURLConnection)
((HttpsURLConnection) connection)
.setSSLSocketFactory(getTrustedFactory());
return this;
}
/**
* Configure HTTPS connection to trust all hosts using a custom
* {@link HostnameVerifier} that always returns <code>true</code> for each
* host verified
* <p>
* This method does nothing if the current request is not a HTTPS request
*
* @return this request
*/
public HttpRequest trustAllHosts() {
final HttpURLConnection connection = getConnection();
if (connection instanceof HttpsURLConnection)
((HttpsURLConnection) connection)
.setHostnameVerifier(getTrustedVerifier());
return this;
}
/**
* Get the {@link URL} of this request's connection
*
* @return request URL
*/
public URL url() {
return getConnection().getURL();
}
/**
* Get the HTTP method of this request
*
* @return method
*/
public String method() {
return getConnection().getRequestMethod();
}
/**
* Configure an HTTP proxy on this connection. Use {{@link #proxyBasic(String, String)} if
* this proxy requires basic authentication.
*
* @param proxyHost
* @param proxyPort
* @return this request
*/
public HttpRequest useProxy(final String proxyHost, final int proxyPort) {
if (connection != null)
throw new IllegalStateException("The connection has already been created. This method must be called before reading or writing to the request.");
this.httpProxyHost = proxyHost;
this.httpProxyPort = proxyPort;
return this;
}
/**
* Set whether or not the underlying connection should follow redirects in
* the response.
*
* @param followRedirects - true fo follow redirects, false to not.
* @return this request
*/
public HttpRequest followRedirects(final boolean followRedirects) {
getConnection().setInstanceFollowRedirects(followRedirects);
return this;
}
}
|
package org.jetel.data.formatter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.BufferOverflowException;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataFieldType;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.bytes.CloverBuffer;
import org.jetel.util.string.QuotingDecoder;
public class DataFormatter extends AbstractFormatter {
private String charSet = null;
private CloverBuffer fieldBuffer;
private CloverBuffer fieldFiller;
private int numberOfBytesPerFillerChar; //this is size of DEFAULT_FILLER_CHAR character in bytes in given charset
private DataRecordMetadata metadata;
private WritableByteChannel writer;
private CharsetEncoder encoder;
private byte[][] delimiters;
private byte[] recordDelimiter;
private int[] delimiterLength;
private int[] fieldLengths;
private boolean[] quotedFields;
private boolean[] byteBasedFields;
private CloverBuffer dataBuffer;
private String sFooter;
private String sHeader;
private CloverBuffer footer;
private CloverBuffer header;
private boolean quotedStrings;
/** This flag indicates the last record does not have record delimiter **/
private boolean skipLastRecordDelimiter = false;
/** This flag is just indication of first record to be written.
* This is just implementation detail of skipping last record delimiter. **/
private boolean firstRecord;
private String[] excludedFieldNames;
private int[] includedFieldIndices;
private QuotingDecoder quotingDecoder = new QuotingDecoder();
static Log logger = LogFactory.getLog(DataFormatter.class);
// use space (' ') to fill/pad field
private final static char DEFAULT_FILLER_CHAR = ' ';
// Associations
// Operations
public DataFormatter(){
dataBuffer = CloverBuffer.allocateDirect(Defaults.Record.RECORDS_BUFFER_SIZE);
fieldBuffer = CloverBuffer.allocateDirect(Defaults.Record.FIELD_INITIAL_SIZE, Defaults.Record.FIELD_LIMIT_SIZE);
charSet = Defaults.DataFormatter.DEFAULT_CHARSET_ENCODER;
metadata = null;
}
public DataFormatter(String charEncoder){
dataBuffer = CloverBuffer.allocateDirect(Defaults.Record.RECORDS_BUFFER_SIZE);
fieldBuffer = CloverBuffer.allocateDirect(Defaults.Record.FIELD_INITIAL_SIZE, Defaults.Record.FIELD_LIMIT_SIZE);
charSet = charEncoder;
metadata = null;
}
public DataFormatter(DataFormatter parent) {
// can't be shared without flushing every record, too slow
dataBuffer = CloverBuffer.allocateDirect(Defaults.Record.RECORDS_BUFFER_SIZE);
fieldBuffer = parent.fieldBuffer; // shared buffer, potentially dangerous
charSet = parent.charSet;
metadata = null;
}
public void setExcludedFieldNames(String[] excludedFieldNames) {
this.excludedFieldNames = excludedFieldNames;
}
/* (non-Javadoc)
* @see org.jetel.data.formatter.Formatter#init(org.jetel.metadata.DataRecordMetadata)
*/
@Override
public void init(DataRecordMetadata _metadata) {
// create array of delimiters & initialize them
// create array of field sizes & initialize them
metadata = _metadata;
encoder = Charset.forName(charSet).newEncoder();
initFieldFiller();
encoder.reset();
delimiters = new byte[metadata.getNumFields()][];
delimiterLength = new int[metadata.getNumFields()];
fieldLengths = new int[metadata.getNumFields()];
quotedFields = new boolean[metadata.getNumFields()];
byteBasedFields = new boolean[metadata.getNumFields()];
for (int i = 0; i < metadata.getNumFields(); i++) {
if(metadata.getField(i).isDelimited()) {
quotedFields[i] = quotedStrings
&& metadata.getField(i).getDataType() != DataFieldType.BYTE
&& metadata.getField(i).getDataType() != DataFieldType.CBYTE;
try {
String[] fDelimiters = null;
fDelimiters = metadata.getField(i).getDelimitersWithoutRecordDelimiter(false); //record delimiter is written manually
if (fDelimiters != null) { //for eof delimiter
delimiters[i] = fDelimiters[0].getBytes(charSet);
}
} catch (UnsupportedEncodingException e) {
// can't happen if we have encoder
}
delimiterLength[i] = delimiters[i] == null ? 0 : delimiters[i].length; //for eof delimiter
} else {
fieldLengths[i] = metadata.getField(i).getSize();
}
byteBasedFields[i] = metadata.getField(i).isByteBased();
}
try {
if(metadata.isSpecifiedRecordDelimiter()) {
recordDelimiter = metadata.getRecordDelimiters()[0].getBytes(charSet);
}
} catch (UnsupportedEncodingException e) {
// can't happen if we have encoder
}
includedFieldIndices = metadata.fieldsIndicesComplement(excludedFieldNames);
int lastFieldIndex = metadata.getNumFields() - 1;
int lastIncludedFieldIndex = includedFieldIndices[includedFieldIndices.length - 1];
if (lastIncludedFieldIndex < lastFieldIndex) {
delimiters[lastIncludedFieldIndex] = delimiters[lastFieldIndex];
delimiterLength[lastIncludedFieldIndex] = delimiterLength[lastFieldIndex];
// CLO-5083: removed possibly incorrect code
// fieldLengths[lastIncludedFieldIndex] = fieldLengths[lastFieldIndex];
}
}
@Override
public void reset() {
if (writer != null && writer.isOpen()) {
try{
flush();
writer.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
encoder.reset();
}
/* (non-Javadoc)
* @see org.jetel.data.formatter.Formatter#setDataTarget(java.lang.Object)
*/
@Override
public void setDataTarget(Object out) throws IOException {
close();
// create buffered output stream reader
if (out == null) {
writer = null;
} else if (out instanceof WritableByteChannel) {
writer = (WritableByteChannel) out;
} else {
writer = Channels.newChannel((OutputStream) out);
}
firstRecord = true;
}
/**
* Description of the Method
* @throws IOException
*
* @since March 28, 2002
*/
@Override
public void close() throws IOException {
if (writer == null || !writer.isOpen()) {
return;
}
try {
flush();
} finally {
writer.close();
writer = null;
}
}
@Override
public void finish() throws IOException {
flush();
writeFooter();
flush();
}
/**
* Description of the Method
* @throws IOException
*
* @since March 28, 2002
*/
@Override
public void flush() throws IOException {
dataBuffer.flip();
while (dataBuffer.remaining() > 0) {
writer.write(dataBuffer.buf());
}
dataBuffer.clear();
}
/**
* Write record to output (or buffer).
* @param record
* @return Number of written bytes.
* @throws IOException
*/
@Override
public int write(DataRecord record) throws IOException {
int size;
int encLen = 0;
int i = 0;
try {
//write record delimiter if necessary
if (skipLastRecordDelimiter) {
//in case the last record delimiter should be skipped
//record delimiter is actually written at the beginning of each written record expect the first one
if (!firstRecord) {
encLen += writeRecordDelimiter();
} else {
firstRecord = false;
}
}
for (int index : includedFieldIndices) {
i = index;
if(metadata.getField(i).isDelimited()) {
fieldBuffer.clear();
if (quotedFields[i]) {
//could it be written in better way? faster?
fieldBuffer.put(encoder.encode(CharBuffer.wrap(quotingDecoder.encode(record.getField(i).toString()))));
} else {
record.getField(i).toByteBuffer(fieldBuffer, encoder);
}
int fieldLen = fieldBuffer.position() + delimiterLength[i];
if(fieldLen > dataBuffer.remaining()) {
flush();
}
encLen += fieldLen;
fieldBuffer.flip();
dataBuffer.put(fieldBuffer);
if (delimiters[i] != null) dataBuffer.put(delimiters[i]); //for eof delimiter
} else { //fixlen field
fieldBuffer.clear();
size = record.getField(i).toByteBuffer(fieldBuffer, encoder, fieldLengths[i]);
if (byteBasedFields[i]) {
//the size returned from toByteBuffer() method is always 0 for byte based fields
//let's count it in other way
size = fieldBuffer.position();
if (size > fieldLengths[i]) {
//only byte based fields need to be manually truncated
//the string based fields are already truncated in toByteBuffer function
fieldBuffer.flip();
fieldBuffer.limit(fieldLengths[i]);
} else {
fieldBuffer.flip();
}
} else {
if (size < fieldLengths[i]) { //byte fields are not auto-filled
fieldFiller.rewind();
fieldFiller.limit((fieldLengths[i] - size) * numberOfBytesPerFillerChar);
fieldBuffer.put(fieldFiller);
fieldBuffer.flip();
} else {
fieldBuffer.flip();
}
}
if (dataBuffer.remaining() < fieldBuffer.limit()) {
flush();
}
dataBuffer.put(fieldBuffer);
encLen += fieldBuffer.limit();
}
}
//write record delimiter if necessary
if (!skipLastRecordDelimiter) {
encLen += writeRecordDelimiter();
}
} catch (BufferOverflowException exception) {
throw new RuntimeException("The size of data buffer is only " + dataBuffer.maximumCapacity()
+ ". Set appropriate parameter in defaultProperties file.", exception);
} catch (CharacterCodingException e) {
throw new RuntimeException("Exception when converting the field value: " + record.getField(i).getValue()
+ " (field name: '" + record.getMetadata().getField(i).getName() + "') to " + encoder.charset()
+ ".\nRecord: " +record.toString(), e);
}
return encLen;
}
/**
* Writes record delimiter.
* @return length of written record delimiter
*/
private int writeRecordDelimiter() {
if (recordDelimiter != null){
dataBuffer.put(recordDelimiter);
return recordDelimiter.length;
} else {
return 0;
}
}
/**
* Returns name of charset which is used by this formatter
* @return Name of charset or null if none was specified
*/
public String getCharsetName() {
return(this.charSet);
}
/**
* Initialization of the FieldFiller buffer
*/
private void initFieldFiller() {
// CL-2607 - minor improvement
// allocate fieldFiller to the maximum size of fixed-length fields
int maxFieldSize = Integer.MIN_VALUE;
for (int i = 0; i < metadata.getNumFields(); i++) {
DataFieldMetadata field = metadata.getField(i);
if (field.isFixed() && field.getSize() > maxFieldSize) {
maxFieldSize = field.getSize();
}
}
if (maxFieldSize >= 0) {
// populate fieldFiller so it can be used later when need comes
char[] fillerArray = new char[maxFieldSize];
Arrays.fill(fillerArray, DEFAULT_FILLER_CHAR);
try {
fieldFiller = CloverBuffer.wrap(encoder.encode(CharBuffer.wrap(fillerArray)));
numberOfBytesPerFillerChar = fieldFiller.limit() / fillerArray.length;
} catch (Exception ex) {
throw new RuntimeException("Failed initialization of FIELD_FILLER buffer :" + ex);
}
}
}
@Override
public int writeFooter() throws IOException {
if (footer == null && sFooter != null) {
try {
footer = CloverBuffer.wrap(sFooter.getBytes(encoder.charset().name()));
} catch (UnsupportedEncodingException e) {
throw new UnsupportedCharsetException(encoder.charset().name());
}
}
if (footer != null) {
dataBuffer.put(footer);
footer.rewind();
return footer.remaining();
} else
return 0;
}
@Override
public int writeHeader() throws IOException {
if (append && appendTargetNotEmpty) {
return 0;
}
if (header == null && sHeader != null) {
try {
header = CloverBuffer.wrap(sHeader.getBytes(encoder.charset().name()));
} catch (UnsupportedEncodingException e) {
throw new UnsupportedCharsetException(encoder.charset().name());
}
}
if (header != null) {
dataBuffer.put(header);
header.rewind();
return header.remaining();
} else
return 0;
}
public void setFooter(String footer) {
sFooter = footer;
}
public void setHeader(String header) {
sHeader = header;
}
public void setQuotedStrings(boolean quotedStrings) {
this.quotedStrings = quotedStrings;
}
public boolean getQuotedStrings() {
return quotedStrings;
}
public void setQuoteChar(Character quoteChar) {
quotingDecoder.setQuoteChar(quoteChar);
}
public void setSkipLastRecordDelimiter(boolean skipLastRecordDelimiter) {
this.skipLastRecordDelimiter = skipLastRecordDelimiter;
}
}
|
package org.jetel.data.parser;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFReader.SheetIterator;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.parser.AbstractSpreadsheetParser.CellValueFormatter;
import org.jetel.data.parser.SpreadsheetStreamParser.CellBuffers;
import org.jetel.data.parser.SpreadsheetStreamParser.RecordFieldValueSetter;
import org.jetel.data.parser.XSSFSheetXMLHandler.SheetContentsHandler;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.JetelException;
import org.jetel.exception.JetelRuntimeException;
import org.jetel.exception.SpreadsheetException;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.SpreadsheetUtils;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
public class XLSXStreamParser implements SpreadsheetStreamHandler {
private final static Log LOGGER = LogFactory.getLog(XLSXStreamParser.class);
private SpreadsheetStreamParser parent;
private String fileName;
private String sheetName;
private OPCPackage opcPackage;
private XSSFReader reader;
private StylesTable stylesTable;
private ReadOnlySharedStringsTable sharedStringsTable;
private XMLStreamReader staxParser;
private XMLInputFactory xmlInputFactory;
private RecordFillingContentHandler sheetContentHandler;
private XSSFSheetXMLHandler xssfContentHandler;
private SheetIterator sheetIterator;
private InputStream currentSheetInputStream;
private CellBuffers<CellValue> cellBuffers;
// private CellValue[][] cellBuffers;
// private int nextPartial = -1;
private int currentSheetIndex;
private int nextRecordStartRow;
/** the data formatter used to format cell values as strings */
private final CellValueFormatter dataFormatter = new CellValueFormatter();
private boolean endOfSheet;
public XLSXStreamParser(SpreadsheetStreamParser parent) {
this.parent = parent;
}
@Override
public void init() throws ComponentNotReadyException {
xmlInputFactory = XMLInputFactory.newInstance();
cellBuffers = parent.new CellBuffers<CellValue>();
}
@Override
public DataRecord parseNext(DataRecord record) throws JetelException {
sheetContentHandler.setRecordStartRow(nextRecordStartRow);
sheetContentHandler.setRecord(record);
try {
while (staxParser.hasNext() && !sheetContentHandler.isRecordFinished()) {
processParserEvent(staxParser, xssfContentHandler);
}
if (!staxParser.hasNext()) {
endOfSheet = true;
if (!sheetContentHandler.isRecordFinished()) {
if (!sheetContentHandler.isRecordStarted() && cellBuffers.isEmpty()) {
return null;
}
sheetContentHandler.finishRecord();
}
}
} catch (XMLStreamException e) {
throw new JetelException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
} catch (SAXException e) {
throw new JetelException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
}
nextRecordStartRow += parent.mappingInfo.getStep();
return record;
}
@Override
public int skip(int nRec) throws JetelException {
if (nRec <= 0) {
return 0;
}
sheetContentHandler.skipRecords(nRec);
try {
while (staxParser.hasNext() && sheetContentHandler.isSkipRecords()) {
processParserEvent(staxParser, xssfContentHandler);
}
int skippedRecords = sheetContentHandler.getNumberOfSkippedRecords();
nextRecordStartRow += skippedRecords * parent.mappingInfo.getStep();
return skippedRecords;
} catch (XMLStreamException e) {
throw new JetelException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
} catch (SAXException e) {
throw new JetelException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
}
}
@Override
public List<String> getSheetNames() {
try {
SheetIterator iterator = (SheetIterator) reader.getSheetsData();
List<String> toReturn = new ArrayList<String>();
while (iterator.hasNext()) {
InputStream stream = iterator.next();
toReturn.add(iterator.getSheetName());
stream.close();
}
return toReturn;
} catch (InvalidFormatException e) {
throw new JetelRuntimeException(e);
} catch (IOException e) {
throw new JetelRuntimeException(e);
}
}
@Override
public int getCurrentRecordStartRow() {
return nextRecordStartRow;
}
@Override
public boolean setCurrentSheet(int sheetNumber) {
endOfSheet = false;
if (currentSheetIndex >= sheetNumber) {
closeCurrentInputStream();
initializeSheetIterator();
}
while (currentSheetIndex < sheetNumber && sheetIterator.hasNext()) {
closeCurrentInputStream();
currentSheetInputStream = sheetIterator.next();
currentSheetIndex++;
}
if (currentSheetIndex == sheetNumber) {
try {
staxParser = xmlInputFactory.createXMLStreamReader(currentSheetInputStream);
xssfContentHandler = new XSSFSheetXMLHandler(sharedStringsTable, sheetContentHandler);
sheetContentHandler.setRecordStartRow(parent.startLine);
sheetContentHandler.prepareForNextSheet();
} catch (Exception e) {
throw new JetelRuntimeException("Failed to create XML parser for sheet " + sheetIterator.getSheetName(), e);
}
this.nextRecordStartRow = parent.startLine;
cellBuffers.clear();
sheetName = getSheetNames().get(sheetNumber);
return true;
}
return false;
}
@Override
public String[][] getHeader(int startRow, int startColumn, int endRow, int endColumn) {
if (opcPackage == null) {
return null;
}
try {
List<List<CellValue>> rows = readRows(startRow, startColumn, endRow, endColumn);
String[][] result = new String[rows.size()][];
int i = 0;
for (List<CellValue> row : rows) {
if (row != null && !row.isEmpty()) {
result[i] = new String[row.get(row.size() - 1).columnIndex - startColumn + 1];
for (CellValue cellValue : row) {
result[i][cellValue.columnIndex - startColumn] = cellValue.value;
}
} else {
result[i] = new String[0];
}
i++;
}
return result;
} catch (ComponentNotReadyException e) {
throw new JetelRuntimeException("Failed to provide preview", e);
}
}
@Override
public void prepareInput(Object inputSource) throws IOException, ComponentNotReadyException {
try {
if (inputSource instanceof InputStream) {
opcPackage = OPCPackage.open((InputStream) inputSource);
} else {
File inputFile = (File) inputSource;
fileName = inputFile.getAbsolutePath();
opcPackage = OPCPackage.open(inputFile.getAbsolutePath());
}
reader = new XSSFReader(opcPackage);
stylesTable = reader.getStylesTable();
sharedStringsTable = new ReadOnlySharedStringsTable(opcPackage);
sheetContentHandler = new RecordFillingContentHandler(stylesTable, dataFormatter);
cellBuffers.init(CellValue.class, sheetContentHandler, sheetContentHandler.getFieldValueToFormatSetter());
} catch (InvalidFormatException e) {
throw new ComponentNotReadyException("Error opening the XLSX workbook!", e);
} catch (OpenXML4JException e) {
throw new ComponentNotReadyException("Error opening the XLSX workbook!", e);
} catch (SAXException e) {
throw new ComponentNotReadyException("Error opening the XLSX workbook!", e);
}
initializeSheetIterator();
}
@Override
public void close() throws IOException {
try {
staxParser.close();
} catch (XMLStreamException e) {
LOGGER.warn("Closing parser threw exception", e);
}
closeCurrentInputStream();
}
private static void processParserEvent(XMLStreamReader staxParser, XSSFSheetXMLHandler contentHandler)
throws XMLStreamException, SAXException {
staxParser.next();
switch (staxParser.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
AttributesImpl attrs = new AttributesImpl();
for (int i = 0; i < staxParser.getAttributeCount(); i++) {
attrs.addAttribute(staxParser.getAttributeNamespace(i), staxParser.getAttributeLocalName(i),
qNameToStr(staxParser.getAttributeName(i)), staxParser.getAttributeType(i), staxParser.getAttributeValue(i));
}
contentHandler.startElement(staxParser.getNamespaceURI(), staxParser.getLocalName(), qNameToStr(staxParser.getName()), attrs);
break;
case XMLStreamConstants.CHARACTERS:
contentHandler.characters(staxParser.getTextCharacters(), staxParser.getTextStart(), staxParser.getTextLength());
break;
case XMLStreamConstants.END_ELEMENT:
contentHandler.endElement(staxParser.getNamespaceURI(), staxParser.getLocalName(), qNameToStr(staxParser.getName()));
break;
}
}
private static String qNameToStr(QName qName) {
String prefix = qName.getPrefix();
return prefix.isEmpty() ? qName.getLocalPart() : prefix + ":" + qName.getLocalPart();
}
private void closeCurrentInputStream() {
if (currentSheetInputStream != null) {
try {
currentSheetInputStream.close();
currentSheetInputStream = null;
} catch (IOException e) {
LOGGER.warn("Failed to close input stream", e);
}
}
}
private void initializeSheetIterator() {
try {
sheetIterator = (SheetIterator) reader.getSheetsData();
currentSheetIndex = -1;
} catch (Exception e) {
throw new JetelRuntimeException(e);
}
}
private List<List<CellValue>> readRows(int startRow, int startColumn, int endRow, int endColumn)
throws ComponentNotReadyException {
List<List<CellValue>> rows = new LinkedList<List<CellValue>>();
XMLStreamReader parser = null;
try {
parser = xmlInputFactory.createXMLStreamReader(currentSheetInputStream);
RawRowContentHandler rowContentHandler = new RawRowContentHandler(stylesTable, dataFormatter, startColumn, endColumn);
XSSFSheetXMLHandler xssfContentHandler = new XSSFSheetXMLHandler(sharedStringsTable, rowContentHandler);
int currentRow = startRow;
while (currentRow < endRow) {
rowContentHandler.setRecordStartRow(currentRow);
while (parser.hasNext() && !rowContentHandler.isRecordFinished()) {
processParserEvent(parser, xssfContentHandler);
}
if (!parser.hasNext() && !rowContentHandler.isRecordFinished()) {
return rows;
}
rows.add(rowContentHandler.getCellValues());
currentRow++;
}
} catch (XMLStreamException e) {
throw new ComponentNotReadyException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
} catch (SAXException e) {
throw new ComponentNotReadyException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
} finally {
closeCurrentInputStream();
if (parser != null) {
try {
parser.close();
} catch (XMLStreamException e) {
LOGGER.warn("Closing parser threw an exception", e);
}
}
}
setCurrentSheet(currentSheetIndex);
return rows;
}
// based on org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(Cell)
// public boolean isCellDateFormatted(CellValue cell) {
// boolean bDate = false;
// double d = Double.parseDouble(cell.value);
// if (DateUtil.isValidExcelDate(d) ) {
// CellStyle style = stylesTable.getStyleAt(cell.styleIndex);
// if (style == null) return false;
// int i = style.getDataFormat();
// String f = style.getDataFormatString();
// if (f == null) {
// f = BuiltinFormats.getBuiltinFormat(i);
// bDate = DateUtil.isADateFormat(i, f);
// return bDate;
private abstract class SheetRowContentHandler implements SheetContentsHandler {
/* row on which starts currently read record */
protected int recordStartRow;
/* row where current record finishes */
protected int recordEndRow;
/* actual row which is being parsed */
protected int currentParseRow;
/* flag indicating whether row where current record finishes was read */
protected boolean recordStarted;
protected boolean recordFinished;
protected CellValueFormatter formatter;
protected StylesTable stylesTable;
public SheetRowContentHandler(StylesTable stylesTable, CellValueFormatter formatter) {
this.stylesTable = stylesTable;
this.formatter = formatter;
}
public void prepareForNextSheet() {
recordStartRow = parent.startLine;
recordEndRow = 0;
currentParseRow = -1;
}
public void setRecordStartRow(int startRow) {
recordStartRow = startRow;
recordEndRow = startRow + parent.mapping.length - 1;
recordStarted = false;
recordFinished = recordEndRow < currentParseRow;
}
public boolean isRecordFinished() {
return recordFinished;
}
public boolean isRecordStarted() {
return recordStarted;
}
@Override
public void startRow(int rowNum) {
currentParseRow = rowNum;
if (currentParseRow > recordEndRow) {
recordFinished = true;
}
}
@Override
public void endRow() {
if (currentParseRow >= recordEndRow) {
recordFinished = true;
}
}
@Override
public void headerFooter(String text, boolean isHeader, String tagName) {
// Do nothing, not interested
}
protected String getFormatString(int styleIndex) {
XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
String formatString = style.getDataFormatString();
if (formatString == null) {
formatString = BuiltinFormats.getBuiltinFormat(style.getDataFormat());
}
return formatString;
}
protected String formatNumericToString(String value, int styleIndex, String locale) {
XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
String formatString = getFormatString(styleIndex);
return formatter.formatRawCellContents(Double.parseDouble(value), style.getDataFormat(), formatString, null);
}
}
private class RawRowContentHandler extends SheetRowContentHandler {
private List<CellValue> cellValues = new ArrayList<CellValue>();
private final int firstColumn;
private final int lastColumn;
public RawRowContentHandler(StylesTable stylesTable, CellValueFormatter formatter, int firstColumn, int lastColumn) {
super(stylesTable, formatter);
this.firstColumn = firstColumn;
this.lastColumn = lastColumn;
}
public List<CellValue> getCellValues() {
return new ArrayList<XLSXStreamParser.CellValue>(cellValues);
}
@Override
public void setRecordStartRow(int startRow) {
recordStartRow = startRow;
recordEndRow = startRow;
recordStarted = false;
recordFinished = false;
cellValues.clear();
}
@Override
public void cell(String cellReference, int cellType, int formulaType, String value, int styleIndex) {
if (currentParseRow == recordStartRow) {
int columnIndex = SpreadsheetUtils.getColumnIndex(cellReference);
if (columnIndex < firstColumn || columnIndex >= lastColumn) {
return;
}
String formattedValue = value;
if (cellType == Cell.CELL_TYPE_NUMERIC || (cellType == Cell.CELL_TYPE_FORMULA && formulaType == Cell.CELL_TYPE_NUMERIC)) {
formattedValue = formatNumericToString(value, styleIndex, null);
}
if (cellType != Cell.CELL_TYPE_BLANK) {
cellValues.add(new CellValue(columnIndex, formattedValue, cellType, formulaType, styleIndex));
}
}
}
}
private class RecordFillingContentHandler extends SheetRowContentHandler implements RecordFieldValueSetter<CellValue> {
private DataRecord record;
private int lastColumn = -1;
private int skipStartRow;
private boolean skipRecords = false;
private final RecordFieldValueSetter<CellValue> fieldValueToFormatSetter = new FieldValueToFormatSetter();
public RecordFillingContentHandler(StylesTable stylesTable, CellValueFormatter formatter) {
super(stylesTable, formatter);
}
public void finishRecord() {
for (int i = currentParseRow + 1; i <= recordEndRow; i++) {
handleMissingCells(i - recordStartRow, lastColumn, parent.mapping[0].length);
}
}
public void setRecord(DataRecord record) {
this.record = record;
cellBuffers.fillRecordFromBuffer(record);
}
public boolean isSkipRecords() {
return skipRecords;
}
public int getNumberOfSkippedRecords() {
int result = currentParseRow - skipStartRow;
return result > 0 ? result / parent.mappingInfo.getStep() : 0;
}
public void skipRecords(int nRec) {
if (nRec > 0) {
skipStartRow = recordStartRow;
record = null;
int numberOfRows = nRec * parent.mappingInfo.getStep();
setRecordStartRow(recordStartRow + numberOfRows);
skipRecords = true;
}
}
@Override
public void cell(String cellReference, int cellType, int formulaType, String value, int styleIndex) {
if (currentParseRow < recordStartRow) {
// not interested yet, skip
return;
}
int columnIndex = SpreadsheetUtils.getColumnIndex(cellReference);
if (columnIndex < parent.mappingMinColumn || columnIndex >= parent.mapping[0].length + parent.mappingMinColumn) {
// not interested, skip
return;
}
int shiftedColumnIndex = columnIndex - parent.mappingMinColumn;
int mappingRow = currentParseRow - recordStartRow;
handleMissingCells(mappingRow, lastColumn, shiftedColumnIndex);
lastColumn = shiftedColumnIndex;
CellValue cellValue = new CellValue(-1, value, cellType, formulaType, styleIndex);
cellBuffers.setCellBufferValue(mappingRow, shiftedColumnIndex, cellValue);
if (record != null) {
if (parent.mapping[mappingRow][shiftedColumnIndex] != XLSMapping.UNDEFINED) {
setFieldValue(parent.mapping[mappingRow][shiftedColumnIndex], cellValue);
}
if (parent.formatMapping != null) {
if (parent.formatMapping[mappingRow][shiftedColumnIndex] != XLSMapping.UNDEFINED) {
fieldValueToFormatSetter.setFieldValue(parent.formatMapping[mappingRow][shiftedColumnIndex], cellValue);
}
}
}
}
@Override
public void startRow(int rowNum) {
super.startRow(rowNum);
if (currentParseRow >= recordStartRow) {
skipRecords = false;
}
}
@Override
public void endRow() {
super.endRow();
if (!skipRecords && currentParseRow >= recordStartRow) {
handleMissingCells(currentParseRow - recordStartRow, lastColumn, parent.mapping[0].length);
}
lastColumn = -1;
}
private void handleMissingCells(int mappingRow, int firstColumn, int lastColumn) {
handleMissingCells(parent.mapping[mappingRow], mappingRow, firstColumn, lastColumn);
if (parent.formatMapping != null) {
handleMissingCells(parent.formatMapping[mappingRow], mappingRow, firstColumn, lastColumn);
}
}
private void handleMissingCells(int[] mappingPart, int mappingRow, int firstColumn, int lastColumn) {
for (int i = firstColumn + 1; i < lastColumn; i++) {
int cloverFieldIndex = mappingPart[i];
if (cloverFieldIndex != XLSMapping.UNDEFINED) {
try {
record.getField(cloverFieldIndex).setNull(true);
if (endOfSheet) {
parent.handleException(new SpreadsheetException("Unexpected end of sheet - expected one more data row for field " + record.getField(cloverFieldIndex).getMetadata().getName() +
". Occurred"), record, cloverFieldIndex, fileName, sheetName, null, null, null, null);
}
} catch (BadDataFormatException e) {
parent.handleException(new SpreadsheetException("Cell is empty, but cannot set default value or null into field " + record.getField(cloverFieldIndex).getMetadata().getName(), e), record, cloverFieldIndex, fileName, sheetName, null, null, null, null);
}
}
}
}
@Override
public void setFieldValue(int fieldIndex, CellValue cell) {
setFieldValue(fieldIndex, cell.type, cell.formulaType, cell.value, cell.styleIndex);
}
private void setFieldValue(int cloverFieldIndex, int cellType, int formulaType, String value, int styleIndex) {
if (!recordStarted) {
recordStarted = true;
}
DataField field = record.getField(cloverFieldIndex);
String cellFormat = null;
try {
switch (field.getType()) {
case DataFieldMetadata.DATE_FIELD:
case DataFieldMetadata.DATETIME_FIELD:
if (cellType == Cell.CELL_TYPE_NUMERIC) {
field.setValue(DateUtil.getJavaDate(Double.parseDouble(value), AbstractSpreadsheetParser.USE_DATE1904));
} else {
throw new IllegalStateException("Cannot get Date value from cell of type " + cellTypeToString(cellType));
}
break;
case DataFieldMetadata.BYTE_FIELD:
case DataFieldMetadata.STRING_FIELD:
if (cellType == Cell.CELL_TYPE_NUMERIC || (cellType == Cell.CELL_TYPE_FORMULA && formulaType == Cell.CELL_TYPE_NUMERIC)) {
field.fromString(formatNumericToString(value, styleIndex, field.getMetadata().getLocaleStr()));
} else {
field.fromString(value);
}
break;
case DataFieldMetadata.DECIMAL_FIELD:
case DataFieldMetadata.INTEGER_FIELD:
case DataFieldMetadata.LONG_FIELD:
case DataFieldMetadata.NUMERIC_FIELD:
field.setValue(Double.parseDouble(value));
break;
case DataFieldMetadata.BOOLEAN_FIELD:
if (cellType == Cell.CELL_TYPE_BOOLEAN) {
field.setValue(XSSFSheetXMLHandler.CELL_VALUE_TRUE.equals(value));
} else {
throw new IllegalStateException("Cannot get Boolean value from cell of type " + cellTypeToString(cellType));
}
break;
}
} catch (RuntimeException ex1) { // exception when trying get date or number from a different cell type
try {
// field.fromString(value);
field.setNull(true);
} catch (Exception ex2) {
}
String cellCoordinates = SpreadsheetUtils.getColumnReference(lastColumn + parent.mappingMinColumn) + String.valueOf(currentParseRow);
// parent.handleException(new BadDataFormatException("All attempts to set value \""+ value +"\" into field \"" + field.getMetadata().getName() + "\" (" + field.getMetadata().getTypeAsString() + ") failed:\n1st try error: " + ex1 + "\n"),
// record, cloverFieldIndex, cellCoordinates, value);
parent.handleException(new SpreadsheetException(ex1.getMessage() + " in " + cellCoordinates), record, cloverFieldIndex,
fileName, sheetName, cellCoordinates, value, cellTypeToString(cellType), cellFormat);
}
}
private String cellTypeToString(int cellType) {
switch (cellType) {
case Cell.CELL_TYPE_BOOLEAN:
return "Boolean";
case Cell.CELL_TYPE_STRING:
return "String";
case Cell.CELL_TYPE_NUMERIC:
return "Numeric";
default:
return "Unknown";
}
}
protected RecordFieldValueSetter<CellValue> getFieldValueToFormatSetter() {
return fieldValueToFormatSetter;
}
private class FieldValueToFormatSetter implements RecordFieldValueSetter<CellValue> {
@Override
public void setFieldValue(int cloverFieldIndex, CellValue cellValue) {
DataField field = record.getField(cloverFieldIndex);
String format = getFormatString(cellValue.styleIndex);
field.fromString(format);
}
}
}
private static class CellValue {
public final int columnIndex;
public final String value;
public final int type;
public final int formulaType;
public final int styleIndex;
CellValue(int columnIndex, String value, int type, int formulaType, int styleIndex) {
this.columnIndex = columnIndex;
this.value = value;
this.type = type;
this.formulaType = formulaType;
this.styleIndex = styleIndex;
}
}
}
|
package com.afollestad.silk.adapters;
import android.content.Context;
import android.database.Cursor;
import com.afollestad.silk.caching.SilkCursorItem;
import java.lang.reflect.Method;
/**
* A CursorAdapter wrapper that makes creating list adapters easier. Contains various convenience methods and handles
* recycling views on its own.
*
* @param <ItemType> The type of items held in the adapter.
* @author Aidan Follestad (afollestad)
*/
public abstract class SilkCursorAdapter<ItemType extends SilkCursorItem> extends SilkAdapter<ItemType> implements ScrollStatePersister {
private Cursor mCursor;
private Class<? extends SilkCursorItem> mClass;
public SilkCursorAdapter(Context context, Class<? extends SilkCursorItem> cls) {
super(context);
mClass = cls;
}
public final Cursor getCursor() {
return mCursor;
}
public final void changeCursor(Cursor cursor) {
mCursor = cursor;
notifyDataSetChanged();
}
@Override
public int getCount() {
if (mCursor == null) return 0;
return mCursor.getCount();
}
public final ItemType getItem(int position) {
if (mCursor == null || mCursor.getCount() == 0) return null;
mCursor.moveToPosition(position);
return performConvert();
}
private ItemType performConvert() {
try {
Object o = mClass.newInstance();
Method m = mClass.getDeclaredMethod("convert", Cursor.class);
return (ItemType) m.invoke(o, getCursor());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("An error occurred while invoking convert() of class " + mClass.getName() + ": " + e.getMessage());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.