answer
stringlengths
17
10.2M
package cpw.mods.fml.common; /** * Copied from ConsoleLogFormatter for shared use on the client * */ import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; final class FMLLogFormatter extends Formatter { private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public String format(LogRecord record) { StringBuilder msg = new StringBuilder(); msg.append(this.dateFormat.format(Long.valueOf(record.getMillis()))); Level lvl = record.getLevel(); if (lvl == Level.FINEST) { msg.append(" [FINEST] "); } else if (lvl == Level.FINER) { msg.append(" [FINER] "); } else if (lvl == Level.FINE) { msg.append(" [FINE] "); } else if (lvl == Level.INFO) { msg.append(" [INFO] "); } else if (lvl == Level.WARNING) { msg.append(" [WARNING] "); } else if (lvl == Level.SEVERE) { msg.append(" [SEVERE] "); } else if (lvl == Level.SEVERE) { msg.append(" [" + lvl.getLocalizedName() + "] "); } msg.append(record.getMessage()); msg.append(System.getProperty("line.separator")); Throwable thr = record.getThrown(); if (thr != null) { StringWriter thrDump = new StringWriter(); thr.printStackTrace(new PrintWriter(thrDump)); msg.append(thrDump.toString()); } return msg.toString(); } }
package net.simpvp.NoSpam; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; public class CommandListener implements Listener { public CommandListener(NoSpam plugin) { plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority=EventPriority.LOW, ignoreCancelled=false) public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) { Player player = event.getPlayer(); String message = event.getMessage().toLowerCase(); /* Important: The spaces afterwards are necessary. Otherwise we get something like this being activated on /world because of /w */ if (message.startsWith("/tell ") || message.startsWith("/me ") || message.startsWith("/msg ") || message.startsWith("/w ") || message.startsWith("/op ") || message.startsWith("/r ") || message.startsWith("/m ") || message.equals("/op")) { boolean cancel = SpamHandler.isSpamming(player); // The Handler class checks if it's spam if ( cancel ) event.setCancelled(true); } } }
package edu.stuy; import static edu.stuy.RobotMap.*; import edu.stuy.commands.ArmsSetNarrowCommand; import edu.stuy.commands.LiftUpInchesCommand; import edu.stuy.subsystems.*; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.CommandGroup; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.stuy.commands.auton.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static Drivetrain drivetrain; public static LeftAcquirer leftAcquirer; public static RightAcquirer rightAcquirer; public static Arms arms; public static Lift lift; public static OI oi; Command autonomousCommand; SendableChooser autonChooser; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { drivetrain = new Drivetrain(); leftAcquirer = new LeftAcquirer(); rightAcquirer = new RightAcquirer(); arms = new Arms(); lift = new Lift(); oi = new OI(); SmartDashboard.putData(drivetrain); SmartDashboard.putData(leftAcquirer); SmartDashboard.putData(rightAcquirer); SmartDashboard.putData(arms); SmartDashboard.putData(lift); SmartDashboard.putData(Scheduler.getInstance()); setupAutonChooser(); } private void setupAutonChooser() { autonChooser = new SendableChooser(); // Driving backward from Scoring Platform means we are doing a mobility auton routine without pushing totes autonChooser.addDefault("1. Drive backward from Scoring Platform", new AutonDriveBackwardInchesCommand(AUTON_DRIVE_BACKWARD_SCORING_PLATFORM_INCHES, AUTON_DRIVE_BACKWARD_SCORING_PLATFORM_TIMEOUT)); autonChooser.addObject("2. Drive forward from Driver Side with arms narrow to push tote", new AutonOneTotePushForwardCommand()); autonChooser.addObject("3. Drive forward from Driver Side with arms released to push both tote and bin", new AutonOneSetPushForwardCommand()); // -1 means that AutonDriveForwardInches/AutonDriveBackwardInches uses INCHES_LABEL. Defers reading of SmartDashboard value until auton starts autonChooser.addObject("4. Drive forward Custom Amount", new AutonDriveForwardInchesCommand(-1, AUTON_DRIVETRAIN_TIMEOUT)); autonChooser.addObject("5. Drive backward Custom Amount", new AutonDriveBackwardInchesCommand(-1, AUTON_DRIVETRAIN_TIMEOUT)); autonChooser.addObject("6. Do nothing", new CommandGroup()); autonChooser.addObject("7. Lift ten inches then do auton 3", new AutonLiftAndDrive()); autonChooser.addObject("8. Lift ten inches, then do nothing", new LiftUpInchesCommand(AUTON_LIFT_DISTANCE)); autonChooser.addObject("9. Lift ten inches, then drive backwards", new AutonLiftAndDriveBackwards()); autonChooser.addObject("10. Lift tote to auton zone", new AutonLiftToteTurnDriveForward()); autonChooser.addObject("11. Lift container to auton zone", new AutonLiftContainerTurnDriveForward()); autonChooser.addObject("12. Lift container and herd tote to auton zone", new AutonLiftContainerHerdTote()); autonChooser.addObject("13. Herd tote into auton zone", new AutonTurnAndHerdTote()); SmartDashboard.putData("Auton setting", autonChooser); SmartDashboard.putNumber(INCHES_LABEL, -1); } public void disabledPeriodic() { Scheduler.getInstance().run(); } public void autonomousInit() { drivetrain.resetEncoders(); drivetrain.setBrakeMode(true); lift.setOverridden(false); autonomousCommand = (Command) autonChooser.getSelected(); autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); SmartDashboard.putNumber("Left Encoder:", Robot.drivetrain.getLeftEncoder()); SmartDashboard.putNumber("Right Encoder:", Robot.drivetrain.getRightEncoder()); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) autonomousCommand.cancel(); // Initialize subsystem states: new ArmsSetNarrowCommand().start(); drivetrain.setBrakeMode(false); drivetrain.setSpeedUp(true); lift.setOverridden(false); } /** * This function is called when the disabled button is hit. * You can use it to reset subsystems before shutting down. */ public void disabledInit(){ } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); lift.runEncoderLogic(); SmartDashboard.putNumber("Left Encoder:", Robot.drivetrain.getLeftEncoder()); SmartDashboard.putNumber("Right Encoder:", Robot.drivetrain.getRightEncoder()); SmartDashboard.putNumber("Gyro Angle:", Robot.drivetrain.getGyroAngle()); SmartDashboard.putNumber("Lift Encoder:", Robot.lift.getLiftEncoder()); SmartDashboard.putBoolean("Lift Limit Switch", Robot.lift.isAtBottom()); SmartDashboard.putBoolean("Lift Overridden?" , Robot.lift.getOverridden()); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
package org.iatrix.widgets; import java.util.Hashtable; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.widgets.FormToolkit; import org.iatrix.data.KonsTextLock; import org.iatrix.dialogs.ChooseKonsRevisionDialog; import org.iatrix.util.Heartbeat; import org.iatrix.util.Heartbeat.IatrixHeartListener; import org.iatrix.util.Helpers; import org.iatrix.views.JournalView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.data.util.Extensions; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.constants.ExtensionPointConstantsUi; import ch.elexis.core.ui.icons.Images; import ch.elexis.core.ui.text.EnhancedTextField; import ch.elexis.core.ui.util.IKonsExtension; import ch.elexis.core.ui.util.IKonsMakro; import ch.elexis.core.ui.util.SWTHelper; import ch.elexis.data.Anwender; import ch.elexis.data.Konsultation; import ch.elexis.data.Patient; import ch.elexis.data.PersistentObject; import ch.rgw.tools.TimeTool; import ch.rgw.tools.VersionedResource; import ch.rgw.tools.VersionedResource.ResourceItem; public class KonsText implements IJournalArea { private static Konsultation actKons = null; private static int konsTextSaverCount = 0; private static Logger log = LoggerFactory.getLogger(org.iatrix.widgets.KonsText.class); private static EnhancedTextField text; private static Label lVersion = null; private static Label lKonsLock = null; private static KonsTextLock konsTextLock = null; int displayedVersion; private Action purgeAction; private Action saveAction; private Action chooseVersionAction; private Action versionFwdAction; private Action versionBackAction; private static final String PATIENT_KEY = "org.iatrix.patient"; private final FormToolkit tk; private Composite parent; private Hashtable<String, IKonsExtension> hXrefs; public KonsText(Composite parentComposite){ parent = parentComposite; tk = UiDesk.getToolkit(); SashForm konsultationSash = new SashForm(parent, SWT.HORIZONTAL); konsultationSash.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); Composite konsultationTextComposite = tk.createComposite(konsultationSash); konsultationTextComposite.setLayout(new GridLayout(1, true)); text = new EnhancedTextField(konsultationTextComposite); hXrefs = new Hashtable<>(); @SuppressWarnings("unchecked") List<IKonsExtension> listKonsextensions = Extensions.getClasses( Extensions.getExtensions(ExtensionPointConstantsUi.KONSEXTENSION), "KonsExtension", //$NON-NLS-1$ //$NON-NLS-2$ false); for (IKonsExtension x : listKonsextensions) { String provider = x.connect(text); hXrefs.put(provider, x); } text.setXrefHandlers(hXrefs); @SuppressWarnings("unchecked") List<IKonsMakro> makros = Extensions.getClasses( Extensions.getExtensions(ExtensionPointConstantsUi.KONSEXTENSION), "KonsMakro", false); //$NON-NLS-1$ text.setExternalMakros(makros); text.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true)); makeActions(); text.getControl().addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e){ logEvent("widgetDisposed removeKonsTextLock"); updateEintrag(); removeKonsTextLock(); } }); tk.adapt(text); lVersion = tk.createLabel(konsultationTextComposite, "<aktuell>"); lVersion.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); lKonsLock = tk.createLabel(konsultationTextComposite, ""); lKonsLock.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false)); lKonsLock.setForeground(lKonsLock.getDisplay().getSystemColor(SWT.COLOR_RED)); lKonsLock.setVisible(false); registerUpdateHeartbeat(); } public Action getPurgeAction(){ return purgeAction; } public Action getSaveAction(){ return saveAction; } public Action getChooseVersionAction(){ return chooseVersionAction; } public Action getVersionForwardAction(){ return versionFwdAction; } public Action getVersionBackAction(){ return versionBackAction; } private void showUnableToSaveKons(String plain, String errMsg) { logEvent("showUnableToSaveKons errMsg: " + errMsg + " plain: " + plain); if (plain.length() == 0 ) { log.warn("showUnableToSaveKons Inhalt war leer"); return; } boolean added = false; try { Clipboard clipboard = new Clipboard(UiDesk.getDisplay()); TextTransfer textTransfer = TextTransfer.getInstance(); Transfer[] transfers = new Transfer[] { textTransfer }; Object[] data = new Object[] { plain }; clipboard.setContents(data, transfers); clipboard.dispose(); added = true; } catch (Exception ex) { log.error("Fehlerhaftes clipboard " + plain); } StringBuilder sb = new StringBuilder(); if (plain.length() > 0 && added) { sb.append("Inhalt wurde in die Zwischenablage aufgenommen\n"); } sb.append("Patient: " + actKons.getFall().getPatient().getPersonalia()+ "\n"); sb.append("\nInhalt ist:\n sb.append(plain); sb.append("\n SWTHelper.alert("Konnte Konsultationstext nicht abspeichern", sb.toString()); } public synchronized void updateEintrag(){ if (actKons != null) { if (actKons.getFall() == null) { return; } if (text.isDirty() || textChanged()) { int old_version = actKons.getHeadVersion(); String plain = text.getContentsPlaintext(); logEvent("updateEintrag old_version " + old_version + " " + actKons.getId() + " dirty " + text.isDirty() + " changed " + textChanged()); if (hasKonsTextLock()) { if (!actKons.isEditable(false)) { String notEditable = "Aktuelle Konsultation kannn nicht editiert werden"; showUnableToSaveKons(plain, notEditable); } else { actKons.updateEintrag(text.getContentsAsXML(), false); int new_version = actKons.getHeadVersion(); if (new_version <= old_version || !actKons.getEintrag().getHead().contentEquals(plain) ) { String errMsg = "Unable to update: old_version " + old_version + " new_version " + new_version; logEvent("updateEintrag " + errMsg + plain); showUnableToSaveKons(plain, errMsg); } else { logEvent("updateEintrag saved rev. " + new_version + " plain: " + plain); text.setDirty(false); // TODO: Warum merkt das KonsListView trotzdem nicht ?? ElexisEventDispatcher.fireSelectionEvent(actKons); } } } else { // should never happen... String errMsg = "Konsultation gesperrt old_version " + old_version + "konsTextLock " + (konsTextLock == null ? "null" : "key " + konsTextLock.getKey() + " lock " + konsTextLock.getLockValue()); showUnableToSaveKons(plain, errMsg); } } } } /** * Check whether the text in the text field has changed compared to the database entry. * * @return true, if the text changed, false else */ private boolean textChanged(){ if (actKons == null || text == null) { return false; } String dbEintrag = actKons.getEintrag().getHead(); String textEintrag = text.getContentsAsXML(); if (textEintrag != null) { if (!textEintrag.equals(dbEintrag)) { // text differs from db entry logEvent("saved text != db entry"); return true; } } return false; } private void updateKonsLockLabel(){ if (konsTextLock == null || hasKonsTextLock()) { lKonsLock.setVisible(false); lKonsLock.setText(""); } else { Anwender user = konsTextLock.getLockValue().getUser(); StringBuilder text = new StringBuilder(); if (user != null && user.exists()) { text.append( "Konsultation wird von Benutzer \"" + user.getLabel() + "\" bearbeitet."); } else { text.append("Konsultation wird von anderem Benutzer bearbeitet."); } text.append(" Rechner \"" + konsTextLock.getLockValue().getHost() + "\"."); log.debug("updateKonsLockLabel: " + text.toString()); lKonsLock.setText(text.toString()); lKonsLock.setVisible(true); } lKonsLock.getParent().layout(); } // helper method to create a KonsTextLock object in a save way // should be called when a new konsultation is set private synchronized void createKonsTextLock(){ // remove old lock removeKonsTextLock(); if (actKons != null && CoreHub.actUser != null) { konsTextLock = new KonsTextLock(actKons, CoreHub.actUser); } else { konsTextLock = null; } if (konsTextLock != null) { konsTextLock.lock(); // boolean success = konsTextLock.lock(); // logEvent( // "createKonsTextLock: konsText locked (" + success + ")" + konsTextLock.getKey()); } } // helper method to release a KonsTextLock // should be called before a new konsultation is set // or the program/view exits private synchronized void removeKonsTextLock(){ if (konsTextLock != null) { konsTextLock.unlock(); // boolean success = konsTextLock.unlock(); // logEvent( // "removeKonsTextLock: konsText unlocked (" + success + ") " + konsTextLock.getKey()); konsTextLock = null; } } /** * Check whether we own the lock * * @return true, if we own the lock, false else */ private synchronized boolean hasKonsTextLock(){ return (konsTextLock != null && konsTextLock.isLocked()); } @Override public synchronized void visible(boolean mode){ } private void makeActions(){ // Konsultationstext purgeAction = new Action("Alte Eintragsversionen entfernen") { @Override public void run(){ actKons.purgeEintrag(); ElexisEventDispatcher.fireSelectionEvent(actKons); } }; versionBackAction = new Action("Vorherige Version") { @Override public void run(){ if (MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Konsultationstext ersetzen", "Wollen Sie wirklich den aktuellen Konsultationstext gegen eine frühere Version desselben Eintrags ersetzen?")) { setKonsText(actKons, displayedVersion - 1, false); text.setDirty(true); } } }; versionFwdAction = new Action("nächste Version") { @Override public void run(){ if (MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Konsultationstext ersetzen", "Wollen Sie wirklich den aktuellen Konsultationstext gegen eine spätere Version desselben Eintrags ersetzen?")) { setKonsText(actKons, displayedVersion + 1, false); text.setDirty(true); } } }; chooseVersionAction = new Action("Version wählen...") { @Override public void run(){ ChooseKonsRevisionDialog dlg = new ChooseKonsRevisionDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), actKons); if (dlg.open() == ChooseKonsRevisionDialog.OK) { int selectedVersion = dlg.getSelectedVersion(); if (MessageDialog.openConfirm( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Konsultationstext ersetzen", "Wollen Sie wirklich den aktuellen Konsultationstext gegen die Version " + selectedVersion + " desselben Eintrags ersetzen?")) { setKonsText(actKons, selectedVersion, false); text.setDirty(true); } } } }; saveAction = new Action("Eintrag sichern") { { setImageDescriptor(Images.IMG_DISK.getImageDescriptor()); setToolTipText("Text explizit speichern"); } @Override public void run(){ logEvent("saveAction: "); updateEintrag(); JournalView.updateAllKonsAreas(actKons.getFall().getPatient(), actKons, KonsActions.SAVE_KONS); } }; }; private void updateKonsultation(boolean updateText){ if (actKons != null) { if (updateText) { setKonsText(actKons, actKons.getHeadVersion(), true); } logEvent("updateKonsultation: " + actKons.getId()); } else { setKonsText(null, 0, true); logEvent("updateKonsultation: null"); } } /** * Aktuelle Konsultation setzen. * * Wenn eine Konsultation gesetzt wird stellen wir sicher, dass der gesetzte Patient zu dieser * Konsultation gehoert. Falls nicht, wird ein neuer Patient gesetzt. * @param putCaretToEnd * if true, activate text field ant put caret to the end */ @Override public synchronized void setKons(Patient newPatient, Konsultation k, KonsActions op){ if (op == KonsActions.SAVE_KONS) { if (text.isDirty() || textChanged()) { logEvent("setKons.SAVE_KONS text.isDirty or changed saving Kons from " + actKons.getDatum() + " is '" + text.getContentsPlaintext() + "'"); updateEintrag(); text.setData(PATIENT_KEY, null); text.setText("saved kons"); removeKonsTextLock(); actKons = null; // Setting it to null made clicking twice for a kons in the kons history the kontext disapper } else { if (actKons != null && text != null) { logEvent("setKons.SAVE_KONS nothing to save for Kons from " + actKons.getDatum() + " is '" + text.getContentsPlaintext() + "'"); } } return; } if (op == KonsActions.ACTIVATE_KONS) { // make sure to unlock the kons edit field and release the lock if (text != null && actKons != null) { logEvent("setKons.ACTIVATE_KONS text.isDirty " + text.isDirty() + " textChanged " + textChanged() + " actKons vom: " + actKons.getDatum()); } removeKonsTextLock(); if (k == null) { actKons = k; logEvent("setKons null"); } else { logEvent("setKons " + (actKons == null ? "null" : actKons.getId()) + " => " + k.getId()); actKons = k; boolean konsEditable = Helpers.hasRightToChangeConsultations(actKons, false); if (!konsEditable) { // isEditable(true) would give feedback to user why consultation // cannot be edited, but this often very shortlived as we create/switch // to a newly created kons of today logEvent("setKons actKons is not editable"); text.setEnabled(false); setKonsText(k, 0, true); updateKonsultation(true); updateKonsLockLabel(); lVersion.setText(lVersion.getText() + " Nicht editierbar. (Keine Zugriffsrechte oder schon verrechnet)"); return; } else { text.setEnabled(true); } createKonsTextLock(); setKonsText(k, 0, true); } updateKonsultation(true); updateKonsLockLabel(); updateKonsVersionLabel(); saveAction.setEnabled(konsTextLock == null || hasKonsTextLock()); } } /** * Set the version label to reflect the current kons' latest version Called by: updateEintrag() */ private void updateKonsVersionLabel(){ if (actKons != null) { int version = actKons.getHeadVersion(); VersionedResource vr = actKons.getEintrag(); ResourceItem entry = vr.getVersion(version); StringBuilder sb = new StringBuilder(); if (entry == null) { sb.append(actKons.getLabel() + " (neu)"); } else { String revisionTime = new TimeTool(entry.timestamp).toString(TimeTool.FULL_GER); String revisionDate = new TimeTool(entry.timestamp).toString(TimeTool.DATE_GER); if (!actKons.getDatum().equals(revisionDate)) { sb.append("Kons vom " + actKons.getDatum() + ": "); } sb.append("rev. ").append(version).append(" vom ") .append(revisionTime).append(" (") .append(entry.remark).append(")"); TimeTool konsDate = new TimeTool(actKons.getDatum()); if (version == -1 && konsDate.isSameDay(new TimeTool())) { sb.append(" (NEU)"); } } lVersion.setText(sb.toString()); logEvent("UpdateVersionLabel: " + sb.toString()); } else { lVersion.setText(""); } } private synchronized void setKonsText(Konsultation b, int version, boolean putCaretToEnd){ if (b != null) { String ntext = ""; if ((version >= 0) && (version <= b.getHeadVersion())) { VersionedResource vr = b.getEintrag(); ResourceItem entry = vr.getVersion(version); ntext = entry.data; StringBuilder sb = new StringBuilder(); sb.append("rev. ").append(version).append(" vom ") .append(new TimeTool(entry.timestamp).toString(TimeTool.FULL_GER)).append(" (") .append(entry.remark).append(")"); lVersion.setText(sb.toString()); } else { lVersion.setText(""); } text.setText(PersistentObject.checkNull(ntext)); text.setKons(b); text.setEnabled(hasKonsTextLock()); displayedVersion = version; versionBackAction.setEnabled(version != 0); versionFwdAction.setEnabled(version != b.getHeadVersion()); boolean locked = hasKonsTextLock(); int strlen = text.getContentsPlaintext().length(); int maxLen = strlen < 120 ? strlen : 120; String label = (konsTextLock == null) ? "null " : konsTextLock.getLabel(); if (!locked) logEvent("setKonsText availabee " + b.getId() + " " + label + " putCaretToEnd " + putCaretToEnd + " " + lVersion.getText() + " '" + text.getContentsPlaintext().substring(0, maxLen) + "'"); else logEvent("setKonsText (locked) " + b.getId() + " " + label + " putCaretToEnd " + putCaretToEnd + " " + lVersion.getText() + " '" + text.getContentsPlaintext().substring(0, maxLen) + "'"); if (putCaretToEnd) { // set focus and put caret at end of text text.putCaretToEnd(); } } else { lVersion.setText(""); text.setText(""); text.setKons(null); text.setEnabled(false); displayedVersion = -1; versionBackAction.setEnabled(false); versionFwdAction.setEnabled(false); logEvent("setKonsText null " + lVersion.getText() + " " + text.getContentsPlaintext()); } } private void logEvent(String msg){ StringBuilder sb = new StringBuilder(msg + ": "); if (actKons == null) { sb.append("actKons null"); } else { sb.append(actKons.getId()); sb.append(" kons rev. " + actKons.getHeadVersion()); sb.append(" vom " + actKons.getDatum()); if (actKons.getFall() != null) { sb.append(" " + actKons.getFall().getPatient().getPersonalia()); } } log.debug(sb.toString()); } @Override public synchronized void activation(boolean mode){ logEvent("activation: " + mode); if (!mode) { updateEintrag(); } } public synchronized void registerUpdateHeartbeat(){ Heartbeat heat = Heartbeat.getInstance(); heat.addListener(new IatrixHeartListener() { @Override public void heartbeat(){ int konsTextSaverPeriod = Heartbeat.getKonsTextSaverPeriod(); logEvent("Period: " + konsTextSaverPeriod); if (!(konsTextSaverPeriod > 0)) { // auto-save disabled return; } // inv: konsTextSaverPeriod > 0 // increment konsTextSaverCount, but stay inside period konsTextSaverCount++; konsTextSaverCount %= konsTextSaverPeriod; logEvent("konsTextSaverCount = " + konsTextSaverCount); if (konsTextSaverCount == 0) { logEvent("Auto Save Kons Text"); updateEintrag(); } } }); } public String getPlainText(){ if (text == null ) { return ""; } return text.getContentsPlaintext(); } }
package com.lithium.dbi.rdbi.recipes.presence; import com.google.common.base.Optional; import com.lithium.dbi.rdbi.RDBI; import org.joda.time.Duration; import org.joda.time.Instant; import org.joda.time.Minutes; import org.joda.time.Seconds; import org.testng.annotations.Test; import redis.clients.jedis.JedisPool; import java.util.Set; import java.util.UUID; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; @Test(groups = "integration") public class PresenceRepositoryTest { @Test public void addTest () throws InterruptedException { final PresenceRepository presenceRepository = new PresenceRepository(new RDBI(new JedisPool("localhost")), "myprefix"); presenceRepository.nukeForTest("mytube"); assertTrue(presenceRepository.expired("mytube", "id1")); presenceRepository.addHeartbeat("mytube", "id1", 1000L); assertFalse(presenceRepository.expired("mytube", "id1")); presenceRepository.cull("mytube"); assertFalse(presenceRepository.expired("mytube", "id1")); Thread.sleep(1500L); assertTrue(presenceRepository.expired("mytube", "id1")); presenceRepository.cull("mytube"); assertTrue(presenceRepository.expired("mytube", "id1")); } @Test public void basicPerformanceTest() throws InterruptedException { final PresenceRepository presenceRepository = new PresenceRepository(new RDBI(new JedisPool("localhost")), "myprefix"); presenceRepository.nukeForTest("mytube"); Instant before = Instant.now(); for ( int i = 0; i < 10000; i++ ) { presenceRepository.addHeartbeat("mytube", "id" + i, 10 * 1000L); } Instant after = Instant.now(); System.out.println("Time for 10,000 heartbeats " + Long.toString(after.getMillis() - before.getMillis())); assertTrue(after.getMillis() - before.getMillis() < 2000L); Instant before2 = Instant.now(); for ( int i = 0; i < 10000; i++ ) { assertFalse(presenceRepository.expired("mytube", "id" + i)); } Instant after2 = Instant.now(); System.out.println("Time for 10,000 expired " + Long.toString(after2.getMillis() - before2.getMillis())); assertTrue(after2.getMillis() - before2.getMillis() < 2000L); Thread.sleep(10 * 1000L); Instant before3 = Instant.now(); for ( int i = 0; i < 5000; i++ ) { assertTrue(presenceRepository.remove("mytube", "id" + i)); } Instant after3 = Instant.now(); System.out.println("Time for 5000 removes " + Long.toString(after3.getMillis() - before3.getMillis())); assertTrue(after3.getMillis() - before3.getMillis() < 1000L); Instant before4 = Instant.now(); presenceRepository.cull("mytube"); Instant after4 = Instant.now(); System.out.println("Time for 5000 cull " + Long.toString(after4.getMillis() - before4.getMillis())); assertTrue(after4.getMillis() - before4.getMillis() < 500L); } @Test public void getPresentTest() throws InterruptedException { final String mytube = "getPresentTest"; final PresenceRepository presenceRepository = new PresenceRepository(new RDBI(new JedisPool("localhost")), "myprefix"); presenceRepository.nukeForTest(mytube); // assert set is empty at start assertTrue(presenceRepository.getPresent(mytube, Optional.<Integer>absent()).isEmpty()); // put something in and verify we can get it back out final String uuid = UUID.randomUUID().toString(); presenceRepository.addHeartbeat(mytube, uuid, Seconds.seconds(1).toStandardDuration().getMillis()); final Set<String> presentSet = presenceRepository.getPresent(mytube, Optional.<Integer>absent()); assertEquals(uuid, presentSet.iterator().next(), "Expected to have one heartbeat with uuid: " + uuid); // call cull and verify heart beat is still present presenceRepository.cull(mytube); final Set<String> stillpresentSet = presenceRepository.getPresent(mytube, Optional.<Integer>absent()); assertEquals(stillpresentSet.iterator().next(), uuid, "Expected to still have one heartbeat with uuid: " + uuid); // wait a second and verify previous heartbeat is expired final Instant beforeSleep = Instant.now(); while (true) { Thread.sleep(Duration.standardSeconds(1).getMillis()); if (new Duration(beforeSleep, Instant.now()).isLongerThan(Duration.standardSeconds(1))) { break; } } assertTrue(presenceRepository.getPresent(mytube, Optional.<Integer>absent()).isEmpty()); // test with limit will not return full set for (int i = 0; i < 100; ++i) { presenceRepository.addHeartbeat(mytube, UUID.randomUUID().toString(), Minutes.ONE.toStandardDuration().getMillis()); } assertEquals(100, presenceRepository.getPresent(mytube, Optional.<Integer>absent()).size()); assertEquals(10, presenceRepository.getPresent(mytube, Optional.of(10)).size()); } }
package com.intellij.ide.impl; import com.intellij.ide.SelectInContext; import com.intellij.ide.SelectInTarget; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import org.jetbrains.annotations.NotNull; public abstract class SelectInTargetPsiWrapper implements SelectInTarget { protected final Project myProject; protected SelectInTargetPsiWrapper(@NotNull final Project project) { myProject = project; } public abstract String toString(); protected abstract boolean canSelect(PsiFile file); public final boolean canSelect(SelectInContext context) { final Document document = FileDocumentManager.getInstance().getDocument(context.getVirtualFile()); final PsiFile psiFile; if (document != null) { psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); } else if (context.getSelectorInFile() instanceof PsiFile) { psiFile = (PsiFile)context.getSelectorInFile(); } else { psiFile = PsiManager.getInstance(myProject).findFile(context.getVirtualFile()); } if (psiFile != null && canSelect(psiFile)) { return true; } return canWorkWithCustomObjects(); } public final void selectIn(SelectInContext context, final boolean requestFocus) { final Object selector = context.getSelectorInFile(); if (selector instanceof PsiElement) { select(((PsiElement)selector).getOriginalElement(), requestFocus); } else { select(selector, context.getVirtualFile(), requestFocus); } } protected abstract void select(final Object selector, VirtualFile virtualFile, final boolean requestFocus); protected abstract boolean canWorkWithCustomObjects(); protected abstract void select(PsiElement element, boolean requestFocus); }
package net.snowflake.client.jdbc; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * Completely compare json and arrow resultSet behaviors */ @RunWith(Parameterized.class) public class ResultSetArrowForceMultiTimeZoneIT extends BaseJDBCTest { @Parameterized.Parameters public static Object[][] data() { // all tests in this class need to run for both query result formats json and arrow if (BaseJDBCTest.isArrowTestsEnabled()) { return new Object[][]{ {"json", "UTC"}, {"json", "America/Los_Angeles"}, {"json", "America/New_York"}, {"json", "Pacific/Honolulu"}, {"json", "Asia/Singapore"}, {"json", "MEZ"}, {"json", "MESZ"}, {"arrow_force", "UTC"}, {"arrow_force", "America/Los_Angeles"}, {"arrow_force", "America/New_York"}, {"arrow_force", "Pacific/Honolulu"}, {"arrow_force", "Asia/Singapore"}, {"arrow_force", "MEZ"}, {"arrow_force", "MESZ"} }; } else { return new Object[][]{ {"json", "UTC"}, {"json", "America/Los_Angeles"}, {"json", "America/New_York"}, {"json", "Pacific/Honolulu"}, {"json", "Asia/Singapore"}, {"json", "MEZ"}, {"json", "MESZ"} }; } } private static String queryResultFormat; private String tz; public static Connection getConnection(int injectSocketTimeout) throws SQLException { Connection connection = BaseJDBCTest.getConnection(injectSocketTimeout); Statement statement = connection.createStatement(); statement.execute( "alter session set " + "TIMEZONE='America/Los_Angeles'," + "TIMESTAMP_TYPE_MAPPING='TIMESTAMP_LTZ'," + "TIMESTAMP_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'," + "TIMESTAMP_TZ_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'," + "TIMESTAMP_LTZ_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'," + "TIMESTAMP_NTZ_OUTPUT_FORMAT='DY, DD MON YYYY HH24:MI:SS TZHTZM'"); statement.close(); return connection; } public ResultSetArrowForceMultiTimeZoneIT(String queryResultFormat, String timeZone) { this.queryResultFormat = queryResultFormat; System.setProperty("user.timezone", timeZone); tz = timeZone; } private Connection init(String table, String column, String values) throws SQLException { Connection con = getConnection(); con.createStatement().execute("create or replace table " + table + " " + column); con.createStatement().execute("insert into " + table + " values " + values); return con; } private void finish(String table, Connection con) throws SQLException { con.createStatement().execute("drop table " + table); con.close(); System.clearProperty("user.timezone"); } public static Connection getConnection() throws SQLException { Connection conn = getConnection(BaseJDBCTest.DONT_INJECT_SOCKET_TIMEOUT); if (isArrowTestsEnabled()) { conn.createStatement().execute("alter session set query_result_format = '" + queryResultFormat + "'"); } return conn; } @Test public void testTimestampNTZ() throws SQLException { for (int scale = 0; scale <= 9; scale++) { testTimestampNTZWithScale(scale); } } public void testTimestampNTZWithScale(int scale) throws SQLException { String[] cases = { "2017-01-01 12:00:00", "2014-01-02 16:00:00", "2014-01-02 12:34:56", "0001-01-02 16:00:00", "1969-12-31 23:59:59", "1970-01-01 00:00:00", "1970-01-01 00:00:01", "9999-01-01 00:00:00" }; String[] results = { "Sun, 01 Jan 2017 12:00:00 Z", "Thu, 02 Jan 2014 16:00:00 Z", "Thu, 02 Jan 2014 12:34:56 Z", "Sun, 02 Jan 0001 16:00:00 Z", "Wed, 31 Dec 1969 23:59:59 Z", "Thu, 01 Jan 1970 00:00:00 Z", "Thu, 01 Jan 1970 00:00:01 Z", "Fri, 01 Jan 9999 00:00:00 Z" }; String table = "test_arrow_ts_ntz"; String column = "(a timestamp_ntz(" + scale + "))"; String values = "('" + StringUtils.join(cases, "'),('") + "'), (null)"; Connection con = init(table, column, values); ResultSet rs = con.createStatement().executeQuery("select * from " + table); int i = 0; while (i < cases.length) { rs.next(); assertEquals(results[i++], rs.getString(1)); } rs.next(); assertNull(rs.getString(1)); finish(table, con); } @Test public void testTimestampNTZWithNanos() throws SQLException { String[] cases = { "2017-01-01 12:00:00.123456789", "2014-01-02 16:00:00.0123", "2014-01-02 12:34:56.234241234", "0001-01-02 16:00:00.999999999", "1969-12-31 23:59:59.000000001", "1970-01-01 00:00:00.111111111", "1970-01-01 00:00:01.00000001", "9999-01-01 00:00:00.1" }; String table = "test_arrow_ts_ntz"; String column = "(a timestamp_ntz)"; String values = "('" + StringUtils.join(cases, "'),('") + "'), (null)"; Connection con = init(table, column, values); ResultSet rs = con.createStatement().executeQuery("select * from " + table); int i = 0; while (i < cases.length) { rs.next(); assertEquals(cases[i++], rs.getTimestamp(1).toString()); } rs.next(); assertNull(rs.getString(1)); finish(table, con); } @Test public void testTimestampLTZ() throws SQLException, ParseException { for (int scale = 0; scale <= 9; scale++) { testTimestampLTZWithScale(scale); } } public void testTimestampLTZWithScale(int scale) throws SQLException, ParseException { String[] cases = { "2017-01-01 12:00:00 Z", "2014-01-02 16:00:00 Z", "2014-01-02 12:34:56 Z", "1970-01-01 00:00:00 Z", "1970-01-01 00:00:01 Z", "1969-12-31 11:59:59 Z", "0000-01-01 00:00:01 Z", "0001-12-31 11:59:59 Z" }; long[] times = { 1483272000000l, 1388678400000l, 1388666096000l, 0, 1000, -43201000, -62167391999000l, -62104276801000l }; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getDefault()); String table = "test_arrow_ts_ltz"; String column = "(a timestamp_ltz(" + scale + "))"; String values = "('" + StringUtils.join(cases, "'),('") + "'), (null)"; Connection con = init(table, column, values); ResultSet rs = con.createStatement().executeQuery("select * from " + table); int i = 0; while (i < cases.length) { rs.next(); assertEquals(times[i++], rs.getTimestamp(1).getTime()); assertEquals(0, rs.getTimestamp(1).getNanos()); } rs.next(); assertNull(rs.getString(1)); finish(table, con); } @Test public void testTimestampLTZWithNanos() throws SQLException, ParseException { String[] cases = { "2017-01-01 12:00:00.123456789", "2014-01-02 16:00:00.000000001", "2014-01-02 12:34:56.1", "1969-12-31 23:59:59.000000001", "1970-01-01 00:00:00.123412423", "1970-01-01 00:00:01.000001", "1969-12-31 11:59:59.001", "0001-12-31 11:59:59.11" }; long[] times = { 1483272000123l, 1388678400000l, 1388666096100l, -1000, 123, 1000, -43200999, -62104276800890l }; int[] nanos = { 123456789, 1, 100000000, 1, 123412423, 1000, 1000000, 110000000 }; String table = "test_arrow_ts_ltz"; String column = "(a timestamp_ltz)"; String values = "('" + StringUtils.join(cases, " Z'),('") + " Z'), (null)"; Connection con = init(table, column, values); ResultSet rs = con.createStatement().executeQuery("select * from " + table); int i = 0; while (i < cases.length) { rs.next(); assertEquals(times[i], rs.getTimestamp(1).getTime()); assertEquals(nanos[i++], rs.getTimestamp(1).getNanos()); } rs.next(); assertNull(rs.getString(1)); finish(table, con); } @Test public void testTimestampTZ() throws SQLException, ParseException { for (int scale = 0; scale <= 9; scale++) { testTimestampTZWithScale(scale); } } public void testTimestampTZWithScale(int scale) throws SQLException, ParseException { String[] cases = { "2017-01-01 12:00:00 Z", "2014-01-02 16:00:00 Z", "2014-01-02 12:34:56 Z", "1970-01-01 00:00:00 Z", "1970-01-01 00:00:01 Z", "1969-12-31 11:59:59 Z", "0000-01-01 00:00:01 Z", "0001-12-31 11:59:59 Z" }; long[] times = { 1483272000000l, 1388678400000l, 1388666096000l, 0, 1000, -43201000l, -62167391999000l, -62104276801000l }; String table = "test_arrow_ts_tz"; String column = "(a timestamp_tz(" + scale + "))"; String values = "('" + StringUtils.join(cases, "'),('") + "'), (null)"; Connection con = init(table, column, values); ResultSet rs = con.createStatement().executeQuery("select * from " + table); int i = 0; while (i < cases.length) { rs.next(); assertEquals(times[i++], rs.getTimestamp(1).getTime()); assertEquals(0, rs.getTimestamp(1).getNanos()); } rs.next(); assertNull(rs.getString(1)); finish(table, con); } @Test public void testTimestampTZWithNanos() throws SQLException, ParseException { String[] cases = { "2017-01-01 12:00:00.1", "2014-01-02 16:00:00.123456789", "2014-01-02 12:34:56.999999999", "1969-12-31 23:59:59.000000001", "1970-01-01 00:00:00.000000001", "1970-01-01 00:00:01.0000001", "1969-12-31 11:59:59.134", "0001-12-31 11:59:59.234141", "0000-01-01 00:00:01.790870987" }; long[] times = { 1483272000100l, 1388678400123l, 1388666096999l, -1000, 0, 1000, -43200866, -62104276800766l, -62167391998210l }; int[] nanos = { 100000000, 123456789, 999999999, 1, 1, 100, 134000000, 234141000, 790870987 }; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String table = "test_arrow_ts_tz"; String column = "(a timestamp_tz)"; String values = "('" + StringUtils.join(cases, " Z'),('") + " Z'), (null)"; Connection con = init(table, column, values); ResultSet rs = con.createStatement().executeQuery("select * from " + table); int i = 0; while (i < cases.length) { rs.next(); if (i == cases.length - 1 && tz.equalsIgnoreCase("utc")) { // TODO: Is this a JDBC bug which happens in both arrow and json cases? assertEquals("0001-01-01 00:00:01.790870987", rs.getTimestamp(1).toString()); } assertEquals(times[i], rs.getTimestamp(1).getTime()); assertEquals(nanos[i++], rs.getTimestamp(1).getNanos()); } rs.next(); assertNull(rs.getString(1)); finish(table, con); } }
package org.elasticsearch.search.facet.script; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.integration.AbstractNodesTests; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Map; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.typeCompatibleWith; public class SimpleScriptFacetTests extends AbstractNodesTests { private Client client; @BeforeClass public void createNodes() throws Exception { Settings settings = ImmutableSettings.settingsBuilder().put("index.number_of_shards", numberOfShards()).put("index.number_of_replicas", 0).build(); for (int i = 0; i < numberOfNodes(); i++) { startNode("node" + i, settings); } client = getClient(); } protected int numberOfShards() { return 1; } protected int numberOfNodes() { return 1; } protected int numberOfRuns() { return 5; } @AfterClass public void closeNodes() { client.close(); closeAllNodes(); } protected Client getClient() { return client("node0"); } @Test public void testBinaryFacet() throws Exception { try { client.admin().indices().prepareDelete("test").execute().actionGet(); } catch (Exception e) { // ignore } client.admin().indices().prepareCreate("test").execute().actionGet(); client.admin().indices().preparePutMapping("test") .setType("type1") .setSource("{ type1 : { properties : { tag : { type : \"string\", store : \"yes\" } } } }") .execute().actionGet(); client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet(); for (int i = 0; i < 10; i++) { client.prepareIndex("test", "type1").setSource(jsonBuilder().startObject() .field("tag", "green") .endObject()).execute().actionGet(); } client.admin().indices().prepareFlush().setRefresh(true).execute().actionGet(); for (int i = 0; i < 5; i++) { client.prepareIndex("test", "type1").setSource(jsonBuilder().startObject() .field("tag", "blue") .endObject()).execute().actionGet(); } client.admin().indices().prepareRefresh().execute().actionGet(); for (int i = 0; i < numberOfRuns(); i++) { SearchResponse searchResponse = client.prepareSearch() .setIndices("test") .setSearchType(SearchType.COUNT) .setExtraSource(XContentFactory.jsonBuilder().startObject() .startObject("facets") .startObject("facet1") .startObject("script") .field("init_script", "" + "def add(map, key, n) {" + " map[key] = map.containsKey(key) ? map[key] + n : n;" + "}") .field("map_script", "add(facet, _fields['tag'].value, 1)") .field("combine_script", "facet") .field("reduce_script", "result = null;" + "for (f : facets) {" + " if (result != null) {" + " for (e : f.entrySet()) {" + " result[e.key] = result.containsKey(e.key) ? result[e.key] + e.value : e.value;" + " }" + " } else {" + " result = f;" + " }" + "};" + "result") .startObject("params") .startObject("facet") .endObject() .endObject() .endObject() .endObject() .endObject() .endObject()) .execute().actionGet(); logger.trace(searchResponse.toString()); assertThat(searchResponse.hits().totalHits(), equalTo(15l)); assertThat(searchResponse.hits().hits().length, equalTo(0)); ScriptFacet facet = searchResponse.facets().facet("facet1"); assertThat(facet.name(), equalTo("facet1")); Map<String, Object> facetResult = (Map<String, Object>) facet.facet(); assertThat(facetResult.size(), equalTo(2)); assertThat(facetResult.get("green"), equalTo((Object) 10)); assertThat(facetResult.get("blue"), equalTo((Object) 5)); } } @Test public void testUpdateFacet() throws Exception { try { client.admin().indices().prepareDelete("test1").execute().actionGet(); client.admin().indices().prepareDelete("test2").execute().actionGet(); } catch (Exception e) { // ignore } client.admin().indices().prepareCreate("test1").execute().actionGet(); client.admin().indices().preparePutMapping("test1") .setType("type1") .setSource("{ type1 : { properties : { tag : { type : \"string\", store : \"yes\" } } } }") .execute().actionGet(); client.admin().indices().prepareCreate("test2").execute().actionGet(); client.admin().indices().preparePutMapping("test2") .setType("type1") .setSource("{ type1 : { properties : { tag : { type : \"string\", store : \"yes\" } } } }") .execute().actionGet(); client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet(); for (int i = 0; i < 10; i++) { client.prepareIndex("test1", "type1").setSource(jsonBuilder().startObject() .field("tag", "green") .endObject()).execute().actionGet(); } client.admin().indices().prepareFlush().setRefresh(true).execute().actionGet(); for (int i = 0; i < 5; i++) { client.prepareIndex("test1", "type1").setSource(jsonBuilder().startObject() .field("tag", "blue") .endObject()).execute().actionGet(); } for (int i = 0; i < 10; i++) { client.prepareIndex("test2", "type1").setSource(jsonBuilder().startObject() .field("tag", "yellow") .endObject()).execute().actionGet(); } client.admin().indices().prepareRefresh().execute().actionGet(); SearchResponse searchResponse = client.prepareSearch() .setSearchType(SearchType.COUNT) .setIndices("test1", "test2") .setExtraSource(XContentFactory.jsonBuilder().startObject() .startObject("facets") .startObject("facet1") .startObject("script") .field("init_script", "index = _ctx.request().index();") .field("map_script", "" + "uid = doc._uid.value;" + "id = org.elasticsearch.index.mapper.Uid.idFromUid(uid);" + "type = org.elasticsearch.index.mapper.Uid.typeFromUid(uid);" + "if (!_source.isEmpty()) {" + " modified = true;" + " map = _source.source();" + " complementary = colors.get(map.tag);" + " if (complementary != null) {" + " map.put(\"complementary\", complementary);" + " _client.prepareIndex(index, type, id).setSource(map).execute().actionGet();" + " }" + "}") .startObject("params") .startObject("facet") .endObject() .startObject("colors") .field("blue", "orange") .field("yellow", "violet") .endObject() .endObject() .endObject() .endObject() .endObject() .endObject()) .execute().actionGet(); logger.trace(searchResponse.toString()); assertThat(searchResponse.hits().totalHits(), equalTo(25l)); assertThat(searchResponse.hits().hits().length, equalTo(0)); client.admin().indices().prepareRefresh().execute().actionGet(); searchResponse = client.prepareSearch() .setIndices("test1", "test2") .setQuery(QueryBuilders.textQuery("complementary","orange")) .execute().actionGet(); assertThat(searchResponse.hits().totalHits(), equalTo(5L)); searchResponse = client.prepareSearch() .setIndices("test2") .setQuery(QueryBuilders.textQuery("complementary","violet")) .execute().actionGet(); assertThat(searchResponse.hits().totalHits(), equalTo(10L)); } }
package org.openlmis.stockmanagement.service; import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static org.openlmis.stockmanagement.service.JasperReportService.CARD_REPORT_URL; import static org.openlmis.stockmanagement.service.JasperReportService.CARD_SUMMARY_REPORT_URL; import static org.openlmis.stockmanagement.service.JasperReportService.PI_LINES_REPORT_URL; import static org.powermock.api.mockito.PowerMockito.mockStatic; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.sql.Connection; import java.sql.SQLException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.sql.DataSource; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.openlmis.stockmanagement.domain.JasperTemplate; import org.openlmis.stockmanagement.dto.StockCardDto; import org.openlmis.stockmanagement.exception.JasperReportViewException; import org.openlmis.stockmanagement.exception.ResourceNotFoundException; import org.openlmis.stockmanagement.testutils.StockCardDtoDataBuilder; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.test.util.ReflectionTestUtils; @RunWith(PowerMockRunner.class) @PrepareForTest({JasperReportService.class, JasperFillManager.class,JasperExportManager.class}) public class JasperReportServiceTest { private static final String DATE_FORMAT = "dd/MM/yyyy"; private static final String DATE_TIME_FORMAT = "dd/MM/yyyy HH:mm:ss"; private static final String GROUPING_SEPARATOR = ","; private static final String GROUPING_SIZE = "3"; @InjectMocks private JasperReportService jasperReportService; @Mock private StockCardService stockCardService; @Mock private StockCardSummariesService stockCardSummariesService; @Mock private DataSource dataSource; private byte[] testReportData; @Before public void setUp() { jasperReportService = spy(new JasperReportService()); ReflectionTestUtils.setField(jasperReportService, "dateFormat", DATE_FORMAT); ReflectionTestUtils.setField(jasperReportService, "dateTimeFormat", DATE_TIME_FORMAT); ReflectionTestUtils.setField(jasperReportService, "groupingSeparator", GROUPING_SEPARATOR); ReflectionTestUtils.setField(jasperReportService, "groupingSize", GROUPING_SIZE); MockitoAnnotations.initMocks(this); mockStatic(JasperFillManager.class); mockStatic(JasperExportManager.class); testReportData = new byte[]{0x1}; } @Test(expected = ResourceNotFoundException.class) public void shouldThrowResourceNotFoundExceptionWhenStockCardNotExists() { UUID stockCardId = UUID.randomUUID(); when(stockCardService.findStockCardById(stockCardId)).thenReturn(null); jasperReportService.generateStockCardReport(stockCardId); } @Test public void shouldGenerateReportWithProperParamsIfStockCardExists() throws JRException { StockCardDto stockCard = StockCardDtoDataBuilder.createStockCardDto(); when(stockCardService.findStockCardById(stockCard.getId())).thenReturn(stockCard); when(jasperReportService.compileReportFromTemplateUrl(CARD_REPORT_URL)) .thenReturn(mock(JasperReport.class)); JasperPrint jasperPrint = mock(JasperPrint.class); PowerMockito.when(JasperFillManager.fillReport(any(JasperReport.class), anyMap(), any(JRBeanCollectionDataSource.class))) .thenReturn(jasperPrint); PowerMockito.when(JasperExportManager.exportReportToPdf(jasperPrint)) .thenReturn(testReportData); byte[] reportData = jasperReportService.generateStockCardReport(stockCard.getId()); assertEquals(testReportData, reportData); } @Test public void shouldGenerateReportWithProperParamsIfStockCardSummaryExists() throws JRException { StockCardDto stockCard = StockCardDtoDataBuilder.createStockCardDto(); UUID programId = UUID.randomUUID(); UUID facilityId = UUID.randomUUID(); when(stockCardSummariesService.findStockCards(programId, facilityId)) .thenReturn(singletonList(stockCard)); when(jasperReportService.compileReportFromTemplateUrl(CARD_SUMMARY_REPORT_URL)) .thenReturn(mock(JasperReport.class)); JasperPrint jasperPrint = mock(JasperPrint.class); PowerMockito.when(JasperFillManager.fillReport(any(JasperReport.class), anyMap(), any(JREmptyDataSource.class))) .thenReturn(jasperPrint); PowerMockito.when(JasperExportManager.exportReportToPdf(jasperPrint)) .thenReturn(testReportData); byte[] reportData = jasperReportService.generateStockCardSummariesReport(programId, facilityId); assertEquals(testReportData, reportData); } @Test public void shouldGenerateReportWithProperParamsForPrintPhysicalInventory() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dateTimeFormat", DATE_TIME_FORMAT); params.put("dateFormat", DATE_FORMAT); params.put("format", "pdf"); params.put("decimalFormat", createDecimalFormat()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(JasperCompileManager.compileReport(getClass().getResourceAsStream( PI_LINES_REPORT_URL))); JasperTemplate jasperTemplate = new JasperTemplate("test template", bos.toByteArray(), "type", "description"); when(dataSource.getConnection()).thenReturn(mock(Connection.class)); JasperPrint jasperPrint = mock(JasperPrint.class); PowerMockito.when(JasperFillManager.fillReport(any(JasperReport.class), anyMap(), any(Connection.class))) .thenReturn(jasperPrint); PowerMockito.when(JasperExportManager.exportReportToPdf(jasperPrint)) .thenReturn(testReportData); byte[] reportData = jasperReportService.generateReport(jasperTemplate, params); assertEquals(testReportData, reportData); } @Test(expected = JasperReportViewException.class) public void shouldThrowJasperReportViewExceptionWhenConnectionCantBeOpen() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("format", "pdf"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(JasperCompileManager.compileReport(getClass().getResourceAsStream( PI_LINES_REPORT_URL))); JasperTemplate jasperTemplate = new JasperTemplate("test template", bos.toByteArray(), "type", "description"); when(dataSource.getConnection()).thenThrow(new SQLException()); jasperReportService.generateReport(jasperTemplate, params); } private DecimalFormat createDecimalFormat() { DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); decimalFormatSymbols.setGroupingSeparator(GROUPING_SEPARATOR.charAt(0)); DecimalFormat decimalFormat = new DecimalFormat("", decimalFormatSymbols); decimalFormat.setGroupingSize(Integer.parseInt(GROUPING_SIZE)); return decimalFormat; } }
package org.zalando.nakadi.service.subscription; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import org.zalando.nakadi.service.subscription.model.Session; import org.zalando.nakadi.service.subscription.state.CleanupState; import org.zalando.nakadi.service.subscription.state.DummyState; import org.zalando.nakadi.service.subscription.state.State; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; public class StreamingContextTest { private static StreamingContext createTestContext(final Consumer<Exception> onException) { final SubscriptionOutput output = new SubscriptionOutput() { @Override public void onInitialized(final String ignore) throws IOException { } @Override public void onException(final Exception ex) { if (null != onException) { onException.accept(ex); } } @Override public void streamData(final byte[] data) throws IOException { } }; return new StreamingContext.Builder() .setOut(output) .setParameters(null) .setSession(Session.generate(1)) .setTimer(null) .setZkClient(null) .setKafkaClient(null) .setRebalancer(null) .setKafkaPollTimeout(0) .setLoggingPath("stream") .setConnectionReady(new AtomicBoolean(true)) .setEventTypesForTopics(null) .setCursorTokenService(null) .setObjectMapper(null) .setBlacklistService(null) .build(); } @Test public void streamingContextShouldStopOnException() throws InterruptedException { final AtomicReference<Exception> caughtException = new AtomicReference<>(null); final RuntimeException killerException = new RuntimeException(); final StreamingContext ctx = createTestContext(caughtException::set); final State killerState = new State() { @Override public void onEnter() { throw killerException; } }; final Thread t = new Thread(() -> { try { ctx.streamInternal(killerState); } catch (final InterruptedException ignore) { } }); t.start(); t.join(1000); // Check that thread died Assert.assertFalse(t.isAlive()); // Check that correct exception was caught by output Assert.assertSame(killerException, caughtException.get()); } @Test public void stateBaseMethodsMustBeCalledOnSwitching() throws InterruptedException { final StreamingContext ctx = createTestContext(null); final boolean[] onEnterCalls = new boolean[]{false, false}; final boolean[] onExitCalls = new boolean[]{false, false}; final boolean[] contextsSet = new boolean[]{false, false}; final State state1 = new State() { @Override public void setContext(final StreamingContext context, final String tmp) { super.setContext(context, tmp); contextsSet[0] = null != context; } @Override public void onEnter() { Assert.assertTrue(contextsSet[0]); onEnterCalls[0] = true; throw new RuntimeException(); // trigger stop. } @Override public void onExit() { onExitCalls[0] = true; } }; final State state2 = new State() { @Override public void setContext(final StreamingContext context, final String tmp) { super.setContext(context, tmp); contextsSet[1] = true; } @Override public void onEnter() { Assert.assertTrue(contextsSet[1]); onEnterCalls[1] = true; switchState(state1); } @Override public void onExit() { onExitCalls[1] = true; } }; ctx.streamInternal(state2); Assert.assertArrayEquals(new boolean[]{true, true}, contextsSet); Assert.assertArrayEquals(new boolean[]{true, true}, onEnterCalls); // Check that onExit called even if onEnter throws exception. Assert.assertArrayEquals(new boolean[]{true, true}, onExitCalls); } @Test public void testOnNodeShutdown() throws Exception { final StreamingContext ctxSpy = Mockito.spy(createTestContext(null)); final Thread t = new Thread(() -> { try { ctxSpy.streamInternal(new State() { @Override public void onEnter() { } }); } catch (final InterruptedException ignore) { } }); t.start(); t.join(2000); ctxSpy.onNodeShutdown(); Mockito.verify(ctxSpy).switchState(Mockito.isA(CleanupState.class)); Mockito.verify(ctxSpy).unregisterSession(); Mockito.verify(ctxSpy).switchState(Mockito.isA(DummyState.class)); } }
package fbissueexport; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.core.JavaProject; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryBuilder; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import com.fasterxml.jackson.databind.ObjectMapper; import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugRankCategory; public class Export { private static Logger logger = Logger.getLogger(Export.class); private BugInstance bug; public Export(BugInstance bug, IProject project) { logger.info("new Export instance created for Bug-ID: " + bug.getInstanceHash() + "in project " + project.getName()); this.bug = bug; // TODO read threshold from project preferences // 1 is highest confidence if(bug.getPriority() > 2) { Shell activeShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); MessageDialog dialog = new MessageDialog( activeShell, "Confidence below threshold!", null, "This bug is only of " + bug.getPriorityString() + "! Are you sure you want to report it?", MessageDialog.QUESTION_WITH_CANCEL, new String[]{ IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL}, 0); switch(dialog.open()) { case 1: logger.debug("stopping export because user is not sure if confidence is high enough."); return; } } // get file location this bug is found in IPath path = project.getFile(bug.getPrimarySourceLineAnnotation().getSourcePath()).getProjectRelativePath(); IResource res = getResource(project, path.removeLastSegments(1).toString(), path.lastSegment()); File file = res.getLocation().toFile(); logger.debug("searching for versioned directory, starting at: " + file); if(new RepositoryBuilder().findGitDir(file).getGitDir() != null) { logger.debug("found versioned directory" + path); try { // get remotes and check if it contains github(or other popular platforms) Repository repository = new RepositoryBuilder().findGitDir(file).build(); Config storedConfig = repository.getConfig(); Set<String> remotes = storedConfig.getSubsections("remote"); for (String remoteName : remotes) { String url = storedConfig.getString("remote", remoteName, "url"); logger.debug(remoteName + " " + url); // parse url for popular social coding platforms //Pattern patternGitHub = Pattern.compile("^*//github.com/([^/]){1}/([^/]){1}") Pattern patternGitHub = Pattern.compile("((git@|https://)([\\w\\.@]+)(/|:))([\\w,\\-,\\_]+)/([\\w,\\-,\\_]+)(.git){0,1}((/){0,1})"); Matcher matcher = patternGitHub.matcher(url); if(matcher.matches()) { // found a plattform logger.debug("regex matched platform: " + matcher.group(3) + " owner: " + matcher.group(5) + " repo: " + matcher.group(6)); exportToPlatformTracker(matcher.group(3), matcher.group(5), matcher.group(6)); } } } catch (IOException e) { logger.error(e.getMessage() + "\n" + e.getStackTrace()); } } } IResource getResource(IProject project, String folderPath, String fileName) { IJavaProject javaProject = JavaCore.create(project); try { for (IPackageFragmentRoot root : javaProject.getAllPackageFragmentRoots()) { IPackageFragment folderFragment = root.getPackageFragment(folderPath); IResource folder = folderFragment.getResource(); if (folder == null || ! folder.exists() || !(folder instanceof IContainer)) { continue; } IResource resource = ((IContainer) folder).findMember(fileName); if (resource.exists()) { return resource; } } } catch (JavaModelException e) { logger.error(e.getMessage() + "\n" + e.getStackTrace()); } // file not found in any source path return null; } /** * Calls the appropriate method for the corresponding platform * @param platformURLPart * @param owner * @param repoName * @return */ protected boolean exportToPlatformTracker(String platformURLPart, String owner, String repoName) { platformURLPart = platformURLPart.toLowerCase(); switch(platformURLPart) { case "github.com": return exportToGitHubTracker(owner, repoName); case "bitbucket.org": return exportToBitbucketTracker(owner, repoName); default: return false; } } /** * Trys to export to Bitbucket * * @todo untested!! * * @param owner * @param repoName * @return */ protected boolean exportToBitbucketTracker(String owner, String repoName) { final String apiRepoUrl = "https://api.bitbucket.org/2.0/repositories/"; String issueRepo = owner + "/" + repoName; try { ResponseWithEntity response = httpGetRequest(apiRepoUrl + issueRepo); if(response == null) { logger.warn("no response"); return false; } // for Bitbucket // check per API if the project is a fork // check for parent and if parent exists for full_name logger.debug("checking if this repo (" + issueRepo + ") is a fork?"); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> repoData = mapper.readValue(response.getEntity(), Map.class); Object parentData = repoData.get("parent"); if(parentData != null) { Map<String,String> parentD = (Map<String, String>) parentData; issueRepo = parentD.get("full_name"); logger.debug("is forked from: " + issueRepo); } // TODO use isBugAlreadyReported to check if the bug was already reported // if the bug is not filed yet create a new issue // TODO provide GUI to edit the issue before reporting HttpPost request = new HttpPost("https://bitbucket.org/api/1.0/repositories/" + issueRepo + "/issues"); List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("title", getTitle())); params.add(new BasicNameValuePair("content", getDescription())); request.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); logger.debug("request line:" + request.getRequestLine()); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse result = httpClient.execute(request); // TODO open issue in webbrowser return true; } catch (ParseException | IOException e) { logger.error(e.getMessage() + "\n" + e.getStackTrace()); }; return false; } /** * Creates a new issue for the bug on GitHub. * @param owner * @param repoName * @return */ protected boolean exportToGitHubTracker(String owner, String repoName) { final String apiRepoUrl = "https://api.github.com/repos/"; String issueRepo = owner + "/" + repoName; try { ResponseWithEntity response = httpGetRequest(apiRepoUrl + issueRepo); if(response == null) { logger.warn("no response"); return false; } // for GitHub // check per API if the project is a fork // check for parent and if parent exists for full_name logger.debug("checking if this repo (" + issueRepo + ") is a fork?"); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> repoData = mapper.readValue(response.getEntity(), Map.class); Object parentData = repoData.get("parent"); if(parentData != null) { Map<String,String> parentD = (Map<String, String>) parentData; issueRepo = parentD.get("full_name"); logger.debug("is forked from: " + issueRepo); } // TODO use isBugAlreadyReported to check if the bug was already reported // if the bug is not filed yet create a new issue URIBuilder uriBuilder = new URIBuilder("https://github.com/" + issueRepo + "/issues/new"); uriBuilder.addParameter("title", getTitle()); uriBuilder.addParameter("body", getDescription()); openWebPage(uriBuilder.build()); return true; } catch (ParseException | IOException | URISyntaxException e) { logger.error(e.getMessage() + "\n" + e.getStackTrace()); }; return false; } protected String getTitle() { return bug.getMessageWithoutPrefix(); } protected String getDescription() { String md = ""; md += "# " + bug.getAbridgedMessage() + "\n"; md += "\n\n" + bug.getBugPattern().getDetailText() + "\n\n"; md += "The problem occurs in `" + bug.getPrimarySourceLineAnnotation().getClassName() + "` on line **" + bug.getPrimarySourceLineAnnotation().getStartLine() + "** in method `" + bug.getPrimaryMethod().getMethodName() + "`\n\n"; // TODO get file content md += ""; md += "We have **" + bug.getPriorityString() + "** confidence for this **" + BugRankCategory.getRank(bug.getBugRank()) + "** bug!"; md +="\n\nThis bug was found using the [FBIssueExport](https://github.com/kmindi/FBIssueExport) by kmindi for FindBugs. \n" + "(FindBugs Bug-ID: "+ bug.getInstanceHash() + ")"; return md; } /** * Opens a new browser window or new tab if browser already open. * @param uri */ public static void openWebPage(URI uri) { Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(uri); } catch (Exception e) { logger.error(e.getMessage() + "\n" + e.getStackTrace()); // TODO fallback to API use / show own GUI to create new issue } } } @SuppressWarnings("unused") private Boolean isBugAlreadyReported(BugInstance bug) { // search issue list for Bug-ID (bug.getInstanceHash()) and don't create a new rather redirect to the existing issue // loop through paginated response until we find a bug with our ID or reach the end // always use the provided link header // link header uses "<" and ">" to enclose the url // but it gets parsed as name (starting with "<") and value (ending with ">") /*Header[] headers = response.getResponse().getAllHeaders(); List<Header> headerList = Arrays.asList(headers); for(Header header : headerList) { //logger.info("header: " + header.getName()); if(header.getName().equals("Link")) { logger.debug("found Link Header: " + header.getValue()); for(HeaderElement e : header.getElements()) { logger.debug("element-name: "+ e.getName() + " value: " + e.getValue() + " parameters:" + e.getParameterCount()); for(NameValuePair nvp:e.getParameters()) { logger.debug(nvp.getName()+"="+nvp.getValue()); } } } }*/ return false; } /** * Performs a HTTP GET Request. * @param url * @return ResponseWithEntity(HTTPResponse, String entity) */ private ResponseWithEntity httpGetRequest(String url) { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpGet request = new HttpGet(url); request.addHeader("content-type", "application/json"); logger.debug("request line:" + request.getRequestLine()); HttpResponse result = httpClient.execute(request); logger.debug("request status: " + result.getStatusLine()); return new ResponseWithEntity(result,EntityUtils.toString(result.getEntity(), "UTF-8")); } catch (IOException e) { logger.error(e.getMessage() + "\n" + e.getStackTrace()); } return null; } }
package com.exedio.cope.console; import java.io.IOException; import java.io.PrintStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.exedio.cope.Model; import com.exedio.cope.util.ConnectToken; import com.exedio.cope.util.ServletUtil; import com.exedio.cops.CopsServlet; import com.exedio.cops.Resource; * &lt;url-pattern&gt;/console/*&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * </pre> * * @author Ralf Wiebicke */ public final class ConsoleServlet extends CopsServlet { private static final long serialVersionUID = 1l; private ConnectToken connectToken = null; private Model model = null; static final Resource stylesheet = new Resource("console.css"); static final Resource schemaScript = new Resource("schema.js"); static final Resource logo = new Resource("logo.png"); static final Resource checkFalse = new Resource("checkfalse.png"); static final Resource checkTrue = new Resource("checktrue.png"); static final Resource nodeFalse = new Resource("nodefalse.png"); static final Resource nodeTrue = new Resource("nodetrue.png"); static final Resource nodeWarningFalse = new Resource("nodewarningfalse.png"); static final Resource nodeWarningTrue = new Resource("nodewarningtrue.png"); static final Resource nodeErrorFalse = new Resource("nodeerrorfalse.png"); static final Resource nodeErrorTrue = new Resource("nodeerrortrue.png"); static final Resource nodeLeaf = new Resource("nodeleaf.png"); static final Resource nodeLeafWarning = new Resource("nodewarningleaf.png"); static final Resource nodeLeafError = new Resource("nodeerrorleaf.png"); static final Resource warning = new Resource("warning.png"); static final Resource error = new Resource("error.png"); static final Resource write = new Resource("write.png"); static final Resource imagebackground = new Resource("imagebackground.png"); @Override public void init() throws ServletException { super.init(); if(model!=null) { System.out.println("reinvokation of jspInit"); return; } connectToken = ServletUtil.getConnectedModel(this); model = connectToken.getModel(); } @Override public void destroy() { connectToken.returnIt(); connectToken = null; model = null; super.destroy(); } @Override protected void doRequest( final HttpServletRequest request, final HttpServletResponse response) throws IOException { final ConsoleCop cop = ConsoleCop.getCop(model, request); cop.initialize(request, model); response.setStatus(cop.getResponseStatus()); final PrintStream out = new PrintStream(response.getOutputStream(), false, ENCODING); Console_Jspm.write(out, request, response, model, cop); out.close(); } }
package org.tigris.subversion.javahl; import java.io.File; import java.io.OutputStream; /** * This is the main interface class. All subversion commandline client svn & * svnversion operation are implemented in this class. This class is not * threadsafe. If you need threadsafe access, use SVNClientSynchronized */ public class SVNClient implements SVNClientInterface { /** * Load the required native library. */ static { NativeResources.loadNativeLibrary(); } /** * Standard empty contructor, builds just the native peer. */ public SVNClient() { cppAddr = ctNative(); // Ensure that Subversion's config file area and templates exist. try { setConfigDirectory(determineInitialConfigDir()); } catch (ClientException suppressed) { // Not an exception-worthy problem, continue on. } } /** * Attempt to determine an initial configuration directory, * <code>%APPDATA%\Subversion</code> on Windows and * <code>~/.subversion</code> on other operating systems. * * @return The initial configuration directory, or * <code>null</code> to use the library default. Note that native * library versions older than 1.4 may segfault if we return * <code>null</code>. */ protected String determineInitialConfigDir() { String path; if (isOSWindows()) { // On Windows, use the %APPDATA%\Subversion directory. path = getEnv("APPDATA"); if (path == null) { path = getUserHomeDirectory(); if (path != null) { path = new File(path, "Application Data").getPath(); } } if (path != null) { path = new File(path, "Subversion").getAbsolutePath(); } } else { // Everywhere else, use the ~/.subversion directory. path = getUserHomeDirectory(); if (path != null) { path = new File(path, ".subversion").getAbsolutePath(); } } return path; } /** * @return The absolute path to the current user's home directory, * or <code>null</code> if it cannot be determined. */ private static String getUserHomeDirectory() { // ### LATER: Wrap the svn_user_get_homedir() API and try it // ### first. String path = System.getProperty("user.home"); return (path != null ? path : getEnv("HOME")); } /** * @param envVar The name of the environment variable to retrieve. * @return The named environment variable, or <code>null</code> if * it cannot be retrieved. */ private static final String getEnv(String envVar) { try { return System.getenv(envVar); } catch (Throwable jreComplaint) { // As an example, Sun JRE 1.4.2_12-b03 throws // java.lang.Error, with the message "getenv no longer // supported, use properties and -D instead: HOME". return null; } } /** * @return Whether the current operating system is Windows. */ private static final boolean isOSWindows() { String opSys = System.getProperty("os.name"); return (opSys.toLowerCase().indexOf("windows") >= 0); } /** * Build the native peer * @return the adress of the peer */ private native long ctNative(); /** * release the native peer (should not depend on finalize) */ public native void dispose(); /** * release the native peer (should use dispose instead) */ protected native void finalize(); /** * slot for the adress of the native peer. The JNI code is the only user * of this member */ protected long cppAddr; /** * @return Version information about the underlying native libraries. */ public Version getVersion() { return NativeResources.version; } public native String getAdminDirectoryName(); /** * @param name The name of the directory to compare. * @return Whether <code>name</code> is that of a working copy * administrative directory. * @since 1.3 */ public native boolean isAdminDirectory(String name); /** * Returns the last destination path submitted. * @deprecated * @return path in Subversion format. */ public native String getLastPath(); /** * List a directory or file of the working copy. * * @param path Path to explore. * @param descend Recurse into subdirectories if they exist. * @param onServer Request status information from server. * @param getAll get status for uninteristing files (unchanged). * @return Array of Status entries. */ public Status[] status(String path, boolean descend, boolean onServer, boolean getAll) throws ClientException { return status(path, descend, onServer, getAll, false); } /** * List a directory or file of the working copy. * * @param path Path to explore. * @param descend Recurse into subdirectories they exist. * @param onServer Request status information from server. * @param getAll get status for uninteristing files (unchanged). * @param noIgnore get status for normaly ignored files and directories. * @return Array of Status entries. */ public Status[] status(String path, boolean descend, boolean onServer, boolean getAll, boolean noIgnore) throws ClientException { return status(path, descend, onServer, getAll, noIgnore, false); } /** * List a directory or file of the working copy. * * @param path Path to explore. * @param descend Recurse into subdirectories if they exist. * @param onServer Request status information from server. * @param getAll get status for uninteristing files (unchanged). * @param noIgnore get status for normaly ignored files and * * directories. * @param ignoreExternals if externals are ignored during status * @return Array of Status entries. * @since 1.2 */ public native Status[] status(String path, boolean descend, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals) throws ClientException; /** * Lists the directory entries of an url on the server. * @param url the url to list * @param revision the revision to list * @param recurse recurse into subdirectories * @return Array of DirEntry objects. */ public DirEntry[] list(String url, Revision revision, boolean recurse) throws ClientException { return list(url, revision, revision, recurse); } /** * Lists the directory entries of an url on the server. * * @param url the url to list * @param revision the revision to list * @param pegRevision the revision to interpret url * @param recurse recurse into subdirectories * @return Array of DirEntry objects. * @since 1.2 */ public native DirEntry[] list(String url, Revision revision, Revision pegRevision, boolean recurse) throws ClientException; /** * Returns the status of a single file in the path. * * @param path File to gather status. * @param onServer Request status information from the server. * @return the subversion status of the file. */ public native Status singleStatus(String path, boolean onServer) throws ClientException; /** * Sets the user name used for authentification. * @param username The user name. */ public native void username(String username); /** * Sets the password used for authification. * @param password the password */ public native void password(String password); /** * Register callback interface to supply user name and password on * demand. This callback can also be used to provide the * equivalent of the <code>--no-auth-cache</code> and * <code>--non-interactive</code> arguments accepted by the * command-line client. * * @param prompt the callback interface */ public native void setPrompt(PromptUserPassword prompt); /** * Retrieve the log messages for an item * @param path path or url to get the log message for. * @param revisionStart first revision to show * @param revisionEnd last revision to show * @return array of LogMessages */ public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd) throws ClientException { return logMessages(path, revisionStart, revisionEnd, true, false); } /** * Retrieve the log messages for an item * @param path path or url to get the log message for. * @param revisionStart first revision to show * @param revisionEnd last revision to show * @param stopOnCopy do not continue on copy operations * @return array of LogMessages */ public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy) throws ClientException { return logMessages(path, revisionStart, revisionEnd, stopOnCopy, false); } /** * Retrieve the log messages for an item * @param path path or url to get the log message for. * @param revisionStart first revision to show * @param revisionEnd last revision to show * @param stopOnCopy do not continue on copy operations * @param discoverPath * @return array of LogMessages */ public LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath) throws ClientException { return logMessages(path, revisionStart, revisionEnd, stopOnCopy, discoverPath, 0); } /** * Retrieve the log messages for an item * @param path path or url to get the log message for. * @param revisionStart first revision to show * @param revisionEnd last revision to show * @param stopOnCopy do not continue on copy operations * @param discoverPath returns the paths of the changed items in the * returned objects * @param limit limit the number of log messages (if 0 or less no * limit) * @return array of LogMessages * @since 1.2 */ public native LogMessage[] logMessages(String path, Revision revisionStart, Revision revisionEnd, boolean stopOnCopy, boolean discoverPath, long limit) throws ClientException; /** * Executes a revision checkout. * @param moduleName name of the module to checkout. * @param destPath destination directory for checkout. * @param revision the revision to checkout. * @param pegRevision the peg revision to interpret the path * @param recurse whether you want it to checkout files recursively. * @param ignoreExternals if externals are ignored during checkout * @param allowUnverObstructions allow unversioned paths that obstruct adds * @exception ClientException * @since 1.5 */ public native long checkout(String moduleName, String destPath, Revision revision, Revision pegRevision, boolean recurse, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException; /** * Executes a revision checkout. * @param moduleName name of the module to checkout. * @param destPath destination directory for checkout. * @param revision the revision to checkout. * @param pegRevision the peg revision to interpret the path * @param recurse whether you want it to checkout files recursively. * @param ignoreExternals if externals are ignored during checkout * @exception ClientException * @since 1.2 */ public long checkout(String moduleName, String destPath, Revision revision, Revision pegRevision, boolean recurse, boolean ignoreExternals) throws ClientException { return checkout(moduleName, destPath, revision, revision, recurse, ignoreExternals, false); } /** * Executes a revision checkout. * @param moduleName name of the module to checkout. * @param destPath destination directory for checkout. * @param revision the revision to checkout. * @param recurse whether you want it to checkout files recursively. * @exception ClientException */ public long checkout(String moduleName, String destPath, Revision revision, boolean recurse) throws ClientException { return checkout(moduleName, destPath, revision, revision, recurse, false, false); } /** * Sets the notification callback used to send processing information back * to the calling program. * @param notify listener that the SVN library should call on many * file operations. * @deprecated use notification2 instead */ public native void notification(Notify notify); /** * Sets the notification callback used to send processing information back * to the calling program. * * @param notify listener that the SVN library should call on many * file operations. * @since 1.2 */ public native void notification2(Notify2 notify); /** * Set the progress callback. * * @param listener The progress callback. * @since 1.5 */ public native void setProgressListener(ProgressListener listener); /** * Sets the commit message handler. This allows more complex commit message * with the list of the elements to be commited as input. * @param messageHandler callback for entering commit messages * if this is set the message parameter is ignored. */ public native void commitMessageHandler(CommitMessage messageHandler); /** * Sets a file for deletion. * @param path path or url to be deleted * @param message if path is a url, this will be the commit message. * @param force delete even when there are local modifications. * @exception ClientException */ public native void remove(String[] path, String message, boolean force) throws ClientException; /** * Reverts a file to a pristine state. * @param path path of the file. * @param recurse recurse into subdirectories * @exception ClientException */ public native void revert(String path, boolean recurse) throws ClientException; /** * Adds a file to the repository. * @param path path to be added. * @param recurse recurse into subdirectories * @exception ClientException */ public void add(String path, boolean recurse)throws ClientException { add(path, recurse, false); } /** * Adds a file to the repository. * @param path path to be added. * @param recurse recurse into subdirectories * @param force if adding a directory and recurse true and path is a * directory, all not already managed files are added. * @exception ClientException * @since 1.2 */ public native void add(String path, boolean recurse, boolean force) throws ClientException; /** * Updates the directory or file from repository * @param path target file. * @param revision the revision number to update. * Revision.HEAD will update to the * latest revision. * @param recurse recursively update. * @exception ClientException */ public long update(String path, Revision revision, boolean recurse) throws ClientException { return update(new String[]{path}, revision, recurse, false, false)[0]; } /** * Updates the directories or files from repository * @param path array of target files. * @param revision the revision number to update. * Revision.HEAD will update to the * latest revision. * @param recurse recursively update. * @param ignoreExternals externals will be ignore during update * @exception ClientException * @since 1.2 */ public long[] update(String[] path, Revision revision, boolean recurse, boolean ignoreExternals) throws ClientException { return update(path, revision, recurse, false, false); } /** * Updates the directory or file from repository * @param path target file. * @param revision the revision number to update. * Revision.HEAD will update to the * latest revision. * @param recurse recursively update. * @param ignoreExternals externals will be ignore during update * @param allowUnverObstructions allow unversioned paths that obstruct adds * @exception ClientException * @since 1.5 */ public long update(String path, Revision revision, boolean recurse, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException { return update(new String[]{path}, revision, recurse, ignoreExternals, allowUnverObstructions)[0]; } /** * Updates the directories or files from repository * @param path array of target files. * @param revision the revision number to update. * Revision.HEAD will update to the * latest revision. * @param recurse recursively update. * @param ignoreExternals externals will be ignore during update * @param allowUnverObstructions allow unversioned paths that obstruct adds * @exception ClientException * @since 1.5 */ public native long[] update(String[] path, Revision revision, boolean recurse, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException; /** * Commits changes to the repository. * @param path files to commit. * @param message log message. * @param recurse whether the operation should be done recursively. * @return Returns a long representing the revision. It returns a * -1 if the revision number is invalid. * @exception ClientException */ public long commit(String[] path, String message, boolean recurse) throws ClientException { return commit(path, message, recurse, false); } /** * Copies a versioned file with the history preserved. * @param srcPath source path or url * @param destPath destination path or url * @param message commit message if destPath is an url * @param revision source revision * @exception ClientException */ public native void copy(String srcPath, String destPath, String message, Revision revision) throws ClientException; /** * Moves or renames a file. * @param srcPath source path or url * @param destPath destination path or url * @param message commit message if destPath is an url * @param revision source revision * @param force even with local modifications. * @exception ClientException */ public void move(String srcPath, String destPath, String message, Revision revision, boolean force) throws ClientException { move(srcPath, destPath, message, force); } /** * Moves or renames a file. * * @param srcPath source path or url * @param destPath destination path or url * @param message commit message if destPath is an url * @param force even with local modifications. * @throws ClientException * @since 1.2 */ public native void move(String srcPath, String destPath, String message, boolean force) throws ClientException; /** * Creates a directory directly in a repository or creates a * directory on disk and schedules it for addition. * @param path directories to be created * @param message commit message to used if path contains urls * @exception ClientException */ public native void mkdir(String[] path, String message) throws ClientException; /** * Recursively cleans up a local directory, finishing any * incomplete operations, removing lockfiles, etc. * @param path a local directory. * @exception ClientException */ public native void cleanup(String path) throws ClientException; /** * Removes the 'conflicted' state on a file. * @param path path to cleanup * @param recurse recurce into subdirectories * @exception ClientException */ public native void resolved(String path, boolean recurse) throws ClientException; /** * Exports the contents of either a subversion repository into a * 'clean' directory (meaning a directory with no administrative * directories). * @param srcPath the url of the repository path to be exported * @param destPath a destination path that must not already exist. * @param revision the revsion to be exported * @param force set if it is ok to overwrite local files * @exception ClientException */ public long doExport(String srcPath, String destPath, Revision revision, boolean force) throws ClientException { return doExport(srcPath, destPath, revision, revision, force, false, true, null); } /** * Exports the contents of either a subversion repository into a * 'clean' directory (meaning a directory with no administrative * directories). * * @param srcPath the url of the repository path to be exported * @param destPath a destination path that must not already exist. * @param revision the revsion to be exported * @param pegRevision the revision to interpret srcPath * @param force set if it is ok to overwrite local files * @param ignoreExternals ignore external during export * @param recurse recurse to subdirectories * @param nativeEOL which EOL characters to use during export * @throws ClientException * @since 1.2 */ public native long doExport(String srcPath, String destPath, Revision revision, Revision pegRevision, boolean force, boolean ignoreExternals, boolean recurse, String nativeEOL) throws ClientException; /** * Update local copy to mirror a new url. * @param path the working copy path * @param url the new url for the working copy * @param revision the new base revision of working copy * @param recurse traverse into subdirectories * @param allowUnverObstructions allow unversioned paths that obstruct adds * @exception ClientException * @since 1.5 */ public native long doSwitch(String path, String url, Revision revision, boolean recurse, boolean allowUnverObstructions) throws ClientException; /** * Update local copy to mirror a new url. * @param path the working copy path * @param url the new url for the working copy * @param revision the new base revision of working copy * @param recurse traverse into subdirectories * @exception ClientException */ public long doSwitch(String path, String url, Revision revision, boolean recurse) throws ClientException { return doSwitch(path, url, revision, recurse, false); } /** * Import a file or directory into a repository directory at * head. * @param path the local path * @param url the target url * @param message the log message. * @param recurse traverse into subdirectories * @exception ClientException */ public native void doImport(String path, String url, String message, boolean recurse) throws ClientException; /** * Merge changes from two paths into a new local path. * @param path1 first path or url * @param revision1 first revision * @param path2 second path or url * @param revision2 second revision * @param localPath target local path * @param force overwrite local changes * @param recurse traverse into subdirectories * @exception ClientException */ public void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, boolean recurse) throws ClientException { merge(path1,revision1, path2, revision2, localPath, force, recurse, false, false); } /** * Merge changes from two paths into a new local path. * * @param path1 first path or url * @param revision1 first revision * @param path2 second path or url * @param revision2 second revision * @param localPath target local path * @param force overwrite local changes * @param recurse traverse into subdirectories * @param ignoreAncestry ignore if files are not related * @param dryRun do not change anything * @throws ClientException * @since 1.2 */ public native void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, boolean recurse, boolean ignoreAncestry, boolean dryRun) throws ClientException; /** * Merge changes from two paths into a new local path. * * @param path path or url * @param pegRevision revision to interpret path * @param revision1 first revision * @param revision2 second revision * @param localPath target local path * @param force overwrite local changes * @param recurse traverse into subdirectories * @param ignoreAncestry ignore if files are not related * @param dryRun do not change anything * @throws ClientException * @since 1.2 */ public native void merge(String path, Revision pegRevision, Revision revision1, Revision revision2, String localPath, boolean force, boolean recurse, boolean ignoreAncestry, boolean dryRun) throws ClientException; /** * Display the differences between two paths * @param target1 first path or url * @param revision1 first revision * @param target2 second path or url * @param revision2 second revision * @param outFileName file name where difference are written * @param recurse traverse into subdirectories * @exception ClientException */ public void diff(String target1, Revision revision1, String target2, Revision revision2, String outFileName, boolean recurse) throws ClientException { diff(target1, revision1, target2, revision2, outFileName, recurse, true, false, false); } /** * Display the differences between two paths * * @param target1 first path or url * @param revision1 first revision * @param target2 second path or url * @param revision2 second revision * @param outFileName file name where difference are written * @param recurse traverse into subdirectories * @param ignoreAncestry ignore if files are not related * @param noDiffDeleted no output on deleted files * @param force diff even on binary files * @throws ClientException * @since 1.2 */ public native void diff(String target1, Revision revision1, String target2, Revision revision2, String outFileName, boolean recurse, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException; /** * Display the differences between two paths * * @param target path or url * @param pegRevision revision tointerpret target * @param startRevision first Revision to compare * @param endRevision second Revision to compare * @param outFileName file name where difference are written * @param recurse traverse into subdirectories * @param ignoreAncestry ignore if files are not related * @param noDiffDeleted no output on deleted files * @param force diff even on binary files * @throws ClientException * @since 1.2 */ public native void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String outFileName, boolean recurse, boolean ignoreAncestry, boolean noDiffDeleted, boolean force) throws ClientException; /** * Produce a diff summary which lists the items changed between * path and revision pairs. * * @param target1 Path or URL. * @param revision1 Revision of <code>target1</code>. * @param target2 Path or URL. * @param revision2 Revision of <code>target2</code>. * @param recurse Whether to recurse. * @param ignoreAncestry Whether to ignore unrelated files during * comparison. False positives may potentially be reported if * this parameter <code>false</code>, since a file might have been * modified between two revisions, but still have the same * contents. * @param receiver As each is difference is found, this callback * is invoked with a description of the difference. * * @exception ClientException * @since 1.5 */ public native void diffSummarize(String target1, Revision revision1, String target2, Revision revision2, boolean recurse, boolean ignoreAncestry, DiffSummaryReceiver receiver) throws ClientException; /** * Produce a diff summary which lists the items changed between * path and revision pairs. * * @param target Path or URL. * @param pegRevision Revision at which to interpret * <code>target</code>. If {@link RevisionKind#unspecified} or * <code>null</code>, behave identically to {@link * diffSummarize(String, Revision, String, Revision, boolean, * boolean, DiffSummaryReceiver)}, using <code>path</code> for * both of that method's targets. * @param startRevision Beginning of range for comparsion of * <code>target</code>. * @param endRevision End of range for comparsion of * <code>target</code>. * @param recurse Whether to recurse. * @param ignoreAncestry Whether to ignore unrelated files during * comparison. False positives may potentially be reported if * this parameter <code>false</code>, since a file might have been * modified between two revisions, but still have the same * contents. * @param receiver As each is difference is found, this callback * is invoked with a description of the difference. * * @exception ClientException * @since 1.5 */ public native void diffSummarize(String target, Revision pegRevision, Revision startRevision, Revision endRevision, boolean recurse, boolean ignoreAncestry, DiffSummaryReceiver receiver) throws ClientException; /** * Retrieves the properties of an item * @param path the path of the item * @return array of property objects */ public PropertyData[] properties(String path) throws ClientException { return properties(path, null); } /** * Retrieves the properties of an item * * @param path the path of the item * @param revision the revision of the item * @return array of property objects * @since 1.2 */ public PropertyData[] properties(String path, Revision revision) throws ClientException { return properties(path, revision, revision); } /** * Retrieves the properties of an item * * @param path the path of the item * @param revision the revision of the item * @param pegRevision the revision to interpret path * @return array of property objects * @since 1.2 */ public native PropertyData[] properties(String path, Revision revision, Revision pegRevision) throws ClientException; /** * Sets one property of an item with a String value * @param path path of the item * @param name name of the property * @param value new value of the property * @param recurse set property also on the subdirectories * @throws ClientException */ public void propertySet(String path, String name, String value, boolean recurse) throws ClientException { propertySet(path, name, value, recurse, false); } /** * Sets one property of an item with a String value * * @param path path of the item * @param name name of the property * @param value new value of the property * @param recurse set property also on the subdirectories * @param force do not check if the value is valid * @throws ClientException * @since 1.2 */ public native void propertySet(String path, String name, String value, boolean recurse, boolean force) throws ClientException; /** * Sets one property of an item with a byte array value * @param path path of the item * @param name name of the property * @param value new value of the property * @param recurse set property also on the subdirectories * @throws ClientException */ public void propertySet(String path, String name, byte[] value, boolean recurse) throws ClientException { propertySet(path, name, value, recurse, false); } /** * Sets one property of an item with a byte array value * * @param path path of the item * @param name name of the property * @param value new value of the property * @param recurse set property also on the subdirectories * @param force do not check if the value is valid * @throws ClientException * @since 1.2 */ public native void propertySet(String path, String name, byte[] value, boolean recurse, boolean force) throws ClientException; /** * Remove one property of an item. * @param path path of the item * @param name name of the property * @param recurse remove the property also on subdirectories * @throws ClientException */ public native void propertyRemove(String path, String name, boolean recurse) throws ClientException; /** * Create and sets one property of an item with a String value * @param path path of the item * @param name name of the property * @param value new value of the property * @param recurse set property also on the subdirectories * @throws ClientException */ public void propertyCreate(String path, String name, String value, boolean recurse) throws ClientException { propertyCreate(path, name, value, recurse, false); } /** * Create and sets one property of an item with a String value * * @param path path of the item * @param name name of the property * @param value new value of the property * @param recurse set property also on the subdirectories * @param force do not check if the value is valid * @throws ClientException * @since 1.2 */ public native void propertyCreate(String path, String name, String value, boolean recurse, boolean force) throws ClientException; /** * Create and sets one property of an item with a byte array value * @param path path of the item * @param name name of the property * @param value new value of the property * @param recurse set property also on the subdirectories * @throws ClientException */ public void propertyCreate(String path, String name, byte[] value, boolean recurse) throws ClientException { propertyCreate(path, name, value, recurse, false); } /** * Create and sets one property of an item with a byte array value * * @param path path of the item * @param name name of the property * @param value new value of the property * @param recurse set property also on the subdirectories * @param force do not check if the value is valid * @throws ClientException * @since 1.2 */ public native void propertyCreate(String path, String name, byte[] value, boolean recurse, boolean force) throws ClientException; /** * Retrieve one revsision property of one item * @param path path of the item * @param name name of the property * @param rev revision to retrieve * @return the Property * @throws ClientException */ public native PropertyData revProperty(String path, String name, Revision rev) throws ClientException; /** * Retrieve all revsision properties of one item * @param path path of the item * @param rev revision to retrieve * @return the Properties * @throws ClientException * @since 1.2 */ public native PropertyData[] revProperties(String path, Revision rev) throws ClientException; /** * set one revsision property of one item * @param path path of the item * @param name name of the property * @param rev revision to retrieve * @param value value of the property * @param force * @throws ClientException * @since 1.2 */ public native void setRevProperty(String path, String name, Revision rev, String value, boolean force) throws ClientException; /** * Retrieve one property of one iten * @param path path of the item * @param name name of property * @return the Property * @throws ClientException */ public PropertyData propertyGet(String path, String name) throws ClientException { return propertyGet(path, name, null); } /** * Retrieve one property of one iten * * @param path path of the item * @param name name of property * @param revision revision of the item * @return the Property * @throws ClientException * @since 1.2 */ public PropertyData propertyGet(String path, String name, Revision revision) throws ClientException { return propertyGet(path, name, revision, revision); } /** * Retrieve one property of one iten * * @param path path of the item * @param name name of property * @param revision revision of the item * @param pegRevision the revision to interpret path * @return the Property * @throws ClientException * @since 1.2 */ public native PropertyData propertyGet(String path, String name, Revision revision, Revision pegRevision) throws ClientException; /** * Retrieve the content of a file * @param path the path of the file * @param revision the revision to retrieve * @return the content as byte array * @throws ClientException */ public byte[] fileContent(String path, Revision revision) throws ClientException { return fileContent(path, revision, revision); } /** * Retrieve the content of a file * * @param path the path of the file * @param revision the revision to retrieve * @param pegRevision the revision to interpret path * @return the content as byte array * @throws ClientException * @since 1.2 */ public native byte[] fileContent(String path, Revision revision, Revision pegRevision) throws ClientException; public native void streamFileContent(String path, Revision revision, Revision pegRevision, int bufferSize, OutputStream stream) throws ClientException; /** * Rewrite the url's in the working copy * @param from old url * @param to new url * @param path working copy path * @param recurse recurse into subdirectories * @throws ClientException */ public native void relocate(String from, String to, String path, boolean recurse) throws ClientException; /** * Return for each line of the file, the author and the revision of the * last together with the content. * @deprecated * @param path the path * @param revisionStart the first revision to show * @param revisionEnd the last revision to show * @return the content together with author and revision of last change * @throws ClientException */ public native byte[] blame(String path, Revision revisionStart, Revision revisionEnd) throws ClientException; /** * Retrieve the content together with the author, the revision and the date * of the last change of each line * @param path the path * @param revisionStart the first revision to show * @param revisionEnd the last revision to show * @param callback callback to receive the file content and the other * information * @throws ClientException */ public void blame(String path, Revision revisionStart, Revision revisionEnd, BlameCallback callback) throws ClientException { blame(path, revisionEnd, revisionStart, revisionEnd, callback); } /** * Retrieve the content together with the author, the revision and the date * of the last change of each line * @param path the path * @param pegRevision the revision to interpret the path * @param revisionStart the first revision to show * @param revisionEnd the last revision to show * @param callback callback to receive the file content and the other * information * @throws ClientException * @since 1.2 */ public native void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, BlameCallback callback) throws ClientException; /** * Set directory for the configuration information * @param configDir path of the directory * @throws ClientException */ public native void setConfigDirectory(String configDir) throws ClientException; /** * Get the configuration directory * @return the directory * @throws ClientException */ public native String getConfigDirectory() throws ClientException; /** * cancel the active operation * @throws ClientException */ public native void cancelOperation() throws ClientException; /** * Retrieves the working copy information for an item * @param path path of the item * @return the information object * @throws ClientException */ public native Info info(String path) throws ClientException; /** * Produce a compact "version number" for a working copy * @param path path of the working copy * @param trailUrl to detect switches of the whole working copy * @param lastChanged last changed rather than current revisions * @return the compact "version number" * @throws ClientException * @since 1.2 */ public native String getVersionInfo(String path, String trailUrl, boolean lastChanged) throws ClientException; /** * Enable logging in the JNI-code * @param logLevel the level of information to log (See * SVNClientLogLevel) * @param logFilePath path of the log file */ public static native void enableLogging(int logLevel, String logFilePath); /** * class for the constants of the logging levels. * The constants are defined in SVNClientLogLevel because of building * reasons */ public static final class LogLevel implements SVNClientLogLevel { } /** * Returns version information of subversion and the javahl binding * @return version information */ public static native String version(); /** * Returns the major version of the javahl binding. Same version of the * javahl support the same interfaces * @return major version number */ public static native int versionMajor(); /** * Returns the minor version of the javahl binding. Same version of the * javahl support the same interfaces * @return minor version number */ public static native int versionMinor(); /** * Returns the micro (patch) version of the javahl binding. Same version of * the javahl support the same interfaces * @return micro version number */ public static native int versionMicro(); /** * Commits changes to the repository. * * @param path files to commit. * @param message log message. * @param recurse whether the operation should be done recursively. * @param noUnlock do remove any locks * @return Returns a long representing the revision. It returns a * -1 if the revision number is invalid. * @throws ClientException * @since 1.2 */ public native long commit(String[] path, String message, boolean recurse, boolean noUnlock) throws ClientException; /** * Lock a working copy item * * @param path path of the item * @param comment * @param force break an existing lock * @throws ClientException * @since 1.2 */ public native void lock(String[] path, String comment, boolean force) throws ClientException; /** * Unlock a working copy item * * @param path path of the item * @param force break an existing lock * @throws ClientException * @since 1.2 */ public native void unlock(String[] path, boolean force) throws ClientException; /** * Retrieve information about repository or working copy items. * * @param pathOrUrl the path or the url of the item * @param revision the revision of the item to return * @param pegRevision the revision to interpret pathOrUrl * @param recurse flag if to recurse, if the item is a directory * @return the information objects * @since 1.2 */ public native Info2[] info2(String pathOrUrl, Revision revision, Revision pegRevision, boolean recurse) throws ClientException; /** * Internal method to initialize the native layer. Only to be called by * NativeResources.loadNativeLibrary */ static native void initNative(); }
package com.jacudibu.components; import com.badlogic.ashley.core.Component; import com.badlogic.ashley.core.ComponentMapper; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; import com.badlogic.gdx.physics.bullet.collision.btCylinderShape; import com.badlogic.gdx.physics.bullet.collision.btSphereShape; import com.badlogic.gdx.utils.Disposable; import com.jacudibu.Core; public class ColliderComponent implements Component, Disposable{ private static final ComponentMapper<ColliderComponent> mapper = ComponentMapper.getFor(ColliderComponent.class); public btCollisionObject collisionObject; private boolean isArrow; public static ColliderComponent get(Entity e) { return mapper.get(e); } public static ColliderComponent createTrackerCollider(Entity entity) { ColliderComponent collider = new ColliderComponent(entity); collider.collisionObject.setCollisionShape(new btSphereShape(0.1f)); collider.collisionObject.setWorldTransform(ModelComponent.get(entity).getWorldTransform()); Core.collisionWorld.addCollisionObject(collider.collisionObject); return collider; } public static ColliderComponent createMarkerCollider(Entity entity) { ColliderComponent collider = new ColliderComponent(entity); collider.collisionObject.setCollisionShape(new btBoxShape(new Vector3(0.1f, 0.1f, 0.01f))); collider.collisionObject.setWorldTransform(ModelComponent.get(entity).getWorldTransform()); Core.collisionWorld.addCollisionObject(collider.collisionObject); return collider; } public static ColliderComponent createArrowCollider(Entity entity) { ColliderComponent collider = new ColliderComponent(entity); collider.updateArrowCollider(ArrowComponent.get(entity)); Core.collisionWorld.addCollisionObject(collider.collisionObject); return collider; } private ColliderComponent(Entity entity) { this.collisionObject = new btCollisionObject(); this.collisionObject.userData = entity; } public void updateTransform(Matrix4 transform) { collisionObject.setWorldTransform(transform); } public void updateArrowCollider(ArrowComponent arrowComponent) { if (arrowComponent.model != null) { collisionObject.setCollisionShape(Bullet.obtainStaticNodeShape(arrowComponent.model.nodes)); collisionObject.setWorldTransform(arrowComponent.getWorldTransform()); } } @Override public void dispose() { Core.collisionWorld.removeCollisionObject(collisionObject); collisionObject.dispose(); } }
package bisq.core.api; import bisq.core.monetary.Altcoin; import bisq.core.monetary.Price; import bisq.core.offer.CreateOfferService; import bisq.core.offer.Offer; import bisq.core.offer.OfferBookService; import bisq.core.offer.OpenOfferManager; import bisq.core.payment.PaymentAccount; import bisq.core.trade.handlers.TransactionResultHandler; import bisq.core.user.User; import org.bitcoinj.core.Coin; import org.bitcoinj.utils.Fiat; import javax.inject.Inject; import java.math.BigDecimal; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import static bisq.common.util.MathUtils.exactMultiply; import static bisq.common.util.MathUtils.roundDoubleToLong; import static bisq.common.util.MathUtils.scaleUpByPowerOf10; import static bisq.core.locale.CurrencyUtil.isCryptoCurrency; import static bisq.core.offer.OfferPayload.Direction; import static bisq.core.offer.OfferPayload.Direction.BUY; @Slf4j class CoreOffersService { private final CreateOfferService createOfferService; private final OfferBookService offerBookService; private final OpenOfferManager openOfferManager; private final User user; @Inject public CoreOffersService(CreateOfferService createOfferService, OfferBookService offerBookService, OpenOfferManager openOfferManager, User user) { this.createOfferService = createOfferService; this.offerBookService = offerBookService; this.openOfferManager = openOfferManager; this.user = user; } List<Offer> getOffers(String direction, String currencyCode) { List<Offer> offers = offerBookService.getOffers().stream() .filter(o -> { var offerOfWantedDirection = o.getDirection().name().equalsIgnoreCase(direction); var offerInWantedCurrency = o.getOfferPayload().getCounterCurrencyCode() .equalsIgnoreCase(currencyCode); return offerOfWantedDirection && offerInWantedCurrency; }) .collect(Collectors.toList()); // A buyer probably wants to see sell orders in price ascending order. // A seller probably wants to see buy orders in price descending order. if (direction.equalsIgnoreCase(BUY.name())) offers.sort(Comparator.comparing(Offer::getPrice).reversed()); else offers.sort(Comparator.comparing(Offer::getPrice)); return offers; } // Create offer with a random offer id. Offer createOffer(String currencyCode, String directionAsString, String priceAsString, boolean useMarketBasedPrice, double marketPriceMargin, long amountAsLong, long minAmountAsLong, double buyerSecurityDeposit, String paymentAccountId, TransactionResultHandler resultHandler) { String upperCaseCurrencyCode = currencyCode.toUpperCase(); String offerId = createOfferService.getRandomOfferId(); Direction direction = Direction.valueOf(directionAsString.toUpperCase()); Price price = Price.valueOf(upperCaseCurrencyCode, priceStringToLong(priceAsString, upperCaseCurrencyCode)); Coin amount = Coin.valueOf(amountAsLong); Coin minAmount = Coin.valueOf(minAmountAsLong); PaymentAccount paymentAccount = user.getPaymentAccount(paymentAccountId); // We don't support atm funding from external wallet to keep it simple boolean useSavingsWallet = true; //noinspection ConstantConditions return createAndPlaceOffer(offerId, upperCaseCurrencyCode, direction, price, useMarketBasedPrice, marketPriceMargin, amount, minAmount, buyerSecurityDeposit, paymentAccount, useSavingsWallet, resultHandler); } // Create offer for given offer id. Offer createOffer(String offerId, String currencyCode, Direction direction, Price price, boolean useMarketBasedPrice, double marketPriceMargin, Coin amount, Coin minAmount, double buyerSecurityDeposit, PaymentAccount paymentAccount, boolean useSavingsWallet, TransactionResultHandler resultHandler) { Coin useDefaultTxFee = Coin.ZERO; Offer offer = createOfferService.createAndGetOffer(offerId, direction, currencyCode.toUpperCase(), amount, minAmount, price, useDefaultTxFee, useMarketBasedPrice, exactMultiply(marketPriceMargin, 0.01), buyerSecurityDeposit, paymentAccount); openOfferManager.placeOffer(offer, buyerSecurityDeposit, useSavingsWallet, resultHandler, log::error); return offer; } private Offer createAndPlaceOffer(String offerId, String currencyCode, Direction direction, Price price, boolean useMarketBasedPrice, double marketPriceMargin, Coin amount, Coin minAmount, double buyerSecurityDeposit, PaymentAccount paymentAccount, boolean useSavingsWallet, TransactionResultHandler resultHandler) { Coin useDefaultTxFee = Coin.ZERO; Offer offer = createOfferService.createAndGetOffer(offerId, direction, currencyCode, amount, minAmount, price, useDefaultTxFee, useMarketBasedPrice, exactMultiply(marketPriceMargin, 0.01), buyerSecurityDeposit, paymentAccount); // TODO give user chance to examine offer before placing it (placeoffer) openOfferManager.placeOffer(offer, buyerSecurityDeposit, useSavingsWallet, resultHandler, log::error); return offer; } private long priceStringToLong(String priceAsString, String currencyCode) { int precision = isCryptoCurrency(currencyCode) ? Altcoin.SMALLEST_UNIT_EXPONENT : Fiat.SMALLEST_UNIT_EXPONENT; double priceAsDouble = new BigDecimal(priceAsString).doubleValue(); double scaled = scaleUpByPowerOf10(priceAsDouble, precision); return roundDoubleToLong(scaled); } }
package graph; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Paint; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.Properties; import java.util.Scanner; import java.util.concurrent.locks.ReentrantLock; import java.util.prefs.Preferences; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.metal.MetalButtonUI; import javax.swing.plaf.metal.MetalIconFactory; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import lpn.parser.LhpnFile; import main.Gui; import main.Log; import main.util.Utility; import main.util.dataparser.DTSDParser; import main.util.dataparser.DataParser; import main.util.dataparser.TSDParser; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.LogarithmicAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.axis.StandardTickUnitSource; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.GradientBarPainter; import org.jfree.chart.renderer.category.StandardBarPainter; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.title.LegendTitle; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jibble.epsgraphics.EpsGraphics2D; import org.sbml.libsbml.ListOf; import org.sbml.libsbml.Model; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.Species; import org.w3c.dom.DOMImplementation; import analysis.AnalysisView; import biomodel.parser.BioModel; import com.lowagie.text.Document; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.DefaultFontMapper; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; /** * This is the Graph class. It takes in data and draws a graph of that data. The * Graph class implements the ActionListener class, the ChartProgressListener * class, and the MouseListener class. This allows the Graph class to perform * actions when buttons are pressed, when the chart is drawn, or when the chart * is clicked. * * @author Curtis Madsen */ public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener { private static final long serialVersionUID = 4350596002373546900L; private JFreeChart chart; // Graph of the output data private XYSeriesCollection curData; // Data in the current graph private String outDir; // output directory private String printer_id; // printer id /* * Text fields used to change the graph window */ private JTextField XMin, XMax, XScale, YMin, YMax, YScale; private ArrayList<String> graphSpecies; // names of species in the graph private Gui biomodelsim; // tstubd gui private JButton save, run, saveAs; private JButton export, refresh; // buttons // private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg, // exportCsv; // buttons private HashMap<String, Paint> colors; private HashMap<String, Shape> shapes; private String selected, lastSelected; private LinkedList<GraphSpecies> graphed; private LinkedList<GraphProbs> probGraphed; private JCheckBox resize; private JComboBox XVariable; private JCheckBox LogX, LogY; private JCheckBox visibleLegend; private LegendTitle legend; private Log log; private ArrayList<JCheckBox> boxes; private ArrayList<JTextField> series; private ArrayList<JComboBox> colorsCombo; private ArrayList<JButton> colorsButtons; private ArrayList<JComboBox> shapesCombo; private ArrayList<JCheckBox> connected; private ArrayList<JCheckBox> visible; private ArrayList<JCheckBox> filled; private JCheckBox use; private JCheckBox connectedLabel; private JCheckBox visibleLabel; private JCheckBox filledLabel; private String graphName; private String separator; private boolean change; private boolean timeSeries; private boolean topLevel; private ArrayList<String> graphProbs; private JTree tree; private IconNode node, simDir; private AnalysisView reb2sac; // reb2sac options private ArrayList<String> learnSpecs; private boolean warn; private ArrayList<String> averageOrder; private JPopupMenu popup; // popup menu private ArrayList<String> directories; private JPanel specPanel; private JScrollPane scrollpane; private JPanel all; private JPanel titlePanel; private JScrollPane scroll; private boolean updateXNumber; private final ReentrantLock lock, lock2; /** * Creates a Graph Object from the data given and calls the private graph * helper method. */ public Graph(AnalysisView reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, Gui biomodelsim, String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) { lock = new ReentrantLock(true); lock2 = new ReentrantLock(true); this.reb2sac = reb2sac; averageOrder = null; popup = new JPopupMenu(); warn = false; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // initializes member variables this.log = log; this.timeSeries = timeSeries; if (graphName != null) { this.graphName = graphName; topLevel = true; } else { if (timeSeries) { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf"; } else { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb"; } topLevel = false; } this.outDir = outDir; this.printer_id = printer_id; this.biomodelsim = biomodelsim; XYSeriesCollection data = new XYSeriesCollection(); if (learnGraph) { updateSpecies(); } else { learnSpecs = null; } // graph the output data if (timeSeries) { setUpShapesAndColors(); graphed = new LinkedList<GraphSpecies>(); selected = ""; lastSelected = ""; graph(printer_track_quantity, label, data, time); if (open != null) { open(open); } } else { setUpShapesAndColors(); probGraphed = new LinkedList<GraphProbs>(); selected = ""; lastSelected = ""; probGraph(label); if (open != null) { open(open); } } } /** * This private helper method calls the private readData method, sets up a * graph frame, and graphs the data. * * @param dataset * @param time */ private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) { chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.addProgressListener(this); legend = chart.getLegend(); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates text fields for changing the graph's dimensions resize = new JCheckBox("Auto Resize"); resize.setSelected(true); XVariable = new JComboBox(); Dimension dim = new Dimension(1,1); XVariable.setPreferredSize(dim); updateXNumber = false; XVariable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (updateXNumber && node != null) { String curDir = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName(); } else if (directories.contains(((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent()).getName(); } else { curDir = ""; } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(curDir)) { graphed.get(i).setXNumber(XVariable.getSelectedIndex()); } } } } }); LogX = new JCheckBox("LogX"); LogX.setSelected(false); LogY = new JCheckBox("LogY"); LogY.setSelected(false); visibleLegend = new JCheckBox("Visible Legend"); visibleLegend.setSelected(true); XMin = new JTextField(); XMax = new JTextField(); XScale = new JTextField(); YMin = new JTextField(); YMax = new JTextField(); YScale = new JTextField(); // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); // determines maximum and minimum values and resizes resize(dataset); this.revalidate(); } private void readGraphSpecies(String file) { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (file.contains(".dtsd")) graphSpecies = (new DTSDParser(file)).getSpecies(); else graphSpecies = new TSDParser(file, true).getSpecies(); Gui.frame.setCursor(null); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); i } } } } /** * This public helper method parses the output file of ODE, monte carlo, and * markov abstractions. */ public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) { warn = warning; String[] s = file.split(separator); String getLast = s[s.length - 1]; String stem = ""; int t = 0; try { while (!Character.isDigit(getLast.charAt(t))) { stem += getLast.charAt(t); t++; } } catch (Exception e) { } if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance")) || (label.contains("deviation") && file.contains("standard_deviation"))) { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); TSDParser p = new TSDParser(file, warn); Gui.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); ArrayList<ArrayList<Double>> data = p.getData(); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } if (label.contains("average") || label.contains("variance") || label.contains("deviation")) { ArrayList<String> runs = new ArrayList<String>(); if (directory == null) { String[] files = new File(outDir).list(); for (String f : files) { if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { runs.add(f); } } } else { String[] files = new File(outDir + separator + directory).list(); for (String f : files) { if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { runs.add(f); } } } if (label.contains("average")) { return calculateAverageVarianceDeviation(runs, 0, directory, warn, false); } else if (label.contains("variance")) { return calculateAverageVarianceDeviation(runs, 1, directory, warn, false); } else { return calculateAverageVarianceDeviation(runs, 2, directory, warn, false); } } //if it's not a stats file else { Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); DTSDParser dtsdParser; TSDParser p; ArrayList<ArrayList<Double>> data; if (file.contains(".dtsd")) { dtsdParser = new DTSDParser(file); Gui.frame.setCursor(null); warn = false; graphSpecies = dtsdParser.getSpecies(); data = dtsdParser.getData(); } else { p = new TSDParser(file, warn); Gui.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); data = p.getData(); } if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } } /** * This method adds and removes plots from the graph depending on what check * boxes are selected. */ public void actionPerformed(ActionEvent e) { // if the save button is clicked if (e.getSource() == run) { reb2sac.getRunButton().doClick(); } if (e.getSource() == save) { save(); } // if the save as button is clicked if (e.getSource() == saveAs) { saveAs(); } // if the export button is clicked else if (e.getSource() == export) { export(); } else if (e.getSource() == refresh) { refresh(); } else if (e.getActionCommand().equals("rename")) { String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { boolean write = true; if (rename.equals(node.getName())) { write = false; } else if (new File(outDir + separator + rename).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.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(outDir + separator + rename); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) { simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(rename)) { graphed.remove(i); i } } } else { write = false; } } if (write) { String getFile = node.getName(); IconNode s = node; while (s.getParent().getParent() != null) { getFile = s.getName() + separator + getFile; s = (IconNode) s.getParent(); } getFile = outDir + separator + getFile; new File(getFile).renameTo(new File(outDir + separator + rename)); for (GraphSpecies spec : graphed) { if (spec.getDirectory().equals(node.getName())) { spec.setDirectory(rename); } } directories.remove(node.getName()); directories.add(rename); node.setUserObject(rename); node.setName(rename); simDir.remove(node); int i; for (i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(rename) > 0) { simDir.insert(node, i); break; } } else { break; } } simDir.insert(node, i); ArrayList<String> rows = new ArrayList<String>(); for (i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); int select = 0; for (i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } if (rename.equals(node.getName())) { select = i; } } tree.removeTreeSelectionListener(t); addTreeListener(); tree.setSelectionRow(select); } } } else if (e.getActionCommand().equals("recalculate")) { TreePath select = tree.getSelectionPath(); String[] files; if (((IconNode) select.getLastPathComponent()).getParent() != null) { files = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()).list(); } else { files = new File(outDir).list(); } ArrayList<String> runs = new ArrayList<String>(); for (String file : files) { if (file.contains("run-") && file.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) { runs.add(file); } } if (((IconNode) select.getLastPathComponent()).getParent() != null) { calculateAverageVarianceDeviation(runs, 0, ((IconNode) select.getLastPathComponent()).getName(), warn, true); } else { calculateAverageVarianceDeviation(runs, 0, null, warn, true); } } else if (e.getActionCommand().equals("delete")) { TreePath[] selected = tree.getSelectionPaths(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) { tree.removeTreeSelectionListener(listen); } tree.addTreeSelectionListener(t); for (TreePath select : selected) { tree.setSelectionPath(select); if (((IconNode) select.getLastPathComponent()).getParent() != null) { for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select.getLastPathComponent())) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { simDir.remove(i); File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } directories.remove(((IconNode) select.getLastPathComponent()).getName()); for (int j = 0; j < graphed.size(); j++) { if (graphed.get(j).getDirectory().equals(((IconNode) select.getLastPathComponent()).getName())) { graphed.remove(j); j } } } else { String name = ((IconNode) select.getLastPathComponent()).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; simDir.remove(i); } else if (name.equals("Termination Time")) { name = "term-time"; simDir.remove(i); } else if (name.equals("Constraint Termination")) { name = "sim-rep"; simDir.remove(i); } else if (name.equals("Bifurcation Statistics")) { name = "bifurcation"; simDir.remove(i); } else { simDir.remove(i); } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } int count = 0; boolean m = false; if (new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { m = true; } boolean v = false; if (new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { v = true; } boolean d = false; if (new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { d = true; } for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(j)).getName().contains("run-")) { count++; } } } if (count == 0) { for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(j)).getName().contains("Average") && !m) { simDir.remove(j); j } else if (((IconNode) simDir.getChildAt(j)).getName().contains("Variance") && !v) { simDir.remove(j); j } else if (((IconNode) simDir.getChildAt(j)).getName().contains("Deviation") && !d) { simDir.remove(j); j } } } } } } else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) { if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select.getLastPathComponent())) { String name = ((IconNode) select.getLastPathComponent()).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; ((IconNode) simDir.getChildAt(i)).remove(j); } else if (name.equals("Termination Time")) { name = "term-time"; ((IconNode) simDir.getChildAt(i)).remove(j); } else if (name.equals("Constraint Termination")) { name = "sim-rep"; ((IconNode) simDir.getChildAt(i)).remove(j); } else if (name.equals("Bifurcation Statistics")) { name = "bifurcation"; ((IconNode) simDir.getChildAt(i)).remove(j); } else { ((IconNode) simDir.getChildAt(i)).remove(j); } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } boolean checked = false; for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { ((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory.getTreeFolderIcon()); ((IconNode) simDir.getChildAt(i)).setIconName(""); } int count = 0; boolean m = false; if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { m = true; } boolean v = false; if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { v = true; } boolean d = false; if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { d = true; } for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("run-")) { count++; } } } if (count == 0) { for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Average") && !m) { ((IconNode) simDir.getChildAt(i)).remove(k); k } else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Variance") && !v) { ((IconNode) simDir.getChildAt(i)).remove(k); k } else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Deviation") && !d) { ((IconNode) simDir.getChildAt(i)).remove(k); k } } } } } } } } } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete runs")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { String name = ((IconNode) simDir.getChildAt(i)).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; } else if (name.equals("Termination Time")) { name = "term-time"; } else if (name.equals("Constraint Termination")) { name = "sim-rep"; } else if (name.equals("Bifurcation Statistics")) { name = "bifurcation"; } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete all")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { String name = ((IconNode) simDir.getChildAt(i)).getName(); if (name.equals("Average")) { name = "mean"; } else if (name.equals("Variance")) { name = "variance"; } else if (name.equals("Standard Deviation")) { name = "standard_deviation"; } else if (name.equals("Percent Termination")) { name = "percent-term-time"; } else if (name.equals("Termination Time")) { name = "term-time"; } else if (name.equals("Constraint Termination")) { name = "sim-rep"; } else if (name.equals("Bifurcation Statistics")) { name = "bifurcation"; } name += "." + printer_id.substring(0, printer_id.length() - 8); File dir = new File(outDir + separator + name); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } else { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } // // if the export as jpeg button is clicked // else if (e.getSource() == exportJPeg) { // export(0); // // if the export as png button is clicked // else if (e.getSource() == exportPng) { // export(1); // // if the export as pdf button is clicked // else if (e.getSource() == exportPdf) { // export(2); // // if the export as eps button is clicked // else if (e.getSource() == exportEps) { // export(3); // // if the export as svg button is clicked // else if (e.getSource() == exportSvg) { // export(4); // } else if (e.getSource() == exportCsv) { // export(5); } /** * Private method used to auto resize the graph. */ private void resize(XYSeriesCollection dataset) { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); XYPlot plot = chart.getXYPlot(); XYItemRenderer rend = plot.getRenderer(); double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; for (int j = 0; j < dataset.getSeriesCount(); j++) { XYSeries series = dataset.getSeries(j); double[][] seriesArray = series.toArray(); Boolean visible = rend.getSeriesVisible(j); if (visible == null || visible.equals(true)) { for (int k = 0; k < series.getItemCount(); k++) { maxY = Math.max(seriesArray[1][k], maxY); minY = Math.min(seriesArray[1][k], minY); maxX = Math.max(seriesArray[0][k], maxX); minX = Math.min(seriesArray[0][k], minX); } } } NumberAxis axis = (NumberAxis) plot.getRangeAxis(); if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxY - minY) < .001) { // axis.setRange(minY - 1, maxY + 1); else { /* * axis.setRange(Double.parseDouble(num.format(minY - * (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY + * (Math.abs(maxY) .1)))); */ if ((maxY - minY) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } else { axis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); } axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1)); } axis.setAutoTickUnitSelection(true); if (LogY.isSelected()) { try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } if (visibleLegend.isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } axis = (NumberAxis) plot.getDomainAxis(); if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxX - minX) < .001) { // axis.setRange(minX - 1, maxX + 1); else { if ((maxX - minX) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } else { axis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); } axis.setRange(minX, maxX); } axis.setAutoTickUnitSelection(true); if (LogX.isSelected()) { try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel()); domainAxis.setStrictValuesFlag(false); plot.setDomainAxis(domainAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } /** * After the chart is redrawn, this method calculates the x and y scale and * updates those text fields. */ public void chartProgress(ChartProgressEvent e) { // if the chart drawing is started if (e.getType() == ChartProgressEvent.DRAWING_STARTED) { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } // if the chart drawing is finished else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) { this.setCursor(null); JFreeChart chart = e.getChart(); XYPlot plot = (XYPlot) chart.getXYPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); YMin.setText("" + axis.getLowerBound()); YMax.setText("" + axis.getUpperBound()); YScale.setText("" + axis.getTickUnit().getSize()); axis = (NumberAxis) plot.getDomainAxis(); XMin.setText("" + axis.getLowerBound()); XMax.setText("" + axis.getUpperBound()); XScale.setText("" + axis.getTickUnit().getSize()); } } /** * Invoked when the mouse is clicked on the chart. Allows the user to edit * the title and labels of the chart. */ public void mouseClicked(MouseEvent e) { if (e.getSource() != tree) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (timeSeries) { editGraph(); } else { editProbGraph(); } } } } public void mousePressed(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0) { JMenuItem recalculate = new JMenuItem("Recalculate Statistics"); recalculate.addActionListener(this); recalculate.setActionCommand("recalculate"); popup.add(recalculate); } if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } public void mouseReleased(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0) { JMenuItem recalculate = new JMenuItem("Recalculate Statistics"); recalculate.addActionListener(this); recalculate.setActionCommand("recalculate"); popup.add(recalculate); } if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } /** * This method currently does nothing. */ public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseExited(MouseEvent e) { } private void setUpShapesAndColors() { DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); colors = new HashMap<String, Paint>(); shapes = new HashMap<String, Shape>(); colors.put("Red", draw.getNextPaint()); colors.put("Blue", draw.getNextPaint()); colors.put("Green", draw.getNextPaint()); colors.put("Yellow", draw.getNextPaint()); colors.put("Magenta", draw.getNextPaint()); colors.put("Cyan", draw.getNextPaint()); colors.put("Tan", draw.getNextPaint()); colors.put("Gray (Dark)", draw.getNextPaint()); colors.put("Red (Dark)", draw.getNextPaint()); colors.put("Blue (Dark)", draw.getNextPaint()); colors.put("Green (Dark)", draw.getNextPaint()); colors.put("Yellow (Dark)", draw.getNextPaint()); colors.put("Magenta (Dark)", draw.getNextPaint()); colors.put("Cyan (Dark)", draw.getNextPaint()); colors.put("Black", draw.getNextPaint()); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); // colors.put("Red ", draw.getNextPaint()); // colors.put("Blue ", draw.getNextPaint()); // colors.put("Green ", draw.getNextPaint()); // colors.put("Yellow ", draw.getNextPaint()); // colors.put("Magenta ", draw.getNextPaint()); // colors.put("Cyan ", draw.getNextPaint()); colors.put("Gray", draw.getNextPaint()); colors.put("Red (Extra Dark)", draw.getNextPaint()); colors.put("Blue (Extra Dark)", draw.getNextPaint()); colors.put("Green (Extra Dark)", draw.getNextPaint()); colors.put("Yellow (Extra Dark)", draw.getNextPaint()); colors.put("Magenta (Extra Dark)", draw.getNextPaint()); colors.put("Cyan (Extra Dark)", draw.getNextPaint()); colors.put("Red (Light)", draw.getNextPaint()); colors.put("Blue (Light)", draw.getNextPaint()); colors.put("Green (Light)", draw.getNextPaint()); colors.put("Yellow (Light)", draw.getNextPaint()); colors.put("Magenta (Light)", draw.getNextPaint()); colors.put("Cyan (Light)", draw.getNextPaint()); colors.put("Gray (Light)", new java.awt.Color(238, 238, 238)); shapes.put("Square", draw.getNextShape()); shapes.put("Circle", draw.getNextShape()); shapes.put("Triangle", draw.getNextShape()); shapes.put("Diamond", draw.getNextShape()); shapes.put("Rectangle (Horizontal)", draw.getNextShape()); shapes.put("Triangle (Upside Down)", draw.getNextShape()); shapes.put("Circle (Half)", draw.getNextShape()); shapes.put("Arrow", draw.getNextShape()); shapes.put("Rectangle (Vertical)", draw.getNextShape()); shapes.put("Arrow (Backwards)", draw.getNextShape()); } public void editGraph() { final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { old.add(g); } titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5); final JLabel xMin = new JLabel("X-Min:"); final JLabel xMax = new JLabel("X-Max:"); final JLabel xScale = new JLabel("X-Step:"); final JLabel yMin = new JLabel("Y-Min:"); final JLabel yMax = new JLabel("Y-Max:"); final JLabel yScale = new JLabel("Y-Step:"); LogX.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel()); domainAxis.setStrictValuesFlag(false); plot.setRangeAxis(domainAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } }); LogY.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } } }); visibleLegend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } } }); resize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } } }); if (resize.isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } Properties p = null; if (learnSpecs != null) { try { String[] split = outDir.split(separator); p = new Properties(); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); } catch (Exception e) { } } String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); // for (int i = 1; i < files.length; i++) { // String index = files[i]; // int j = i; // while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { // files[j] = files[j - 1]; // j = j - 1; // files[j] = index; boolean addMean = false; boolean addVar = false; boolean addDev = false; boolean addTerm = false; boolean addPercent = false; boolean addConst = false; boolean addBif = false; directories = new ArrayList<String>(); for (String file : files) { if ((file.length() > 3 && (file.substring(file.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (file.length() > 4 && file.substring(file.length() - 5).equals(".dtsd"))) { if (file.contains("run-") || file.contains("mean")) { addMean = true; } else if (file.contains("run-") || file.contains("variance")) { addVar = true; } else if (file.contains("run-") || file.contains("standard_deviation")) { addDev = true; } else if (file.startsWith("term-time")) { addTerm = true; } else if (file.contains("percent-term-time")) { addPercent = true; } else if (file.contains("sim-rep")) { addConst = true; } else if (file.contains("bifurcation")) { addBif = true; } else { IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(0, file.length() - 4)); boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; String[] files3 = new File(outDir + separator + file).list(); // for (int i = 1; i < files3.length; i++) { // String index = files3[i]; // int j = i; // while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) > // files3[j] = files3[j - 1]; // j = j - 1; // files3[j] = index; for (String getFile : files3) { if ((getFile.length() > 3 && (getFile.substring(getFile.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (getFile.length() > 4 && getFile.substring(getFile.length() - 5).equals(".dtsd"))) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile).isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if ((getFile2.length() > 3 && (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)))) || (getFile2.length() > 4 && getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); boolean addMean2 = false; boolean addVar2 = false; boolean addDev2 = false; boolean addTerm2 = false; boolean addPercent2 = false; boolean addConst2 = false; boolean addBif2 = false; for (String f : files3) { if (f.contains(printer_id.substring(0, printer_id.length() - 8)) || f.contains(".dtsd")) { if (f.contains("run-") || f.contains("mean")) { addMean2 = true; } else if (f.contains("run-") || f.contains("variance")) { addVar2 = true; } else if (f.contains("run-") || f.contains("standard_deviation")) { addDev2 = true; } else if (f.startsWith("term-time")) { addTerm2 = true; } else if (f.contains("percent-term-time")) { addPercent2 = true; } else if (f.contains("sim-rep")) { addConst2 = true; } else if (f.contains("bifurcation")) { addBif2 = true; } else { IconNode n = new IconNode(f.substring(0, f.length() - 4), f.substring(0, f.length() - 4)); boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if (d.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; String[] files2 = new File(outDir + separator + file + separator + f).list(); // for (int i = 1; i < files2.length; i++) { // String index = files2[i]; // int j = i; // while ((j > 0) && files2[j - // 1].compareToIgnoreCase(index) > 0) { // files2[j] = files2[j - 1]; // j = j - 1; // files2[j] = index; for (String getFile2 : files2) { if (getFile2.length() > 3 && (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8)) || getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); boolean addMean3 = false; boolean addVar3 = false; boolean addDev3 = false; boolean addTerm3 = false; boolean addPercent3 = false; boolean addConst3 = false; boolean addBif3 = false; for (String f2 : files2) { if (f2.contains(printer_id.substring(0, printer_id.length() - 8)) || f2.contains(".dtsd")) { if (f2.contains("run-") || f2.contains("mean")) { addMean3 = true; } else if (f2.contains("run-") || f2.contains("variance")) { addVar3 = true; } else if (f2.contains("run-") || f2.contains("standard_deviation")) { addDev3 = true; } else if (f2.startsWith("term-time")) { addTerm3 = true; } else if (f2.contains("percent-term-time")) { addPercent3 = true; } else if (f2.contains("sim-rep")) { addConst3 = true; } else if (f2.contains("bifurcation")) { addBif3 = true; } else { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); boolean added = false; for (int j = 0; j < d2.getChildCount(); j++) { if (d2.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(f2.substring(0, f2.length() - 4)) && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (addMean3) { IconNode n = new IconNode("Average", "Average"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addDev3) { IconNode n = new IconNode("Standard Deviation", "Standard Deviation"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addVar3) { IconNode n = new IconNode("Variance", "Variance"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm3) { IconNode n = new IconNode("Termination Time", "Termination Time"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent3) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst3) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addBif3) { IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r2 = null; for (String s : files2) { if (s.contains("run-")) { r2 = s; } } if (r2 != null) { for (String s : files2) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + ".dtsd").exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (d2.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d2.getChildCount(); j++) { if (d2.getChildAt(j) .toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } } else { d2.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0) || new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) { d.insert(d2, j); added = true; break; } } if (!added) { d.add(d2); } } } } if (addMean2) { IconNode n = new IconNode("Average", "Average"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addDev2) { IconNode n = new IconNode("Standard Deviation", "Standard Deviation"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addVar2) { IconNode n = new IconNode("Variance", "Variance"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm2) { IconNode n = new IconNode("Termination Time", "Termination Time"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent2) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst2) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addBif2) { IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r = null; for (String s : files3) { if (s.contains("run-")) { r = s; } } if (r != null) { for (String s : files3) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (d.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d.getChildCount(); j++) { if (d.getChildAt(j) .toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } } else { d.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0) || new File(outDir + separator + (simDir.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) { simDir.insert(d, j); added = true; break; } } if (!added) { simDir.add(d); } } } } if (addMean) { IconNode n = new IconNode("Average", "Average"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addDev) { IconNode n = new IconNode("Standard Deviation", "Standard Deviation"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addVar) { IconNode n = new IconNode("Variance", "Variance"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addTerm) { IconNode n = new IconNode("Termination Time", "Termination Time"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addPercent) { IconNode n = new IconNode("Percent Termination", "Percent Termination"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addConst) { IconNode n = new IconNode("Constraint Termination", "Constraint Termination"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (addBif) { IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String runs = null; for (String s : new File(outDir).list()) { if (s.contains("run-")) { runs = s; } } if (runs != null) { for (String s : new File(outDir).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + "run-" + (i + 1) + ".dtsd").exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (simDir.getChildCount() > 3) { boolean added = false; for (int j = 3; j < simDir.getChildCount(); j++) { if (simDir .getChildAt(j) .toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } } else { simDir.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { all = new JPanel(new BorderLayout()); specPanel = new JPanel(); scrollpane = new JScrollPane(); refreshTree(); addTreeListener(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); scroll.getVerticalScrollBar().setUnitIncrement(10); // JButton ok = new JButton("Ok"); /* * ok.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { double minY; double maxY; double * scaleY; double minX; double maxX; double scaleX; change = true; * try { minY = Double.parseDouble(YMin.getText().trim()); maxY = * Double.parseDouble(YMax.getText().trim()); scaleY = * Double.parseDouble(YScale.getText().trim()); minX = * Double.parseDouble(XMin.getText().trim()); maxX = * Double.parseDouble(XMax.getText().trim()); scaleX = * Double.parseDouble(XScale.getText().trim()); NumberFormat num = * NumberFormat.getInstance(); num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { * JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles * into the inputs " + "to change the graph's dimensions!", "Error", * JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; * selected = ""; ArrayList<XYSeries> graphData = new * ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = * (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int * thisOne = -1; for (int i = 1; i < graphed.size(); i++) { * GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && * (graphed.get(j - * 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { * graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, * index); } ArrayList<GraphSpecies> unableToGraph = new * ArrayList<GraphSpecies>(); HashMap<String, * ArrayList<ArrayList<Double>>> allData = new HashMap<String, * ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { * if (g.getDirectory().equals("")) { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8)).exists()) { * readGraphSpecies(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getRunNumber() + * "." + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir).list()) { if * (s.length() > 3 && s.substring(0, 4).equals("run-")) { * ableToGraph = true; } } } catch (Exception e1) { ableToGraph = * false; } if (ableToGraph) { int next = 1; while (!new File(outDir * + separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + "run-" + next + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + "run-1." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame, * y.getText().trim(), g.getRunNumber().toLowerCase(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } else { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getDirectory() + separator + * g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { readGraphSpecies( outDir + * separator + g.getDirectory() + separator + g.getRunNumber() + "." * + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame); ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber(), g.getDirectory()); for (int i = 2; i < * graphSpecies.size(); i++) { String index = graphSpecies.get(i); * ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) * && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { * graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, * data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); * data.set(j, index2); } allData.put(g.getRunNumber() + " " + * g.getDirectory(), data); } graphData.add(new * XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = * 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir + separator + * g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, * 4).equals("run-")) { ableToGraph = true; } } } catch (Exception * e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; * while (!new File(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + "run-1." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i = * 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : * unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset * = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); * i++) { dataset.addSeries(graphData.get(i)); } * fixGraph(title.getText().trim(), x.getText().trim(), * y.getText().trim(), dataset); * chart.getXYPlot().setRenderer(rend); XYPlot plot = * chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } * else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); * axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); * axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) * plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); * axis.setRange(minX, maxX); axis.setTickUnit(new * NumberTickUnit(scaleX)); } //f.dispose(); } }); */ // final JButton cancel = new JButton("Cancel"); // cancel.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // selected = ""; // int size = graphed.size(); // for (int i = 0; i < size; i++) { // graphed.remove(); // for (GraphSpecies g : old) { // graphed.add(g); // f.dispose(); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(3, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xMin); titlePanel1.add(XMin); titlePanel1.add(yMin); titlePanel1.add(YMin); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(xMax); titlePanel1.add(XMax); titlePanel1.add(yMax); titlePanel1.add(YMax); titlePanel1.add(yLabel); titlePanel1.add(y); titlePanel1.add(xScale); titlePanel1.add(XScale); titlePanel1.add(yScale); titlePanel1.add(YScale); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(resize); titlePanel2.add(XVariable); titlePanel2.add(LogX); titlePanel2.add(LogY); titlePanel2.add(visibleLegend); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); // JPanel buttonPanel = new JPanel(); // buttonPanel.add(ok); // buttonPanel.add(deselect); // buttonPanel.add(cancel); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); // all.add(buttonPanel, "South"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { double minY; double maxY; double scaleY; double minX; double maxX; double scaleX; change = true; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected = ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { String extension = printer_id.substring(0, printer_id.length() - 8); if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() == false && new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) { extension = "dtsd"; } data = readData(outDir + separator + g.getRunNumber() + "." + extension, g.getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber() .toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() || new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) { ArrayList<ArrayList<Double>> data; //if the data has already been put into the data structure if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { String extension = printer_id.substring(0, printer_id.length() - 8); if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists() == false && new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) { extension = "dtsd"; } data = readData( outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + extension, g.getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } //if it's one of the stats/termination files else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end average else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end variance else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end standard deviation else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end termination time else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end percent termination else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } //end constraint termination else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData( outDir + separator + g.getDirectory() + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } //end of "Ok" option being true else { selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } for (GraphSpecies g : old) { graphed.add(g); } } // WindowListener w = new WindowListener() { // public void windowClosing(WindowEvent arg0) { // cancel.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) { // f.addWindowListener(w); // f.setContentPane(all); // 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 xx = screenSize.width / 2 - frameSize.width / 2; // int yy = screenSize.height / 2 - frameSize.height / 2; // f.setLocation(xx, yy); // f.setVisible(true); } } private void refreshTree() { tree = new JTree(simDir); if (!topLevel && learnSpecs == null) { tree.addMouseListener(this); } tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); } private void addTreeListener() { boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName()) && node.getParent() != null && !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) { selected = node.getName(); int select; if (selected.equals("Average")) { select = 0; } else if (selected.equals("Variance")) { select = 1; } else if (selected.equals("Standard Deviation")) { select = 2; } else if (selected.contains("-run")) { select = 0; } else if (selected.equals("Termination Time")) { select = 0; } else if (selected.equals("Percent Termination")) { select = 0; } else if (selected.equals("Constraint Termination")) { select = 0; } else { try { if (selected.contains("run-")) { select = Integer.parseInt(selected.substring(4)) + 2; } else { select = -1; } } catch (Exception e1) { select = -1; } } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName())); } else { specPanel.add(fixGraphChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphSpecies.get(i + 1)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals(((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]); shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } boolean allChecked = true; boolean allCheckedVisible = true; boolean allCheckedFilled = true; boolean allCheckedConnected = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = graphSpecies.get(i + 1); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colors.get("Black")); colorsButtons.get(i).setForeground((Color) colors.get("Black")); shapesCombo.get(i).setSelectedIndex(0); } else { String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = series.get(i).getText(); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); } if (!visible.get(i).isSelected()) { allCheckedVisible = false; } if (!connected.get(i).isSelected()) { allCheckedConnected = false; } if (!filled.get(i).isSelected()) { allCheckedFilled = false; } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } if (allCheckedVisible) { visibleLabel.setSelected(true); } else { visibleLabel.setSelected(false); } if (allCheckedFilled) { filledLabel.setSelected(true); } else { filledLabel.setSelected(false); } if (allCheckedConnected) { connectedLabel.setSelected(true); } else { connectedLabel.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } } private JPanel fixGraphChoices(final String directory) { if (directory.equals("")) { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation") || selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) { if (selected.equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Bifurcation Statistics") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { String extension = printer_id.substring(0, printer_id.length() - 8); if (new File(outDir + separator + selected + "." + extension).exists() == false) extension = "dtsd"; readGraphSpecies(outDir + separator + selected + "." + extension); } } else { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation") || selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) { if (selected.equals("Average") && new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Termination Time") && new File(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Percent Termination") && new File(outDir + separator + directory + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Constraint Termination") && new File(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Bifurcation Statistics") && new File(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8)); } } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3)); JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3)); use = new JCheckBox("Use"); JLabel specs; specs = new JLabel("Variables"); JLabel color = new JLabel("Color"); JLabel shape = new JLabel("Shape"); connectedLabel = new JCheckBox("Connect"); visibleLabel = new JCheckBox("Visible"); filledLabel = new JCheckBox("Fill"); connectedLabel.setSelected(true); visibleLabel.setSelected(true); filledLabel.setSelected(true); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); colorsButtons = new ArrayList<JButton>(); shapesCombo = new ArrayList<JComboBox>(); connected = new ArrayList<JCheckBox>(); visible = new ArrayList<JCheckBox>(); filled = new ArrayList<JCheckBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); connectedLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (connectedLabel.isSelected()) { for (JCheckBox box : connected) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : connected) { if (box.isSelected()) { box.doClick(); } } } } }); visibleLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (visibleLabel.isSelected()) { for (JCheckBox box : visible) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : visible) { if (box.isSelected()) { box.doClick(); } } } } }); filledLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (filledLabel.isSelected()) { for (JCheckBox box : filled) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : filled) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); speciesPanel2.add(shape); speciesPanel3.add(connectedLabel); speciesPanel3.add(visibleLabel); speciesPanel3.add(filledLabel); final HashMap<String, Shape> shapey = this.shapes; final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphSpecies.size() - 1; i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; int[] shaps = new int[10]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; colorsButtons.get(k).setBackground((Color) colory.get("Red")); colorsButtons.get(k).setForeground((Color) colory.get("Red")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue")); colorsButtons.get(k).setForeground((Color) colory.get("Blue")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; colorsButtons.get(k).setBackground((Color) colory.get("Green")); colorsButtons.get(k).setForeground((Color) colory.get("Green")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; colorsButtons.get(k).setBackground((Color) colory.get("Tan")); colorsButtons.get(k).setForeground((Color) colory.get("Tan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) { cols[10]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) { cols[11]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) { cols[12]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; colorsButtons.get(k).setBackground((Color) colory.get("Black")); colorsButtons.get(k).setForeground((Color) colory.get("Black")); } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray")); colorsButtons.get(k).setForeground((Color) colory.get("Gray")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) { cols[22]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) { cols[23]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) { cols[24]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) { cols[25]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) { cols[26]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) { cols[27]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) { cols[29]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) { cols[30]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) { cols[31]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) { cols[32]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) { cols[33]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) { cols[34]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)")); } if (shapesCombo.get(k).getSelectedItem().equals("Square")) { shaps[0]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) { shaps[1]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) { shaps[2]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) { shaps[3]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) { shaps[4]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) { shaps[5]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) { shaps[6]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) { shaps[7]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) { shaps[8]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) { shaps[9]++; } } } for (GraphSpecies graph : graphed) { if (graph.getShapeAndPaint().getPaintName().equals("Red")) { cols[0]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green")) { cols[2]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) { cols[12]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Black")) { cols[14]++; } /* * else if * (graph.getShapeAndPaint().getPaintName().equals * ("Red ")) { cols[15]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Blue ")) { cols[16]++; * } else if * (graph.getShapeAndPaint().getPaintName() * .equals("Green ")) { cols[17]++; } else if * (graph. * getShapeAndPaint().getPaintName().equals("Yellow " * )) { cols[18]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getShapeAndPaint().getPaintName * ().equals("Cyan ")) { cols[20]++; } */ else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) { cols[22]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) { cols[23]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) { cols[24]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) { cols[30]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) { cols[31]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) { cols[32]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) { cols[34]++; } if (graph.getShapeAndPaint().getShapeName().equals("Square")) { shaps[0]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) { shaps[1]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) { shaps[2]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) { shaps[3]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) { shaps[4]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) { shaps[5]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) { shaps[6]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) { shaps[7]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) { shaps[8]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) { shaps[9]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } int shapeSet = 0; for (int j = 1; j < shaps.length; j++) { if (shaps[j] < shaps[shapeSet]) { shapeSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); colorsButtons.get(i).setBackground((Color) paint); colorsButtons.get(i).setForeground((Color) paint); } } for (int j = 0; j < shapeSet; j++) { draw.getNextShape(); } Shape shape = draw.getNextShape(); set = shapey.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (shape == shapey.get(set[j])) { shapesCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } String color = (String) colorsCombo.get(i).getSelectedItem(); if (color.equals("Custom")) { color += "_" + colorsButtons.get(i).getBackground().getRGB(); } graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), color, filled.get(i).isSelected(), visible .get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i).getName(), series.get(i).getText().trim(), XVariable.getSelectedIndex(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphSpecies g : remove) { graphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colory.get("Black")); colorsButtons.get(i).setForeground((Color) colory.get("Black")); shapesCombo.get(i).setSelectedIndex(0); } } }); boxes.add(temp); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : visible) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { visibleLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(true); } } } else { visibleLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(false); } } } } }); visible.add(temp); visible.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : filled) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { filledLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(true); } } } else { filledLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(false); } } } } }); filled.add(temp); filled.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : connected) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { connectedLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(true); } } } else { connectedLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(false); } } } } }); connected.add(temp); connected.get(i).setSelected(true); JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); ArrayList<String> allColors = new ArrayList<String>(); for (String c : this.colors.keySet()) { allColors.add(c); } allColors.add("Custom"); Object[] col = allColors.toArray(); Arrays.sort(col); Object[] shap = this.shapes.keySet().toArray(); Arrays.sort(shap); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) { colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint("Custom_" + colorsButtons.get(i).getBackground().getRGB()); } } } } }); JComboBox shapBox = new JComboBox(shap); shapBox.setActionCommand("" + i); shapBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); colorsCombo.add(colBox); JButton colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(30, 20)); colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray)); colorButton.setBackground((Color) colory.get("Black")); colorButton.setForeground((Color) colory.get("Black")); colorButton.setUI(new MetalButtonUI()); colorButton.setActionCommand("" + i); colorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground()); if (newColor != null) { ((JButton) e.getSource()).setBackground(newColor); ((JButton) e.getSource()).setForeground(newColor); colorsCombo.get(i).setSelectedItem("Custom"); } } }); colorsButtons.add(colorButton); JPanel colorPanel = new JPanel(new BorderLayout()); colorPanel.add(colorsCombo.get(i), "Center"); colorPanel.add(colorsButtons.get(i), "East"); shapesCombo.add(shapBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorPanel); speciesPanel2.add(shapesCombo.get(i)); speciesPanel3.add(connected.get(i)); speciesPanel3.add(visible.get(i)); speciesPanel3.add(filled.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); speciesPanel.add(speciesPanel3, "East"); return speciesPanel; } private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) { curData = dataset; // chart = ChartFactory.createXYLineChart(title, x, y, dataset, // PlotOrientation.VERTICAL, // true, true, false); chart.getXYPlot().setDataset(dataset); chart.setTitle(title); chart.getXYPlot().getDomainAxis().setLabel(x); chart.getXYPlot().getRangeAxis().setLabel(y); // chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); // chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); // chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); // chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); // chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); if (graphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } /** * This method saves the graph as a jpeg or as a png file. */ public void export() { try { int output = 2; /* Default is currently pdf */ int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output); if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) { output = 0; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) { output = 1; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) { output = 2; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) { output = 3; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) { output = 4; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) { output = 5; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) { output = 6; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) { output = 7; } if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void export(int output) { // jpg = 0 // png = 1 // pdf = 2 // eps = 3 // svg = 4 // csv = 5 (data) // dat = 6 (data) // tsd = 7 (data) try { int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output); if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void exportDataFile(File file, int output) { try { int count = curData.getSeries(0).getItemCount(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (curData.getSeries(i).getItemCount() != count) { JOptionPane.showMessageDialog(Gui.frame, "Data series do not have the same number of points!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } for (int j = 0; j < count; j++) { Number Xval = curData.getSeries(0).getDataItem(j).getX(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) { JOptionPane.showMessageDialog(Gui.frame, "Data series time points are not the same!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } } FileOutputStream csvFile = new FileOutputStream(file); PrintWriter csvWriter = new PrintWriter(csvFile); if (output == 7) { csvWriter.print("(("); } else if (output == 6) { csvWriter.print(" } csvWriter.print("\"Time\""); count = curData.getSeries(0).getItemCount(); int pos = 0; for (int i = 0; i < curData.getSeriesCount(); i++) { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print("\"" + curData.getSeriesKey(i) + "\""); if (curData.getSeries(i).getItemCount() > count) { count = curData.getSeries(i).getItemCount(); pos = i; } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } for (int j = 0; j < count; j++) { if (output == 7) { csvWriter.print(","); } for (int i = 0; i < curData.getSeriesCount(); i++) { if (i == 0) { if (output == 7) { csvWriter.print("("); } csvWriter.print(curData.getSeries(pos).getDataItem(j).getX()); } XYSeries data = curData.getSeries(i); if (j < data.getItemCount()) { XYDataItem item = data.getDataItem(j); if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print(item.getY()); } else { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } } if (output == 7) { csvWriter.println(")"); } csvWriter.close(); csvFile.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(ArrayList<String> files, int choice, String directory, boolean warning, boolean output) { if (files.size() > 0) { ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>(); lock.lock(); try { warn = warning; // TSDParser p = new TSDParser(startFile, biomodelsim, false); ArrayList<ArrayList<Double>> data; if (directory == null) { data = readData(outDir + separator + files.get(0), "", directory, warn); } else { data = readData(outDir + separator + directory + separator + files.get(0), "", directory, warn); } averageOrder = graphSpecies; boolean first = true; for (int i = 0; i < graphSpecies.size(); i++) { average.add(new ArrayList<Double>()); variance.add(new ArrayList<Double>()); } HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>(); // int count = 0; for (String run : files) { if (directory == null) { if (new File(outDir + separator + run).exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + run, "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } } } else { if (new File(outDir + separator + directory + separator + run).exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + run, "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } } } // ArrayList<ArrayList<Double>> data = p.getData(); for (int k = 0; k < data.get(0).size(); k++) { if (first) { double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); dataCounts.put(put, 1); } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } for (int i = 0; i < data.size(); i++) { if (i == 0) { variance.get(i).add((data.get(i)).get(k)); average.get(i).add(put); } else { variance.get(i).add(0.0); average.get(i).add((data.get(i)).get(k)); } } } else { int index = -1; double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); } else { put = (data.get(0)).get(k); } } else if (k == data.get(0).size() - 1 && k == 1) { if (average.get(0).size() > 1) { put = (average.get(0)).get(k); } else { put = (data.get(0)).get(k); } } else { put = (data.get(0)).get(k); } if (average.get(0).contains(put)) { index = average.get(0).indexOf(put); int count = dataCounts.get(put); dataCounts.put(put, count + 1); for (int i = 1; i < data.size(); i++) { double old = (average.get(i)).get(index); (average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1))); double newMean = (average.get(i)).get(index); double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data.get(i)).get(k) - newMean) * ((data.get(i)).get(k) - old)) / count; (variance.get(i)).set(index, vary); } } else { dataCounts.put(put, 1); for (int a = 0; a < average.get(0).size(); a++) { if (average.get(0).get(a) > put) { index = a; break; } } if (index == -1) { index = average.get(0).size() - 1; } average.get(0).add(put); variance.get(0).add(put); for (int a = 1; a < average.size(); a++) { average.get(a).add(data.get(a).get(k)); variance.get(a).add(0.0); } if (index != average.get(0).size() - 1) { for (int a = average.get(0).size() - 2; a >= 0; a if (average.get(0).get(a) > average.get(0).get(a + 1)) { for (int b = 0; b < average.size(); b++) { double temp = average.get(b).get(a); average.get(b).set(a, average.get(b).get(a + 1)); average.get(b).set(a + 1, temp); temp = variance.get(b).get(a); variance.get(b).set(a, variance.get(b).get(a + 1)); variance.get(b).set(a + 1, temp); } } else { break; } } } } } } first = false; } deviation = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < variance.size(); i++) { deviation.add(new ArrayList<Double>()); for (int j = 0; j < variance.get(i).size(); j++) { deviation.get(i).add(variance.get(i).get(j)); } } for (int i = 1; i < deviation.size(); i++) { for (int j = 0; j < deviation.get(i).size(); j++) { deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j))); } } averageOrder = null; } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Unable to output average, variance, and standard deviation!", "Error", JOptionPane.ERROR_MESSAGE); } lock.unlock(); if (output) { DataParser m = new DataParser(graphSpecies, average); DataParser d = new DataParser(graphSpecies, deviation); DataParser v = new DataParser(graphSpecies, variance); if (directory == null) { m.outputTSD(outDir + separator + "mean.tsd"); v.outputTSD(outDir + separator + "variance.tsd"); d.outputTSD(outDir + separator + "standard_deviation.tsd"); } else { m.outputTSD(outDir + separator + directory + separator + "mean.tsd"); v.outputTSD(outDir + separator + directory + separator + "variance.tsd"); d.outputTSD(outDir + separator + directory + separator + "standard_deviation.tsd"); } } if (choice == 0) { return average; } else if (choice == 1) { return variance; } else { return deviation; } } return null; } public void run() { reb2sac.getRunButton().doClick(); } public void save() { if (timeSeries) { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB()); graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB()); graph.setProperty("plot.domain.grid.line.paint", "" + ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB()); graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName()); graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB()); graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB()); graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter)); graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Probability Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public void saveAs() { if (timeSeries) { String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:", "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"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.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 del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File( outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName()); if (topLevel) { graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } else { if (graphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + graphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } else { String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Probability Graph Name:", "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"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.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 del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File( outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter)); graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); graph.setProperty("visibleLegend", "" + visibleLegend.isSelected()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); if (topLevel) { graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory()); } else { if (probGraphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + probGraphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Probability Graph Data"); store.close(); log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } } private void open(String filename) { if (timeSeries) { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); XMin.setText(graph.getProperty("x.min")); XMax.setText(graph.getProperty("x.max")); XScale.setText(graph.getProperty("x.scale")); YMin.setText(graph.getProperty("y.min")); YMax.setText(graph.getProperty("y.max")); YScale.setText(graph.getProperty("y.scale")); chart.setTitle(graph.getProperty("title")); if (graph.containsKey("chart.background.paint")) { chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint")))); } if (graph.containsKey("plot.background.paint")) { chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint")))); } if (graph.containsKey("plot.domain.grid.line.paint")) { chart.getXYPlot().setDomainGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.domain.grid.line.paint")))); } if (graph.containsKey("plot.range.grid.line.paint")) { chart.getXYPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint")))); } chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.getProperty("auto.resize").equals("true")) { resize.setSelected(true); } else { resize.setSelected(false); } if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) { LogX.setSelected(true); } else { LogX.setSelected(false); } if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) { LogY.setSelected(true); } else { LogY.setSelected(false); } if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) { visibleLegend.setSelected(false); } else { visibleLegend.setSelected(true); } int next = 0; while (graph.containsKey("species.name." + next)) { boolean connected, filled, visible; if (graph.getProperty("species.connected." + next).equals("true")) { connected = true; } else { connected = false; } if (graph.getProperty("species.filled." + next).equals("true")) { filled = true; } else { filled = false; } if (graph.getProperty("species.visible." + next).equals("true")) { visible = true; } else { visible = false; } int xnumber = 0; if (graph.containsKey("species.xnumber." + next)) { xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next)); } graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), graph.getProperty("species.paint." + next) .trim(), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id." + next), graph.getProperty("species.name." + next), xnumber, Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next))); next++; } updateXNumber = false; XVariable.addItem("time"); refresh(); } catch (IOException except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); chart.setTitle(graph.getProperty("title")); if (graph.containsKey("chart.background.paint")) { chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint")))); } if (graph.containsKey("plot.background.paint")) { chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint")))); } if (graph.containsKey("plot.range.grid.line.paint")) { chart.getCategoryPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint")))); } chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new GradientBarPainter()); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter()); } if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true); } if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) { visibleLegend.setSelected(false); } else { visibleLegend.setSelected(true); } int next = 0; while (graph.containsKey("species.name." + next)) { String color = graph.getProperty("species.paint." + next).trim(); Paint paint; if (color.startsWith("Custom_")) { paint = new Color(Integer.parseInt(color.replace("Custom_", ""))); } else { paint = colors.get(color); } probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id." + next), graph.getProperty("species.name." + next), Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next))); next++; } refreshProb(); } catch (Exception except) { JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public boolean isTSDGraph() { return timeSeries; } public void refresh() { lock2.lock(); if (timeSeries) { if (learnSpecs != null) { updateSpecies(); } double minY = 0; double maxY = 0; double scaleY = 0; double minX = 0; double maxX = 0; double scaleX = 0; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); num.setGroupingUsed(false); * minY = Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { } ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + "run-" + // nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber() .toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData( outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + // g.getDirectory() + separator // + "run-" + nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Termination Time") && new File(outDir + separator + g.getDirectory() + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Percent Termination") && new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Constraint Termination") && new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Bifurcation Statistics") && new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { data = readData( outDir + separator + g.getDirectory() + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } data = readData( outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), g.getDirectory(), false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) { graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } else { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { if (graphProbs.contains(g.getID())) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { String compare = g.getID().replace(" (", "~"); if (graphProbs.contains(compare.split("~")[0].trim())) { for (int i = 0; i < graphProbs.size(); i++) { if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis() .getLabel(), histDataset, rend); } lock2.unlock(); } private class ShapeAndPaint { private Shape shape; private Paint paint; private ShapeAndPaint(Shape s, String p) { shape = s; if (p.startsWith("Custom_")) { paint = new Color(Integer.parseInt(p.replace("Custom_", ""))); } else { paint = colors.get(p); } } private Shape getShape() { return shape; } private Paint getPaint() { return paint; } private String getShapeName() { Object[] set = shapes.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (shape == shapes.get(set[i])) { return (String) set[i]; } } return "Unknown Shape"; } private String getPaintName() { Object[] set = colors.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (paint == colors.get(set[i])) { return (String) set[i]; } } return "Custom_" + ((Color) paint).getRGB(); } public void setPaint(String paint) { if (paint.startsWith("Custom_")) { this.paint = new Color(Integer.parseInt(paint.replace("Custom_", ""))); } else { this.paint = colors.get(paint); } } public void setShape(String shape) { this.shape = shapes.get(shape); } } private class GraphSpecies { private ShapeAndPaint sP; private boolean filled, visible, connected; private String runNumber, species, directory, id; private int xnumber, number; private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species, int xnumber, int number, String directory) { sP = new ShapeAndPaint(s, p); this.filled = filled; this.visible = visible; this.connected = connected; this.runNumber = runNumber; this.species = species; this.xnumber = xnumber; this.number = number; this.directory = directory; this.id = id; } private void setDirectory(String directory) { this.directory = directory; } private void setXNumber(int xnumber) { this.xnumber = xnumber; } private void setNumber(int number) { this.number = number; } private void setSpecies(String species) { this.species = species; } private void setPaint(String paint) { sP.setPaint(paint); } private void setShape(String shape) { sP.setShape(shape); } private void setVisible(boolean b) { visible = b; } private void setFilled(boolean b) { filled = b; } private void setConnected(boolean b) { connected = b; } private int getXNumber() { return xnumber; } private int getNumber() { return number; } private String getSpecies() { return species; } private ShapeAndPaint getShapeAndPaint() { return sP; } private boolean getFilled() { return filled; } private boolean getVisible() { return visible; } private boolean getConnected() { return connected; } private String getRunNumber() { return runNumber; } private String getDirectory() { return directory; } private String getID() { return id; } } public void setDirectory(String newDirectory) { outDir = newDirectory; } public void setGraphName(String graphName) { this.graphName = graphName; } public boolean hasChanged() { return change; } private void probGraph(String label) { chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false); ((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter()); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); legend = chart.getLegend(); visibleLegend = new JCheckBox("Visible Legend"); visibleLegend.setSelected(true); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); } private void editProbGraph() { final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { old.add(g); } final JPanel titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JCheckBox gradient = new JCheckBox("Paint In Gradient Style"); gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof StandardBarPainter)); final JCheckBox shadow = new JCheckBox("Paint Bar Shadows"); shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); visibleLegend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } } }); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5); String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); // for (int i = 1; i < files.length; i++) { // String index = files[i]; // int j = i; // while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { // files[j] = files[j - 1]; // j = j - 1; // files[j] = index; boolean add = false; final ArrayList<String> directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) { if (file.contains("sim-rep")) { add = true; } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; for (String getFile : new File(outDir + separator + file).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile).isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); String[] files2 = new File(outDir + separator + file).list(); // for (int i = 1; i < files2.length; i++) { // String index = files2[i]; // int j = i; // while ((j > 0) && files2[j - // 1].compareToIgnoreCase(index) > 0) { // files2[j] = files2[j - 1]; // j = j - 1; // files2[j] = index; boolean add2 = false; for (String f : files2) { if (f.equals("sim-rep.txt")) { add2 = true; } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; for (String getFile : new File(outDir + separator + file + separator + f).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); for (String f2 : new File(outDir + separator + file + separator + f).list()) { if (f2.equals("sim-rep.txt")) { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); d2.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } boolean added = false; for (int j = 0; j < d.getChildCount(); j++) { if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0) || new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + ".txt")) .isFile()) { d.insert(d2, j); added = true; break; } } if (!added) { d.add(d2); } } } } if (add2) { IconNode n = new IconNode("sim-rep", "sim-rep"); d.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } boolean added = false; for (int j = 0; j < simDir.getChildCount(); j++) { if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0) || new File(outDir + separator + (simDir.getChildAt(j).toString() + ".txt")).isFile()) { simDir.insert(d, j); added = true; break; } } if (!added) { simDir.add(d); } } } } if (add) { IconNode n = new IconNode("sim-rep", "sim-rep"); simDir.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { tree = new JTree(simDir); tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); final JPanel all = new JPanel(new BorderLayout()); final JScrollPane scroll = new JScrollPane(); tree.addTreeExpansionListener(new TreeExpansionListener() { public void treeCollapsed(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } public void treeExpanded(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } }); // for (int i = 0; i < tree.getRowCount(); i++) { // tree.expandRow(i); JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); final JPanel specPanel = new JPanel(); boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName())) { selected = node.getName(); int select; if (selected.equals("sim-rep")) { select = 0; } else { select = -1; } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent()).getName())); } else { specPanel.add(fixProbChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphProbs.get(i)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory() .equals(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]); } } } else { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint()); colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint()); colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]); } } } boolean allChecked = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = series.get(i).getText(); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colors.get("Black")); colorsButtons.get(i).setForeground((Color) colors.get("Black")); } else { String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = graphProbs.get(i); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(1, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(yLabel); titlePanel1.add(y); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(gradient); titlePanel2.add(shadow); titlePanel2.add(visibleLegend); titlePanel2.add(new JPanel()); titlePanel2.add(new JPanel()); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { change = true; lastSelected = selected; selected = ""; BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); if (gradient.isSelected()) { rend.setBarPainter(new GradientBarPainter()); } else { rend.setBarPainter(new StandardBarPainter()); } if (shadow.isSelected()) { rend.setShadowVisible(true); } else { rend.setShadowVisible(false); } int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend); } else { selected = ""; int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } for (GraphProbs g : old) { probGraphed.add(g); } } } } private JPanel fixProbChoices(final String directory) { if (directory.equals("")) { readProbSpecies(outDir + separator + "sim-rep.txt"); } else { readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt"); } for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); j = j - 1; } graphProbs.set(j, index); } JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2)); use = new JCheckBox("Use"); JLabel specs = new JLabel("Constraint"); JLabel color = new JLabel("Color"); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); colorsButtons = new ArrayList<JButton>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphProbs.size(); i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; colorsButtons.get(k).setBackground((Color) colory.get("Red")); colorsButtons.get(k).setForeground((Color) colory.get("Red")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue")); colorsButtons.get(k).setForeground((Color) colory.get("Blue")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; colorsButtons.get(k).setBackground((Color) colory.get("Green")); colorsButtons.get(k).setForeground((Color) colory.get("Green")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; colorsButtons.get(k).setBackground((Color) colory.get("Tan")); colorsButtons.get(k).setForeground((Color) colory.get("Tan")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) { cols[10]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) { cols[11]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) { cols[12]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; colorsButtons.get(k).setBackground((Color) colory.get("Black")); colorsButtons.get(k).setForeground((Color) colory.get("Black")); } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray")); colorsButtons.get(k).setForeground((Color) colory.get("Gray")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) { cols[22]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) { cols[23]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) { cols[24]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) { cols[25]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) { cols[26]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) { cols[27]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) { cols[29]++; colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) { cols[30]++; colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) { cols[31]++; colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) { cols[32]++; colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) { cols[33]++; colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)")); } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) { cols[34]++; colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)")); colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)")); } } } for (GraphProbs graph : probGraphed) { if (graph.getPaintName().equals("Red")) { cols[0]++; } else if (graph.getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getPaintName().equals("Green")) { cols[2]++; } else if (graph.getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getPaintName().equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getPaintName().equals("Magenta (Dark)")) { cols[12]++; } else if (graph.getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getPaintName().equals("Black")) { cols[14]++; } /* * else if (graph.getPaintName().equals("Red ")) { * cols[15]++; } else if * (graph.getPaintName().equals("Blue ")) { * cols[16]++; } else if * (graph.getPaintName().equals("Green ")) { * cols[17]++; } else if * (graph.getPaintName().equals("Yellow ")) { * cols[18]++; } else if * (graph.getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getPaintName().equals("Cyan ")) { * cols[20]++; } */ else if (graph.getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getPaintName().equals("Red (Extra Dark)")) { cols[22]++; } else if (graph.getPaintName().equals("Blue (Extra Dark)")) { cols[23]++; } else if (graph.getPaintName().equals("Green (Extra Dark)")) { cols[24]++; } else if (graph.getPaintName().equals("Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getPaintName().equals("Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getPaintName().equals("Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getPaintName().equals("Green (Light)")) { cols[30]++; } else if (graph.getPaintName().equals("Yellow (Light)")) { cols[31]++; } else if (graph.getPaintName().equals("Magenta (Light)")) { cols[32]++; } else if (graph.getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getPaintName().equals("Gray (Light)")) { cols[34]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); colorsButtons.get(i).setBackground((Color) paint); colorsButtons.get(i).setForeground((Color) paint); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } String color = (String) colorsCombo.get(i).getSelectedItem(); if (color.equals("Custom")) { color += "_" + colorsButtons.get(i).getBackground().getRGB(); } probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color, boxes.get(i).getName(), series.get(i).getText() .trim(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphProbs g : remove) { probGraphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); colorsButtons.get(i).setBackground((Color) colory.get("Black")); colorsButtons.get(i).setForeground((Color) colory.get("Black")); } } }); boxes.add(temp); JTextField seriesName = new JTextField(graphProbs.get(i)); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); ArrayList<String> allColors = new ArrayList<String>(); for (String c : this.colors.keySet()) { allColors.add(c); } allColors.add("Custom"); Object[] col = allColors.toArray(); Arrays.sort(col); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) { colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem())); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem()); g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem())); } } } else { for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName("Custom_" + colorsButtons.get(i).getBackground().getRGB()); g.setPaint(colorsButtons.get(i).getBackground()); } } } } }); colorsCombo.add(colBox); JButton colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(30, 20)); colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray)); colorButton.setBackground((Color) colory.get("Black")); colorButton.setForeground((Color) colory.get("Black")); colorButton.setUI(new MetalButtonUI()); colorButton.setActionCommand("" + i); colorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground()); if (newColor != null) { ((JButton) e.getSource()).setBackground(newColor); ((JButton) e.getSource()).setForeground(newColor); colorsCombo.get(i).setSelectedItem("Custom"); } } }); colorsButtons.add(colorButton); JPanel colorPanel = new JPanel(new BorderLayout()); colorPanel.add(colorsCombo.get(i), "Center"); colorPanel.add(colorsButtons.get(i), "East"); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorPanel); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); return speciesPanel; } private void readProbSpecies(String file) { graphProbs = new ArrayList<String>(); ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } for (String s : data) { if (!s.split(" ")[0].equals("#total")) { graphProbs.add(s.split(" ")[0]); } } } private double[] readProbs(String file) { ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return new double[0]; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } double[] dataSet = new double[data.size()]; double total = 0; int i = 0; if (data.get(0).split(" ")[0].equals("#total")) { total = Double.parseDouble(data.get(0).split(" ")[1]); i = 1; } for (; i < data.size(); i++) { if (total == 0) { dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]); } else { dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total); } } return dataSet; } private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) { Paint chartBackground = chart.getBackgroundPaint(); Paint plotBackground = chart.getPlot().getBackgroundPaint(); Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint(); chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false); chart.getCategoryPlot().setRenderer(rend); chart.setBackgroundPaint(chartBackground); chart.getPlot().setBackgroundPaint(plotBackground); chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine); ChartPanel graph = new ChartPanel(chart); legend = chart.getLegend(); if (visibleLegend.isSelected()) { if (chart.getLegend() == null) { chart.addLegend(legend); } } else { if (chart.getLegend() != null) { legend = chart.getLegend(); } chart.removeLegend(); } if (probGraphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } public void refreshProb() { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis() .getLabel(), histDataset, rend); } private void updateSpecies() { String background; try { Properties p = new Properties(); String[] split = outDir.split(separator); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else { background = null; } } catch (Exception e) { JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); background = null; } learnSpecs = new ArrayList<String>(); if (background != null) { if (background.contains(".gcm")) { BioModel gcm = new BioModel(biomodelsim.getRoot()); gcm.load(background); learnSpecs = gcm.getSpecies(); } else if (background.contains(".lpn")) { LhpnFile lhpn = new LhpnFile(biomodelsim.log); lhpn.load(background); /* HashMap<String, Properties> speciesMap = lhpn.getContinuous(); * for (String s : speciesMap.keySet()) { learnSpecs.add(s); } */ // ADDED BY SB. TSDParser extractVars; ArrayList<String> datFileVars = new ArrayList<String>(); // ArrayList<String> allVars = new ArrayList<String>(); Boolean varPresent = false; // Finding the intersection of all the variables present in all // data files. for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) { extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false); datFileVars = extractVars.getSpecies(); if (i == 1) { learnSpecs.addAll(datFileVars); } for (String s : learnSpecs) { varPresent = false; for (String t : datFileVars) { if (s.equalsIgnoreCase(t)) { varPresent = true; break; } } if (!varPresent) { learnSpecs.remove(s); } } } // END ADDED BY SB. } else { SBMLDocument document = Gui.readSBML(background); Model model = document.getModel(); ListOf ids = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { learnSpecs.add(((Species) ids.get(i)).getId()); } } } for (int i = 0; i < learnSpecs.size(); i++) { String index = learnSpecs.get(i); int j = i; while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) { learnSpecs.set(j, learnSpecs.get(j - 1)); j = j - 1; } learnSpecs.set(j, index); } } public boolean getWarning() { return warn; } private class GraphProbs { private Paint paint; private String species, directory, id, paintName; private int number; private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) { this.paint = paint; this.paintName = paintName; this.species = species; this.number = number; this.directory = directory; this.id = id; } private Paint getPaint() { return paint; } private void setPaint(Paint p) { paint = p; } private String getPaintName() { return paintName; } private void setPaintName(String p) { paintName = p; } private String getSpecies() { return species; } private void setSpecies(String s) { species = s; } private String getDirectory() { return directory; } private String getID() { return id; } private int getNumber() { return number; } private void setNumber(int n) { number = n; } } private Hashtable makeIcons() { Hashtable<String, Icon> icons = new Hashtable<String, Icon>(); icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon()); icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon()); icons.put("computer", MetalIconFactory.getTreeComputerIcon()); icons.put("c", TextIcons.getIcon("c")); icons.put("java", TextIcons.getIcon("java")); icons.put("html", TextIcons.getIcon("html")); return icons; } } class IconNodeRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = -940588131120912851L; public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); Icon icon = ((IconNode) value).getIcon(); if (icon == null) { Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons"); String name = ((IconNode) value).getIconName(); if ((icons != null) && (name != null)) { icon = (Icon) icons.get(name); if (icon != null) { setIcon(icon); } } } else { setIcon(icon); } return this; } } class IconNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 2887169888272379817L; protected Icon icon; protected String iconName; private String hiddenName; public IconNode() { this(null, ""); } public IconNode(Object userObject, String name) { this(userObject, true, null, name); } public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) { super(userObject, allowsChildren); this.icon = icon; hiddenName = name; } public String getName() { return hiddenName; } public void setName(String name) { hiddenName = name; } public void setIcon(Icon icon) { this.icon = icon; } public Icon getIcon() { return icon; } public String getIconName() { if (iconName != null) { return iconName; } else { String str = userObject.toString(); int index = str.lastIndexOf("."); if (index != -1) { return str.substring(++index); } else { return null; } } } public void setIconName(String name) { iconName = name; } } class TextIcons extends MetalIconFactory.TreeLeafIcon { private static final long serialVersionUID = 1623303213056273064L; protected String label; private static Hashtable<String, String> labels; protected TextIcons() { } public void paintIcon(Component c, Graphics g, int x, int y) { super.paintIcon(c, g, x, y); if (label != null) { FontMetrics fm = g.getFontMetrics(); int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2; int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2; g.drawString(label, x + offsetX, y + offsetY + fm.getHeight()); } } public static Icon getIcon(String str) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } TextIcons icon = new TextIcons(); icon.label = (String) labels.get(str); return icon; } public static void setLabelSet(String ext, String label) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } labels.put(ext, label); } private static void setDefaultSet() { labels.put("c", "C"); labels.put("java", "J"); labels.put("html", "H"); labels.put("htm", "H"); labels.put("g", "" + (char) 10003); // and so on /* * labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc" * ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++"); * labels.put("exe" ,"BIN"); labels.put("class" ,"BIN"); * labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF"); * * labels.put("", ""); */ } }
package cucumber.runtime; import java.io.InputStream; /** * After Hooks that declare a parameter of this type will receive an instance of this class. * This allows an After hook to inspect whether or not a Scenario failed. */ public interface ScenarioResult { /** * @return the <em>most severe</em> status of the Scenario's Steps. One of "passed", "undefined", "pending", "skipped", "failed" */ String getStatus(); /** * @return true if and only if {@link #getStatus()} returns "failed" */ boolean isFailed(); /** * Embeds data into the report(s). Some reporters (such as the progress one) don't embed data, but others do (html and json). * * @see cucumber.formatter.ProgressFormatter * @see cucumber.formatter.HTMLFormatter * @see gherkin.formatter.JSONFormatter * @param data what to embed, for example an image. * @param mimeType what is the data? */ void embed(InputStream data, String mimeType); /** * Outputs some text into the report. * * @param text what to put in the report. */ void write(String text); }
package graph; import gcm2sbml.parser.GCMFile; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Paint; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.metal.MetalIconFactory; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import lhpn2sbml.parser.LhpnFile; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.LogarithmicAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.axis.StandardTickUnitSource; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.GradientBarPainter; import org.jfree.chart.renderer.category.StandardBarPainter; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jibble.epsgraphics.EpsGraphics2D; import org.sbml.libsbml.ListOf; import org.sbml.libsbml.Model; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.Species; import org.w3c.dom.DOMImplementation; import parser.TSDParser; import reb2sac.Reb2Sac; import biomodelsim.BioSim; import biomodelsim.Log; import buttons.Buttons; import com.lowagie.text.Document; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.DefaultFontMapper; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; /** * This is the Graph class. It takes in data and draws a graph of that data. The * Graph class implements the ActionListener class, the ChartProgressListener * class, and the MouseListener class. This allows the Graph class to perform * actions when buttons are pressed, when the chart is drawn, or when the chart * is clicked. * * @author Curtis Madsen */ public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener { private static final long serialVersionUID = 4350596002373546900L; private JFreeChart chart; // Graph of the output data private XYSeriesCollection curData; // Data in the current graph private String outDir; // output directory private String printer_id; // printer id /* * Text fields used to change the graph window */ private JTextField XMin, XMax, XScale, YMin, YMax, YScale; private ArrayList<String> graphSpecies; // names of species in the graph private BioSim biomodelsim; // tstubd gui private JButton save, run, saveAs; private JButton export, refresh; // buttons // private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg, // exportCsv; // buttons private HashMap<String, Paint> colors; private HashMap<String, Shape> shapes; private String selected, lastSelected; private LinkedList<GraphSpecies> graphed; private LinkedList<GraphProbs> probGraphed; private JCheckBox resize; private JComboBox XVariable; private JCheckBox LogX, LogY; private Log log; private ArrayList<JCheckBox> boxes; private ArrayList<JTextField> series; private ArrayList<JComboBox> colorsCombo; private ArrayList<JComboBox> shapesCombo; private ArrayList<JCheckBox> connected; private ArrayList<JCheckBox> visible; private ArrayList<JCheckBox> filled; private JCheckBox use; private JCheckBox connectedLabel; private JCheckBox visibleLabel; private JCheckBox filledLabel; private String graphName; private String separator; private boolean change; private boolean timeSeries; private boolean topLevel; private ArrayList<String> graphProbs; private JTree tree; private IconNode node, simDir; private Reb2Sac reb2sac; // reb2sac options private ArrayList<String> learnSpecs; private boolean warn; private ArrayList<String> averageOrder; private JPopupMenu popup; // popup menu private ArrayList<String> directories; private JPanel specPanel; private JScrollPane scrollpane; private JPanel all; private JPanel titlePanel; private JScrollPane scroll; private boolean updateXNumber; /** * Creates a Graph Object from the data given and calls the private graph * helper method. */ public Graph(Reb2Sac reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, BioSim biomodelsim, String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) { this.reb2sac = reb2sac; averageOrder = null; popup = new JPopupMenu(); warn = false; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // initializes member variables this.log = log; this.timeSeries = timeSeries; if (graphName != null) { this.graphName = graphName; topLevel = true; } else { if (timeSeries) { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf"; } else { this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb"; } topLevel = false; } this.outDir = outDir; this.printer_id = printer_id; this.biomodelsim = biomodelsim; XYSeriesCollection data = new XYSeriesCollection(); if (learnGraph) { updateSpecies(); } else { learnSpecs = null; } // graph the output data if (timeSeries) { setUpShapesAndColors(); graphed = new LinkedList<GraphSpecies>(); selected = ""; lastSelected = ""; graph(printer_track_quantity, label, data, time); if (open != null) { open(open); } } else { setUpShapesAndColors(); probGraphed = new LinkedList<GraphProbs>(); selected = ""; lastSelected = ""; probGraph(label); if (open != null) { open(open); } } } /** * This private helper method calls the private readData method, sets up a * graph frame, and graphs the data. * * @param dataset * @param time */ private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) { chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates text fields for changing the graph's dimensions resize = new JCheckBox("Auto Resize"); resize.setSelected(true); XVariable = new JComboBox(); updateXNumber = false; XVariable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (updateXNumber && node != null) { String curDir = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName(); } else if (directories.contains(((IconNode) node.getParent()).getName())) { curDir = ((IconNode) node.getParent()).getName(); } else { curDir = ""; } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(curDir)) { graphed.get(i).setXNumber(XVariable.getSelectedIndex()); } } } } }); LogX = new JCheckBox("LogX"); LogX.setSelected(false); LogY = new JCheckBox("LogY"); LogY.setSelected(false); XMin = new JTextField(); XMax = new JTextField(); XScale = new JTextField(); YMin = new JTextField(); YMax = new JTextField(); YScale = new JTextField(); // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); // determines maximum and minimum values and resizes resize(dataset); this.revalidate(); } private void readGraphSpecies(String file) { BioSim.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); graphSpecies = new TSDParser(file, true).getSpecies(); BioSim.frame.setCursor(null); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); i } } } } /** * This public helper method parses the output file of ODE, monte carlo, and * markov abstractions. */ public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) { warn = warning; String[] s = file.split(separator); String getLast = s[s.length - 1]; String stem = ""; int t = 0; try { while (!Character.isDigit(getLast.charAt(t))) { stem += getLast.charAt(t); t++; } } catch (Exception e) { } if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance")) || (label.contains("deviation") && file.contains("standard_deviation"))) { BioSim.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); TSDParser p = new TSDParser(file, warn); BioSim.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); ArrayList<ArrayList<Double>> data = p.getData(); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } if (label.contains("average") || label.contains("variance") || label.contains("deviation")) { int counter = 1; while (!(new File(file).exists())) { file = file.substring(0, file.length() - getLast.length()); file += stem; file += counter + ""; file += "." + printer_id.substring(0, printer_id.length() - 8); counter++; } } if (label.contains("average")) { return calculateAverageVarianceDeviation(file, stem, 0, directory, warn); } else if (label.contains("variance")) { return calculateAverageVarianceDeviation(file, stem, 1, directory, warn); } else if (label.contains("deviation")) { return calculateAverageVarianceDeviation(file, stem, 2, directory, warn); } else { BioSim.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); TSDParser p = new TSDParser(file, warn); BioSim.frame.setCursor(null); warn = p.getWarning(); graphSpecies = p.getSpecies(); ArrayList<ArrayList<Double>> data = p.getData(); if (learnSpecs != null) { for (String spec : learnSpecs) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!learnSpecs.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } else if (averageOrder != null) { for (String spec : averageOrder) { if (!graphSpecies.contains(spec)) { graphSpecies.add(spec); ArrayList<Double> d = new ArrayList<Double>(); for (int i = 0; i < data.get(0).size(); i++) { d.add(0.0); } data.add(d); } } for (int i = 1; i < graphSpecies.size(); i++) { if (!averageOrder.contains(graphSpecies.get(i))) { graphSpecies.remove(i); data.remove(i); i } } } return data; } } /** * This method adds and removes plots from the graph depending on what check * boxes are selected. */ public void actionPerformed(ActionEvent e) { // if the save button is clicked if (e.getSource() == run) { reb2sac.getRunButton().doClick(); } if (e.getSource() == save) { save(); } // if the save as button is clicked if (e.getSource() == saveAs) { saveAs(); } // if the export button is clicked else if (e.getSource() == export) { export(); } else if (e.getSource() == refresh) { refresh(); } else if (e.getActionCommand().equals("rename")) { String rename = JOptionPane.showInputDialog(BioSim.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { boolean write = true; if (rename.equals(node.getName())) { write = false; } else if (new File(outDir + separator + rename).exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(BioSim.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(outDir + separator + rename); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) { simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals( "" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } for (int i = 0; i < graphed.size(); i++) { if (graphed.get(i).getDirectory().equals(rename)) { graphed.remove(i); i } } } else { write = false; } } if (write) { String getFile = node.getName(); IconNode s = node; while (s.getParent().getParent() != null) { getFile = s.getName() + separator + getFile; s = (IconNode) s.getParent(); } getFile = outDir + separator + getFile; new File(getFile).renameTo(new File(outDir + separator + rename)); for (GraphSpecies spec : graphed) { if (spec.getDirectory().equals(node.getName())) { spec.setDirectory(rename); } } directories.remove(node.getName()); directories.add(rename); node.setUserObject(rename); node.setName(rename); simDir.remove(node); int i; for (i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase( rename) > 0) { simDir.insert(node, i); break; } } else { break; } } simDir.insert(node, i); ArrayList<String> rows = new ArrayList<String>(); for (i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); int select = 0; for (i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } if (rename.equals(node.getName())) { select = i; } } tree.removeTreeSelectionListener(t); addTreeListener(); tree.setSelectionRow(select); } } } else if (e.getActionCommand().equals("delete")) { TreePath[] selected = tree.getSelectionPaths(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) { tree.removeTreeSelectionListener(listen); } tree.addTreeSelectionListener(t); for (TreePath select : selected) { tree.setSelectionPath(select); if (!((IconNode) select.getLastPathComponent()).getName().equals("Average") && !((IconNode) select.getLastPathComponent()).getName().equals("Variance") && !((IconNode) select.getLastPathComponent()).getName().equals( "Standard Deviation") && ((IconNode) select.getLastPathComponent()).getParent() != null) { for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select .getLastPathComponent())) { if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { simDir.remove(i); File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } directories.remove(((IconNode) select.getLastPathComponent()) .getName()); for (int j = 0; j < graphed.size(); j++) { if (graphed.get(j).getDirectory().equals( ((IconNode) select.getLastPathComponent()).getName())) { graphed.remove(j); j } } } else { simDir.remove(i); File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } int count = 0; for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { count++; } } if (count == 3) { for (int j = 0; j < simDir.getChildCount(); j++) { if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) { simDir.remove(j); j } } } } } else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) { for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) { if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select .getLastPathComponent())) { ((IconNode) simDir.getChildAt(i)).remove(j); File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + ((IconNode) select.getLastPathComponent()).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } boolean checked = false; for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)) .getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { ((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory .getTreeFolderIcon()); ((IconNode) simDir.getChildAt(i)).setIconName(""); } int count = 0; for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) { if (((IconNode) simDir.getChildAt(i).getChildAt(k)) .getChildCount() == 0) { count++; } } if (count == 3) { File dir2 = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName()); if (dir2.isDirectory()) { biomodelsim.deleteDir(dir2); } else { dir2.delete(); } directories.remove(((IconNode) simDir.getChildAt(i)) .getName()); for (int k = 0; k < graphed.size(); k++) { if (graphed.get(k).getDirectory().equals( ((IconNode) simDir.getChildAt(i)).getName())) { graphed.remove(k); k } } simDir.remove(i); } } } } } } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete runs")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average") && !((IconNode) simDir.getChildAt(i)).getName().equals("Variance") && !((IconNode) simDir.getChildAt(i)).getName().equals( "Standard Deviation")) { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } else if (e.getActionCommand().equals("delete all")) { for (int i = simDir.getChildCount() - 1; i >= 0; i if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) { if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average") && !((IconNode) simDir.getChildAt(i)).getName().equals("Variance") && !((IconNode) simDir.getChildAt(i)).getName().equals( "Standard Deviation")) { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + "." + printer_id.substring(0, printer_id.length() - 8)); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } } simDir.remove(i); } else { File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName()); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { dir.delete(); } simDir.remove(i); } } boolean checked = false; for (int i = 0; i < simDir.getChildCount(); i++) { if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) { checked = true; } } if (!checked) { simDir.setIcon(MetalIconFactory.getTreeFolderIcon()); simDir.setIconName(""); } ArrayList<String> rows = new ArrayList<String>(); for (int i = 0; i < tree.getRowCount(); i++) { if (tree.isExpanded(i)) { tree.setSelectionRow(i); rows.add(node.getName()); } } scrollpane = new JScrollPane(); refreshTree(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); TreeSelectionListener t = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); } }; tree.addTreeSelectionListener(t); for (int i = 0; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (rows.contains(node.getName())) { tree.expandRow(i); } } tree.removeTreeSelectionListener(t); addTreeListener(); } // // if the export as jpeg button is clicked // else if (e.getSource() == exportJPeg) { // export(0); // // if the export as png button is clicked // else if (e.getSource() == exportPng) { // export(1); // // if the export as pdf button is clicked // else if (e.getSource() == exportPdf) { // export(2); // // if the export as eps button is clicked // else if (e.getSource() == exportEps) { // export(3); // // if the export as svg button is clicked // else if (e.getSource() == exportSvg) { // export(4); // } else if (e.getSource() == exportCsv) { // export(5); } /** * Private method used to auto resize the graph. */ private void resize(XYSeriesCollection dataset) { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); XYPlot plot = chart.getXYPlot(); XYItemRenderer rend = plot.getRenderer(); double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; for (int j = 0; j < dataset.getSeriesCount(); j++) { XYSeries series = dataset.getSeries(j); double[][] seriesArray = series.toArray(); Boolean visible = rend.getSeriesVisible(j); if (visible == null || visible.equals(true)) { for (int k = 0; k < series.getItemCount(); k++) { maxY = Math.max(seriesArray[1][k], maxY); minY = Math.min(seriesArray[1][k], minY); maxX = Math.max(seriesArray[0][k], maxX); minX = Math.min(seriesArray[0][k], minX); } } } NumberAxis axis = (NumberAxis) plot.getRangeAxis(); if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxY - minY) < .001) { // axis.setRange(minY - 1, maxY + 1); else { /* * axis.setRange(Double.parseDouble(num.format(minY - * (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY + * (Math.abs(maxY) .1)))); */ if ((maxY - minY) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1)); } axis.setAutoTickUnitSelection(true); if (LogY.isSelected()) { try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis() .getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(BioSim.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } axis = (NumberAxis) plot.getDomainAxis(); if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) { axis.setRange(-1, 1); } // else if ((maxX - minX) < .001) { // axis.setRange(minX - 1, maxX + 1); else { if ((maxX - minX) < .001) { axis.setStandardTickUnits(new StandardTickUnitSource()); } axis.setRange(minX, maxX); } axis.setAutoTickUnitSelection(true); if (LogX.isSelected()) { try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis() .getLabel()); domainAxis.setStrictValuesFlag(false); plot.setDomainAxis(domainAxis); } catch (Exception e1) { JOptionPane.showMessageDialog(BioSim.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } /** * After the chart is redrawn, this method calculates the x and y scale and * updates those text fields. */ public void chartProgress(ChartProgressEvent e) { // if the chart drawing is started if (e.getType() == ChartProgressEvent.DRAWING_STARTED) { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } // if the chart drawing is finished else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) { this.setCursor(null); JFreeChart chart = e.getChart(); XYPlot plot = (XYPlot) chart.getXYPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); YMin.setText("" + axis.getLowerBound()); YMax.setText("" + axis.getUpperBound()); YScale.setText("" + axis.getTickUnit().getSize()); axis = (NumberAxis) plot.getDomainAxis(); XMin.setText("" + axis.getLowerBound()); XMax.setText("" + axis.getUpperBound()); XScale.setText("" + axis.getTickUnit().getSize()); } } /** * Invoked when the mouse is clicked on the chart. Allows the user to edit * the title and labels of the chart. */ public void mouseClicked(MouseEvent e) { if (e.getSource() != tree) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (timeSeries) { editGraph(); } else { editProbGraph(); } } } } public void mousePressed(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } public void mouseReleased(MouseEvent e) { if (e.getSource() == tree) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); if (selRow < 0) return; TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); boolean set = true; for (TreePath p : tree.getSelectionPaths()) { if (p.equals(selPath)) { tree.addSelectionPath(selPath); set = false; } } if (set) { tree.setSelectionPath(selPath); } if (e.isPopupTrigger()) { popup.removeAll(); if (node.getChildCount() != 0 && node.getParent() != null) { JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(rename); } if (node.getParent() != null) { JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); popup.add(delete); } else { JMenuItem delete = new JMenuItem("Delete All Runs"); delete.addActionListener(this); delete.setActionCommand("delete runs"); popup.add(delete); JMenuItem deleteAll = new JMenuItem("Delete Recursive"); deleteAll.addActionListener(this); deleteAll.setActionCommand("delete all"); popup.add(deleteAll); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } /** * This method currently does nothing. */ public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseExited(MouseEvent e) { } private void setUpShapesAndColors() { DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); colors = new HashMap<String, Paint>(); shapes = new HashMap<String, Shape>(); colors.put("Red", draw.getNextPaint()); colors.put("Blue", draw.getNextPaint()); colors.put("Green", draw.getNextPaint()); colors.put("Yellow", draw.getNextPaint()); colors.put("Magenta", draw.getNextPaint()); colors.put("Cyan", draw.getNextPaint()); colors.put("Tan", draw.getNextPaint()); colors.put("Gray (Dark)", draw.getNextPaint()); colors.put("Red (Dark)", draw.getNextPaint()); colors.put("Blue (Dark)", draw.getNextPaint()); colors.put("Green (Dark)", draw.getNextPaint()); colors.put("Yellow (Dark)", draw.getNextPaint()); colors.put("Magenta (Dark)", draw.getNextPaint()); colors.put("Cyan (Dark)", draw.getNextPaint()); colors.put("Black", draw.getNextPaint()); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); draw.getNextPaint(); // colors.put("Red ", draw.getNextPaint()); // colors.put("Blue ", draw.getNextPaint()); // colors.put("Green ", draw.getNextPaint()); // colors.put("Yellow ", draw.getNextPaint()); // colors.put("Magenta ", draw.getNextPaint()); // colors.put("Cyan ", draw.getNextPaint()); colors.put("Gray", draw.getNextPaint()); colors.put("Red (Extra Dark)", draw.getNextPaint()); colors.put("Blue (Extra Dark)", draw.getNextPaint()); colors.put("Green (Extra Dark)", draw.getNextPaint()); colors.put("Yellow (Extra Dark)", draw.getNextPaint()); colors.put("Magenta (Extra Dark)", draw.getNextPaint()); colors.put("Cyan (Extra Dark)", draw.getNextPaint()); colors.put("Red (Light)", draw.getNextPaint()); colors.put("Blue (Light)", draw.getNextPaint()); colors.put("Green (Light)", draw.getNextPaint()); colors.put("Yellow (Light)", draw.getNextPaint()); colors.put("Magenta (Light)", draw.getNextPaint()); colors.put("Cyan (Light)", draw.getNextPaint()); colors.put("Gray (Light)", new java.awt.Color(238, 238, 238)); shapes.put("Square", draw.getNextShape()); shapes.put("Circle", draw.getNextShape()); shapes.put("Triangle", draw.getNextShape()); shapes.put("Diamond", draw.getNextShape()); shapes.put("Rectangle (Horizontal)", draw.getNextShape()); shapes.put("Triangle (Upside Down)", draw.getNextShape()); shapes.put("Circle (Half)", draw.getNextShape()); shapes.put("Arrow", draw.getNextShape()); shapes.put("Rectangle (Vertical)", draw.getNextShape()); shapes.put("Arrow (Backwards)", draw.getNextShape()); } private void editGraph() { final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { old.add(g); } titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5); final JLabel xMin = new JLabel("X-Min:"); final JLabel xMax = new JLabel("X-Max:"); final JLabel xScale = new JLabel("X-Step:"); final JLabel yMin = new JLabel("Y-Min:"); final JLabel yMax = new JLabel("Y-Max:"); final JLabel yScale = new JLabel("Y-Step:"); LogX.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot() .getDomainAxis().getLabel()); domainAxis.setStrictValuesFlag(false); plot.setRangeAxis(domainAxis); } catch (Exception e1) { JOptionPane .showMessageDialog( BioSim.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis() .getLabel()); plot.setRangeAxis(domainAxis); LogX.setSelected(false); } } } }); LogY.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { XYPlot plot = (XYPlot) chart.getXYPlot(); try { LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot() .getRangeAxis().getLabel()); rangeAxis.setStrictValuesFlag(false); plot.setRangeAxis(rangeAxis); } catch (Exception e1) { JOptionPane .showMessageDialog( BioSim.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.", "Error", JOptionPane.ERROR_MESSAGE); NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis() .getLabel()); plot.setRangeAxis(rangeAxis); LogY.setSelected(false); } } } }); resize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } } }); if (resize.isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } Properties p = null; if (learnSpecs != null) { try { String[] split = outDir.split(separator); p = new Properties(); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); } catch (Exception e) { } } String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); for (int i = 1; i < files.length; i++) { String index = files[i]; int j = i; while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { files[j] = files[j - 1]; j = j - 1; } files[j] = index; } boolean add = false; directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { if (file.contains("run-") || file.contains("mean") || file.contains("variance") || file.contains("standard_deviation")) { add = true; } else { IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring( 0, file.length() - 4)); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; String[] files3 = new File(outDir + separator + file).list(); for (int i = 1; i < files3.length; i++) { String index = files3[i]; int j = i; while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) > 0) { files3[j] = files3[j - 1]; j = j - 1; } files3[j] = index; } for (String getFile : files3) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile) .isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); boolean add2 = false; for (String f : files3) { if (f.contains(printer_id.substring(0, printer_id.length() - 8))) { if (f.contains("run-") || f.contains("mean") || f.contains("variance") || f.contains("standard_deviation")) { add2 = true; } else { IconNode n = new IconNode(f.substring(0, f.length() - 4), f .substring(0, f.length() - 4)); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; String[] files2 = new File(outDir + separator + file + separator + f) .list(); for (int i = 1; i < files2.length; i++) { String index = files2[i]; int j = i; while ((j > 0) && files2[j - 1].compareToIgnoreCase(index) > 0) { files2[j] = files2[j - 1]; j = j - 1; } files2[j] = index; } for (String getFile2 : files2) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals( "." + printer_id.substring(0, printer_id .length() - 8))) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); boolean add3 = false; for (String f2 : files2) { if (f2.contains(printer_id .substring(0, printer_id.length() - 8))) { if (f2.contains("run-") || f2.contains("mean") || f2.contains("variance") || f2.contains("standard_deviation")) { add3 = true; } else { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals( f2.substring(0, f2.length() - 4)) && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (add3) { IconNode n = new IconNode("Average", "Average"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Variance", "Variance"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Standard Deviation", "Standard Deviation"); d2.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d .setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r2 = null; for (String s : files2) { if (s.contains("run-")) { r2 = s; } } if (r2 != null) { for (String s : files2) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer .parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id .length() - 8)), "run-" + (i + 1)); if (d2.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d2.getChildCount(); j++) { if (d2 .getChildAt(j) .toString() .compareToIgnoreCase( (String) p .get("run-" + (i + 1) + "." + printer_id .substring( 0, printer_id .length() - 8))) > 0) { d2.insert(n, j); added = true; break; } } if (!added) { d2.add(n); } } else { d2.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d2.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } d.add(d2); } } } if (add2) { IconNode n = new IconNode("Average", "Average"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Variance", "Variance"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Standard Deviation", "Standard Deviation"); d.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String r = null; for (String s : files3) { if (s.contains("run-")) { r = s; } } if (r != null) { for (String s : files3) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s .length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (d.getChildCount() > 3) { boolean added = false; for (int j = 3; j < d.getChildCount(); j++) { if (d.getChildAt(j).toString().compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id .length() - 8))) > 0) { d.insert(n, j); added = true; break; } } if (!added) { d.add(n); } } else { d.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); d.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } simDir.add(d); } } } if (add) { IconNode n = new IconNode("Average", "Average"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Variance", "Variance"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } n = new IconNode("Standard Deviation", "Standard Deviation"); simDir.add(n); n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } int run = 1; String runs = null; for (String s : new File(outDir).list()) { if (s.contains("run-")) { runs = s; } } if (runs != null) { for (String s : new File(outDir).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { IconNode n; if (learnSpecs != null) { n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1)); if (simDir.getChildCount() > 3) { boolean added = false; for (int j = 3; j < simDir.getChildCount(); j++) { if (simDir.getChildAt(j).toString() .compareToIgnoreCase( (String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id .length() - 8))) > 0) { simDir.insert(n, j); added = true; break; } } if (!added) { simDir.add(n); } } else { simDir.add(n); } } else { n = new IconNode("run-" + (i + 1), "run-" + (i + 1)); simDir.add(n); } n.setIconName(""); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(BioSim.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { all = new JPanel(new BorderLayout()); specPanel = new JPanel(); scrollpane = new JScrollPane(); refreshTree(); addTreeListener(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); // JButton ok = new JButton("Ok"); /* * ok.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { double minY; double maxY; double * scaleY; double minX; double maxX; double scaleX; change = true; * try { minY = Double.parseDouble(YMin.getText().trim()); maxY = * Double.parseDouble(YMax.getText().trim()); scaleY = * Double.parseDouble(YScale.getText().trim()); minX = * Double.parseDouble(XMin.getText().trim()); maxX = * Double.parseDouble(XMax.getText().trim()); scaleX = * Double.parseDouble(XScale.getText().trim()); NumberFormat num = * NumberFormat.getInstance(); num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { * JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles * into the inputs " + "to change the graph's dimensions!", "Error", * JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; * selected = ""; ArrayList<XYSeries> graphData = new * ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = * (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int * thisOne = -1; for (int i = 1; i < graphed.size(); i++) { * GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && * (graphed.get(j - * 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { * graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, * index); } ArrayList<GraphSpecies> unableToGraph = new * ArrayList<GraphSpecies>(); HashMap<String, * ArrayList<ArrayList<Double>>> allData = new HashMap<String, * ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { * if (g.getDirectory().equals("")) { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8)).exists()) { * readGraphSpecies(outDir + separator + g.getRunNumber() + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getRunNumber() + * "." + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir).list()) { if * (s.length() > 3 && s.substring(0, 4).equals("run-")) { * ableToGraph = true; } } } catch (Exception e1) { ableToGraph = * false; } if (ableToGraph) { int next = 1; while (!new File(outDir * + separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + "run-" + next + "." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + "run-1." + * printer_id.substring(0, printer_id.length() - 8), BioSim.frame, * y.getText().trim(), g.getRunNumber().toLowerCase(), null); for * (int i = 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } else { thisOne++; * rend.setSeriesVisible(thisOne, true); * rend.setSeriesLinesVisible(thisOne, g.getConnected()); * rend.setSeriesShapesFilled(thisOne, g.getFilled()); * rend.setSeriesShapesVisible(thisOne, g.getVisible()); * rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); * rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if * (!g.getRunNumber().equals("Average") && * !g.getRunNumber().equals("Variance") && * !g.getRunNumber().equals("Standard Deviation")) { if (new * File(outDir + separator + g.getDirectory() + separator + * g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { readGraphSpecies( outDir + * separator + g.getDirectory() + separator + g.getRunNumber() + "." * + printer_id.substring(0, printer_id.length() - 8), * BioSim.frame); ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + g.getRunNumber() + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber(), g.getDirectory()); for (int i = 2; i < * graphSpecies.size(); i++) { String index = graphSpecies.get(i); * ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) * && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { * graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, * data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); * data.set(j, index2); } allData.put(g.getRunNumber() + " " + * g.getDirectory(), data); } graphData.add(new * XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = * 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = * false; try { for (String s : new File(outDir + separator + * g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, * 4).equals("run-")) { ableToGraph = true; } } } catch (Exception * e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; * while (!new File(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8)).exists()) { next++; } * readGraphSpecies(outDir + separator + g.getDirectory() + * separator + "run-" + next + "." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame); * ArrayList<ArrayList<Double>> data; if * (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) * { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); * } else { data = readData(outDir + separator + g.getDirectory() + * separator + "run-1." + printer_id.substring(0, * printer_id.length() - 8), BioSim.frame, y.getText().trim(), * g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i = * 2; i < graphSpecies.size(); i++) { String index = * graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int * j = i; while ((j > 1) && graphSpecies.get(j - * 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, * graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - * 1; } graphSpecies.set(j, index); data.set(j, index2); } * allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } * graphData.add(new XYSeries(g.getSpecies())); if (data.size() != * 0) { for (int i = 0; i < (data.get(0)).size(); i++) { * graphData.get(graphData.size() - 1).add((data.get(0)).get(i), * (data.get(g.getNumber() + 1)).get(i)); } } } else { * unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : * unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset * = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); * i++) { dataset.addSeries(graphData.get(i)); } * fixGraph(title.getText().trim(), x.getText().trim(), * y.getText().trim(), dataset); * chart.getXYPlot().setRenderer(rend); XYPlot plot = * chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } * else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); * axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); * axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) * plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); * axis.setRange(minX, maxX); axis.setTickUnit(new * NumberTickUnit(scaleX)); } //f.dispose(); } }); */ // final JButton cancel = new JButton("Cancel"); // cancel.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // selected = ""; // int size = graphed.size(); // for (int i = 0; i < size; i++) { // graphed.remove(); // for (GraphSpecies g : old) { // graphed.add(g); // f.dispose(); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n .getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(3, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xMin); titlePanel1.add(XMin); titlePanel1.add(yMin); titlePanel1.add(YMin); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(xMax); titlePanel1.add(XMax); titlePanel1.add(yMax); titlePanel1.add(YMax); titlePanel1.add(yLabel); titlePanel1.add(y); titlePanel1.add(xScale); titlePanel1.add(XScale); titlePanel1.add(yScale); titlePanel1.add(YScale); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(resize); titlePanel2.add(XVariable); titlePanel2.add(LogX); titlePanel2.add(new JPanel()); titlePanel2.add(LogY); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); // JPanel buttonPanel = new JPanel(); // buttonPanel.add(ok); // buttonPanel.add(deselect); // buttonPanel.add(cancel); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); // all.add(buttonPanel, "South"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane .showOptionDialog(BioSim.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { double minY; double maxY; double scaleY; double minX; double maxX; double scaleX; change = true; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); * num.setGroupingUsed(false); minY = * Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected = ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot() .getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData .put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()) .list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); } else { data = readData(outDir + separator + g.getDirectory() + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData .put(g.getRunNumber() + " " + g.getDirectory(), data); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } else { selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } for (GraphSpecies g : old) { graphed.add(g); } } // WindowListener w = new WindowListener() { // public void windowClosing(WindowEvent arg0) { // cancel.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) { // f.addWindowListener(w); // f.setContentPane(all); // 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 xx = screenSize.width / 2 - frameSize.width / 2; // int yy = screenSize.height / 2 - frameSize.height / 2; // f.setLocation(xx, yy); // f.setVisible(true); } } private void refreshTree() { tree = new JTree(simDir); if (!topLevel && learnSpecs == null) { tree.addMouseListener(this); } tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); } private void addTreeListener() { boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName()) && node.getParent() != null && !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) { selected = node.getName(); int select; if (selected.equals("Average")) { select = 0; } else if (selected.equals("Variance")) { select = 1; } else if (selected.equals("Standard Deviation")) { select = 2; } else if (selected.contains("-run")) { select = 0; } else if (selected.contains("term-time")) { select = 0; } else { try { if (selected.contains("run-")) { select = Integer.parseInt(selected.substring(4)) + 2; } else { select = -1; } } catch (Exception e1) { select = -1; } } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName())); } else { specPanel.add(fixGraphChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphSpecies.get(i + 1)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( ((IconNode) node.getParent()).getName())) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) { XVariable.setSelectedIndex(g.getXNumber()); boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected(g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } boolean allChecked = true; boolean allCheckedVisible = true; boolean allCheckedFilled = true; boolean allCheckedConnected = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()) .getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = graphSpecies.get(i + 1); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); shapesCombo.get(i).setSelectedIndex(0); } else { String s = ""; s = ((IconNode) e.getPath().getLastPathComponent()).toString(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else if (directories.contains(((IconNode) node.getParent()) .getName())) { if (s.equals("Average")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.endsWith("-run")) { s = s.substring(0, s.length() - 4); } else if (s.startsWith("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = series.get(i).getText(); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } boxes.get(i).setName(text); } if (!visible.get(i).isSelected()) { allCheckedVisible = false; } if (!connected.get(i).isSelected()) { allCheckedConnected = false; } if (!filled.get(i).isSelected()) { allCheckedFilled = false; } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } if (allCheckedVisible) { visibleLabel.setSelected(true); } else { visibleLabel.setSelected(false); } if (allCheckedFilled) { filledLabel.setSelected(true); } else { filledLabel.setSelected(false); } if (allCheckedConnected) { connectedLabel.setSelected(true); } else { connectedLabel.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } } private JPanel fixGraphChoices(final String directory) { if (directory.equals("")) { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")) { if (selected.equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { readGraphSpecies(outDir + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")) { if (selected.equals("Average") && new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Variance") && new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (selected.equals("Standard Deviation") && new File(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { int nextOne = 1; while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } } else { readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8)); } } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3)); JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3)); use = new JCheckBox("Use"); JLabel specs; if (biomodelsim.lema || biomodelsim.atacs) { specs = new JLabel("Variables"); } else { specs = new JLabel("Species"); } JLabel color = new JLabel("Color"); JLabel shape = new JLabel("Shape"); connectedLabel = new JCheckBox("Connect"); visibleLabel = new JCheckBox("Visible"); filledLabel = new JCheckBox("Fill"); connectedLabel.setSelected(true); visibleLabel.setSelected(true); filledLabel.setSelected(true); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); shapesCombo = new ArrayList<JComboBox>(); connected = new ArrayList<JCheckBox>(); visible = new ArrayList<JCheckBox>(); filled = new ArrayList<JCheckBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); connectedLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (connectedLabel.isSelected()) { for (JCheckBox box : connected) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : connected) { if (box.isSelected()) { box.doClick(); } } } } }); visibleLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (visibleLabel.isSelected()) { for (JCheckBox box : visible) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : visible) { if (box.isSelected()) { box.doClick(); } } } } }); filledLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (filledLabel.isSelected()) { for (JCheckBox box : filled) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : filled) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); speciesPanel2.add(shape); speciesPanel3.add(connectedLabel); speciesPanel3.add(visibleLabel); speciesPanel3.add(filledLabel); final HashMap<String, Shape> shapey = this.shapes; final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphSpecies.size() - 1; i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; int[] shaps = new int[10]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Green (Dark)")) { cols[10]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Dark)")) { cols[11]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Dark)")) { cols[12]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Extra Dark)")) { cols[22]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Extra Dark)")) { cols[24]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Blue (Light)")) { cols[29]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Light)")) { cols[30]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Light)")) { cols[31]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Light)")) { cols[32]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Cyan (Light)")) { cols[33]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Gray (Light)")) { cols[34]++; } if (shapesCombo.get(k).getSelectedItem().equals("Square")) { shaps[0]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) { shaps[1]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) { shaps[2]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) { shaps[3]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Circle (Half)")) { shaps[6]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) { shaps[7]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Arrow (Backwards)")) { shaps[9]++; } } } for (GraphSpecies graph : graphed) { if (graph.getShapeAndPaint().getPaintName().equals("Red")) { cols[0]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green")) { cols[2]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Dark)")) { cols[12]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Black")) { cols[14]++; } /* * else if * (graph.getShapeAndPaint().getPaintName().equals * ("Red ")) { cols[15]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Blue ")) { cols[16]++; * } else if * (graph.getShapeAndPaint().getPaintName() * .equals("Green ")) { cols[17]++; } else if * (graph. * getShapeAndPaint().getPaintName().equals("Yellow " * )) { cols[18]++; } else if * (graph.getShapeAndPaint * ().getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getShapeAndPaint().getPaintName * ().equals("Cyan ")) { cols[20]++; } */ else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Red (Extra Dark)")) { cols[22]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Green (Extra Dark)")) { cols[24]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Green (Light)")) { cols[30]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Light)")) { cols[31]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Light)")) { cols[32]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) { cols[34]++; } if (graph.getShapeAndPaint().getShapeName().equals("Square")) { shaps[0]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) { shaps[1]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) { shaps[2]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) { shaps[3]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (graph.getShapeAndPaint().getShapeName() .equals("Circle (Half)")) { shaps[6]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) { shaps[7]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Arrow (Backwards)")) { shaps[9]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } int shapeSet = 0; for (int j = 1; j < shaps.length; j++) { if (shaps[j] < shaps[shapeSet]) { shapeSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); } } for (int j = 0; j < shapeSet; j++) { draw.getNextShape(); } Shape shape = draw.getNextShape(); set = shapey.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (shape == shapey.get(set[j])) { shapesCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i) .getSelectedItem()), colory.get(colorsCombo.get(i) .getSelectedItem()), filled.get(i).isSelected(), visible.get(i) .isSelected(), connected.get(i).isSelected(), selected, boxes .get(i).getName(), series.get(i).getText().trim(), XVariable .getSelectedIndex(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals( "" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphSpecies g : remove) { graphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); shapesCombo.get(i).setSelectedIndex(0); } } }); boxes.add(temp); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : visible) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { visibleLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(true); } } } else { visibleLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(false); } } } } }); visible.add(temp); visible.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : filled) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { filledLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(true); } } } else { filledLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(false); } } } } }); filled.add(temp); filled.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : connected) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { connectedLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(true); } } } else { connectedLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(false); } } } } }); connected.add(temp); connected.get(i).setSelected(true); JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); Object[] col = this.colors.keySet().toArray(); Arrays.sort(col); Object[] shap = this.shapes.keySet().toArray(); Arrays.sort(shap); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); JComboBox shapBox = new JComboBox(shap); shapBox.setActionCommand("" + i); shapBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); colorsCombo.add(colBox); shapesCombo.add(shapBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorsCombo.get(i)); speciesPanel2.add(shapesCombo.get(i)); speciesPanel3.add(connected.get(i)); speciesPanel3.add(visible.get(i)); speciesPanel3.add(filled.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); speciesPanel.add(speciesPanel3, "East"); return speciesPanel; } private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) { curData = dataset; // chart = ChartFactory.createXYLineChart(title, x, y, dataset, // PlotOrientation.VERTICAL, // true, true, false); chart.getXYPlot().setDataset(dataset); chart.setTitle(title); chart.getXYPlot().getDomainAxis().setLabel(x); chart.getXYPlot().getRangeAxis().setLabel(y); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); // chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); if (graphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); saveAs.addActionListener(this); export = new JButton("Export"); refresh = new JButton("Refresh"); // exportJPeg = new JButton("Export As JPEG"); // exportPng = new JButton("Export As PNG"); // exportPdf = new JButton("Export As PDF"); // exportEps = new JButton("Export As EPS"); // exportSvg = new JButton("Export As SVG"); // exportCsv = new JButton("Export As CSV"); run.addActionListener(this); save.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); // exportJPeg.addActionListener(this); // exportPng.addActionListener(this); // exportPdf.addActionListener(this); // exportEps.addActionListener(this); // exportSvg.addActionListener(this); // exportCsv.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // ButtonHolder.add(exportJPeg); // ButtonHolder.add(exportPng); // ButtonHolder.add(exportPdf); // ButtonHolder.add(exportEps); // ButtonHolder.add(exportSvg); // ButtonHolder.add(exportCsv); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } /** * This method saves the graph as a jpeg or as a png file. */ public void export() { try { int output = 2; /* Default is currently pdf */ int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Buttons.browse(BioSim.frame, file, null, JFileChooser.FILES_ONLY, export, output); if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".jpg"))) { output = 0; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".png"))) { output = 1; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".pdf"))) { output = 2; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".eps"))) { output = 3; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".svg"))) { output = 4; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".csv"))) { output = 5; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".dat"))) { output = 6; } else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()) .equals(".tsd"))) { output = 7; } if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(BioSim.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(BioSim.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(BioSim.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(BioSim.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(BioSim.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(BioSim.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(BioSim.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void export(int output) { // jpg = 0 // png = 1 // pdf = 2 // eps = 3 // svg = 4 // csv = 5 (data) // dat = 6 (data) // tsd = 7 (data) try { int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value; String export = "Export"; if (timeSeries) { export += " TSD"; } else { export += " Probability"; } File file; Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.general.export_dir", "").equals("")) { file = null; } else { file = new File(biosimrc.get("biosim.general.export_dir", "")); } String filename = Buttons.browse(BioSim.frame, file, null, JFileChooser.FILES_ONLY, export, output); if (!filename.equals("")) { file = new File(filename); biosimrc.put("biosim.general.export_dir", filename); boolean exportIt = true; if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(BioSim.frame, "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); exportIt = false; if (value == JOptionPane.YES_OPTION) { exportIt = true; } } if (exportIt) { if ((output != 5) && (output != 6) && (output != 7)) { value = JOptionPane.showOptionDialog(BioSim.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(BioSim.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(BioSim.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(BioSim.frame, "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(BioSim.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); FileOutputStream out = new FileOutputStream(file); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); out.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; FileOutputStream outStream = new FileOutputStream(file); Writer out = new OutputStreamWriter(outStream, "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); outStream.close(); } else if ((output == 5) || (output == 6) || (output == 7)) { exportDataFile(file, output); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(BioSim.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } public void exportDataFile(File file, int output) { try { int count = curData.getSeries(0).getItemCount(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (curData.getSeries(i).getItemCount() != count) { JOptionPane.showMessageDialog(BioSim.frame, "Data series do not have the same number of points!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } for (int j = 0; j < count; j++) { Number Xval = curData.getSeries(0).getDataItem(j).getX(); for (int i = 1; i < curData.getSeriesCount(); i++) { if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) { JOptionPane.showMessageDialog(BioSim.frame, "Data series time points are not the same!", "Unable to Export Data File", JOptionPane.ERROR_MESSAGE); return; } } } FileOutputStream csvFile = new FileOutputStream(file); PrintWriter csvWriter = new PrintWriter(csvFile); if (output == 7) { csvWriter.print("(("); } else if (output == 6) { csvWriter.print(" } csvWriter.print("\"Time\""); count = curData.getSeries(0).getItemCount(); int pos = 0; for (int i = 0; i < curData.getSeriesCount(); i++) { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print("\"" + curData.getSeriesKey(i) + "\""); if (curData.getSeries(i).getItemCount() > count) { count = curData.getSeries(i).getItemCount(); pos = i; } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } for (int j = 0; j < count; j++) { if (output == 7) { csvWriter.print(","); } for (int i = 0; i < curData.getSeriesCount(); i++) { if (i == 0) { if (output == 7) { csvWriter.print("("); } csvWriter.print(curData.getSeries(pos).getDataItem(j).getX()); } XYSeries data = curData.getSeries(i); if (j < data.getItemCount()) { XYDataItem item = data.getDataItem(j); if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } csvWriter.print(item.getY()); } else { if (output == 6) { csvWriter.print(" "); } else { csvWriter.print(","); } } } if (output == 7) { csvWriter.print(")"); } else { csvWriter.println(""); } } if (output == 7) { csvWriter.println(")"); } csvWriter.close(); csvFile.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(BioSim.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile, String fileStem, int choice, String directory, boolean warning) { warn = warning; ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>(); // TSDParser p = new TSDParser(startFile, biomodelsim, false); ArrayList<ArrayList<Double>> data = readData(startFile, "", directory, warn); averageOrder = graphSpecies; boolean first = true; int runsToMake = 1; String[] findNum = startFile.split(separator); String search = findNum[findNum.length - 1]; int firstOne = Integer.parseInt(search.substring(4, search.length() - 4)); if (directory == null) { for (String f : new File(outDir).list()) { if (f.contains(fileStem)) { try { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } catch (Exception e) { } } } } else { for (String f : new File(outDir + separator + directory).list()) { if (f.contains(fileStem)) { try { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f.length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } catch (Exception e) { } } } } for (int i = 0; i < graphSpecies.size(); i++) { average.add(new ArrayList<Double>()); variance.add(new ArrayList<Double>()); } HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>(); // int count = 0; int skip = firstOne; for (int j = 0; j < runsToMake; j++) { if (!first) { if (firstOne != 1) { j firstOne = 1; } boolean loop = true; while (loop && j < runsToMake && (j + 1) != skip) { if (directory == null) { if (new File(outDir + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8), "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } loop = false; // count++; } else { j++; } } else { if (new File(outDir + separator + directory + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8), "", directory, warn); data = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < averageOrder.size(); i++) { for (int k = 0; k < graphSpecies.size(); k++) { if (averageOrder.get(i).equals(graphSpecies.get(k))) { data.add(newData.get(k)); break; } } } loop = false; // count++; } else { j++; } } } } // ArrayList<ArrayList<Double>> data = p.getData(); for (int k = 0; k < data.get(0).size(); k++) { if (first) { double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); dataCounts.put(put, 1); } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } } else { put = (data.get(0)).get(k); dataCounts.put(put, 1); } for (int i = 0; i < data.size(); i++) { if (i == 0) { variance.get(i).add((data.get(i)).get(k)); average.get(i).add(put); } else { variance.get(i).add(0.0); average.get(i).add((data.get(i)).get(k)); } } } else { int index = -1; double put; if (k == data.get(0).size() - 1 && k >= 2) { if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) { put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2)); } else { put = (data.get(0)).get(k); } } else if (k == data.get(0).size() - 1 && k == 1) { if (average.get(0).size() > 1) { put = (average.get(0)).get(k); } else { put = (data.get(0)).get(k); } } else { put = (data.get(0)).get(k); } if (average.get(0).contains(put)) { index = average.get(0).indexOf(put); int count = dataCounts.get(put); dataCounts.put(put, count + 1); for (int i = 1; i < data.size(); i++) { double old = (average.get(i)).get(index); (average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1))); double newMean = (average.get(i)).get(index); double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data .get(i)).get(k) - newMean) * ((data.get(i)).get(k) - old)) / count; (variance.get(i)).set(index, vary); } } else { dataCounts.put(put, 1); for (int a = 0; a < average.get(0).size(); a++) { if (average.get(0).get(a) > put) { index = a; break; } } if (index == -1) { index = average.get(0).size() - 1; } average.get(0).add(put); variance.get(0).add(put); for (int a = 1; a < average.size(); a++) { average.get(a).add(data.get(a).get(k)); variance.get(a).add(0.0); } if (index != average.get(0).size() - 1) { for (int a = average.get(0).size() - 2; a >= 0; a if (average.get(0).get(a) > average.get(0).get(a + 1)) { for (int b = 0; b < average.size(); b++) { double temp = average.get(b).get(a); average.get(b).set(a, average.get(b).get(a + 1)); average.get(b).set(a + 1, temp); temp = variance.get(b).get(a); variance.get(b).set(a, variance.get(b).get(a + 1)); variance.get(b).set(a + 1, temp); } } else { break; } } } } } } first = false; } deviation = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < variance.size(); i++) { deviation.add(new ArrayList<Double>()); for (int j = 0; j < variance.get(i).size(); j++) { deviation.get(i).add(variance.get(i).get(j)); } } for (int i = 1; i < deviation.size(); i++) { for (int j = 0; j < deviation.get(i).size(); j++) { deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j))); } } averageOrder = null; if (choice == 0) { return average; } else if (choice == 1) { return variance; } else { return deviation; } } public void run() { reb2sac.getRunButton().doClick(); } public void save() { if (timeSeries) { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint() .getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint() .getShapeName()); graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(BioSim.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()) .getBarPainter() instanceof GradientBarPainter)); graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory()); } try { FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName)); graph.store(store, "Probability Data"); store.close(); log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n"); change = false; } catch (Exception except) { JOptionPane.showMessageDialog(BioSim.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public void saveAs() { if (timeSeries) { String graphName = JOptionPane.showInputDialog(BioSim.frame, "Enter Graph Name:", "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"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(BioSim.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 del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1] .length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); graph.setProperty("LogX", "" + LogX.isSelected()); graph.setProperty("LogY", "" + LogY.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.id." + i, graphed.get(i).getID()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint() .getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint() .getShapeName()); if (topLevel) { graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } else { if (graphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + graphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Graph Data"); store.close(); log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane.showMessageDialog(BioSim.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } else { String graphName = JOptionPane.showInputDialog(BioSim.frame, "Enter Probability Graph Name:", "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"; } File f; if (topLevel) { f = new File(outDir + separator + graphName); } else { f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length()) + separator + graphName); } if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(BioSim.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 del; if (topLevel) { del = new File(outDir + separator + graphName); } else { del = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1] .length()) + separator + graphName); } if (del.isDirectory()) { biomodelsim.deleteDir(del); } else { del.delete(); } for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) { if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) { biomodelsim.getTab().remove(i); } } } else { return; } } Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel()); graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()) .getBarPainter() instanceof GradientBarPainter)); graph .setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()) .getShadowsVisible()); for (int i = 0; i < probGraphed.size(); i++) { graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber()); graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies()); graph.setProperty("species.id." + i, probGraphed.get(i).getID()); graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName()); if (topLevel) { graph.setProperty("species.directory." + i, probGraphed.get(i) .getDirectory()); } else { if (probGraphed.get(i).getDirectory().equals("")) { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]); } else { graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/" + probGraphed.get(i).getDirectory()); } } } try { FileOutputStream store = new FileOutputStream(f); graph.store(store, "Probability Graph Data"); store.close(); log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n"); change = false; biomodelsim.addToTree(f.getName()); } catch (Exception except) { JOptionPane .showMessageDialog(BioSim.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } } private void open(String filename) { if (timeSeries) { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); XMin.setText(graph.getProperty("x.min")); XMax.setText(graph.getProperty("x.max")); XScale.setText(graph.getProperty("x.scale")); YMin.setText(graph.getProperty("y.min")); YMax.setText(graph.getProperty("y.max")); YScale.setText(graph.getProperty("y.scale")); chart.setTitle(graph.getProperty("title")); chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.getProperty("auto.resize").equals("true")) { resize.setSelected(true); } else { resize.setSelected(false); } if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) { LogX.setSelected(true); } else { LogX.setSelected(false); } if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) { LogY.setSelected(true); } else { LogY.setSelected(false); } int next = 0; while (graph.containsKey("species.name." + next)) { boolean connected, filled, visible; if (graph.getProperty("species.connected." + next).equals("true")) { connected = true; } else { connected = false; } if (graph.getProperty("species.filled." + next).equals("true")) { filled = true; } else { filled = false; } if (graph.getProperty("species.visible." + next).equals("true")) { visible = true; } else { visible = false; } int xnumber = 0; if (graph.containsKey("species.xnumber." + next)) { xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next)); } graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), colors.get(graph.getProperty("species.paint." + next).trim()), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id." + next), graph .getProperty("species.name." + next), xnumber, Integer .parseInt(graph.getProperty("species.number." + next)), graph .getProperty("species.directory." + next))); next++; } updateXNumber = false; XVariable.addItem("time"); refresh(); } catch (IOException except) { JOptionPane.showMessageDialog(BioSim.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } else { Properties graph = new Properties(); try { FileInputStream load = new FileInputStream(new File(filename)); graph.load(load); load.close(); chart.setTitle(graph.getProperty("title")); chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()) .setBarPainter(new GradientBarPainter()); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()) .setBarPainter(new StandardBarPainter()); } if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false); } else { ((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true); } int next = 0; while (graph.containsKey("species.name." + next)) { probGraphed.add(new GraphProbs(colors.get(graph.getProperty( "species.paint." + next).trim()), graph.getProperty( "species.paint." + next).trim(), graph .getProperty("species.id." + next), graph.getProperty("species.name." + next), Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next))); next++; } refreshProb(); } catch (Exception except) { JOptionPane.showMessageDialog(BioSim.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } } public boolean isTSDGraph() { return timeSeries; } public void refresh() { if (timeSeries) { if (learnSpecs != null) { updateSpecies(); } double minY = 0; double maxY = 0; double scaleY = 0; double minX = 0; double maxX = 0; double scaleX = 0; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); /* * NumberFormat num = NumberFormat.getInstance(); * num.setMaximumFractionDigits(4); num.setGroupingUsed(false); * minY = Double.parseDouble(num.format(minY)); maxY = * Double.parseDouble(num.format(maxY)); scaleY = * Double.parseDouble(num.format(scaleY)); minX = * Double.parseDouble(num.format(minX)); maxX = * Double.parseDouble(num.format(maxX)); scaleX = * Double.parseDouble(num.format(scaleX)); */ } catch (Exception e1) { } ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), null, false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + "run-" + // nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { data = readData(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber(), g.getDirectory(), false); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (!ableToGraph) { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { ableToGraph = true; } } if (ableToGraph) { int nextOne = 1; // while (!new File(outDir + separator + // g.getDirectory() + separator // + "run-" + nextOne + "." // + printer_id.substring(0, printer_id.length() - // 8)).exists()) { // nextOne++; ArrayList<ArrayList<Double>> data; if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) { data = allData.get(g.getRunNumber() + " " + g.getDirectory()); if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } updateXNumber = false; XVariable.removeAllItems(); for (int i = 0; i < graphSpecies.size(); i++) { XVariable.addItem(graphSpecies.get(i)); } updateXNumber = true; } else { if (g.getRunNumber().equals("Average") && new File(outDir + separator + g.getDirectory() + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Variance") && new File(outDir + separator + g.getDirectory() + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else if (g.getRunNumber().equals("Standard Deviation") && new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { data = readData(outDir + separator + g.getDirectory() + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), null, false); } else { while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } data = readData(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g .getRunNumber().toLowerCase(), g.getDirectory(), false); } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } allData.put(g.getRunNumber() + " " + g.getDirectory(), data); } boolean set = false; for (int i = 1; i < graphSpecies.size(); i++) { String compare = g.getID().replace(" (", "~"); if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) { g.setNumber(i - 1); set = true; } } if (g.getNumber() + 1 < graphSpecies.size() && set) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(g.getXNumber())).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne } } else { unableToGraph.add(g); thisOne } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } else { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { if (graphProbs.contains(g.getID())) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt") .exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { String compare = g.getID().replace(" (", "~"); if (graphProbs.contains(compare.split("~")[0].trim())) { for (int i = 0; i < graphProbs.size(); i++) { if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } else { unableToGraph.add(g); thisOne } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis() .getLabel(), chart.getCategoryPlot().getRangeAxis().getLabel(), histDataset, rend); } } private class ShapeAndPaint { private Shape shape; private Paint paint; private ShapeAndPaint(Shape s, Paint p) { shape = s; paint = p; } private Shape getShape() { return shape; } private Paint getPaint() { return paint; } private String getShapeName() { Object[] set = shapes.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (shape == shapes.get(set[i])) { return (String) set[i]; } } return "Unknown Shape"; } private String getPaintName() { Object[] set = colors.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (paint == colors.get(set[i])) { return (String) set[i]; } } return "Unknown Color"; } public void setPaint(String paint) { this.paint = colors.get(paint); } public void setShape(String shape) { this.shape = shapes.get(shape); } } private class GraphSpecies { private ShapeAndPaint sP; private boolean filled, visible, connected; private String runNumber, species, directory, id; private int xnumber, number; private GraphSpecies(Shape s, Paint p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species, int xnumber, int number, String directory) { sP = new ShapeAndPaint(s, p); this.filled = filled; this.visible = visible; this.connected = connected; this.runNumber = runNumber; this.species = species; this.xnumber = xnumber; this.number = number; this.directory = directory; this.id = id; } private void setDirectory(String directory) { this.directory = directory; } private void setXNumber(int xnumber) { this.xnumber = xnumber; } private void setNumber(int number) { this.number = number; } private void setSpecies(String species) { this.species = species; } private void setPaint(String paint) { sP.setPaint(paint); } private void setShape(String shape) { sP.setShape(shape); } private void setVisible(boolean b) { visible = b; } private void setFilled(boolean b) { filled = b; } private void setConnected(boolean b) { connected = b; } private int getXNumber() { return xnumber; } private int getNumber() { return number; } private String getSpecies() { return species; } private ShapeAndPaint getShapeAndPaint() { return sP; } private boolean getFilled() { return filled; } private boolean getVisible() { return visible; } private boolean getConnected() { return connected; } private String getRunNumber() { return runNumber; } private String getDirectory() { return directory; } private String getID() { return id; } } public void setDirectory(String newDirectory) { outDir = newDirectory; } public void setGraphName(String graphName) { this.graphName = graphName; } public boolean hasChanged() { return change; } private void probGraph(String label) { chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false); ((BarRenderer) chart.getCategoryPlot().getRenderer()) .setBarPainter(new StandardBarPainter()); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); change = false; // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // puts all the components of the graph gui into a display panel // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); } private void editProbGraph() { final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { old.add(g); } final JPanel titlePanel = new JPanel(new BorderLayout()); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JCheckBox gradient = new JCheckBox("Paint In Gradient Style"); gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()) .getBarPainter() instanceof StandardBarPainter)); final JCheckBox shadow = new JCheckBox("Paint Bar Shadows"); shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()) .getShadowsVisible()); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5); String simDirString = outDir.split(separator)[outDir.split(separator).length - 1]; simDir = new IconNode(simDirString, simDirString); simDir.setIconName(""); String[] files = new File(outDir).list(); for (int i = 1; i < files.length; i++) { String index = files[i]; int j = i; while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { files[j] = files[j - 1]; j = j - 1; } files[j] = index; } boolean add = false; final ArrayList<String> directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) { if (file.contains("sim-rep")) { add = true; } } else if (new File(outDir + separator + file).isDirectory()) { boolean addIt = false; for (String getFile : new File(outDir + separator + file).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt = true; } else if (new File(outDir + separator + file + separator + getFile) .isDirectory()) { for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) { if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) { addIt = true; } } } } if (addIt) { directories.add(file); IconNode d = new IconNode(file, file); d.setIconName(""); String[] files2 = new File(outDir + separator + file).list(); for (int i = 1; i < files2.length; i++) { String index = files2[i]; int j = i; while ((j > 0) && files2[j - 1].compareToIgnoreCase(index) > 0) { files2[j] = files2[j - 1]; j = j - 1; } files2[j] = index; } boolean add2 = false; for (String f : files2) { if (f.equals("sim-rep.txt")) { add2 = true; } else if (new File(outDir + separator + file + separator + f).isDirectory()) { boolean addIt2 = false; for (String getFile : new File(outDir + separator + file + separator + f).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) { addIt2 = true; } } if (addIt2) { directories.add(file + separator + f); IconNode d2 = new IconNode(f, f); d2.setIconName(""); for (String f2 : new File(outDir + separator + file + separator + f) .list()) { if (f2.equals("sim-rep.txt")) { IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4)); d2.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals( d.getName() + separator + d2.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d2.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d2.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory .getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } } d.add(d2); } } } if (add2) { IconNode n = new IconNode("sim-rep", "sim-rep"); d.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals(d.getName())) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); d.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } simDir.add(d); } } } if (add) { IconNode n = new IconNode("sim-rep", "sim-rep"); simDir.add(n); n.setIconName(""); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { n.setIcon(TextIcons.getIcon("g")); n.setIconName("" + (char) 10003); simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); simDir.setIconName("" + (char) 10003); } } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(BioSim.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { tree = new JTree(simDir); tree.putClientProperty("JTree.icons", makeIcons()); tree.setCellRenderer(new IconNodeRenderer()); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon()); renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon()); renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon()); final JPanel all = new JPanel(new BorderLayout()); final JScrollPane scroll = new JScrollPane(); tree.addTreeExpansionListener(new TreeExpansionListener() { public void treeCollapsed(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } public void treeExpanded(TreeExpansionEvent e) { JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); all.removeAll(); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); all.revalidate(); all.repaint(); } }); // for (int i = 0; i < tree.getRowCount(); i++) { // tree.expandRow(i); JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); scrollpane.setPreferredSize(new Dimension(175, 100)); final JPanel specPanel = new JPanel(); boolean stop = false; int selectionRow = 1; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; selectionRow = i; break; } } tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { node = (IconNode) e.getPath().getLastPathComponent(); if (!directories.contains(node.getName())) { selected = node.getName(); int select; if (selected.equals("sim-rep")) { select = 0; } else { select = -1; } if (select != -1) { specPanel.removeAll(); if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())); } else if (directories.contains(((IconNode) node.getParent()).getName())) { specPanel.add(fixProbChoices(((IconNode) node.getParent()) .getName())); } else { specPanel.add(fixProbChoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphProbs.get(i)); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals( ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getPaintName()); } } } else if (directories.contains(((IconNode) node.getParent()).getName())) { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals( ((IconNode) node.getParent()).getName())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getPaintName()); } } } else { for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); series.get(g.getNumber()).setSelectionStart(0); series.get(g.getNumber()).setSelectionEnd(0); colorsCombo.get(g.getNumber()).setSelectedItem( g.getPaintName()); } } } boolean allChecked = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()) .getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = series.get(i).getText(); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); series.get(i).setText(text); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); colorsCombo.get(i).setSelectedIndex(0); } else { String s = ""; if (node.getParent().getParent() != null && directories.contains(((IconNode) node.getParent() .getParent()).getName() + separator + ((IconNode) node.getParent()).getName())) { s = "(" + ((IconNode) node.getParent().getParent()) .getName() + separator + ((IconNode) node.getParent()).getName() + ")"; } else if (directories.contains(((IconNode) node.getParent()) .getName())) { s = "(" + ((IconNode) node.getParent()).getName() + ")"; } String text = graphProbs.get(i); String end = ""; if (!s.equals("")) { if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } } boxes.get(i).setName(text); } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); if (!stop) { tree.setSelectionRow(0); tree.setSelectionRow(1); } else { tree.setSelectionRow(0); tree.setSelectionRow(selectionRow); } scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(specPanel, "Center"); scroll.setViewportView(editPanel); final JButton deselect = new JButton("Deselect All"); deselect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } IconNode n = simDir; while (n != null) { if (n.isLeaf()) { n.setIcon(MetalIconFactory.getTreeLeafIcon()); n.setIconName(""); IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); if (check == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n .getParent()).getChildAfter(n); if (check2 == null) { n = (IconNode) n.getParent(); if (n.getParent() == null) { n = null; } else { n = (IconNode) ((DefaultMutableTreeNode) n.getParent()) .getChildAfter(n); } } else { n = check2; } } } else { n = check; } } else { n.setIcon(MetalIconFactory.getTreeFolderIcon()); n.setIconName(""); n = (IconNode) n.getChildAt(0); } } tree.revalidate(); tree.repaint(); if (tree.getSelectionCount() > 0) { int selectedRow = tree.getSelectionRows()[0]; tree.setSelectionRow(0); tree.setSelectionRow(selectedRow); } } }); JPanel titlePanel1 = new JPanel(new GridLayout(1, 6)); JPanel titlePanel2 = new JPanel(new GridLayout(1, 6)); titlePanel1.add(titleLabel); titlePanel1.add(title); titlePanel1.add(xLabel); titlePanel1.add(x); titlePanel1.add(yLabel); titlePanel1.add(y); titlePanel2.add(new JPanel()); JPanel deselectPanel = new JPanel(); deselectPanel.add(deselect); titlePanel2.add(deselectPanel); titlePanel2.add(gradient); titlePanel2.add(shadow); titlePanel2.add(new JPanel()); titlePanel2.add(new JPanel()); titlePanel.add(titlePanel1, "Center"); titlePanel.add(titlePanel2, "South"); all.add(titlePanel, "North"); all.add(scroll, "Center"); all.add(scrollpane, "West"); Object[] options = { "Ok", "Cancel" }; int value = JOptionPane .showOptionDialog(BioSim.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { change = true; lastSelected = selected; selected = ""; BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); if (gradient.isSelected()) { rend.setBarPainter(new GradientBarPainter()); } else { rend.setBarPainter(new StandardBarPainter()); } if (shadow.isSelected()) { rend.setShadowVisible(true); } else { rend.setShadowVisible(false); } int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend); } else { selected = ""; int size = probGraphed.size(); for (int i = 0; i < size; i++) { probGraphed.remove(); } for (GraphProbs g : old) { probGraphed.add(g); } } } } private JPanel fixProbChoices(final String directory) { if (directory.equals("")) { readProbSpecies(outDir + separator + "sim-rep.txt"); } else { readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt"); } for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); j = j - 1; } graphProbs.set(j, index); } JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2)); use = new JCheckBox("Use"); JLabel specs = new JLabel("Constraint"); JLabel color = new JLabel("Color"); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphProbs.size(); i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { node.setIcon(TextIcons.getIcon("g")); node.setIconName("" + (char) 10003); IconNode n = ((IconNode) node.getParent()); while (n != null) { n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon()); n.setIconName("" + (char) 10003); if (n.getParent() == null) { n = null; } else { n = ((IconNode) n.getParent()); } } tree.revalidate(); tree.repaint(); String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[35]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) { cols[7]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) { cols[8]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) { cols[9]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Green (Dark)")) { cols[10]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Dark)")) { cols[11]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Dark)")) { cols[12]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) { cols[13]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; } /* * else if * (colorsCombo.get(k).getSelectedItem(). * equals("Red ")) { cols[15]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Blue ")) { * cols[16]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Green ")) { cols[17]++; } else if * (colorsCombo.get(k).getSelectedItem().equals( * "Yellow ")) { cols[18]++; } else if * (colorsCombo * .get(k).getSelectedItem().equals("Magenta ")) * { cols[19]++; } else if * (colorsCombo.get(k).getSelectedItem * ().equals("Cyan ")) { cols[20]++; } */ else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) { cols[21]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Extra Dark)")) { cols[22]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Extra Dark)")) { cols[24]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) { cols[28]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Blue (Light)")) { cols[29]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Light)")) { cols[30]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Light)")) { cols[31]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Light)")) { cols[32]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Cyan (Light)")) { cols[33]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Gray (Light)")) { cols[34]++; } } } for (GraphProbs graph : probGraphed) { if (graph.getPaintName().equals("Red")) { cols[0]++; } else if (graph.getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getPaintName().equals("Green")) { cols[2]++; } else if (graph.getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getPaintName().equals("Gray (Dark)")) { cols[7]++; } else if (graph.getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getPaintName().equals("Blue (Dark)")) { cols[9]++; } else if (graph.getPaintName().equals("Green (Dark)")) { cols[10]++; } else if (graph.getPaintName().equals("Yellow (Dark)")) { cols[11]++; } else if (graph.getPaintName().equals("Magenta (Dark)")) { cols[12]++; } else if (graph.getPaintName().equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getPaintName().equals("Black")) { cols[14]++; } /* * else if (graph.getPaintName().equals("Red ")) { * cols[15]++; } else if * (graph.getPaintName().equals("Blue ")) { * cols[16]++; } else if * (graph.getPaintName().equals("Green ")) { * cols[17]++; } else if * (graph.getPaintName().equals("Yellow ")) { * cols[18]++; } else if * (graph.getPaintName().equals("Magenta ")) { * cols[19]++; } else if * (graph.getPaintName().equals("Cyan ")) { * cols[20]++; } */ else if (graph.getPaintName().equals("Gray")) { cols[21]++; } else if (graph.getPaintName().equals("Red (Extra Dark)")) { cols[22]++; } else if (graph.getPaintName().equals("Blue (Extra Dark)")) { cols[23]++; } else if (graph.getPaintName().equals("Green (Extra Dark)")) { cols[24]++; } else if (graph.getPaintName().equals("Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getPaintName().equals("Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getPaintName().equals("Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getPaintName().equals("Red (Light)")) { cols[28]++; } else if (graph.getPaintName().equals("Blue (Light)")) { cols[29]++; } else if (graph.getPaintName().equals("Green (Light)")) { cols[30]++; } else if (graph.getPaintName().equals("Yellow (Light)")) { cols[31]++; } else if (graph.getPaintName().equals("Magenta (Light)")) { cols[32]++; } else if (graph.getPaintName().equals("Cyan (Light)")) { cols[33]++; } else if (graph.getPaintName().equals("Gray (Light)")) { cols[34]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); series.get(i).setSelectionStart(0); series.get(i).setSelectionEnd(0); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) { colorSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); Paint paint; if (colorSet == 34) { paint = colors.get("Gray (Light)"); } else { for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } paint = draw.getNextPaint(); } Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } probGraphed.add(new GraphProbs(colory.get(colorsCombo.get(i) .getSelectedItem()), (String) colorsCombo.get(i).getSelectedItem(), boxes.get(i).getName(), series.get(i).getText().trim(), i, directory)); } else { boolean check = false; for (JCheckBox b : boxes) { if (b.isSelected()) { check = true; } } if (!check) { node.setIcon(MetalIconFactory.getTreeLeafIcon()); node.setIconName(""); boolean check2 = false; IconNode parent = ((IconNode) node.getParent()); while (parent != null) { for (int j = 0; j < parent.getChildCount(); j++) { if (((IconNode) parent.getChildAt(j)).getIconName().equals( "" + (char) 10003)) { check2 = true; } } if (!check2) { parent.setIcon(MetalIconFactory.getTreeFolderIcon()); parent.setIconName(""); } check2 = false; if (parent.getParent() == null) { parent = null; } else { parent = ((IconNode) parent.getParent()); } } tree.revalidate(); tree.repaint(); } ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>(); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphProbs g : remove) { probGraphed.remove(g); } use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); } } }); boxes.add(temp); JTextField seriesName = new JTextField(graphProbs.get(i)); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); Object[] col = this.colors.keySet().toArray(); Arrays.sort(col); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphProbs g : probGraphed) { if (g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem()); g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem())); } } } }); colorsCombo.add(colBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorsCombo.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); return speciesPanel; } private void readProbSpecies(String file) { graphProbs = new ArrayList<String>(); ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } for (String s : data) { if (!s.split(" ")[0].equals("#total")) { graphProbs.add(s.split(" ")[0]); } } } private double[] readProbs(String file) { ArrayList<String> data = new ArrayList<String>(); try { Scanner s = new Scanner(new File(file)); while (s.hasNextLine()) { String[] ss = s.nextLine().split(" "); if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) { return new double[0]; } if (data.size() == 0) { for (String add : ss) { data.add(add); } } else { for (int i = 0; i < ss.length; i++) { data.set(i, data.get(i) + " " + ss[i]); } } } } catch (Exception e) { } double[] dataSet = new double[data.size()]; double total = 0; int i = 0; if (data.get(0).split(" ")[0].equals("#total")) { total = Double.parseDouble(data.get(0).split(" ")[1]); i = 1; } for (; i < data.size(); i++) { if (total == 0) { dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]); } else { dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total); } } return dataSet; } private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) { chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false); chart.getCategoryPlot().setRenderer(rend); chart.setBackgroundPaint(new java.awt.Color(238, 238, 238)); chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE); chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); ChartPanel graph = new ChartPanel(chart); if (probGraphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Double click here to create graph"); edit.addMouseListener(this); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); run = new JButton("Save and Run"); save = new JButton("Save Graph"); saveAs = new JButton("Save As"); export = new JButton("Export"); refresh = new JButton("Refresh"); run.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); export.addActionListener(this); refresh.addActionListener(this); if (reb2sac != null) { ButtonHolder.add(run); } ButtonHolder.add(save); ButtonHolder.add(saveAs); ButtonHolder.add(export); ButtonHolder.add(refresh); // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, // ButtonHolder, null); // splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); // this.add(splitPane, "South"); this.revalidate(); } public void refreshProb() { BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < probGraphed.size(); i++) { GraphProbs index = probGraphed.get(i); int j = i; while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { probGraphed.set(j, probGraphed.get(j - 1)); j = j - 1; } probGraphed.set(j, index); } ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>(); DefaultCategoryDataset histDataset = new DefaultCategoryDataset(); for (GraphProbs g : probGraphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + "sim-rep.txt").exists()) { readProbSpecies(outDir + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { if (g.getID().equals(graphProbs.get(i))) { g.setNumber(i); histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } else { thisOne++; rend.setSeriesPaint(thisOne, g.getPaint()); if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt") .exists()) { readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt"); for (int i = 1; i < graphProbs.size(); i++) { String index = graphProbs.get(i); double index2 = data[i]; int j = i; while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) { graphProbs.set(j, graphProbs.get(j - 1)); data[j] = data[j - 1]; j = j - 1; } graphProbs.set(j, index); data[j] = index2; } if (graphProbs.size() != 0) { for (int i = 0; i < graphProbs.size(); i++) { String compare = g.getID().replace(" (", "~"); if (compare.split("~")[0].trim().equals(graphProbs.get(i))) { histDataset.setValue(data[i], g.getSpecies(), ""); } } } } else { unableToGraph.add(g); thisOne } } } for (GraphProbs g : unableToGraph) { probGraphed.remove(g); } fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot() .getRangeAxis().getLabel(), histDataset, rend); } private void updateSpecies() { String background; try { Properties p = new Properties(); String[] split = outDir.split(separator); FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); background = outDir .substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else if (p.containsKey("learn.file")) { String[] getProp = p.getProperty("learn.file").split(separator); background = outDir .substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1]; } else { background = null; } } catch (Exception e) { JOptionPane.showMessageDialog(BioSim.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); background = null; } learnSpecs = new ArrayList<String>(); if (background != null) { if (background.contains(".gcm")) { GCMFile gcm = new GCMFile(biomodelsim.getRoot()); gcm.load(background); HashMap<String, Properties> speciesMap = gcm.getSpecies(); for (String s : speciesMap.keySet()) { learnSpecs.add(s); } } else if (background.contains(".lpn")) { LhpnFile lhpn = new LhpnFile(biomodelsim.log); lhpn.load(background); HashMap<String, Properties> speciesMap = lhpn.getContinuous(); /* * for (String s : speciesMap.keySet()) { learnSpecs.add(s); } */ // ADDED BY SB. TSDParser extractVars; ArrayList<String> datFileVars = new ArrayList<String>(); // ArrayList<String> allVars = new ArrayList<String>(); Boolean varPresent = false; // Finding the intersection of all the variables present in all // data files. for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) { extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false); datFileVars = extractVars.getSpecies(); if (i == 1) { learnSpecs.addAll(datFileVars); } for (String s : learnSpecs) { varPresent = false; for (String t : datFileVars) { if (s.equalsIgnoreCase(t)) { varPresent = true; break; } } if (!varPresent) { learnSpecs.remove(s); } } } // END ADDED BY SB. } else { SBMLDocument document = BioSim.readSBML(background); Model model = document.getModel(); ListOf ids = model.getListOfSpecies(); for (int i = 0; i < model.getNumSpecies(); i++) { learnSpecs.add(((Species) ids.get(i)).getId()); } } } for (int i = 0; i < learnSpecs.size(); i++) { String index = learnSpecs.get(i); int j = i; while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) { learnSpecs.set(j, learnSpecs.get(j - 1)); j = j - 1; } learnSpecs.set(j, index); } } public boolean getWarning() { return warn; } private class GraphProbs { private Paint paint; private String species, directory, id, paintName; private int number; private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) { this.paint = paint; this.paintName = paintName; this.species = species; this.number = number; this.directory = directory; this.id = id; } private Paint getPaint() { return paint; } private void setPaint(Paint p) { paint = p; } private String getPaintName() { return paintName; } private void setPaintName(String p) { paintName = p; } private String getSpecies() { return species; } private void setSpecies(String s) { species = s; } private String getDirectory() { return directory; } private String getID() { return id; } private int getNumber() { return number; } private void setNumber(int n) { number = n; } } private Hashtable makeIcons() { Hashtable<String, Icon> icons = new Hashtable<String, Icon>(); icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon()); icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon()); icons.put("computer", MetalIconFactory.getTreeComputerIcon()); icons.put("c", TextIcons.getIcon("c")); icons.put("java", TextIcons.getIcon("java")); icons.put("html", TextIcons.getIcon("html")); return icons; } } class IconNodeRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = -940588131120912851L; public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); Icon icon = ((IconNode) value).getIcon(); if (icon == null) { Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons"); String name = ((IconNode) value).getIconName(); if ((icons != null) && (name != null)) { icon = (Icon) icons.get(name); if (icon != null) { setIcon(icon); } } } else { setIcon(icon); } return this; } } class IconNode extends DefaultMutableTreeNode { private static final long serialVersionUID = 2887169888272379817L; protected Icon icon; protected String iconName; private String hiddenName; public IconNode() { this(null, ""); } public IconNode(Object userObject, String name) { this(userObject, true, null, name); } public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) { super(userObject, allowsChildren); this.icon = icon; hiddenName = name; } public String getName() { return hiddenName; } public void setName(String name) { hiddenName = name; } public void setIcon(Icon icon) { this.icon = icon; } public Icon getIcon() { return icon; } public String getIconName() { if (iconName != null) { return iconName; } else { String str = userObject.toString(); int index = str.lastIndexOf("."); if (index != -1) { return str.substring(++index); } else { return null; } } } public void setIconName(String name) { iconName = name; } } class TextIcons extends MetalIconFactory.TreeLeafIcon { private static final long serialVersionUID = 1623303213056273064L; protected String label; private static Hashtable<String, String> labels; protected TextIcons() { } public void paintIcon(Component c, Graphics g, int x, int y) { super.paintIcon(c, g, x, y); if (label != null) { FontMetrics fm = g.getFontMetrics(); int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2; int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2; g.drawString(label, x + offsetX, y + offsetY + fm.getHeight()); } } public static Icon getIcon(String str) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } TextIcons icon = new TextIcons(); icon.label = (String) labels.get(str); return icon; } public static void setLabelSet(String ext, String label) { if (labels == null) { labels = new Hashtable<String, String>(); setDefaultSet(); } labels.put(ext, label); } private static void setDefaultSet() { labels.put("c", "C"); labels.put("java", "J"); labels.put("html", "H"); labels.put("htm", "H"); labels.put("g", "" + (char) 10003); // and so on /* * labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc" * ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++"); * labels.put("exe" ,"BIN"); labels.put("class" ,"BIN"); * labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF"); * * labels.put("", ""); */ } }
package de.cdietze.ld37.core; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import pythagoras.i.Dimension; import react.IntValue; import react.RList; import react.Value; import tripleplay.util.Logger; import java.util.List; import static de.cdietze.ld37.core.PointUtils.isNeighbor; public class BoardState { public static final Logger log = new Logger("state"); public final Dimension dim = new Dimension(8, 8); public final int fieldCount = dim.width * dim.height; public final RList<Entity> entities = RList.create(); public final Entities.Vacuum vacuum; public final List<Value<Boolean>> explored = buildExplored(fieldCount); public final IntValue dustRemaining = new IntValue(0); public final IntValue battery = new IntValue(0); { vacuum = new Entities.Vacuum(56, Direction.UP); entities.add(vacuum); entities.add(Entities.createBase(vacuum.fieldIndex.get())); entities.add(Entities.createCable(vacuum.fieldIndex.get())); entities.add(Entities.createBase(0)); entities.add(Entities.createCable(0)); entities.add(Entities.createCable(1)); entities.add(Entities.createCable(8)); entities.add(Entities.createCable(9)); entities.add(Entities.createLint(9)); entities.add(Entities.createLint(10)); entities.add(new Entities.Dust(57, 4, dustRemaining)); entities.add(new Entities.Dust(60, 4, dustRemaining)); entities.add(new Entities.Mouse(62, Direction.UP)); explore(vacuum.fieldIndex.get()); battery.update(10); } public boolean tryMoveVacuum(int target) { if (!canMoveHere(target)) return false; vacuum.fieldIndex.update(target); explore(target); tryToCollectDust(); consumeBattery(); tryToRechargeBattery(); return false; } private boolean canMoveHere(int target) { return canMoveOneFieldHere(target) || canStayHere(target) || isExploredBase(target); } private boolean canMoveOneFieldHere(int target) { return battery.get() > 0 && isNeighbor(dim, vacuum.fieldIndex.get(), target); } private boolean canStayHere(int target) { return battery.get() > 0 && target == vacuum.fieldIndex.get() && getEntityAt(target, Entity.Type.DUST).isPresent(); } private boolean isExploredBase(int target) { return explored.get(target).get() && getEntityAt(target, Entity.Type.BASE).isPresent(); } private void tryToCollectDust() { Optional<Entity> entity = getEntityAt(vacuum.fieldIndex.get(), Entity.Type.DUST); if (!entity.isPresent()) return; Entities.Dust dust = (Entities.Dust) entity.get(); dust.dustAmount.decrementClamp(1, 0); if (dust.dustAmount.get() == 0) { entities.remove(dust); } } private void consumeBattery() { battery.decrementClamp(1, 0); } private void tryToRechargeBattery() { Optional<Entity> base = getEntityAt(vacuum.fieldIndex.get(), Entity.Type.BASE); if (base.isPresent()) { battery.update(10); } } private static List<Value<Boolean>> buildExplored(int fieldCount) { ImmutableList.Builder<Value<Boolean>> builder = ImmutableList.builder(); for (int i = 0; i < fieldCount; i++) { builder.add(Value.create(false)); } return builder.build(); } private void explore(int fieldIndex) { explored.get(fieldIndex).update(true); } private Optional<Entity> getEntityAt(int index, Entity.Type type) { for (Entity entity : entities) { if (entity.type == type && entity.fieldIndex.get() == index) return Optional.of(entity); } return Optional.absent(); } }
package learn; import gcm2sbml.parser.GCMFile; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.util.prefs.Preferences; import javax.swing.*; import org.sbml.libsbml.*; import biomodelsim.*; /** * This class creates a GUI for the Learn program. It implements the * ActionListener class. This allows the GUI to perform actions when menu items * and buttons are selected. * * @author Curtis Madsen */ public class Learn extends JPanel implements ActionListener, Runnable { private static final long serialVersionUID = -5806315070287184299L; // private JTextField initNetwork; // text field for initial network // private JButton browseInit; // the browse initial network button private JButton save, run, viewGcm, saveGcm, viewLog; // the run button private JComboBox debug; // debug combo box private JTextField activation, repression, parent; // private JTextField windowRising, windowSize; private JComboBox numBins; private JTextField influenceLevel, relaxIPDelta, letNThrough, maxVectorSize; // private JCheckBox harshenBoundsOnTie, donotInvertSortOrder, seedParents; // private JCheckBox mustNotWinMajority, donotTossSingleRatioParents, // donotTossChangedInfluenceSingleParents; private JRadioButton succ, pred, both; private JCheckBox basicFBP; private ArrayList<ArrayList<Component>> species; private JPanel speciesPanel; private JRadioButton user, auto, spacing, data; private JButton suggest; private String directory, lrnFile; private JLabel numBinsLabel; private Log log; private String separator; private BioSim biosim; private String learnFile; private boolean change; private ArrayList<String> speciesList; private boolean firstRead; /** * This is the constructor for the Learn class. It initializes all the input * fields, puts them on panels, adds the panels to the frame, and then * displays the frame. */ public Learn(String directory, Log log, BioSim biosim) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } this.biosim = biosim; this.log = log; this.directory = directory; String[] getFilename = directory.split(separator); lrnFile = getFilename[getFilename.length - 1] + ".lrn"; Preferences biosimrc = Preferences.userRoot(); // Sets up the encodings area JPanel radioPanel = new JPanel(new BorderLayout()); JPanel selection1 = new JPanel(); JPanel selection2 = new JPanel(); JPanel selection = new JPanel(new BorderLayout()); spacing = new JRadioButton("Equal Spacing Of Bins"); data = new JRadioButton("Equal Data Per Bins"); user = new JRadioButton("Use User Generated Levels"); auto = new JRadioButton("Use Auto Generated Levels"); suggest = new JButton("Suggest Levels"); ButtonGroup select = new ButtonGroup(); select.add(auto); select.add(user); ButtonGroup select2 = new ButtonGroup(); select2.add(spacing); select2.add(data); if (biosimrc.get("biosim.learn.autolevels", "").equals("Auto")) { auto.setSelected(true); } else { user.setSelected(true); } user.addActionListener(this); spacing.addActionListener(this); auto.addActionListener(this); suggest.addActionListener(this); if (biosimrc.get("biosim.learn.equaldata", "").equals("Equal Data Per Bins")) { data.setSelected(true); } else { spacing.setSelected(true); } data.addActionListener(this); selection1.add(data); selection1.add(spacing); selection2.add(auto); selection2.add(user); selection2.add(suggest); selection.add(selection1, "North"); selection.add(selection2, "Center"); suggest.setEnabled(false); JPanel encodingPanel = new JPanel(new BorderLayout()); speciesPanel = new JPanel(); JPanel sP = new JPanel(); ((FlowLayout) sP.getLayout()).setAlignment(FlowLayout.LEFT); sP.add(speciesPanel); JLabel encodingsLabel = new JLabel("Species Levels:"); JScrollPane scroll2 = new JScrollPane(); scroll2.setMinimumSize(new Dimension(260, 200)); scroll2.setPreferredSize(new Dimension(276, 132)); scroll2.setViewportView(sP); radioPanel.add(selection, "North"); radioPanel.add(encodingPanel, "Center"); encodingPanel.add(encodingsLabel, "North"); encodingPanel.add(scroll2, "Center"); // Sets up initial network and experiments text fields // JPanel initNet = new JPanel(); // JLabel initNetLabel = new JLabel("Background Knowledge Network:"); // browseInit = new JButton("Browse"); // browseInit.addActionListener(this); // initNetwork = new JTextField(39); // initNet.add(initNetLabel); // initNet.add(initNetwork); // initNet.add(browseInit); // Sets up the thresholds area JPanel thresholdPanel1 = new JPanel(new GridLayout(4, 2)); JPanel thresholdPanel2 = new JPanel(new GridLayout(8, 2)); JLabel activationLabel = new JLabel("Ratio For Activation (Ta):"); thresholdPanel2.add(activationLabel); activation = new JTextField(biosimrc.get("biosim.learn.ta", "")); // activation.addActionListener(this); thresholdPanel2.add(activation); JLabel repressionLabel = new JLabel("Ratio For Repression (Tr):"); thresholdPanel2.add(repressionLabel); repression = new JTextField(biosimrc.get("biosim.learn.tr", "")); // repression.addActionListener(this); thresholdPanel2.add(repression); JLabel influenceLevelLabel = new JLabel("Merge Influence Vectors Delta (Tm):"); thresholdPanel2.add(influenceLevelLabel); influenceLevel = new JTextField(biosimrc.get("biosim.learn.tm", "")); // influenceLevel.addActionListener(this); thresholdPanel2.add(influenceLevel); JLabel letNThroughLabel = new JLabel("Minimum Number Of Initial Vectors (Tn): "); thresholdPanel1.add(letNThroughLabel); letNThrough = new JTextField(biosimrc.get("biosim.learn.tn", "")); // letNThrough.addActionListener(this); thresholdPanel1.add(letNThrough); JLabel maxVectorSizeLabel = new JLabel("Maximum Influence Vector Size (Tj):"); thresholdPanel1.add(maxVectorSizeLabel); maxVectorSize = new JTextField(biosimrc.get("biosim.learn.tj", "")); // maxVectorSize.addActionListener(this); thresholdPanel1.add(maxVectorSize); JLabel parentLabel = new JLabel("Score For Empty Influence Vector (Ti):"); thresholdPanel1.add(parentLabel); parent = new JTextField(biosimrc.get("biosim.learn.ti", "")); parent.addActionListener(this); thresholdPanel1.add(parent); JLabel relaxIPDeltaLabel = new JLabel("Relax Thresholds Delta (Tt):"); thresholdPanel2.add(relaxIPDeltaLabel); relaxIPDelta = new JTextField(biosimrc.get("biosim.learn.tt", "")); // relaxIPDelta.addActionListener(this); thresholdPanel2.add(relaxIPDelta); numBinsLabel = new JLabel("Number Of Bins:"); String[] bins = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; numBins = new JComboBox(bins); numBins.setSelectedItem(biosimrc.get("biosim.learn.bins", "")); numBins.addActionListener(this); thresholdPanel1.add(numBinsLabel); thresholdPanel1.add(numBins); JPanel thresholdPanelHold1 = new JPanel(); thresholdPanelHold1.add(thresholdPanel1); JLabel debugLabel = new JLabel("Debug Level:"); String[] options = new String[4]; options[0] = "0"; options[1] = "1"; options[2] = "2"; options[3] = "3"; debug = new JComboBox(options); debug.setSelectedItem(biosimrc.get("biosim.learn.debug", "")); debug.addActionListener(this); thresholdPanel2.add(debugLabel); thresholdPanel2.add(debug); succ = new JRadioButton("Successors"); pred = new JRadioButton("Predecessors"); both = new JRadioButton("Both"); if (biosimrc.get("biosim.learn.succpred", "").equals("Successors")) { succ.setSelected(true); } else if (biosimrc.get("biosim.learn.succpred", "").equals("Predecessors")) { pred.setSelected(true); } else { both.setSelected(true); } succ.addActionListener(this); pred.addActionListener(this); both.addActionListener(this); basicFBP = new JCheckBox("Basic FindBaseProb"); if (biosimrc.get("biosim.learn.findbaseprob", "").equals("True")) { basicFBP.setSelected(true); } else { basicFBP.setSelected(false); } basicFBP.addActionListener(this); ButtonGroup succOrPred = new ButtonGroup(); succOrPred.add(succ); succOrPred.add(pred); succOrPred.add(both); JPanel three = new JPanel(); three.add(succ); three.add(pred); three.add(both); ((FlowLayout) three.getLayout()).setAlignment(FlowLayout.LEFT); thresholdPanel2.add(three); thresholdPanel2.add(new JPanel()); thresholdPanel2.add(basicFBP); thresholdPanel2.add(new JPanel()); JPanel thresholdPanelHold2 = new JPanel(); thresholdPanelHold2.add(thresholdPanel2); /* * JLabel windowRisingLabel = new JLabel("Window Rising Amount:"); * windowRising = new JTextField("1"); * thresholdPanel2.add(windowRisingLabel); * thresholdPanel2.add(windowRising); JLabel windowSizeLabel = new * JLabel("Window Size:"); windowSize = new JTextField("1"); * thresholdPanel2.add(windowSizeLabel); thresholdPanel2.add(windowSize); * harshenBoundsOnTie = new JCheckBox("Harshen Bounds On Tie"); * harshenBoundsOnTie.setSelected(true); donotInvertSortOrder = new * JCheckBox("Do Not Invert Sort Order"); * donotInvertSortOrder.setSelected(true); seedParents = new * JCheckBox("Parents Should Be Ranked By Score"); * seedParents.setSelected(true); mustNotWinMajority = new JCheckBox("Must * Not Win Majority"); mustNotWinMajority.setSelected(true); * donotTossSingleRatioParents = new JCheckBox("Single Ratio Parents Should * Be Kept"); donotTossChangedInfluenceSingleParents = new JCheckBox( * "Parents That Change Influence Should Not Be Tossed"); * thresholdPanel2.add(harshenBoundsOnTie); * thresholdPanel2.add(donotInvertSortOrder); * thresholdPanel2.add(seedParents); * thresholdPanel2.add(mustNotWinMajority); * thresholdPanel2.add(donotTossSingleRatioParents); * thresholdPanel2.add(donotTossChangedInfluenceSingleParents); */ // load parameters Properties load = new Properties(); learnFile = ""; try { FileInputStream in = new FileInputStream(new File(directory + separator + lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { String[] getProp = load.getProperty("genenet.file").split(separator); learnFile = directory.substring(0, directory.length() - getFilename[getFilename.length - 1].length()) + separator + getProp[getProp.length - 1]; } if (load.containsKey("genenet.Tn")) { letNThrough.setText(load.getProperty("genenet.Tn")); } if (load.containsKey("genenet.Tj")) { maxVectorSize.setText(load.getProperty("genenet.Tj")); } if (load.containsKey("genenet.Ti")) { parent.setText(load.getProperty("genenet.Ti")); } if (load.containsKey("genenet.Ta")) { activation.setText(load.getProperty("genenet.Ta")); } if (load.containsKey("genenet.Tr")) { repression.setText(load.getProperty("genenet.Tr")); } if (load.containsKey("genenet.Tm")) { influenceLevel.setText(load.getProperty("genenet.Tm")); } if (load.containsKey("genenet.Tt")) { relaxIPDelta.setText(load.getProperty("genenet.Tt")); } if (load.containsKey("genenet.bins")) { numBins.setSelectedItem(load.getProperty("genenet.bins")); } if (load.containsKey("genenet.debug")) { debug.setSelectedItem(load.getProperty("genenet.debug")); } if (load.containsKey("genenet.equal")) { if (load.getProperty("genenet.equal").equals("data")) { data.setSelected(true); } else { spacing.setSelected(true); } } if (load.containsKey("genenet.use")) { if (load.getProperty("genenet.use").equals("auto")) { auto.setSelected(true); } else { user.setSelected(true); } } if (load.containsKey("genenet.find.base.prob")) { if (load.getProperty("genenet.find.base.prob").equals("true")) { basicFBP.setSelected(true); } } if (load.containsKey("genenet.data.type")) { if (load.getProperty("genenet.data.type").equals("succ")) { succ.setSelected(true); } else if (load.getProperty("genenet.data.type").equals("pred")) { pred.setSelected(true); } else { both.setSelected(true); } } } catch (Exception e) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } speciesList = new ArrayList<String>(); if ((learnFile.contains(".sbml")) || (learnFile.contains(".xml"))) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(learnFile); Model model = document.getModel(); ListOf ids = model.getListOfSpecies(); try { FileWriter write = new FileWriter(new File(directory + separator + "background.gcm")); write.write("digraph G {\n"); for (int i = 0; i < model.getNumSpecies(); i++) { speciesList.add(((Species) ids.get(i)).getId()); write.write("s" + i + " [shape=ellipse,color=black,label=\"" + ((Species) ids.get(i)).getId() + "\"" + "];\n"); } write.write("}\n"); write.close(); } catch (Exception e) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to create background file!", "Error Writing Background", JOptionPane.ERROR_MESSAGE); } } else { GCMFile gcm = new GCMFile(); gcm.load(learnFile); HashMap<String, Properties> speciesMap = gcm.getSpecies(); for (String s : speciesMap.keySet()) { speciesList.add(s); } try { FileWriter write = new FileWriter(new File(directory + separator + "background.gcm")); BufferedReader input = new BufferedReader(new FileReader(new File(learnFile))); String line = null; while ((line = input.readLine()) != null) { write.write(line + "\n"); } write.close(); input.close(); } catch (Exception e) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to create background file!", "Error Writing Background", JOptionPane.ERROR_MESSAGE); } } sortSpecies(); JPanel runHolder = new JPanel(); // Creates the run button run = new JButton("Save and Learn"); runHolder.add(run); run.addActionListener(this); run.setMnemonic(KeyEvent.VK_L); // Creates the run button save = new JButton("Save Parameters"); runHolder.add(save); save.addActionListener(this); save.setMnemonic(KeyEvent.VK_S); // Creates the view circuit button viewGcm = new JButton("View Circuit"); runHolder.add(viewGcm); viewGcm.addActionListener(this); viewGcm.setMnemonic(KeyEvent.VK_V); // Creates the save circuit button saveGcm = new JButton("Save Circuit"); runHolder.add(saveGcm); saveGcm.addActionListener(this); saveGcm.setMnemonic(KeyEvent.VK_C); // Creates the view circuit button viewLog = new JButton("View Run Log"); runHolder.add(viewLog); viewLog.addActionListener(this); viewLog.setMnemonic(KeyEvent.VK_R); if (!(new File(directory + separator + "method.gcm").exists())) { viewGcm.setEnabled(false); saveGcm.setEnabled(false); } if (!(new File(directory + separator + "run.log").exists())) { viewLog.setEnabled(false); } // Creates the main panel this.setLayout(new BorderLayout()); JPanel middlePanel = new JPanel(new BorderLayout()); JPanel firstTab = new JPanel(new BorderLayout()); JPanel firstTab1 = new JPanel(new BorderLayout()); JPanel secondTab = new JPanel(new BorderLayout()); middlePanel.add(radioPanel, "Center"); // firstTab1.add(initNet, "North"); firstTab1.add(thresholdPanelHold1, "Center"); firstTab.add(firstTab1, "North"); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, middlePanel, null); splitPane.setDividerSize(0); secondTab.add(thresholdPanelHold2, "North"); firstTab.add(splitPane, "Center"); JTabbedPane tab = new JTabbedPane(); tab.addTab("Basic Options", firstTab); tab.addTab("Advanced Options", secondTab); this.add(tab, "Center"); this.add(runHolder, "South"); firstRead = true; if (user.isSelected()) { auto.doClick(); user.doClick(); } else { user.doClick(); auto.doClick(); } firstRead = false; change = false; } /** * This method performs different functions depending on what menu items or * buttons are selected. */ public void actionPerformed(ActionEvent e) { /* * if (e.getActionCommand().contains("box")) { int num = * Integer.parseInt(e.getActionCommand().substring(3)) - 1; if * (!((JCheckBox) this.species.get(num).get(0)).isSelected()) { ((JComboBox) * this.species.get(num).get(2)).setSelectedItem("0"); editText(num); * speciesPanel.revalidate(); speciesPanel.repaint(); for (int i = 1; i < * this.species.get(num).size(); i++) { * this.species.get(num).get(i).setEnabled(false); } } else { * this.species.get(num).get(1).setEnabled(true); if (user.isSelected()) { * for (int i = 2; i < this.species.get(num).size(); i++) { * this.species.get(num).get(i).setEnabled(true); } } } } else */ change = true; if (e.getActionCommand().contains("text")) { int num = Integer.parseInt(e.getActionCommand().substring(4)) - 1; editText(num); speciesPanel.revalidate(); speciesPanel.repaint(); } else if (e.getSource() == user) { if (!firstRead) { try { FileWriter write = new FileWriter(new File(directory + separator + "levels.lvl")); write.write("time, 0\n"); for (int i = 0; i < species.size(); i++) { if (((JTextField) species.get(i).get(0)).getText().trim().equals("")) { write.write("-1"); } else { write.write(((JTextField) species.get(i).get(0)).getText().trim()); } write.write(", " + ((JComboBox) species.get(i).get(1)).getSelectedItem()); for (int j = 2; j < species.get(i).size(); j++) { if (((JTextField) species.get(i).get(j)).getText().trim().equals("")) { write.write(", -1"); } else { write.write(", " + ((JTextField) species.get(i).get(j)).getText().trim()); } } write.write("\n"); } write.close(); } catch (Exception e1) { } } numBinsLabel.setEnabled(false); numBins.setEnabled(false); suggest.setEnabled(true); // levelsBin(); speciesPanel.revalidate(); speciesPanel.repaint(); levels(true); } else if (e.getSource() == auto) { numBinsLabel.setEnabled(true); numBins.setEnabled(true); suggest.setEnabled(false); for (Component c : speciesPanel.getComponents()) { for (int i = 1; i < ((JPanel) c).getComponentCount(); i++) { ((JPanel) c).getComponent(i).setEnabled(false); } } } else if (e.getSource() == suggest) { levels(false); speciesPanel.revalidate(); speciesPanel.repaint(); } // if the browse initial network button is clicked // else if (e.getSource() == browseInit) { // Buttons.browse(this, new File(initNetwork.getText().trim()), // initNetwork, // JFileChooser.FILES_ONLY, "Open"); // if the run button is selected else if (e.getSource() == run) { save(); new Thread(this).start(); } else if (e.getSource() == save) { save(); } else if (e.getSource() == viewGcm) { viewGcm(); } else if (e.getSource() == viewLog) { viewLog(); } else if (e.getSource() == saveGcm) { saveGcm(); } } private void levels(boolean readfile) { ArrayList<String> str = null; try { if (!readfile) { FileWriter write = new FileWriter(new File(directory + separator + "levels.lvl")); write.write("time, 0\n"); for (int i = 0; i < species.size(); i++) { if (((JTextField) species.get(i).get(0)).getText().trim().equals("")) { write.write("-1"); } else { write.write(((JTextField) species.get(i).get(0)).getText().trim()); } write.write(", " + ((JComboBox) species.get(i).get(1)).getSelectedItem()); for (int j = 2; j < species.get(i).size(); j++) { if (((JTextField) species.get(i).get(j)).getText().trim().equals("")) { write.write(", -1"); } else { write.write(", " + ((JTextField) species.get(i).get(j)).getText().trim()); } } write.write("\n"); } write.close(); String geneNet = ""; if (spacing.isSelected()) { geneNet = "GeneNet --readLevels --lvl -binN ."; } else { geneNet = "GeneNet --readLevels --lvl ."; } log.addText("Executing:\n" + geneNet + " " + directory + "\n"); Runtime exec = Runtime.getRuntime(); File work = new File(directory); Process learn = exec.exec(geneNet, null, work); try { String output = ""; InputStream reb = learn.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); FileWriter out = new FileWriter(new File(directory + separator + "run.log")); while ((output = br.readLine()) != null) { out.write(output); out.write("\n"); } out.close(); br.close(); isr.close(); reb.close(); viewLog.setEnabled(true); } catch (Exception e) { } learn.waitFor(); } Scanner f = new Scanner(new File(directory + separator + "levels.lvl")); str = new ArrayList<String>(); while (f.hasNextLine()) { str.add(f.nextLine()); } } catch (Exception e1) { } if (!directory.equals("")) { // File n = null; // for (File f : new File(directory).listFiles()) { // if (f.getAbsolutePath().contains(".tsd")) { // n = f; if (true) { // if (n != null) { // ArrayList<String> species = new ArrayList<String>(); // try { // InputStream input = new FileInputStream(n); // boolean reading = true; // char cha; // while (reading) { // String word = ""; // boolean readWord = true; // while (readWord) { // int read = input.read(); // if (read == -1) { // reading = false; // readWord = false; // cha = (char) read; // if (Character.isWhitespace(cha)) { // word += cha; // else if (cha == ',' || cha == ':' || cha == ';' || cha == '\"' || cha // || cha == '(' || cha == ')' || cha == '[' || cha == ']') { // if (!word.equals("") && !word.equals("time")) { // try { // Double.parseDouble(word); // catch (Exception e2) { // species.add(word); // word = ""; // else if (read != -1) { // word += cha; // input.close(); // catch (Exception e1) { speciesPanel.removeAll(); this.species = new ArrayList<ArrayList<Component>>(); speciesPanel.setLayout(new GridLayout(speciesList.size() + 1, 1)); int max = 0; if (str != null) { for (String st : str) { String[] getString = st.split(","); max = Math.max(max, getString.length + 1); } } JPanel label = new JPanel(new GridLayout()); // label.add(new JLabel("Use")); label.add(new JLabel("Species")); label.add(new JLabel("Number Of Bins")); for (int i = 0; i < max - 3; i++) { label.add(new JLabel("Level " + (i + 1))); } speciesPanel.add(label); int j = 0; for (String s : speciesList) { j++; JPanel sp = new JPanel(new GridLayout()); ArrayList<Component> specs = new ArrayList<Component>(); // JCheckBox check = new JCheckBox(); // check.setSelected(true); // specs.add(check); specs.add(new JTextField(s)); String[] options = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; JComboBox combo = new JComboBox(options); combo.setSelectedItem(numBins.getSelectedItem()); specs.add(combo); ((JTextField) specs.get(0)).setEditable(false); // sp.add(specs.get(0)); // ((JCheckBox) specs.get(0)).addActionListener(this); // ((JCheckBox) specs.get(0)).setActionCommand("box" + j); sp.add(specs.get(0)); sp.add(specs.get(1)); ((JComboBox) specs.get(1)).addActionListener(this); ((JComboBox) specs.get(1)).setActionCommand("text" + j); this.species.add(specs); if (str != null) { boolean found = false; for (String st : str) { String[] getString = st.split(","); if (getString[0].trim().equals(s)) { found = true; if (getString.length >= 2) { ((JComboBox) specs.get(1)).setSelectedItem(getString[1].trim()); for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(1)) .getSelectedItem()) - 1; i++) { if (getString[i + 2].trim().equals("-1")) { specs.add(new JTextField("")); } else { specs.add(new JTextField(getString[i + 2].trim())); } sp.add(specs.get(i + 2)); } for (int i = Integer.parseInt((String) ((JComboBox) specs.get(1)) .getSelectedItem()) - 1; i < max - 3; i++) { sp.add(new JLabel()); } } } } if (!found) { for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(1)) .getSelectedItem()) - 1; i++) { specs.add(new JTextField("")); sp.add(specs.get(i + 2)); } for (int i = Integer.parseInt((String) ((JComboBox) specs.get(1)).getSelectedItem()) - 1; i < max - 3; i++) { sp.add(new JLabel()); } } } else { for (int i = 0; i < Integer.parseInt((String) ((JComboBox) specs.get(1)) .getSelectedItem()) - 1; i++) { specs.add(new JTextField("")); sp.add(specs.get(i + 2)); } } speciesPanel.add(sp); } } } editText(0); } /* * private void levelsBin() { if (!directory.equals("")) { // File n = null; // * for (File f : new File(directory).listFiles()) { // if * (f.getAbsolutePath().contains(".tsd")) { // n = f; // } // } if (true) { // * if (n != null) { // ArrayList<String> species = new ArrayList<String>(); // * try { // InputStream input = new FileInputStream(n); // boolean reading = * true; // char cha; // while (reading) { // String word = ""; // boolean * readWord = true; // while (readWord) { // int read = input.read(); // if * (read == -1) { // reading = false; // readWord = false; // } // cha = * (char) read; // if (Character.isWhitespace(cha)) { // word += cha; // } // * else if (cha == ',' || cha == ':' || cha == ';' || cha == '\"' || cha // == * '\'' // || cha == '(' || cha == ')' || cha == '[' || cha == ']') { // if * (!word.equals("") && !word.equals("time")) { // try { // * Double.parseDouble(word); // } // catch (Exception e2) { // * species.add(word); // } // } // word = ""; // } // else if (read != -1) { // * word += cha; // } // } // } // input.close(); // } // catch (Exception e1) { // } * speciesPanel.removeAll(); this.species = new ArrayList<ArrayList<Component>>(); * speciesPanel.setLayout(new GridLayout(speciesList.size() + 1, 1)); JPanel * label = new JPanel(new GridLayout()); // label.add(new JLabel("Use")); * label.add(new JLabel("Species")); label.add(new JLabel("Number Of Bins")); * for (int i = 0; i < Integer.parseInt((String) numBins.getSelectedItem()) - * 1; i++) { label.add(new JLabel("Level " + (i + 1))); } * speciesPanel.add(label); int j = 0; for (String s : speciesList) { j++; * JPanel sp = new JPanel(new GridLayout()); ArrayList<Component> specs = new * ArrayList<Component>(); // JCheckBox check = new JCheckBox(); // * check.setSelected(true); // specs.add(check); specs.add(new JTextField(s)); * String[] options = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; * JComboBox combo = new JComboBox(options); * combo.setSelectedItem(numBins.getSelectedItem()); specs.add(combo); * ((JTextField) specs.get(0)).setEditable(false); // sp.add(specs.get(0)); // * ((JCheckBox) specs.get(0)).addActionListener(this); // ((JCheckBox) * specs.get(0)).setActionCommand("box" + j); sp.add(specs.get(0)); * sp.add(specs.get(1)); ((JComboBox) specs.get(1)).addActionListener(this); * ((JComboBox) specs.get(1)).setActionCommand("text" + j); * this.species.add(specs); for (int i = 0; i < Integer.parseInt((String) * ((JComboBox) specs.get(1)) .getSelectedItem()) - 1; i++) { specs.add(new * JTextField("")); sp.add(specs.get(i + 2)); } speciesPanel.add(sp); } } } } */ private void editText(int num) { try { ArrayList<Component> specs = species.get(num); Component[] panels = speciesPanel.getComponents(); int boxes = Integer.parseInt((String) ((JComboBox) specs.get(1)).getSelectedItem()); if ((specs.size() - 2) < boxes) { for (int i = 0; i < boxes - 1; i++) { try { specs.get(i + 2); } catch (Exception e1) { JTextField temp = new JTextField(""); ((JPanel) panels[num + 1]).add(temp); specs.add(temp); } } } else { try { if (boxes > 0) { while (true) { specs.remove(boxes + 1); ((JPanel) panels[num + 1]).remove(boxes + 1); } } else if (boxes == 0) { while (true) { specs.remove(2); ((JPanel) panels[num + 1]).remove(2); } } } catch (Exception e1) { } } int max = 0; for (int i = 0; i < this.species.size(); i++) { max = Math.max(max, species.get(i).size()); } if (((JPanel) panels[0]).getComponentCount() < max) { for (int i = 0; i < max - 2; i++) { try { ((JPanel) panels[0]).getComponent(i + 2); } catch (Exception e) { ((JPanel) panels[0]).add(new JLabel("Level " + (i + 1))); } } } else { try { while (true) { ((JPanel) panels[0]).remove(max); } } catch (Exception e) { } } for (int i = 1; i < panels.length; i++) { JPanel sp = (JPanel) panels[i]; for (int j = sp.getComponentCount() - 1; j >= 2; j if (sp.getComponent(j) instanceof JLabel) { sp.remove(j); } } if (max > sp.getComponentCount()) { for (int j = sp.getComponentCount(); j < max; j++) { sp.add(new JLabel()); } } else { for (int j = sp.getComponentCount() - 2; j >= max; j sp.remove(j); } } } } catch (Exception e) { } } public void saveGcm() { try { if (new File(directory + separator + "method.gcm").exists()) { String copy = JOptionPane.showInputDialog(biosim.frame(), "Enter Circuit Name:", "Save Circuit", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } if (!copy.equals("")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".gcm")) { copy += ".gcm"; } } else { copy += ".gcm"; } } biosim.saveGcm(copy, directory + separator + "method.gcm"); } else { JOptionPane.showMessageDialog(biosim.frame(), "No circuit has been generated yet.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to save circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } public void viewGcm() { try { File work = new File(directory); if (new File(directory + separator + "method.gcm").exists()) { if (System.getProperty("os.name").contentEquals("Linux")) { String command = "dotty method.gcm"; log.addText("Executing:\n" + "dotty " + directory + separator + "method.gcm\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { String command = "open method.dot"; log.addText("Executing:\n" + "open " + directory + separator + "method.dot\n"); Runtime exec = Runtime.getRuntime(); exec.exec("cp method.gcm method.dot", null, work); exec = Runtime.getRuntime(); exec.exec(command, null, work); } else { String command = "dotty method.gcm"; log.addText("Executing:\n" + "dotty " + directory + separator + "method.gcm\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command, null, work); } } else { JOptionPane.showMessageDialog(biosim.frame(), "No circuit has been generated yet.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to view circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } public void viewLog() { try { if (new File(directory + separator + "run.log").exists()) { File log = new File(directory + separator + "run.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Run Log", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(biosim.frame(), "No run log exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to view run log.", "Error", JOptionPane.ERROR_MESSAGE); } } public void save() { try { Properties prop = new Properties(); FileInputStream in = new FileInputStream(new File(directory + separator + lrnFile)); prop.load(in); in.close(); prop.setProperty("genenet.file", learnFile); prop.setProperty("genenet.Tn", this.letNThrough.getText().trim()); prop.setProperty("genenet.Tj", this.maxVectorSize.getText().trim()); prop.setProperty("genenet.Ti", this.parent.getText().trim()); prop.setProperty("genenet.Ta", this.activation.getText().trim()); prop.setProperty("genenet.Tr", this.repression.getText().trim()); prop.setProperty("genenet.Tm", this.influenceLevel.getText().trim()); prop.setProperty("genenet.Tt", this.relaxIPDelta.getText().trim()); prop.setProperty("genenet.bins", (String) this.numBins.getSelectedItem()); prop.setProperty("genenet.debug", (String) this.debug.getSelectedItem()); if (spacing.isSelected()) { prop.setProperty("genenet.equal", "spacing"); } else { prop.setProperty("genenet.equal", "data"); } if (auto.isSelected()) { prop.setProperty("genenet.use", "auto"); } else { prop.setProperty("genenet.use", "user"); } if (succ.isSelected()) { prop.setProperty("genenet.data.type", "succ"); } else if (pred.isSelected()) { prop.setProperty("genenet.data.type", "pred"); } else { prop.setProperty("genenet.data.type", "both"); } if (basicFBP.isSelected()) { prop.setProperty("genenet.find.base.prob", "true"); } else { prop.setProperty("genenet.find.base.prob", "false"); } log.addText("Saving learn parameters to file:\n" + directory + separator + lrnFile + "\n"); FileOutputStream out = new FileOutputStream(new File(directory + separator + lrnFile)); prop.store(out, learnFile); out.close(); log.addText("Creating levels file:\n" + directory + separator + "levels.lvl\n"); FileWriter write = new FileWriter(new File(directory + separator + "levels.lvl")); write.write("time, 0\n"); for (int i = 0; i < species.size(); i++) { if (((JTextField) species.get(i).get(0)).getText().trim().equals("")) { write.write("-1"); } else { write.write(((JTextField) species.get(i).get(0)).getText().trim()); } write.write(", " + ((JComboBox) species.get(i).get(1)).getSelectedItem()); for (int j = 2; j < species.get(i).size(); j++) { if (((JTextField) species.get(i).get(j)).getText().trim().equals("")) { write.write(", -1"); } else { write.write(", " + ((JTextField) species.get(i).get(j)).getText().trim()); } } write.write("\n"); } write.close(); change = false; } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } } public void run() { try { String geneNet = "GeneNet"; geneNet += " --debug " + debug.getSelectedItem(); try { double activation = Double.parseDouble(this.activation.getText().trim()); geneNet += " -ta " + activation; double repression = Double.parseDouble(this.repression.getText().trim()); geneNet += " -tr " + repression; double parent = Double.parseDouble(this.parent.getText().trim()); geneNet += " -ti " + parent; // int windowRising = // Integer.parseInt(this.windowRising.getText().trim()); // geneNet += " --windowRisingAmount " + windowRising; // int windowSize = // Integer.parseInt(this.windowSize.getText().trim()); // geneNet += " --windowSize " + windowSize; int numBins = Integer.parseInt((String) this.numBins.getSelectedItem()); geneNet += " --numBins " + numBins; double influenceLevel = Double.parseDouble(this.influenceLevel.getText().trim()); geneNet += " -tm " + influenceLevel; double relaxIPDelta = Double.parseDouble(this.relaxIPDelta.getText().trim()); geneNet += " -tt " + relaxIPDelta; int letNThrough = Integer.parseInt(this.letNThrough.getText().trim()); geneNet += " -tn " + letNThrough; int maxVectorSize = Integer.parseInt(this.maxVectorSize.getText().trim()); geneNet += " -tj " + maxVectorSize; if (succ.isSelected()) { } if (pred.isSelected()) { geneNet += " -noSUCC -PRED"; } if (both.isSelected()) { geneNet += " -PRED"; } if (basicFBP.isSelected()) { geneNet += " -basicFBP"; } } catch (Exception e2) { JOptionPane.showMessageDialog(this, "Must enter numbers into input fields.", "Error", JOptionPane.ERROR_MESSAGE); } if (user.isSelected()) { FileWriter write = new FileWriter(new File(directory + separator + "levels.lvl")); write.write("time, 0\n"); for (int i = 0; i < species.size(); i++) { if (((JTextField) species.get(i).get(0)).getText().trim().equals("")) { write.write("-1"); } else { write.write(((JTextField) species.get(i).get(0)).getText().trim()); } write.write(", " + ((JComboBox) species.get(i).get(1)).getSelectedItem()); for (int j = 2; j < species.get(i).size(); j++) { if (((JTextField) species.get(i).get(j)).getText().trim().equals("")) { write.write(", -1"); } else { write.write(", " + ((JTextField) species.get(i).get(j)).getText().trim()); } } write.write("\n"); } write.close(); geneNet += " --readLevels"; } geneNet += " --cpp_harshenBoundsOnTie --cpp_cmp_output_donotInvertSortOrder --cpp_seedParents --cmp_score_mustNotWinMajority"; /* * if (harshenBoundsOnTie.isSelected()) { geneNet += " * --cpp_harshenBoundsOnTie"; } if (donotInvertSortOrder.isSelected()) { * geneNet += " --cpp_cmp_output_donotInvertSortOrder"; } if * (seedParents.isSelected()) { geneNet += " --cpp_seedParents"; } if * (mustNotWinMajority.isSelected()) { geneNet += " * --cmp_score_mustNotWinMajority"; } if * (donotTossSingleRatioParents.isSelected()) { geneNet += " * --score_donotTossSingleRatioParents"; } if * (donotTossChangedInfluenceSingleParents.isSelected()) { geneNet += " * --output_donotTossChangedInfluenceSingleParents"; } */ if (spacing.isSelected()) { geneNet += " -binN"; } final JButton cancel = new JButton("Cancel"); final JFrame running = new JFrame("Progress"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { cancel.doClick(); running.dispose(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; running.addWindowListener(w); JPanel text = new JPanel(); JPanel progBar = new JPanel(); JPanel button = new JPanel(); JPanel all = new JPanel(new BorderLayout()); JLabel label = new JLabel("Running..."); JProgressBar progress = new JProgressBar(0, species.size()); progress.setStringPainted(true); // progress.setString(""); progress.setValue(0); text.add(label); progBar.add(progress); button.add(cancel); all.add(text, "North"); all.add(progBar, "Center"); all.add(button, "South"); running.setContentPane(all); running.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = running.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; running.setLocation(x, y); running.setVisible(true); running.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Runtime exec = Runtime.getRuntime(); log.addText("Executing:\n" + geneNet + " " + directory + "\n"); geneNet += " ."; File work = new File(directory); final Process learn = exec.exec(geneNet, null, work); cancel.setActionCommand("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { learn.destroy(); running.setCursor(null); running.dispose(); } }); biosim.getExitButton().setActionCommand("Exit program"); biosim.getExitButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { learn.destroy(); running.setCursor(null); running.dispose(); } }); try { String output = ""; InputStream reb = learn.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); FileWriter out = new FileWriter(new File(directory + separator + "run.log")); int count = 0; while ((output = br.readLine()) != null) { if (output.startsWith("Gene = ", 0)) { // log.addText(output); count++; progress.setValue(count); } out.write(output); out.write("\n"); } br.close(); isr.close(); reb.close(); out.close(); viewLog.setEnabled(true); } catch (Exception e) { } int exitValue = learn.waitFor(); if (exitValue == 143) { JOptionPane.showMessageDialog(biosim.frame(), "Learning was" + " canceled by the user.", "Canceled Learning", JOptionPane.ERROR_MESSAGE); } else { if (new File(directory + separator + "method.gcm").exists()) { if (System.getProperty("os.name").contentEquals("Linux")) { String command = "dotty method.gcm"; log.addText("Executing:\n" + "dotty " + directory + separator + "method.gcm\n"); exec = Runtime.getRuntime(); exec.exec(command, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { String command = "open method.dot"; log.addText("Executing:\n" + "open " + directory + separator + "method.dot\n"); exec = Runtime.getRuntime(); exec.exec("cp method.gcm method.dot", null, work); exec = Runtime.getRuntime(); exec.exec(command, null, work); } else { String command = "dotty method.gcm"; log.addText("Executing:\n" + "dotty " + directory + separator + "method.gcm\n"); exec = Runtime.getRuntime(); exec.exec(command, null, work); } } else { JOptionPane.showMessageDialog(biosim.frame(), "A gcm file was not generated." + "\nPlease see the run.log file.", "Error", JOptionPane.ERROR_MESSAGE); } running.setCursor(null); running.dispose(); if (new File(directory + separator + "method.gcm").exists()) { viewGcm.setEnabled(true); saveGcm.setEnabled(true); } if (new File(directory + separator + "run.log").exists()) { viewLog.setEnabled(true); } } } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to learn from data.", "Error", JOptionPane.ERROR_MESSAGE); } } public boolean hasChanged() { return change; } public boolean getViewGcmEnabled() { return viewGcm.isEnabled(); } public boolean getSaveGcmEnabled() { return saveGcm.isEnabled(); } public boolean getViewLogEnabled() { return viewLog.isEnabled(); } public void updateSpecies(String newLearnFile) { learnFile = newLearnFile; speciesList = new ArrayList<String>(); if ((learnFile.contains(".sbml")) || (learnFile.contains(".xml"))) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(learnFile); Model model = document.getModel(); ListOf ids = model.getListOfSpecies(); try { FileWriter write = new FileWriter(new File(directory + separator + "background.gcm")); write.write("digraph G {\n"); for (int i = 0; i < model.getNumSpecies(); i++) { speciesList.add(((Species) ids.get(i)).getId()); write.write("s" + i + " [shape=ellipse,color=black,label=\"" + ((Species) ids.get(i)).getId() + "\"" + "];\n"); } write.write("}\n"); write.close(); } catch (Exception e) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to create background file!", "Error Writing Background", JOptionPane.ERROR_MESSAGE); } } else { GCMFile gcm = new GCMFile(); gcm.load(learnFile); HashMap<String, Properties> speciesMap = gcm.getSpecies(); for (String s : speciesMap.keySet()) { speciesList.add(s); } try { FileWriter write = new FileWriter(new File(directory + separator + "background.gcm")); BufferedReader input = new BufferedReader(new FileReader(new File(learnFile))); String line = null; while ((line = input.readLine()) != null) { write.write(line + "\n"); } write.close(); input.close(); } catch (Exception e) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to create background file!", "Error Writing Background", JOptionPane.ERROR_MESSAGE); } } sortSpecies(); if (user.isSelected()) { auto.doClick(); user.doClick(); } else { user.doClick(); auto.doClick(); } } private void sortSpecies() { int i, j; String index; for (i = 1; i < speciesList.size(); i++) { index = speciesList.get(i); j = i; while ((j > 0) && speciesList.get(j - 1).compareToIgnoreCase(index) > 0) { speciesList.set(j, speciesList.get(j - 1)); j = j - 1; } speciesList.set(j, index); } } public void setDirectory(String directory) { this.directory = directory; String[] getFilename = directory.split(separator); lrnFile = getFilename[getFilename.length - 1] + ".lrn"; } }
package lucee.runtime.config; import static lucee.runtime.db.DatasourceManagerImpl.QOQ_DATASOURCE_NAME; import static org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength.SOFT; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.TimeZone; import lucee.commons.io.CharsetUtil; import lucee.commons.io.SystemUtil; import lucee.commons.io.cache.Cache; import lucee.commons.io.log.Log; import lucee.commons.io.log.LoggerAndSourceData; import lucee.commons.io.log.log4j.Log4jUtil; import lucee.commons.io.log.log4j.layout.ClassicLayout; import lucee.commons.io.res.Resource; import lucee.commons.io.res.ResourceProvider; import lucee.commons.io.res.Resources; import lucee.commons.io.res.ResourcesImpl; import lucee.commons.io.res.filter.ExtensionResourceFilter; import lucee.commons.io.res.type.compress.Compress; import lucee.commons.io.res.type.compress.CompressResource; import lucee.commons.io.res.type.compress.CompressResourceProvider; import lucee.commons.io.res.util.ResourceClassLoader; import lucee.commons.io.res.util.ResourceUtil; import lucee.commons.lang.CharSet; import lucee.commons.lang.ClassException; import lucee.commons.lang.ClassUtil; import lucee.commons.lang.ExceptionUtil; import lucee.commons.lang.Md5; import lucee.commons.lang.PhysicalClassLoader; import lucee.commons.lang.StringUtil; import lucee.commons.lang.SystemOut; import lucee.commons.net.IPRange; import lucee.loader.engine.CFMLEngine; import lucee.runtime.CIPage; import lucee.runtime.Component; import lucee.runtime.Mapping; import lucee.runtime.MappingImpl; import lucee.runtime.Page; import lucee.runtime.PageContext; import lucee.runtime.PageContextImpl; import lucee.runtime.PageSource; import lucee.runtime.PageSourceImpl; import lucee.runtime.cache.CacheConnection; import lucee.runtime.cache.ram.RamCache; import lucee.runtime.cache.tag.CacheHandler; import lucee.runtime.cfx.CFXTagPool; import lucee.runtime.cfx.customtag.CFXTagPoolImpl; import lucee.runtime.component.ImportDefintion; import lucee.runtime.component.ImportDefintionImpl; import lucee.runtime.customtag.InitFile; import lucee.runtime.db.ClassDefinition; import lucee.runtime.db.DataSource; import lucee.runtime.db.DatasourceConnectionPool; import lucee.runtime.db.JDBCDriver; import lucee.runtime.dump.DumpWriter; import lucee.runtime.dump.DumpWriterEntry; import lucee.runtime.dump.HTMLDumpWriter; import lucee.runtime.engine.ExecutionLogFactory; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.ApplicationException; import lucee.runtime.exp.DatabaseException; import lucee.runtime.exp.DeprecatedException; import lucee.runtime.exp.ExpressionException; import lucee.runtime.exp.PageException; import lucee.runtime.exp.PageRuntimeException; import lucee.runtime.exp.SecurityException; import lucee.runtime.exp.TemplateException; import lucee.runtime.extension.Extension; import lucee.runtime.extension.ExtensionDefintion; import lucee.runtime.extension.ExtensionProvider; import lucee.runtime.extension.RHExtension; import lucee.runtime.extension.RHExtensionProvider; import lucee.runtime.functions.other.CreateUniqueId; import lucee.runtime.functions.system.ContractPath; import lucee.runtime.gateway.GatewayEntry; import lucee.runtime.listener.AppListenerUtil; import lucee.runtime.listener.ApplicationContext; import lucee.runtime.listener.ApplicationListener; import lucee.runtime.net.mail.Server; import lucee.runtime.net.ntp.NtpClient; import lucee.runtime.net.proxy.ProxyData; import lucee.runtime.op.Caster; import lucee.runtime.op.Duplicator; import lucee.runtime.orm.ORMConfiguration; import lucee.runtime.orm.ORMEngine; import lucee.runtime.osgi.BundleInfo; import lucee.runtime.osgi.EnvClassLoader; import lucee.runtime.osgi.OSGiUtil.BundleDefinition; import lucee.runtime.rest.RestSettingImpl; import lucee.runtime.rest.RestSettings; import lucee.runtime.schedule.Scheduler; import lucee.runtime.schedule.SchedulerImpl; import lucee.runtime.search.SearchEngine; import lucee.runtime.security.SecurityManager; import lucee.runtime.spooler.SpoolerEngine; import lucee.runtime.type.Collection.Key; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.UDF; import lucee.runtime.type.dt.TimeSpan; import lucee.runtime.type.dt.TimeSpanImpl; import lucee.runtime.type.scope.Cluster; import lucee.runtime.type.scope.ClusterNotSupported; import lucee.runtime.type.scope.Undefined; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.video.VideoExecuterNotSupported; import lucee.transformer.library.function.FunctionLib; import lucee.transformer.library.function.FunctionLibException; import lucee.transformer.library.function.FunctionLibFactory; import lucee.transformer.library.function.FunctionLibFunction; import lucee.transformer.library.function.FunctionLibFunctionArg; import lucee.transformer.library.tag.TagLib; import lucee.transformer.library.tag.TagLibException; import lucee.transformer.library.tag.TagLibFactory; import lucee.transformer.library.tag.TagLibTag; import lucee.transformer.library.tag.TagLibTagAttr; import org.apache.commons.collections4.map.ReferenceMap; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.PatternLayout; import org.osgi.framework.BundleException; import org.osgi.framework.Version; /** * Hold the definitions of the Lucee configuration. */ public abstract class ConfigImpl implements Config { public static final int CLIENT_BOOLEAN_TRUE = 0; public static final int CLIENT_BOOLEAN_FALSE = 1; public static final int SERVER_BOOLEAN_TRUE = 2; public static final int SERVER_BOOLEAN_FALSE = 3; public static final int DEBUG_DATABASE = 1; public static final int DEBUG_EXCEPTION = 2; public static final int DEBUG_TRACING = 4; public static final int DEBUG_TIMER = 8; public static final int DEBUG_IMPLICIT_ACCESS = 16; public static final int DEBUG_QUERY_USAGE = 32; public static final int DEBUG_DUMP = 64; private static final Extension[] EXTENSIONS_EMPTY = new Extension[0]; private static final RHExtension[] RHEXTENSIONS_EMPTY = new RHExtension[0]; public static final int MODE_CUSTOM = 1; public static final int MODE_STRICT = 2; public static final int CFML_WRITER_REFULAR=1; public static final int CFML_WRITER_WS=2; public static final int CFML_WRITER_WS_PREF=3; public static final String DEFAULT_STORAGE_SESSION = "memory"; public static final String DEFAULT_STORAGE_CLIENT = "cookie"; private int mode=MODE_CUSTOM; private PhysicalClassLoader rpcClassLoader; private Map<String,DataSource> datasources=new HashMap<String,DataSource>(); private Map<String,CacheConnection> caches=new HashMap<String, CacheConnection>(); private CacheConnection defaultCacheFunction=null; private CacheConnection defaultCacheObject=null; private CacheConnection defaultCacheTemplate=null; private CacheConnection defaultCacheQuery=null; private CacheConnection defaultCacheResource=null; private CacheConnection defaultCacheInclude=null; private CacheConnection defaultCacheHTTP=null; private CacheConnection defaultCacheFile=null; private CacheConnection defaultCacheWebservice=null; private String cacheDefaultConnectionNameFunction=null; private String cacheDefaultConnectionNameObject=null; private String cacheDefaultConnectionNameTemplate=null; private String cacheDefaultConnectionNameQuery=null; private String cacheDefaultConnectionNameResource=null; private String cacheDefaultConnectionNameInclude=null; private String cacheDefaultConnectionNameHTTP=null; private String cacheDefaultConnectionNameFile=null; private String cacheDefaultConnectionNameWebservice=null; private TagLib[] cfmlTlds=new TagLib[0]; private TagLib[] luceeTlds=new TagLib[0]; private FunctionLib[] cfmlFlds=new FunctionLib[0]; private FunctionLib[] luceeFlds=new FunctionLib[0]; private FunctionLib combinedCFMLFLDs; private FunctionLib combinedLuceeFLDs; private short type=SCOPE_STANDARD; private boolean _allowImplicidQueryCall=true; private boolean _mergeFormAndURL=false; private Map<String,LoggerAndSourceData> loggers=new HashMap<String, LoggerAndSourceData>(); private int _debug; private int debugLogOutput=SERVER_BOOLEAN_FALSE; private int debugOptions=0; private boolean suppresswhitespace = false; private boolean suppressContent = false; private boolean showVersion = false; private Resource tempDirectory; private TimeSpan clientTimeout=new TimeSpanImpl(90,0,0,0); private TimeSpan sessionTimeout=new TimeSpanImpl(0,0,30,0); private TimeSpan applicationTimeout=new TimeSpanImpl(1,0,0,0); private TimeSpan requestTimeout=new TimeSpanImpl(0,0,0,30); private boolean sessionManagement=true; private boolean clientManagement=false; private boolean clientCookies=true; private boolean domainCookies=false; private Resource configFile; private Resource configDir; private String sessionStorage=DEFAULT_STORAGE_SESSION; private String clientStorage=DEFAULT_STORAGE_CLIENT; private long loadTime; private int spoolInterval=30; private boolean spoolEnable=true; private boolean sendPartial=false; private Server[] mailServers; private int mailTimeout=30; private TimeZone timeZone; private String timeServer=""; private boolean useTimeServer=true; private long timeOffset; private ClassDefinition<SearchEngine> searchEngineClassDef; private String searchEngineDirectory; private Locale locale; private boolean psq=false; private boolean debugShowUsage; private Map<String,String> errorTemplates=new HashMap<String,String>(); protected Password password; private String salt; private Mapping[] mappings=new Mapping[0]; private Mapping[] customTagMappings=new Mapping[0]; private Mapping[] componentMappings=new Mapping[0]; private SchedulerImpl scheduler; private CFXTagPool cfxTagPool; private PageSource baseComponentPageSourceCFML; private String baseComponentTemplateCFML; private PageSource baseComponentPageSourceLucee; private String baseComponentTemplateLucee; private boolean restList=false; private short clientType=CLIENT_SCOPE_TYPE_COOKIE; private String componentDumpTemplate; private int componentDataMemberDefaultAccess=Component.ACCESS_PRIVATE; private boolean triggerComponentDataMember=false; private short sessionType=SESSION_TYPE_APPLICATION; private Resource deployDirectory; private short compileType=RECOMPILE_NEVER; private CharSet resourceCharset=SystemUtil.getCharSet(); private CharSet templateCharset=SystemUtil.getCharSet(); private CharSet webCharset=CharSet.UTF8; private CharSet mailDefaultCharset = CharSet.UTF8; private Resource tldFile; private Resource fldFile; private Resources resources=new ResourcesImpl(); private Map<String,Class<CacheHandler>> cacheHandlerClasses=new HashMap<String,Class<CacheHandler>>(); private ApplicationListener applicationListener; private int scriptProtect=ApplicationContext.SCRIPT_PROTECT_ALL; private ProxyData proxy =null; private Resource clientScopeDir; private Resource sessionScopeDir; private long clientScopeDirSize=1024*1024*10; private long sessionScopeDirSize=1024*1024*10; private Resource cacheDir; private long cacheDirSize=1024*1024*10; private boolean useComponentShadow=true; private PrintWriter out=SystemUtil.getPrintWriter(SystemUtil.OUT); private PrintWriter err=SystemUtil.getPrintWriter(SystemUtil.ERR); private DatasourceConnectionPool pool=new DatasourceConnectionPool(); private boolean doCustomTagDeepSearch=false; private boolean doComponentTagDeepSearch=false; private double version=1.0D; private boolean closeConnection=false; private boolean contentLength=true; private boolean allowCompression=false; private boolean doLocalCustomTag=true; private Struct constants=null; private RemoteClient[] remoteClients; private SpoolerEngine remoteClientSpoolerEngine; private Resource remoteClientDirectory; private boolean allowURLRequestTimeout=false; private boolean errorStatusCode=true; private int localMode=Undefined.MODE_LOCAL_OR_ARGUMENTS_ONLY_WHEN_EXISTS; //private String securityToken; //private String securityKey; private ExtensionProvider[] extensionProviders=Constants.CLASSIC_EXTENSION_PROVIDERS; private RHExtensionProvider[] rhextensionProviders=Constants.RH_EXTENSION_PROVIDERS; private Extension[] extensions=EXTENSIONS_EMPTY; private RHExtension[] rhextensions=RHEXTENSIONS_EMPTY; private boolean extensionEnabled; private boolean allowRealPath=true; private DumpWriterEntry[] dmpWriterEntries; private Class clusterClass=ClusterNotSupported.class;//ClusterRemoteNotSupported.class;// private Struct remoteClientUsage; private Class adminSyncClass=AdminSyncNotSupported.class; private AdminSync adminSync; private String[] customTagExtensions=Constants.getExtensions(); private Class videoExecuterClass=VideoExecuterNotSupported.class; protected MappingImpl tagMapping; protected MappingImpl scriptMapping; //private Resource tagDirectory; protected MappingImpl functionMapping; private short inspectTemplate=INSPECT_ONCE; private boolean typeChecking=true; private String serial=""; private String cacheMD5; private boolean executionLogEnabled; private ExecutionLogFactory executionLogFactory; private Map<String, ORMEngine> ormengines=new HashMap<String, ORMEngine>(); private ClassDefinition<? extends ORMEngine> cdORMEngine; private ORMConfiguration ormConfig; private ResourceClassLoader resourceCL; private ImportDefintion componentDefaultImport=new ImportDefintionImpl(Constants.DEFAULT_PACKAGE,"*"); private boolean componentLocalSearch=true; private boolean componentRootSearch=true; private boolean useComponentPathCache=true; private boolean useCTPathCache=true; private lucee.runtime.rest.Mapping[] restMappings; protected int writerType=CFML_WRITER_REFULAR; private long configFileLastModified; private boolean checkForChangesInConfigFile; //protected String apiKey=null; private List<Layout> consoleLayouts=new ArrayList<Layout>(); private List<Layout> resourceLayouts=new ArrayList<Layout>(); private Map<Key, Map<Key, Object>> tagDefaultAttributeValues; private boolean handleUnQuotedAttrValueAsString=true; private Map<Integer,Object> cachedWithins=new HashMap<Integer, Object>(); private int queueMax=100; private long queueTimeout=0; private boolean queueEnable=false; /** * @return the allowURLRequestTimeout */ public boolean isAllowURLRequestTimeout() { return allowURLRequestTimeout; } /** * @param allowURLRequestTimeout the allowURLRequestTimeout to set */ public void setAllowURLRequestTimeout(boolean allowURLRequestTimeout) { this.allowURLRequestTimeout = allowURLRequestTimeout; } @Override public short getCompileType() { return compileType; } @Override public void reset() { timeServer=""; componentDumpTemplate=""; //resources.reset(); ormengines.clear(); compressResources.clear(); clearFunctionCache(); clearCTCache(); clearComponentCache(); //clearComponentMetadata(); } @Override public void reloadTimeServerOffset() { timeOffset=0; if(useTimeServer && !StringUtil.isEmpty(timeServer,true)) { NtpClient ntp=new NtpClient(timeServer); timeOffset=ntp.getOffset(0); } } /** * private constructor called by factory method * @param configDir - config directory * @param configFile - config file */ protected ConfigImpl(Resource configDir, Resource configFile) { this.configDir=configDir; this.configFile=configFile; } protected static TagLib[] duplicate(TagLib[] tlds, boolean deepCopy) { TagLib[] rst = new TagLib[tlds.length]; for(int i=0;i<tlds.length;i++){ rst[i]=tlds[i].duplicate(deepCopy); } return rst; } protected static FunctionLib[] duplicate(FunctionLib[] flds, boolean deepCopy) { FunctionLib[] rst = new FunctionLib[flds.length]; for(int i=0;i<flds.length;i++){ rst[i]=flds[i].duplicate(deepCopy); } return rst; } public long lastModified() { return configFileLastModified; } protected void setLastModified() { this.configFileLastModified=configFile.lastModified(); } @Override public short getScopeCascadingType() { return type; } /* @Override public String[] getCFMLExtensions() { return getAllExtensions(); } @Override public String getCFCExtension() { return getComponentExtension(); } @Override public String[] getAllExtensions() { return Constants.ALL_EXTENSION; } @Override public String getComponentExtension() { return Constants.COMPONENT_EXTENSION; } @Override public String[] getTemplateExtensions() { return Constants.TEMPLATE_EXTENSIONS; }*/ protected void setFLDs(FunctionLib[] flds, int dialect) { if(dialect==CFMLEngine.DIALECT_CFML){ cfmlFlds=flds; combinedCFMLFLDs=null; // TODO improve check (hash) } else { luceeFlds=flds; combinedLuceeFLDs=null; // TODO improve check (hash) } } /** * return all Function Library Deskriptors * @return Array of Function Library Deskriptors */ public FunctionLib[] getFLDs(int dialect) { return dialect==CFMLEngine.DIALECT_CFML?cfmlFlds:luceeFlds; } public FunctionLib getCombinedFLDs(int dialect) { if(dialect==CFMLEngine.DIALECT_CFML) { if(combinedCFMLFLDs==null)combinedCFMLFLDs=FunctionLibFactory.combineFLDs(cfmlFlds); return combinedCFMLFLDs; } if(combinedLuceeFLDs==null)combinedLuceeFLDs=FunctionLibFactory.combineFLDs(luceeFlds); return combinedLuceeFLDs; } /** * return all Tag Library Deskriptors * @return Array of Tag Library Deskriptors */ public TagLib[] getTLDs(int dialect) { return dialect==CFMLEngine.DIALECT_CFML?cfmlTlds:luceeTlds; } protected void setTLDs(TagLib[] tlds,int dialect) { if(dialect==CFMLEngine.DIALECT_CFML)cfmlTlds=tlds; else luceeTlds=tlds; } @Override public boolean allowImplicidQueryCall() { return _allowImplicidQueryCall; } @Override public boolean mergeFormAndURL() { return _mergeFormAndURL; } @Override public TimeSpan getApplicationTimeout() { return applicationTimeout; } @Override public TimeSpan getSessionTimeout() { return sessionTimeout; } @Override public TimeSpan getClientTimeout() { return clientTimeout; } @Override public TimeSpan getRequestTimeout() { return requestTimeout; } @Override public boolean isClientCookies() { return clientCookies; } @Override public boolean isClientManagement() { return clientManagement; } @Override public boolean isDomainCookies() { return domainCookies; } @Override public boolean isSessionManagement() { return sessionManagement; } @Override public boolean isMailSpoolEnable() { return spoolEnable; } // FUTURE add to interface public boolean isMailSendPartial() { return sendPartial; } // FUTURE add to interface and impl public boolean isUserset() { return true; } @Override public Server[] getMailServers() { if(mailServers==null) mailServers=new Server[0]; return mailServers; } @Override public int getMailTimeout() { return mailTimeout; } @Override public boolean getPSQL() { return psq; } @Override public ClassLoader getClassLoader() { ResourceClassLoader rcl = getResourceClassLoader(null); if(rcl!=null) return rcl; return new lucee.commons.lang.ClassLoaderHelper().getClass().getClassLoader(); } // do not remove, ised in Hibernate extension public ClassLoader getClassLoaderEnv() { return new EnvClassLoader(this); } public ClassLoader getClassLoaderCore() { return new lucee.commons.lang.ClassLoaderHelper().getClass().getClassLoader(); } /*public ClassLoader getClassLoaderLoader() { return new TP().getClass().getClassLoader(); }*/ public ResourceClassLoader getResourceClassLoader() { if(resourceCL==null) throw new RuntimeException("no RCL defined yet!"); return resourceCL; } public ResourceClassLoader getResourceClassLoader(ResourceClassLoader defaultValue) { if(resourceCL==null) return defaultValue; return resourceCL; } protected void setResourceClassLoader(ResourceClassLoader resourceCL) { this.resourceCL=resourceCL; } @Override public Locale getLocale() { return locale; } @Override public boolean debug() { if(!(_debug==CLIENT_BOOLEAN_TRUE || _debug==SERVER_BOOLEAN_TRUE)) return false; return true; } public boolean debugLogOutput() { return debug() && debugLogOutput==CLIENT_BOOLEAN_TRUE || debugLogOutput==SERVER_BOOLEAN_TRUE; } @Override public Resource getTempDirectory() { if(tempDirectory==null) { Resource tmp = SystemUtil.getTempDirectory(); if(!tmp.exists()) tmp.mkdirs(); return tmp; } if(!tempDirectory.exists()) tempDirectory.mkdirs(); return tempDirectory; } @Override public int getMailSpoolInterval() { return spoolInterval; } @Override public TimeZone getTimeZone() { return timeZone; } @Override public long getTimeServerOffset() { return timeOffset; } /** * @return return the Scheduler */ public Scheduler getScheduler() { return scheduler; } /** * @return gets the password as hash */ protected Password getPassword() { return password; } public Password isPasswordEqual(String password) { if(this.password==null) return null; return ((PasswordImpl)this.password).isEqual(this,password); } @Override public boolean hasPassword() { return password!=null; } @Override public boolean passwordEqual(Password password) { if(this.password==null) return false; return this.password.equals(password); } @Override public Mapping[] getMappings() { return mappings; } public lucee.runtime.rest.Mapping[] getRestMappings() { if(restMappings==null) restMappings=new lucee.runtime.rest.Mapping[0]; return restMappings; } protected void setRestMappings(lucee.runtime.rest.Mapping[] restMappings) { // make sure only one is default boolean hasDefault=false; lucee.runtime.rest.Mapping m; for(int i=0;i<restMappings.length;i++){ m=restMappings[i]; if(m.isDefault()) { if(hasDefault) m.setDefault(false); hasDefault=true; } } this.restMappings= restMappings; } public PageSource getPageSource(Mapping[] mappings, String realPath,boolean onlyTopLevel) { throw new PageRuntimeException(new DeprecatedException("method not supported")); } public PageSource getPageSourceExisting(PageContext pc,Mapping[] mappings, String realPath,boolean onlyTopLevel,boolean useSpecialMappings, boolean useDefaultMapping, boolean onlyPhysicalExisting) { realPath=realPath.replace('\\','/'); String lcRealPath = StringUtil.toLowerCase(realPath)+'/'; Mapping mapping; PageSource ps; if(mappings!=null){ for(int i=0;i<mappings.length;i++) { mapping = mappings[i]; //print.err(lcRealPath+".startsWith"+(mapping.getStrPhysical())); if(lcRealPath.startsWith(mapping.getVirtualLowerCaseWithSlash(),0)) { ps= mapping.getPageSource(realPath.substring(mapping.getVirtual().length())); if(onlyPhysicalExisting) { if(ps.physcalExists())return ps; } else if(ps.exists()) return ps; } } } /// special mappings if(useSpecialMappings && lcRealPath.startsWith("/mapping-",0)){ String virtual="/mapping-tag"; // tag mappings Mapping[] tagMappings=(this instanceof ConfigWebImpl)?new Mapping[]{((ConfigWebImpl)this).getServerTagMapping(),getTagMapping()}:new Mapping[]{getTagMapping()}; if(lcRealPath.startsWith(virtual,0)){ for(int i=0;i<tagMappings.length;i++) { mapping = tagMappings[i]; //if(lcRealPath.startsWith(mapping.getVirtualLowerCaseWithSlash(),0)) { ps = mapping.getPageSource(realPath.substring(virtual.length())); if(onlyPhysicalExisting) { if(ps.physcalExists())return ps; } else if(ps.exists()) return ps; } } // customtag mappings tagMappings=getCustomTagMappings(); virtual="/mapping-customtag"; if(lcRealPath.startsWith(virtual,0)){ for(int i=0;i<tagMappings.length;i++) { mapping = tagMappings[i]; //if(lcRealPath.startsWith(mapping.getVirtualLowerCaseWithSlash(),0)) { ps = mapping.getPageSource(realPath.substring(virtual.length())); if(onlyPhysicalExisting) { if(ps.physcalExists())return ps; } else if(ps.exists()) return ps; } } } // component mappings (only used for gateway) if(pc!=null && ((PageContextImpl)pc).isGatewayContext()) { boolean isCFC=Constants.isComponentExtension(ResourceUtil.getExtension(realPath, null)); if(isCFC) { Mapping[] cmappings = getComponentMappings(); for(int i=0;i<cmappings.length;i++) { ps = cmappings[i].getPageSource(realPath); if(onlyPhysicalExisting) { if(ps.physcalExists())return ps; } else if(ps.exists()) return ps; } } } // config mappings for(int i=0;i<this.mappings.length-1;i++) { mapping = this.mappings[i]; if((!onlyTopLevel || mapping.isTopLevel()) && lcRealPath.startsWith(mapping.getVirtualLowerCaseWithSlash(),0)) { ps= mapping.getPageSource(realPath.substring(mapping.getVirtual().length())); if(onlyPhysicalExisting) { if(ps.physcalExists())return ps; } else if(ps.exists()) return ps; } } if(useDefaultMapping){ ps= this.mappings[this.mappings.length-1].getPageSource(realPath); if(onlyPhysicalExisting) { if(ps.physcalExists())return ps; } else if(ps.exists()) return ps; } return null; } @Override public PageSource[] getPageSources(PageContext pc,Mapping[] mappings, String realPath,boolean onlyTopLevel,boolean useSpecialMappings, boolean useDefaultMapping) { return getPageSources(pc, mappings, realPath, onlyTopLevel, useSpecialMappings, useDefaultMapping, false); } @Override public PageSource[] getPageSources(PageContext pc,Mapping[] mappings, String realPath,boolean onlyTopLevel,boolean useSpecialMappings, boolean useDefaultMapping, boolean useComponentMappings) { realPath=realPath.replace('\\','/'); String lcRealPath = StringUtil.toLowerCase(realPath)+'/'; Mapping mapping; PageSource ps; List<PageSource> list=new ArrayList<PageSource>(); if(mappings!=null){ for(int i=0;i<mappings.length;i++) { mapping = mappings[i]; //print.err(lcRealPath+".startsWith"+(mapping.getStrPhysical())); if(lcRealPath.startsWith(mapping.getVirtualLowerCaseWithSlash(),0)) { list.add(mapping.getPageSource(realPath.substring(mapping.getVirtual().length()))); } } } /// special mappings if(useSpecialMappings && lcRealPath.startsWith("/mapping-",0)){ String virtual="/mapping-tag"; // tag mappings Mapping[] tagMappings=(this instanceof ConfigWebImpl)?new Mapping[]{((ConfigWebImpl)this).getServerTagMapping(),getTagMapping()}:new Mapping[]{getTagMapping()}; if(lcRealPath.startsWith(virtual,0)){ for(int i=0;i<tagMappings.length;i++) { ps=tagMappings[i].getPageSource(realPath.substring(virtual.length())); if(ps.exists()) list.add(ps); } } // customtag mappings tagMappings=getCustomTagMappings(); virtual="/mapping-customtag"; if(lcRealPath.startsWith(virtual,0)){ for(int i=0;i<tagMappings.length;i++) { ps=tagMappings[i].getPageSource(realPath.substring(virtual.length())); if(ps.exists()) list.add(ps); } } } // component mappings (only used for gateway) if(useComponentMappings || (pc!=null && ((PageContextImpl)pc).isGatewayContext())) { boolean isCFC=Constants.isComponentExtension(ResourceUtil.getExtension(realPath, null)); if(isCFC) { Mapping[] cmappings = getComponentMappings(); for(int i=0;i<cmappings.length;i++) { ps=cmappings[i].getPageSource(realPath); if(ps.exists()) list.add(ps); } } } // config mappings for(int i=0;i<this.mappings.length-1;i++) { mapping = this.mappings[i]; if((!onlyTopLevel || mapping.isTopLevel()) && lcRealPath.startsWith(mapping.getVirtualLowerCaseWithSlash(),0)) { list.add(mapping.getPageSource(realPath.substring(mapping.getVirtual().length()))); } } if(useDefaultMapping){ list.add(this.mappings[this.mappings.length-1].getPageSource(realPath)); } return list.toArray(new PageSource[list.size()]); } /** * @param mappings * @param realPath * @param alsoDefaultMapping ignore default mapping (/) or not * @return physical path from mapping */ public Resource getPhysical(Mapping[] mappings, String realPath, boolean alsoDefaultMapping) { throw new PageRuntimeException(new DeprecatedException("method not supported")); } public Resource[] getPhysicalResources(PageContext pc,Mapping[] mappings, String realPath,boolean onlyTopLevel,boolean useSpecialMappings, boolean useDefaultMapping) { // now that archives can be used the same way as physical resources, there is no need anymore to limit to that throw new PageRuntimeException(new DeprecatedException("method not supported")); } public Resource getPhysicalResourceExisting(PageContext pc,Mapping[] mappings, String realPath,boolean onlyTopLevel,boolean useSpecialMappings, boolean useDefaultMapping) { // now that archives can be used the same way as physical resources, there is no need anymore to limit to that throw new PageRuntimeException(new DeprecatedException("method not supported")); } public PageSource toPageSource(Mapping[] mappings, Resource res,PageSource defaultValue) { Mapping mapping; String path; // app mappings if(mappings!=null){ for(int i=0;i<mappings.length;i++) { mapping = mappings[i]; // Physical if(mapping.hasPhysical()) { path=ResourceUtil.getPathToChild(res, mapping.getPhysical()); if(path!=null) { return mapping.getPageSource(path); } } // Archive if(mapping.hasArchive() && res.getResourceProvider() instanceof CompressResourceProvider) { Resource archive = mapping.getArchive(); CompressResource cr = ((CompressResource) res); if(archive.equals(cr.getCompressResource())) { return mapping.getPageSource(cr.getCompressPath()); } } } } // config mappings for(int i=0;i<this.mappings.length;i++) { mapping = this.mappings[i]; // Physical if(mapping.hasPhysical()) { path=ResourceUtil.getPathToChild(res, mapping.getPhysical()); if(path!=null) { return mapping.getPageSource(path); } } // Archive if(mapping.hasArchive() && res.getResourceProvider() instanceof CompressResourceProvider) { Resource archive = mapping.getArchive(); CompressResource cr = ((CompressResource) res); if(archive.equals(cr.getCompressResource())) { return mapping.getPageSource(cr.getCompressPath()); } } } // map resource to root mapping when same filesystem Mapping rootMapping = this.mappings[this.mappings.length-1]; Resource root; if(rootMapping.hasPhysical() && res.getResourceProvider().getScheme().equals((root=rootMapping.getPhysical()).getResourceProvider().getScheme())) { String realpath=""; while(root!=null && !ResourceUtil.isChildOf(res, root)){ root=root.getParentResource(); realpath+="../"; } String p2c=ResourceUtil.getPathToChild(res,root); if(StringUtil.startsWith(p2c, '/') || StringUtil.startsWith(p2c, '\\') ) p2c=p2c.substring(1); realpath+=p2c; return rootMapping.getPageSource(realpath); } // MUST better impl than this if(this instanceof ConfigWebImpl) { Resource parent = res.getParentResource(); if(parent!=null && !parent.equals(res)) { Mapping m = ((ConfigWebImpl)this).getApplicationMapping("application","/", parent.getAbsolutePath(),null,true,false); return m.getPageSource(res.getName()); } } // Archive // MUST check archive return defaultValue; } @Override public Resource getConfigDir() { return configDir; } @Override public Resource getConfigFile() { return configFile; } /** * sets the password * @param password */ protected void setPassword(Password password) { this.password=password; } /** * set how lucee cascade scopes * @param type cascading type */ protected void setScopeCascadingType(short type) { this.type=type; } protected void addTag(String nameSpace, String nameSpaceSeperator,String name, int dialect, ClassDefinition cd){ if(dialect==CFMLEngine.DIALECT_BOTH) { addTag(nameSpace, nameSpaceSeperator, name, CFMLEngine.DIALECT_CFML, cd); addTag(nameSpace, nameSpaceSeperator, name, CFMLEngine.DIALECT_LUCEE, cd); return; } TagLib[] tlds = dialect==CFMLEngine.DIALECT_CFML?cfmlTlds:luceeTlds; for(int i=0;i<tlds.length;i++) { if(tlds[i].getNameSpaceAndSeparator().equalsIgnoreCase(nameSpace+nameSpaceSeperator)){ TagLibTag tlt = new TagLibTag(tlds[i]); tlt.setAttributeType(TagLibTag.ATTRIBUTE_TYPE_DYNAMIC); tlt.setBodyContent("free"); tlt.setTagClassDefinition(cd); tlt.setName(name); tlds[i].setTag(tlt); } } } /** * set the optional directory of the tag library deskriptors * @param fileTld directory of the tag libray deskriptors * @throws TagLibException */ protected void setTldFile(Resource fileTld, int dialect) throws TagLibException { if(dialect==CFMLEngine.DIALECT_BOTH) { setTldFile(fileTld, CFMLEngine.DIALECT_CFML); setTldFile(fileTld, CFMLEngine.DIALECT_LUCEE); return; } TagLib[] tlds = dialect==CFMLEngine.DIALECT_CFML?cfmlTlds:luceeTlds; if(fileTld==null) return; this.tldFile=fileTld; String key; Map<String,TagLib> map=new HashMap<String,TagLib>(); // First fill existing to set for(int i=0;i<tlds.length;i++) { key=getKey(tlds[i]); map.put(key,tlds[i]); } TagLib tl; // now overwrite with new data if(fileTld.isDirectory()) { Resource[] files=fileTld.listResources(new ExtensionResourceFilter(new String[]{"tld","tldx"})); for(int i=0;i<files.length;i++) { try { tl = TagLibFactory.loadFromFile(files[i],getIdentification()); key=getKey(tl); if(!map.containsKey(key)) map.put(key,tl); else overwrite(map.get(key),tl); } catch(TagLibException tle) { SystemOut.printDate(out,"can't load tld "+files[i]); tle.printStackTrace(getErrWriter()); } } } else if(fileTld.isFile()){ tl = TagLibFactory.loadFromFile(fileTld,getIdentification()); key=getKey(tl); if(!map.containsKey(key)) map.put(key,tl); else overwrite(map.get(key),tl); } // now fill back to array tlds=new TagLib[map.size()]; if(dialect==CFMLEngine.DIALECT_CFML) cfmlTlds=tlds; else luceeTlds=tlds; int index=0; Iterator<TagLib> it = map.values().iterator(); while(it.hasNext()) { tlds[index++]=it.next(); } } public TagLib getCoreTagLib(int dialect){ TagLib[] tlds = dialect==CFMLEngine.DIALECT_CFML?cfmlTlds:luceeTlds; for(int i=0;i<tlds.length;i++) { if(tlds[i].isCore())return tlds[i]; } throw new RuntimeException("no core taglib found"); // this should never happen } protected void setTagDirectory(Resource tagDirectory) { //this.tagDirectory=tagDirectory; this.tagMapping= new MappingImpl(this,"/mapping-tag/",tagDirectory.getAbsolutePath(),null,ConfigImpl.INSPECT_NEVER,true,true,true,true,false,true,null,-1,-1); TagLib tlc=getCoreTagLib(CFMLEngine.DIALECT_CFML); TagLib tll=getCoreTagLib(CFMLEngine.DIALECT_LUCEE); // now overwrite with new data if(tagDirectory.isDirectory()) { String[] files=tagDirectory.list(new ExtensionResourceFilter( getMode() == ConfigImpl.MODE_STRICT? Constants.getComponentExtensions(): Constants.getExtensions())); for(int i=0;i<files.length;i++) { if(tlc!=null)createTag(tlc, files[i]); if(tll!=null)createTag(tll, files[i]); } } } public void createTag(TagLib tl,String filename) {// Jira 1298 String name=toName(filename);//filename.substring(0,filename.length()-(getCFCExtension().length()+1)); TagLibTag tlt = new TagLibTag(tl); tlt.setName(name); tlt.setTagClassDefinition("lucee.runtime.tag.CFTagCore",getIdentification(),null); tlt.setHandleExceptions(true); tlt.setBodyContent("free"); tlt.setParseBody(false); tlt.setDescription(""); tlt.setAttributeType(TagLibTag.ATTRIBUTE_TYPE_MIXED); TagLibTagAttr tlta = new TagLibTagAttr(tlt); tlta.setName("__filename"); tlta.setRequired(true); tlta.setRtexpr(true); tlta.setType("string"); tlta.setHidden(true); tlta.setDefaultValue(filename); tlt.setAttribute(tlta); tlta = new TagLibTagAttr(tlt); tlta.setName("__name"); tlta.setRequired(true); tlta.setRtexpr(true); tlta.setHidden(true); tlta.setType("string"); tlta.setDefaultValue(name); tlt.setAttribute(tlta); tlta = new TagLibTagAttr(tlt); tlta.setName("__isweb"); tlta.setRequired(true); tlta.setRtexpr(true); tlta.setHidden(true); tlta.setType("boolean"); tlta.setDefaultValue(this instanceof ConfigWeb?"true":"false"); tlt.setAttribute(tlta); tl.setTag(tlt); } protected void setFunctionDirectory(Resource functionDirectory) { this.functionMapping= new MappingImpl(this,"/mapping-function/",functionDirectory.getAbsolutePath(),null,ConfigImpl.INSPECT_NEVER,true,true,true,true,false,true,null,-1,-1); FunctionLib flc=cfmlFlds[cfmlFlds.length-1]; FunctionLib fll=luceeFlds[luceeFlds.length-1]; // now overwrite with new data if(functionDirectory.isDirectory()) { String[] files=functionDirectory.list(new ExtensionResourceFilter(Constants.getTemplateExtensions())); for(int i=0;i<files.length;i++) { if(flc!=null)createFunction(flc, files[i]); if(fll!=null)createFunction(fll, files[i]); } combinedCFMLFLDs=null; combinedLuceeFLDs=null; } } public void createFunction(FunctionLib fl,String filename) { String name=toName(filename);//filename.substring(0,filename.length()-(getCFMLExtensions().length()+1)); FunctionLibFunction flf = new FunctionLibFunction(fl,true); flf.setArgType(FunctionLibFunction.ARG_DYNAMIC); flf.setFunctionClass("lucee.runtime.functions.system.CFFunction",null,null); flf.setName(name); flf.setReturn("object"); FunctionLibFunctionArg arg = new FunctionLibFunctionArg(flf); arg.setName("__filename"); arg.setRequired(true); arg.setType("string"); arg.setHidden(true); arg.setDefaultValue(filename); flf.setArg(arg); arg = new FunctionLibFunctionArg(flf); arg.setName("__name"); arg.setRequired(true); arg.setHidden(true); arg.setType("string"); arg.setDefaultValue(name); flf.setArg(arg); arg = new FunctionLibFunctionArg(flf); arg.setName("__isweb"); arg.setRequired(true); arg.setHidden(true); arg.setType("boolean"); arg.setDefaultValue(this instanceof ConfigWeb?"true":"false"); flf.setArg(arg); fl.setFunction(flf); } private static String toName(String filename) { int pos=filename.lastIndexOf('.'); if(pos==-1)return filename; return filename.substring(0,pos); } private void overwrite(TagLib existingTL, TagLib newTL) { Iterator<TagLibTag> it = newTL.getTags().values().iterator(); while(it.hasNext()){ existingTL.setTag(it.next()); } } private String getKey(TagLib tl) { return tl.getNameSpaceAndSeparator().toLowerCase(); } protected void setFldFile(Resource fileFld, int dialect) throws FunctionLibException { if(dialect==CFMLEngine.DIALECT_BOTH) { setFldFile(fileFld, CFMLEngine.DIALECT_CFML); setFldFile(fileFld, CFMLEngine.DIALECT_LUCEE); return; } FunctionLib[] flds = dialect==CFMLEngine.DIALECT_CFML?cfmlFlds:luceeFlds; // merge all together (backward compatibility) if(flds.length>1)for(int i=1;i<flds.length;i++) { overwrite(flds[0], flds[i]); } flds=new FunctionLib[]{flds[0]}; if(dialect==CFMLEngine.DIALECT_CFML) { cfmlFlds=flds; if(cfmlFlds!=flds)combinedCFMLFLDs=null;// TODO improve check } else { luceeFlds=flds; if(luceeFlds!=flds)combinedLuceeFLDs=null;// TODO improve check } if(fileFld==null) return; this.fldFile=fileFld; // overwrite with addional functions FunctionLib fl; if(fileFld.isDirectory()) { Resource[] files=fileFld.listResources(new ExtensionResourceFilter(new String[]{"fld","fldx"})); for(int i=0;i<files.length;i++) { try { fl = FunctionLibFactory.loadFromFile(files[i],getIdentification()); overwrite(flds[0],fl); } catch(FunctionLibException fle) { SystemOut.printDate(out,"can't load fld "+files[i]); fle.printStackTrace(getErrWriter()); } } } else { fl = FunctionLibFactory.loadFromFile(fileFld,getIdentification()); overwrite(flds[0],fl); } } private void overwrite(FunctionLib existingFL, FunctionLib newFL) { Iterator<FunctionLibFunction> it = newFL.getFunctions().values().iterator(); while(it.hasNext()){ existingFL.setFunction(it.next()); } } private String getKey(FunctionLib functionLib) { return functionLib.getDisplayName().toLowerCase(); } /** * sets if it is allowed to implizit query call, call a query member witot define name of the query. * @param _allowImplicidQueryCall is allowed */ protected void setAllowImplicidQueryCall(boolean _allowImplicidQueryCall) { this._allowImplicidQueryCall=_allowImplicidQueryCall; } /** * sets if url and form scope will be merged * @param _mergeFormAndURL merge yes or no */ protected void setMergeFormAndURL(boolean _mergeFormAndURL) { this._mergeFormAndURL=_mergeFormAndURL; } /** * @param strApplicationTimeout The applicationTimeout to set. * @throws PageException */ void setApplicationTimeout(String strApplicationTimeout) throws PageException { setApplicationTimeout(Caster.toTimespan(strApplicationTimeout)); } /** * @param applicationTimeout The applicationTimeout to set. */ protected void setApplicationTimeout(TimeSpan applicationTimeout) { this.applicationTimeout = applicationTimeout; } /** * @param strSessionTimeout The sessionTimeout to set. * @throws PageException */ protected void setSessionTimeout(String strSessionTimeout) throws PageException { setSessionTimeout(Caster.toTimespan(strSessionTimeout)); } /** * @param sessionTimeout The sessionTimeout to set. */ protected void setSessionTimeout(TimeSpan sessionTimeout) { this.sessionTimeout = sessionTimeout; } protected void setClientTimeout(String strClientTimeout) throws PageException { setClientTimeout(Caster.toTimespan(strClientTimeout)); } /** * @param clientTimeout The sessionTimeout to set. */ protected void setClientTimeout(TimeSpan clientTimeout) { this.clientTimeout = clientTimeout; } /** * @param strRequestTimeout The requestTimeout to set. * @throws PageException */ protected void setRequestTimeout(String strRequestTimeout) throws PageException { setRequestTimeout(Caster.toTimespan(strRequestTimeout)); } /** * @param requestTimeout The requestTimeout to set. */ protected void setRequestTimeout(TimeSpan requestTimeout) { this.requestTimeout = requestTimeout; } /** * @param clientCookies The clientCookies to set. */ protected void setClientCookies(boolean clientCookies) { this.clientCookies = clientCookies; } /** * @param clientManagement The clientManagement to set. */ protected void setClientManagement(boolean clientManagement) { this.clientManagement = clientManagement; } /** * @param domainCookies The domainCookies to set. */ protected void setDomainCookies(boolean domainCookies) { this.domainCookies = domainCookies; } /** * @param sessionManagement The sessionManagement to set. */ protected void setSessionManagement(boolean sessionManagement) { this.sessionManagement = sessionManagement; } /** * @param spoolEnable The spoolEnable to set. */ protected void setMailSpoolEnable(boolean spoolEnable) { this.spoolEnable = spoolEnable; } protected void setMailSendPartial(boolean sendPartial) { this.sendPartial = sendPartial; } /** * @param mailTimeout The mailTimeout to set. */ protected void setMailTimeout(int mailTimeout) { this.mailTimeout = mailTimeout; } /** * @param psq (preserve single quote) * sets if sql string inside a cfquery will be prederved for Single Quotes */ protected void setPSQL(boolean psq) { this.psq=psq; } /** * set if lucee make debug output or not * @param _debug debug or not */ protected void setDebug(int _debug) { this._debug=_debug; } protected void setDebugLogOutput(int debugLogOutput) { this.debugLogOutput=debugLogOutput; } /** * sets the temp directory * @param strTempDirectory temp directory * @throws ExpressionException */ protected void setTempDirectory(String strTempDirectory, boolean flush) throws ExpressionException { setTempDirectory(resources.getResource(strTempDirectory),flush); } /** * sets the temp directory * @param tempDirectory temp directory * @throws ExpressionException */ protected void setTempDirectory(Resource tempDirectory, boolean flush) throws ExpressionException { if(!isDirectory(tempDirectory) || !tempDirectory.isWriteable()) { SystemOut.printDate(getErrWriter(), "temp directory ["+tempDirectory+"] is not writable or can not be created, using directory ["+SystemUtil.getTempDirectory()+"] instead"); tempDirectory=SystemUtil.getTempDirectory(); if(!tempDirectory.isWriteable()){ SystemOut.printDate(getErrWriter(), "temp directory ["+tempDirectory+"] is not writable"); } } if(flush)ResourceUtil.removeChildrenEL(tempDirectory);// start with a empty temp directory this.tempDirectory=tempDirectory; } /** * sets the Schedule Directory * @param scheduleDirectory sets the schedule Directory * @param logger * @throws PageException */ protected void setScheduler(CFMLEngine engine,Resource scheduleDirectory) throws PageException { if(scheduleDirectory==null) { if(this.scheduler==null) this.scheduler=new SchedulerImpl(engine,"<?xml version=\"1.0\"?>\n<schedule></schedule>",this); return; } if(!isDirectory(scheduleDirectory)) throw new ExpressionException("schedule task directory "+scheduleDirectory+" doesn't exist or is not a directory"); try { if(this.scheduler==null) this.scheduler=new SchedulerImpl(engine,this,scheduleDirectory,SystemUtil.getCharset().name()); } catch (Exception e) { throw Caster.toPageException(e); } } /** * @param spoolInterval The spoolInterval to set. */ protected void setMailSpoolInterval(int spoolInterval) { this.spoolInterval = spoolInterval; } /** * sets the timezone * @param timeZone */ protected void setTimeZone(TimeZone timeZone) { this.timeZone=timeZone; } /** * sets the time server * @param timeServer */ protected void setTimeServer(String timeServer) { this.timeServer=timeServer; } /** * sets the locale * @param strLocale */ protected void setLocale(String strLocale) { if(strLocale==null) { this.locale=Locale.US; } else { try { this.locale=Caster.toLocale(strLocale); if(this.locale==null)this.locale=Locale.US; } catch (ExpressionException e) { this.locale=Locale.US; } } } /** * sets the locale * @param locale */ protected void setLocale(Locale locale) { this.locale=locale; } /** * @param mappings The mappings to set. */ protected void setMappings(Mapping[] mappings) { Arrays.sort(mappings,new Comparator(){ public int compare(Object left, Object right) { Mapping r = ((Mapping)right); Mapping l = ((Mapping)left); int rtn=r.getVirtualLowerCaseWithSlash().length()-l.getVirtualLowerCaseWithSlash().length(); if(rtn==0) return slashCount(r)-slashCount(l); return rtn; } private int slashCount(Mapping l) { String str=l.getVirtualLowerCaseWithSlash(); int count=0,lastIndex=-1; while((lastIndex=str.indexOf('/', lastIndex))!=-1) { count++; lastIndex++; } return count; } }); this.mappings = mappings; } /** * @param datasources The datasources to set */ protected void setDataSources(Map<String,DataSource> datasources) { this.datasources=datasources; } /** * @param customTagMappings The customTagMapping to set. */ protected void setCustomTagMappings(Mapping[] customTagMappings) { this.customTagMappings = customTagMappings; } @Override public Mapping[] getCustomTagMappings() { return customTagMappings; } /** * @param mailServers The mailsServers to set. */ protected void setMailServers(Server[] mailServers) { this.mailServers = mailServers; } /** * is file a directory or not, touch if not exist * @param directory * @return true if existing directory or has created new one */ protected boolean isDirectory(Resource directory) { if(directory.exists()) return directory.isDirectory(); try { directory.createDirectory(true); return true; } catch (IOException e) { e.printStackTrace(getErrWriter()); } return false; } @Override public long getLoadTime() { return loadTime; } /** * @param loadTime The loadTime to set. */ protected void setLoadTime(long loadTime) { this.loadTime = loadTime; } /** * @return Returns the configLogger. * / public Log getConfigLogger() { return configLogger; }*/ @Override public CFXTagPool getCFXTagPool() throws SecurityException { return cfxTagPool; } /** * @param cfxTagPool The customTagPool to set. */ protected void setCFXTagPool(CFXTagPool cfxTagPool) { this.cfxTagPool = cfxTagPool; } /** * @param cfxTagPool The customTagPool to set. */ protected void setCFXTagPool(Map cfxTagPool) { this.cfxTagPool = new CFXTagPoolImpl(cfxTagPool); } @Override public String getBaseComponentTemplate(int dialect) { if(dialect==CFMLEngine.DIALECT_CFML) return baseComponentTemplateCFML; return baseComponentTemplateLucee; } /** * @return pagesource of the base component */ public PageSource getBaseComponentPageSource(int dialect) { return getBaseComponentPageSource(dialect,ThreadLocalPageContext.get()); } public PageSource getBaseComponentPageSource(int dialect, PageContext pc) { PageSource base = dialect==CFMLEngine.DIALECT_CFML?baseComponentPageSourceCFML:baseComponentPageSourceLucee; if(base==null) { base=PageSourceImpl.best(getPageSources(pc,null,getBaseComponentTemplate(dialect),false,false,true)); if(!base.exists()) { String baseTemplate = getBaseComponentTemplate(dialect); String mod = ContractPath.call(pc, baseTemplate, false); if(!mod.equals(baseTemplate)) { base=PageSourceImpl.best(getPageSources(pc,null,mod,false,false,true)); } } if(dialect==CFMLEngine.DIALECT_CFML) this.baseComponentPageSourceCFML=base; else this.baseComponentPageSourceLucee=base; } return base; } /** * @param template The baseComponent template to set. */ protected void setBaseComponentTemplate(int dialect,String template) { if(dialect==CFMLEngine.DIALECT_CFML) { this.baseComponentPageSourceCFML=null; this.baseComponentTemplateCFML = template; } else { this.baseComponentPageSourceLucee=null; this.baseComponentTemplateLucee = template; } } protected void setRestList(boolean restList) { this.restList=restList; } public boolean getRestList() { return restList; } /** * @param clientType */ protected void setClientType(short clientType) { this.clientType=clientType; } /** * @param strClientType */ protected void setClientType(String strClientType) { strClientType=strClientType.trim().toLowerCase(); if(strClientType.equals("file"))clientType=Config.CLIENT_SCOPE_TYPE_FILE; else if(strClientType.equals("db"))clientType=Config.CLIENT_SCOPE_TYPE_DB; else if(strClientType.equals("database"))clientType=Config.CLIENT_SCOPE_TYPE_DB; else clientType=Config.CLIENT_SCOPE_TYPE_COOKIE; } @Override public short getClientType() { return this.clientType; } /** * @param searchEngine The searchEngine to set. */ protected void setSearchEngine(ClassDefinition cd, String directory) { this.searchEngineClassDef = cd; this.searchEngineDirectory = directory; } @Override public ClassDefinition<SearchEngine> getSearchEngineClassDefinition() { return this.searchEngineClassDef; } @Override public String getSearchEngineDirectory() { return this.searchEngineDirectory; } @Override public int getComponentDataMemberDefaultAccess() { return componentDataMemberDefaultAccess; } /** * @param componentDataMemberDefaultAccess The componentDataMemberDefaultAccess to set. */ protected void setComponentDataMemberDefaultAccess( int componentDataMemberDefaultAccess) { this.componentDataMemberDefaultAccess = componentDataMemberDefaultAccess; } @Override public String getTimeServer() { return timeServer; } @Override public String getComponentDumpTemplate() { return componentDumpTemplate; } /** * @param template The componentDump template to set. */ protected void setComponentDumpTemplate(String template) { this.componentDumpTemplate = template; } public String createSecurityToken() { try { return Md5.getDigestAsString(getConfigDir().getAbsolutePath()); } catch (IOException e) { return null; } } @Override public String getDebugTemplate() { throw new PageRuntimeException(new DeprecatedException("no longer supported, use instead getDebugEntry(ip, defaultValue)")); } @Override public String getErrorTemplate(int statusCode) { return errorTemplates.get(Caster.toString(statusCode)); } /** * @param errorTemplate the errorTemplate to set */ protected void setErrorTemplate(int statusCode,String errorTemplate) { this.errorTemplates.put(Caster.toString(statusCode), errorTemplate); } @Override public short getSessionType() { return sessionType; } /** * @param sessionType The sessionType to set. */ protected void setSessionType(short sessionType) { this.sessionType = sessionType; } @Override public abstract String getUpdateType() ; @Override public abstract URL getUpdateLocation(); @Override public Resource getClassDirectory() { return deployDirectory; } public Resource getLibraryDirectory() { Resource dir = getConfigDir().getRealResource("lib"); if(!dir.exists())dir.mkdir(); return dir; } public Resource getEventGatewayDirectory() { Resource dir = getConfigDir().getRealResource("context/admin/gdriver"); if(!dir.exists())dir.mkdir(); return dir; } public Resource getClassesDirectory() { Resource dir = getConfigDir().getRealResource("classes"); if(!dir.exists())dir.mkdir(); return dir; } /** * set the deploy directory, directory where lucee deploy transalted cfml classes (java and class files) * @param strDeployDirectory deploy directory * @throws ExpressionException */ protected void setDeployDirectory(String strDeployDirectory) throws ExpressionException { setDeployDirectory(resources.getResource(strDeployDirectory)); } /** * set the deploy directory, directory where lucee deploy transalted cfml classes (java and class files) * @param deployDirectory deploy directory * @throws ExpressionException * @throws ExpressionException */ protected void setDeployDirectory(Resource deployDirectory) throws ExpressionException { if(!isDirectory(deployDirectory)) { throw new ExpressionException("deploy directory "+deployDirectory+" doesn't exist or is not a directory"); } this.deployDirectory=deployDirectory; } @Override public abstract Resource getRootDirectory(); /** * sets the compileType value. * @param compileType The compileType to set. */ protected void setCompileType(short compileType) { this.compileType = compileType; } /** FUTHER * Returns the value of suppresswhitespace. * @return value suppresswhitespace */ public boolean isSuppressWhitespace() { return suppresswhitespace; } /** FUTHER * sets the suppresswhitespace value. * @param suppresswhitespace The suppresswhitespace to set. */ protected void setSuppressWhitespace(boolean suppresswhitespace) { this.suppresswhitespace = suppresswhitespace; } public boolean isSuppressContent() { return suppressContent; } protected void setSuppressContent(boolean suppressContent) { this.suppressContent = suppressContent; } @Override public String getDefaultEncoding() { return webCharset.name(); } @Override public Charset getTemplateCharset() { return CharsetUtil.toCharset(templateCharset); } public CharSet getTemplateCharSet() { return templateCharset; } /** * sets the charset to read the files * @param templateCharset */ protected void setTemplateCharset(String templateCharset) { this.templateCharset = CharsetUtil.toCharSet(templateCharset, this.templateCharset); } protected void setTemplateCharset(Charset templateCharset) { this.templateCharset = CharsetUtil.toCharSet(templateCharset); } @Override public Charset getWebCharset() { return CharsetUtil.toCharset(webCharset); } public CharSet getWebCharSet() { return webCharset; } /** * sets the charset to read and write resources * @param resourceCharset */ protected void setResourceCharset(String resourceCharset) { this.resourceCharset = CharsetUtil.toCharSet(resourceCharset, this.resourceCharset); } protected void setResourceCharset(Charset resourceCharset) { this.resourceCharset = CharsetUtil.toCharSet(resourceCharset); } @Override public Charset getResourceCharset() { return CharsetUtil.toCharset(resourceCharset); } public CharSet getResourceCharSet() { return resourceCharset; } /** * sets the charset for the response stream * @param webCharset */ protected void setWebCharset(String webCharset) { this.webCharset = CharsetUtil.toCharSet(webCharset, this.webCharset); } protected void setWebCharset(Charset webCharset) { this.webCharset = CharsetUtil.toCharSet(webCharset); } public SecurityManager getSecurityManager() { return null; } @Override public Resource getFldFile() { return fldFile; } @Override public Resource getTldFile() { return tldFile; } @Override public DataSource[] getDataSources() { Map<String, DataSource> map = getDataSourcesAsMap(); Iterator<DataSource> it = map.values().iterator(); DataSource[] ds = new DataSource[map.size()]; int count=0; while(it.hasNext()) { ds[count++]=it.next(); } return ds; } public Map<String,DataSource> getDataSourcesAsMap() { Map<String,DataSource> map=new HashMap<String, DataSource>(); Iterator<Entry<String, DataSource>> it = datasources.entrySet().iterator(); Entry<String, DataSource> entry; while(it.hasNext()) { entry = it.next(); if(!entry.getKey().equals(QOQ_DATASOURCE_NAME)) map.put(entry.getKey(),entry.getValue()); } return map; } /** * @return the mailDefaultCharset */ public Charset getMailDefaultCharset() { return mailDefaultCharset.toCharset(); } public CharSet getMailDefaultCharSet() { return mailDefaultCharset; } /** * @param mailDefaultEncoding the mailDefaultCharset to set */ protected void setMailDefaultEncoding(String mailDefaultCharset) { this.mailDefaultCharset = CharsetUtil.toCharSet(mailDefaultCharset,this.mailDefaultCharset); } protected void setMailDefaultEncoding(Charset mailDefaultCharset) { this.mailDefaultCharset = CharsetUtil.toCharSet(mailDefaultCharset); } protected void setDefaultResourceProvider(Class defaultProviderClass, Map arguments) throws ClassException { Object o=ClassUtil.loadInstance(defaultProviderClass); if(o instanceof ResourceProvider) { ResourceProvider rp=(ResourceProvider) o; rp.init(null,arguments); setDefaultResourceProvider(rp); } else throw new ClassException("object ["+Caster.toClassName(o)+"] must implement the interface "+ResourceProvider.class.getName()); } /** * @param defaultResourceProvider the defaultResourceProvider to set */ protected void setDefaultResourceProvider(ResourceProvider defaultResourceProvider) { resources.registerDefaultResourceProvider(defaultResourceProvider); } /** * @return the defaultResourceProvider */ public ResourceProvider getDefaultResourceProvider() { return resources.getDefaultResourceProvider(); } protected void addCacheHandler(String id, ClassDefinition<CacheHandler> cd) throws ClassException, BundleException { Class<CacheHandler> clazz=cd.getClazz(); Object o = ClassUtil.loadInstance(clazz); // just try to load and forget afterwards if(o instanceof CacheHandler) { addCacheHandler(id,clazz); } else throw new ClassException("object ["+Caster.toClassName(o)+"] must implement the interface "+CacheHandler.class.getName()); } protected void addCacheHandler(String id, Class<CacheHandler> chc) { cacheHandlerClasses.put(id,chc); } public Iterator<Entry<String, Class<CacheHandler>>> getCacheHandlers() { return cacheHandlerClasses.entrySet().iterator(); } protected void addResourceProvider(String strProviderScheme, ClassDefinition cd, Map arguments) throws ClassException, BundleException { Object o=ClassUtil.loadInstance(cd.getClazz()); if(o instanceof ResourceProvider) { ResourceProvider rp=(ResourceProvider) o; rp.init(strProviderScheme,arguments); addResourceProvider(rp); } else throw new ClassException("object ["+Caster.toClassName(o)+"] must implement the interface "+ResourceProvider.class.getName()); } protected void addResourceProvider(String strProviderScheme, Class providerClass, Map arguments) throws ClassException { Object o=ClassUtil.loadInstance(providerClass); if(o instanceof ResourceProvider) { ResourceProvider rp=(ResourceProvider) o; rp.init(strProviderScheme,arguments); addResourceProvider(rp); } else throw new ClassException("object ["+Caster.toClassName(o)+"] must implement the interface "+ResourceProvider.class.getName()); } protected void addResourceProvider(ResourceProvider provider) { resources.registerResourceProvider(provider); } public void clearResourceProviders() { resources.reset(); } /** * @return return the resource providers */ public ResourceProvider[] getResourceProviders() { return resources.getResourceProviders(); } public boolean hasResourceProvider(String scheme) { ResourceProvider[] providers = resources.getResourceProviders(); for(int i=0;i<providers.length;i++){ if(providers[i].getScheme().equalsIgnoreCase(scheme)) return true; } return false; } protected void setResourceProviders(ResourceProvider[] resourceProviders) { for(int i=0;i<resourceProviders.length;i++) { resources.registerResourceProvider(resourceProviders[i]); } } @Override public Resource getResource(String path) { return resources.getResource(path); } @Override public ApplicationListener getApplicationListener() { return applicationListener; } /** * @param applicationListener the applicationListener to set */ protected void setApplicationListener(ApplicationListener applicationListener) { this.applicationListener = applicationListener; } /** * @return the scriptProtect */ public int getScriptProtect() { return scriptProtect; } /** * @param scriptProtect the scriptProtect to set */ protected void setScriptProtect(int scriptProtect) { this.scriptProtect = scriptProtect; } /** * @return the proxyPassword */ public ProxyData getProxyData() { return proxy; } /** * @param proxy the proxyPassword to set */ protected void setProxyData(ProxyData proxy) { this.proxy = proxy; } @Override public boolean isProxyEnableFor(String host) { return false;// TODO proxyEnable; } /** * @return the triggerComponentDataMember */ public boolean getTriggerComponentDataMember() { return triggerComponentDataMember; } /** * @param triggerComponentDataMember the triggerComponentDataMember to set */ protected void setTriggerComponentDataMember(boolean triggerComponentDataMember) { this.triggerComponentDataMember = triggerComponentDataMember; } @Override public Resource getClientScopeDir() { if(clientScopeDir==null) clientScopeDir=getConfigDir().getRealResource("client-scope"); return clientScopeDir; } public Resource getSessionScopeDir() { if(sessionScopeDir==null) sessionScopeDir=getConfigDir().getRealResource("session-scope"); return sessionScopeDir; } @Override public long getClientScopeDirSize() { return clientScopeDirSize; } public long getSessionScopeDirSize() { return sessionScopeDirSize; } /** * @param clientScopeDir the clientScopeDir to set */ protected void setClientScopeDir(Resource clientScopeDir) { this.clientScopeDir = clientScopeDir; } protected void setSessionScopeDir(Resource sessionScopeDir) { this.sessionScopeDir = sessionScopeDir; } /** * @param clientScopeDirSize the clientScopeDirSize to set */ protected void setClientScopeDirSize(long clientScopeDirSize) { this.clientScopeDirSize = clientScopeDirSize; } @Override public ClassLoader getRPCClassLoader(boolean reload) throws IOException { if(rpcClassLoader!=null && !reload) return rpcClassLoader; Resource dir = getClassDirectory().getRealResource("RPC"); if(!dir.exists())dir.createDirectory(true); rpcClassLoader = new PhysicalClassLoader(this,dir,null,false); return rpcClassLoader; } public ClassLoader getRPCClassLoader(boolean reload, ClassLoader[] parents) throws IOException { if(rpcClassLoader!=null && !reload) return rpcClassLoader; Resource dir = getClassDirectory().getRealResource("RPC"); if(!dir.exists())dir.createDirectory(true); rpcClassLoader = new PhysicalClassLoader(this,dir,parents,false); return rpcClassLoader; } public void resetRPCClassLoader() { rpcClassLoader=null; } protected void setCacheDir(Resource cacheDir) { this.cacheDir=cacheDir; } public Resource getCacheDir() { return this.cacheDir; } public long getCacheDirSize() { return cacheDirSize; } protected void setCacheDirSize(long cacheDirSize) { this.cacheDirSize=cacheDirSize; } protected void setDumpWritersEntries(DumpWriterEntry[] dmpWriterEntries) { this.dmpWriterEntries=dmpWriterEntries; } public DumpWriterEntry[] getDumpWritersEntries() { return dmpWriterEntries; } @Override public DumpWriter getDefaultDumpWriter(int defaultType) { DumpWriterEntry[] entries = getDumpWritersEntries(); if(entries!=null)for(int i=0;i<entries.length;i++){ if(entries[i].getDefaultType()==defaultType) { return entries[i].getWriter(); } } return new HTMLDumpWriter(); } @Override public DumpWriter getDumpWriter(String name) throws DeprecatedException { throw new DeprecatedException("this method is no longer supported"); } public DumpWriter getDumpWriter(String name,int defaultType) throws ExpressionException { if(StringUtil.isEmpty(name)) return getDefaultDumpWriter(defaultType); DumpWriterEntry[] entries = getDumpWritersEntries(); for(int i=0;i<entries.length;i++){ if(entries[i].getName().equals(name)) { return entries[i].getWriter(); } } // error StringBuilder sb=new StringBuilder(); for(int i=0;i<entries.length;i++){ if(i>0)sb.append(", "); sb.append(entries[i].getName()); } throw new ExpressionException("invalid format definition ["+name+"], valid definitions are ["+sb+"]"); } @Override public boolean useComponentShadow() { return useComponentShadow; } public boolean useComponentPathCache() { return useComponentPathCache; } public boolean useCTPathCache() { return useCTPathCache; } public void flushComponentPathCache() { if(componentPathCache!=null)componentPathCache.clear(); } public void flushCTPathCache() { if(ctPatchCache!=null)ctPatchCache.clear(); } protected void setUseCTPathCache(boolean useCTPathCache) { this.useCTPathCache = useCTPathCache; } protected void setUseComponentPathCache(boolean useComponentPathCache) { this.useComponentPathCache = useComponentPathCache; } /** * @param useComponentShadow the useComponentShadow to set */ protected void setUseComponentShadow(boolean useComponentShadow) { this.useComponentShadow = useComponentShadow; } @Override public DataSource getDataSource(String datasource) throws DatabaseException { DataSource ds=(datasource==null)?null:(DataSource) datasources.get(datasource.toLowerCase()); if(ds!=null) return ds; // create error detail DatabaseException de = new DatabaseException("datasource ["+datasource+"] doesn't exist",null,null,null); de.setDetail(ExceptionUtil.createSoundexDetail(datasource,datasources.keySet().iterator(),"datasource names")); de.setAdditional(KeyConstants._Datasource,datasource); throw de; } @Override public DataSource getDataSource(String datasource, DataSource defaultValue) { DataSource ds=(datasource==null)?null:(DataSource) datasources.get(datasource.toLowerCase()); if(ds!=null) return ds; return defaultValue; } @Override public PrintWriter getErrWriter() { return err; } /** * @param err the err to set */ protected void setErr(PrintWriter err) { this.err = err; } @Override public PrintWriter getOutWriter() { return out; } /** * @param out the out to set */ protected void setOut(PrintWriter out) { this.out = out; } public DatasourceConnectionPool getDatasourceConnectionPool() { return pool; } public boolean doLocalCustomTag() { return doLocalCustomTag; } @Override public String[] getCustomTagExtensions() { return customTagExtensions; } protected void setCustomTagExtensions(String... customTagExtensions) { this.customTagExtensions = customTagExtensions; } protected void setDoLocalCustomTag(boolean doLocalCustomTag) { this.doLocalCustomTag= doLocalCustomTag; } public boolean doComponentDeepSearch() { return doComponentTagDeepSearch; } protected void setDoComponentDeepSearch(boolean doComponentTagDeepSearch) { this.doComponentTagDeepSearch = doComponentTagDeepSearch; } @Override public boolean doCustomTagDeepSearch() { return doCustomTagDeepSearch; } /** * @param doCustomTagDeepSearch the doCustomTagDeepSearch to set */ protected void setDoCustomTagDeepSearch(boolean doCustomTagDeepSearch) { this.doCustomTagDeepSearch = doCustomTagDeepSearch; } protected void setVersion(double version) { this.version=version; } /** * @return the version */ public double getVersion() { return version; } public boolean closeConnection() { return closeConnection; } protected void setCloseConnection(boolean closeConnection) { this.closeConnection=closeConnection; } public boolean contentLength() { return contentLength; } public boolean allowCompression() { return allowCompression; } protected void setAllowCompression(boolean allowCompression) { this.allowCompression= allowCompression; } protected void setContentLength(boolean contentLength) { this.contentLength=contentLength; } /** * @return the constants */ public Struct getConstants() { return constants; } /** * @param constants the constants to set */ protected void setConstants(Struct constants) { this.constants = constants; } /** * @return the showVersion */ public boolean isShowVersion() { return showVersion; } /** * @param showVersion the showVersion to set */ protected void setShowVersion(boolean showVersion) { this.showVersion = showVersion; } protected void setRemoteClients(RemoteClient[] remoteClients) { this.remoteClients=remoteClients; } public RemoteClient[] getRemoteClients() { if(remoteClients==null) return new RemoteClient[0]; return remoteClients; } public SpoolerEngine getSpoolerEngine() { return remoteClientSpoolerEngine; } protected void setRemoteClientDirectory(Resource remoteClientDirectory) { this.remoteClientDirectory=remoteClientDirectory; } /** * @return the remoteClientDirectory */ public Resource getRemoteClientDirectory() { return remoteClientDirectory; } protected void setSpoolerEngine(SpoolerEngine spoolerEngine) { this.remoteClientSpoolerEngine=spoolerEngine; } /* * * @return the structCase * / public int getStructCase() { return structCase; }*/ /* * * @param structCase the structCase to set * / protected void setStructCase(int structCase) { this.structCase = structCase; }*/ /** * @return if error status code will be returned or not */ public boolean getErrorStatusCode() { return errorStatusCode; } /** * @param errorStatusCode the errorStatusCode to set */ protected void setErrorStatusCode(boolean errorStatusCode) { this.errorStatusCode = errorStatusCode; } @Override public int getLocalMode() { return localMode; } /** * @param localMode the localMode to set */ protected void setLocalMode(int localMode) { this.localMode = localMode; } /** * @param strLocalMode the localMode to set */ protected void setLocalMode(String strLocalMode) { this.localMode=AppListenerUtil.toLocalMode(strLocalMode,this.localMode); } public Resource getVideoDirectory() { // TODO take from tag <video> Resource dir = getConfigDir().getRealResource("video"); if(!dir.exists())dir.mkdirs(); return dir; } public Resource getExtensionDirectory() { // TODO take from tag <extensions> Resource dir = getConfigDir().getRealResource("extensions/installed"); if(!dir.exists())dir.mkdirs(); return dir; } protected void setExtensionProviders(ExtensionProvider[] extensionProviders) { this.extensionProviders=extensionProviders; } @Override public ExtensionProvider[] getExtensionProviders() { return extensionProviders; } protected void setRHExtensionProviders(RHExtensionProvider[] extensionProviders) { this.rhextensionProviders=extensionProviders; } public RHExtensionProvider[] getRHExtensionProviders() { return rhextensionProviders; } public Extension[] getExtensions() { return extensions; } public RHExtension[] getRHExtensions() { return rhextensions; } public abstract RHExtension[] getServerRHExtensions(); protected void setExtensions(Extension[] extensions) { this.extensions=extensions; } protected void setExtensions(RHExtension[] extensions) { this.rhextensions=extensions; } protected void setExtensionEnabled(boolean extensionEnabled) { this.extensionEnabled=extensionEnabled; } public boolean isExtensionEnabled() { return extensionEnabled; } public boolean allowRealPath() { return allowRealPath; } protected void setAllowRealPath(boolean allowRealPath) { this.allowRealPath=allowRealPath; } /** * @return the classClusterScope */ public Class getClusterClass() { return clusterClass; } /** * @param clusterClass the classClusterScope to set */ protected void setClusterClass(Class clusterClass) { this.clusterClass = clusterClass; } @Override public Struct getRemoteClientUsage() { if(remoteClientUsage==null)remoteClientUsage=new StructImpl(); return remoteClientUsage; } protected void setRemoteClientUsage(Struct remoteClientUsage) { this.remoteClientUsage=remoteClientUsage; } @Override public Class<AdminSync> getAdminSyncClass() { return adminSyncClass; } protected void setAdminSyncClass(Class adminSyncClass) { this.adminSyncClass=adminSyncClass; this.adminSync=null; } public AdminSync getAdminSync() throws ClassException { if(adminSync==null){ adminSync=(AdminSync) ClassUtil.loadInstance(getAdminSyncClass()); } return this.adminSync; } @Override public Class getVideoExecuterClass() { return videoExecuterClass; } protected void setVideoExecuterClass(Class videoExecuterClass) { this.videoExecuterClass=videoExecuterClass; } protected void setUseTimeServer(boolean useTimeServer) { this.useTimeServer=useTimeServer; } public boolean getUseTimeServer() { return useTimeServer; } /** * @return the tagMappings */ public Mapping getTagMapping() { return tagMapping; } public Mapping getFunctionMapping() { return functionMapping; } /* * * @return the tagDirectory public Resource getTagDirectory() { return tagDirectory; } */ /** * mapping used for script (JSR 223) * @return */ public Mapping getScriptMapping() { if(scriptMapping==null) { // Physical resource TODO make in RAM Resource physical=getConfigDir().getRealResource("jsr223"); if(!physical.exists()) physical.mkdirs(); this.scriptMapping= new MappingImpl(this,"/mapping-script/",physical.getAbsolutePath(),null,ConfigImpl.INSPECT_NEVER,true,true,true,true,false,true,null,-1,-1); } return scriptMapping; } public String getDefaultDataSource() { // TODO Auto-generated method stub return null; } protected void setDefaultDataSource(String defaultDataSource) { //this.defaultDataSource=defaultDataSource; } /** * @return the inspectTemplate */ public short getInspectTemplate() { return inspectTemplate; } public boolean getTypeChecking() { return typeChecking; } protected void setTypeChecking(boolean typeChecking) { this.typeChecking=typeChecking; } /** * @param inspectTemplate the inspectTemplate to set */ protected void setInspectTemplate(short inspectTemplate) { this.inspectTemplate = inspectTemplate; } protected void setSerialNumber(String serial) { this.serial=serial; } public String getSerialNumber() { return serial; } protected void setCaches(Map<String,CacheConnection> caches) { this.caches=caches; Iterator<Entry<String, CacheConnection>> it = caches.entrySet().iterator(); Entry<String, CacheConnection> entry; CacheConnection cc; while(it.hasNext()){ entry = it.next(); cc=entry.getValue(); if(cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameTemplate)){ defaultCacheTemplate=cc; } else if(cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameFunction)){ defaultCacheFunction=cc; } else if(cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameQuery)){ defaultCacheQuery=cc; } else if(cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameResource)){ defaultCacheResource=cc; } else if(cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameObject)){ defaultCacheObject=cc; } else if(cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameInclude)){ defaultCacheInclude=cc; } else if(cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameHTTP)){ defaultCacheHTTP=cc; } else if(cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameFile)){ defaultCacheFile=cc; } else if(cc.getName().equalsIgnoreCase(cacheDefaultConnectionNameWebservice)){ defaultCacheWebservice=cc; } } } @Override public Map<String,CacheConnection> getCacheConnections() { return caches; } // used by argus cache FUTURE add to interface /** * creates a new RamCache, please make sure to finalize. * @param arguments possible arguments are "timeToLiveSeconds", "timeToIdleSeconds" and "controlInterval" * @throws IOException */ public Cache createRAMCache(Struct arguments) throws IOException { RamCache rc = new RamCache(); if(arguments==null) arguments=new StructImpl(); rc.init(this, ""+CreateUniqueId.invoke(), arguments); return rc; } @Override public CacheConnection getCacheDefaultConnection(int type) { if(type==CACHE_TYPE_FUNCTION) return defaultCacheFunction; if(type==CACHE_TYPE_OBJECT) return defaultCacheObject; if(type==CACHE_TYPE_TEMPLATE) return defaultCacheTemplate; if(type==CACHE_TYPE_QUERY) return defaultCacheQuery; if(type==CACHE_TYPE_RESOURCE) return defaultCacheResource; if(type==CACHE_TYPE_INCLUDE) return defaultCacheInclude; if(type==CACHE_TYPE_HTTP) return defaultCacheHTTP; if(type==CACHE_TYPE_FILE) return defaultCacheFile; if(type==CACHE_TYPE_WEBSERVICE) return defaultCacheWebservice; return null; } protected void setCacheDefaultConnectionName(int type,String cacheDefaultConnectionName) { if(type==CACHE_TYPE_FUNCTION) cacheDefaultConnectionNameFunction=cacheDefaultConnectionName; else if(type==CACHE_TYPE_OBJECT) cacheDefaultConnectionNameObject=cacheDefaultConnectionName; else if(type==CACHE_TYPE_TEMPLATE) cacheDefaultConnectionNameTemplate=cacheDefaultConnectionName; else if(type==CACHE_TYPE_QUERY) cacheDefaultConnectionNameQuery=cacheDefaultConnectionName; else if(type==CACHE_TYPE_RESOURCE) cacheDefaultConnectionNameResource=cacheDefaultConnectionName; else if(type==CACHE_TYPE_INCLUDE) cacheDefaultConnectionNameInclude=cacheDefaultConnectionName; else if(type==CACHE_TYPE_HTTP) cacheDefaultConnectionNameHTTP=cacheDefaultConnectionName; else if(type==CACHE_TYPE_FILE) cacheDefaultConnectionNameFile=cacheDefaultConnectionName; else if(type==CACHE_TYPE_WEBSERVICE) cacheDefaultConnectionNameWebservice=cacheDefaultConnectionName; } @Override public String getCacheDefaultConnectionName(int type) { if(type==CACHE_TYPE_FUNCTION) return cacheDefaultConnectionNameFunction; if(type==CACHE_TYPE_OBJECT) return cacheDefaultConnectionNameObject; if(type==CACHE_TYPE_TEMPLATE) return cacheDefaultConnectionNameTemplate; if(type==CACHE_TYPE_QUERY) return cacheDefaultConnectionNameQuery; if(type==CACHE_TYPE_RESOURCE) return cacheDefaultConnectionNameResource; if(type==CACHE_TYPE_INCLUDE) return cacheDefaultConnectionNameInclude; if(type==CACHE_TYPE_HTTP) return cacheDefaultConnectionNameHTTP; if(type==CACHE_TYPE_FILE) return cacheDefaultConnectionNameFile; if(type==CACHE_TYPE_WEBSERVICE) return cacheDefaultConnectionNameWebservice; return null; } public String getCacheMD5() { return cacheMD5; } public void setCacheMD5(String cacheMD5) { this.cacheMD5 = cacheMD5; } public boolean getExecutionLogEnabled() { return executionLogEnabled; } protected void setExecutionLogEnabled(boolean executionLogEnabled) { this.executionLogEnabled= executionLogEnabled; } public ExecutionLogFactory getExecutionLogFactory() { return executionLogFactory; } protected void setExecutionLogFactory(ExecutionLogFactory executionLogFactory) { this.executionLogFactory= executionLogFactory; } public ORMEngine resetORMEngine(PageContext pc, boolean force) throws PageException { //String name = pc.getApplicationContext().getName(); //ormengines.remove(name); ORMEngine e = getORMEngine(pc); e.reload(pc,force); return e; } @Override public ORMEngine getORMEngine(PageContext pc) throws PageException { String name = pc.getApplicationContext().getName(); ORMEngine engine = ormengines.get(name); if(engine==null){ //try { Throwable t=null; try { engine=(ORMEngine)ClassUtil.loadInstance(cdORMEngine.getClazz()); engine.init(pc); } catch (ClassException ce) { t=ce; } catch (BundleException be) { t=be; } catch (NoClassDefFoundError ncfe) { t=ncfe; } if(t!=null) { ApplicationException ae = new ApplicationException( "cannot initialize ORM Engine ["+cdORMEngine+"], make sure you have added all the required jar files"); ae.setStackTrace(t.getStackTrace()); ae.setDetail(t.getMessage()); } ormengines.put(name,engine); /*} catch (PageException pe) { throw pe; }*/ } return engine; } public ClassDefinition<? extends ORMEngine> getORMEngineClassDefintion() { return cdORMEngine; } @Override public Mapping[] getComponentMappings() { return componentMappings; } /** * @param componentMappings the componentMappings to set */ protected void setComponentMappings(Mapping[] componentMappings) { this.componentMappings = componentMappings; } protected void setORMEngineClass(ClassDefinition<? extends ORMEngine> cd) { this.cdORMEngine=cd; } public ClassDefinition<? extends ORMEngine> getORMEngineClass() { return this.cdORMEngine; } protected void setORMConfig(ORMConfiguration ormConfig) { this.ormConfig=ormConfig; } public ORMConfiguration getORMConfig() { return ormConfig; } private Map<String,PageSource> componentPathCache=null;//new ArrayList<Page>(); private Map<String,InitFile> ctPatchCache=null;//new ArrayList<Page>(); private Map<String,UDF> udfCache=new ReferenceMap<String,UDF>(); public CIPage getCachedPage(PageContext pc,String pathWithCFC) throws TemplateException { if(componentPathCache==null) return null; PageSource ps = componentPathCache.get(pathWithCFC.toLowerCase()); if(ps==null) return null; try { return (CIPage) ps.loadPageThrowTemplateException(pc,false,(Page)null); } catch (PageException pe) { throw (TemplateException)pe; } } public void putCachedPageSource(String pathWithCFC,PageSource ps) { if(componentPathCache==null) componentPathCache=Collections.synchronizedMap(new HashMap<String, PageSource>());//MUSTMUST new ReferenceMap(ReferenceMap.SOFT,ReferenceMap.SOFT); componentPathCache.put(pathWithCFC.toLowerCase(),ps); } public InitFile getCTInitFile(PageContext pc,String key) { if(ctPatchCache==null) return null; InitFile initFile = ctPatchCache.get(key.toLowerCase()); if(initFile!=null){ if(MappingImpl.isOK(initFile.getPageSource()))return initFile; ctPatchCache.remove(key.toLowerCase()); } return null; } public void putCTInitFile(String key,InitFile initFile) { if(ctPatchCache==null) ctPatchCache=Collections.synchronizedMap(new HashMap<String, InitFile>());//MUSTMUST new ReferenceMap(ReferenceMap.SOFT,ReferenceMap.SOFT); ctPatchCache.put(key.toLowerCase(),initFile); } public Struct listCTCache() { Struct sct=new StructImpl(); if(ctPatchCache==null) return sct; Iterator<Entry<String, InitFile>> it = ctPatchCache.entrySet().iterator(); Entry<String, InitFile> entry; while(it.hasNext()){ entry = it.next(); sct.setEL(entry.getKey(),entry.getValue().getPageSource().getDisplayPath()); } return sct; } public void clearCTCache() { if(ctPatchCache==null) return; ctPatchCache.clear(); } public void clearFunctionCache() { udfCache.clear(); } public UDF getFromFunctionCache(String key) { return udfCache.get(key); } public void putToFunctionCache(String key,UDF udf) { udfCache.put(key, udf); } public Struct listComponentCache() { Struct sct=new StructImpl(); if(componentPathCache==null) return sct; Iterator<Entry<String, PageSource>> it = componentPathCache.entrySet().iterator(); Entry<String, PageSource> entry; while(it.hasNext()){ entry = it.next(); sct.setEL(entry.getKey(),entry.getValue().getDisplayPath()); } return sct; } public void clearComponentCache() { if(componentPathCache==null) return; componentPathCache.clear(); } public ImportDefintion getComponentDefaultImport() { return componentDefaultImport; } protected void setComponentDefaultImport(String str) { if(StringUtil.isEmpty(str)) return; if("org.railo.cfml.*".equalsIgnoreCase(str)) str="org.lucee.cfml.*"; ImportDefintion cdi = ImportDefintionImpl.getInstance(str, null); if(cdi!=null)this.componentDefaultImport= cdi; } /** * @return the componentLocalSearch */ public boolean getComponentLocalSearch() { return componentLocalSearch; } /** * @param componentLocalSearch the componentLocalSearch to set */ protected void setComponentLocalSearch(boolean componentLocalSearch) { this.componentLocalSearch = componentLocalSearch; } /** * @return the componentLocalSearch */ public boolean getComponentRootSearch() { return componentRootSearch; } /** * @param componentRootSearch the componentLocalSearch to set */ protected void setComponentRootSearch(boolean componentRootSearch) { this.componentRootSearch = componentRootSearch; } private final Map<String,Compress> compressResources= new ReferenceMap<String,Compress>(SOFT,SOFT); public Compress getCompressInstance(Resource zipFile, int format, boolean caseSensitive) throws IOException { Compress compress=(Compress) compressResources.get(zipFile.getPath()); if(compress==null) { compress=new Compress(zipFile,format,caseSensitive); compressResources.put(zipFile.getPath(), compress); } return compress; } public boolean getSessionCluster() { return false; } public boolean getClientCluster() { return false; } public String getClientStorage() { return clientStorage; } public String getSessionStorage() { return sessionStorage; } protected void setClientStorage(String clientStorage) { this.clientStorage = clientStorage; } protected void setSessionStorage(String sessionStorage) { this.sessionStorage = sessionStorage; } private Map<String,ComponentMetaData> componentMetaData=null; public ComponentMetaData getComponentMetadata(String key) { if(componentMetaData==null) return null; return componentMetaData.get(key.toLowerCase()); } public void putComponentMetadata(String key,ComponentMetaData data) { if(componentMetaData==null) componentMetaData=new HashMap<String, ComponentMetaData>(); componentMetaData.put(key.toLowerCase(),data); } public void clearComponentMetadata() { if(componentMetaData==null) return; componentMetaData.clear(); } public static class ComponentMetaData { public final Struct meta; public final long lastMod; public ComponentMetaData(Struct meta, long lastMod) { this.meta=meta; this.lastMod=lastMod; } } private DebugEntry[] debugEntries; protected void setDebugEntries(DebugEntry[] debugEntries) { this.debugEntries=debugEntries; } public DebugEntry[] getDebugEntries() { if(debugEntries==null)debugEntries=new DebugEntry[0]; return debugEntries; } public DebugEntry getDebugEntry(String ip, DebugEntry defaultValue) { if(debugEntries.length==0) return defaultValue; short[] sarr; try { sarr = IPRange.toShortArray(ip); } catch (IOException e) { return defaultValue; } for(int i=0;i<debugEntries.length;i++){ if(debugEntries[i].getIpRange().inRange(sarr)) return debugEntries[i]; } return defaultValue; } private int debugMaxRecordsLogged=10; protected void setDebugMaxRecordsLogged(int debugMaxRecordsLogged) { this.debugMaxRecordsLogged=debugMaxRecordsLogged; } public int getDebugMaxRecordsLogged() { return debugMaxRecordsLogged; } private boolean dotNotationUpperCase=true; protected void setDotNotationUpperCase(boolean dotNotationUpperCase) { this.dotNotationUpperCase=dotNotationUpperCase; } public boolean getDotNotationUpperCase() { return dotNotationUpperCase; } public boolean preserveCase() { return !dotNotationUpperCase; } private boolean defaultFunctionOutput=true; protected void setDefaultFunctionOutput(boolean defaultFunctionOutput) { this.defaultFunctionOutput=defaultFunctionOutput; } public boolean getDefaultFunctionOutput() { return defaultFunctionOutput; } private boolean getSuppressWSBeforeArg=true; protected void setSuppressWSBeforeArg(boolean getSuppressWSBeforeArg) { this.getSuppressWSBeforeArg=getSuppressWSBeforeArg; } public boolean getSuppressWSBeforeArg() { return getSuppressWSBeforeArg; } private RestSettings restSetting=new RestSettingImpl(false,UDF.RETURN_FORMAT_JSON); protected void setRestSetting(RestSettings restSetting){ this.restSetting= restSetting; } @Override public RestSettings getRestSetting(){ return restSetting; } protected void setMode(int mode) { this.mode=mode; } public int getMode() { return mode; } // do not move to Config interface, do instead getCFMLWriterClass protected void setCFMLWriterType(int writerType) { this.writerType=writerType; } // do not move to Config interface, do instead setCFMLWriterClass public int getCFMLWriterType() { return writerType; } private boolean bufferOutput=false; private int externalizeStringGTE=-1; private Map<String, BundleDefinition> extensionBundles; private JDBCDriver[] drivers; private Resource logDir; public boolean getBufferOutput() { return bufferOutput; } protected void setBufferOutput(boolean bufferOutput) { this.bufferOutput= bufferOutput; } public int getDebugOptions() { return debugOptions; } public boolean hasDebugOptions(int debugOption) { return (debugOptions&debugOption)>0 ; } protected void setDebugOptions(int debugOptions) { this.debugOptions = debugOptions; } protected void setCheckForChangesInConfigFile(boolean checkForChangesInConfigFile) { this.checkForChangesInConfigFile=checkForChangesInConfigFile; } public boolean checkForChangesInConfigFile() { return checkForChangesInConfigFile; } public abstract Cluster createClusterScope() throws PageException; protected void setExternalizeStringGTE(int externalizeStringGTE) { this.externalizeStringGTE=externalizeStringGTE; } public int getExternalizeStringGTE() { return externalizeStringGTE; } protected void addConsoleLayout(Layout layout) { consoleLayouts.add(layout); } protected void addResourceLayout(Layout layout) { resourceLayouts.add(layout); } public Layout[] getConsoleLayouts() { if(consoleLayouts.isEmpty()) consoleLayouts.add(new PatternLayout("%d{dd.MM.yyyy HH:mm:ss,SSS} %-5p [%c] %m%n")); return consoleLayouts.toArray(new Layout[consoleLayouts.size()]); } public Layout[] getResourceLayouts() { if(resourceLayouts.isEmpty()) resourceLayouts.add(new ClassicLayout()); return resourceLayouts.toArray(new Layout[resourceLayouts.size()]); } protected void clearLoggers(Boolean dyn) { if(loggers.size()==0) return; List<String> list=dyn!=null?new ArrayList<String>():null; try{ Iterator<Entry<String, LoggerAndSourceData>> it = loggers.entrySet().iterator(); Entry<String, LoggerAndSourceData> e; while(it.hasNext()){ e = it.next(); if(dyn==null || dyn.booleanValue()==e.getValue().getDyn()) { e.getValue().close(); if(list!=null)list.add(e.getKey()); } } } catch(Exception e) {} if(list==null) loggers.clear(); else { Iterator<String> it = list.iterator(); while(it.hasNext()) { loggers.remove(it.next()); } } } protected LoggerAndSourceData addLogger(String name, Level level, ClassDefinition appender, Map<String, String> appenderArgs, ClassDefinition layout, Map<String, String> layoutArgs, boolean readOnly, boolean dyn) { LoggerAndSourceData existing = loggers.get(name.toLowerCase()); String id=LoggerAndSourceData.id(name.toLowerCase(), appender,appenderArgs,layout,layoutArgs,level,readOnly); if(existing!=null) { if(existing.id().equals(id)) { return existing; } existing.close(); } LoggerAndSourceData las = new LoggerAndSourceData(this,id,name.toLowerCase(), appender,appenderArgs,layout,layoutArgs, level,readOnly,dyn); loggers.put(name.toLowerCase(),las); return las; } public Map<String,LoggerAndSourceData> getLoggers(){ return loggers; } // FUTURE add to interface public String[] getLogNames(){ return loggers.keySet().toArray(new String[loggers.size()]); } @Override public Log getLog(String name){ return getLog(name, true); } public Log getLog(String name, boolean createIfNecessary){ LoggerAndSourceData lsd = _getLoggerAndSourceData(name,createIfNecessary); if(lsd==null) return null; return lsd.getLog(); } private LoggerAndSourceData _getLoggerAndSourceData(String name, boolean createIfNecessary){ LoggerAndSourceData las = loggers.get(name.toLowerCase()); if(las==null) { if(!createIfNecessary) return null; return addLogger(name, Level.ERROR, Log4jUtil.appenderClassDefintion("console"), null, Log4jUtil.layoutClassDefintion("pattern"), null,true,true); } return las; } public Map<Key, Map<Key, Object>> getTagDefaultAttributeValues() { return tagDefaultAttributeValues==null?null:Duplicator.duplicateMap(tagDefaultAttributeValues,new HashMap<Key, Map<Key, Object>>(),true); } protected void setTagDefaultAttributeValues(Map<Key, Map<Key, Object>> values) { this.tagDefaultAttributeValues=values; } @Override public Boolean getHandleUnQuotedAttrValueAsString(){ return handleUnQuotedAttrValueAsString; } protected void setHandleUnQuotedAttrValueAsString(boolean handleUnQuotedAttrValueAsString){ this.handleUnQuotedAttrValueAsString=handleUnQuotedAttrValueAsString; } protected void setCachedWithin(int type, Object value) { cachedWithins.put(type,value); } @Override public Object getCachedWithin(int type) { return cachedWithins.get(type); } public Resource getPluginDirectory() { return getConfigDir().getRealResource("context/admin/plugin"); } public Resource getLogDirectory() { if(logDir==null) { logDir=getConfigDir().getRealResource("logs"); logDir.mkdir(); } return logDir; } protected void setSalt(String salt) { this.salt=salt; } public String getSalt() { return this.salt; } public int getPasswordType() { if(password==null) return Password.HASHED_SALTED;// when there is no password, we will have a HS password return password.getType(); } public String getPasswordSalt() { if(password==null || password.getSalt()==null) return this.salt; return password.getSalt(); } public int getPasswordOrigin() { if(password==null) return Password.ORIGIN_UNKNOW; return password.getOrigin(); } public static ConfigServer getConfigServer(Config config, Password password) throws PageException { if(config instanceof ConfigServer) return (ConfigServer) config; return ((ConfigWeb)config).getConfigServer(password); } public Collection<BundleDefinition> getExtensionBundleDefintions() { if(this.extensionBundles==null) { RHExtension[] rhes = getRHExtensions(); Map<String, BundleDefinition> extensionBundles=new HashMap<String,BundleDefinition>(); for(RHExtension rhe:rhes) { BundleInfo[] bis; try { bis = rhe.getBundles(); } catch (Exception e) { continue; } if(bis!=null)for(BundleInfo bi:bis) { extensionBundles.put(bi.getSymbolicName()+"|"+bi.getVersionAsString(), bi.toBundleDefinition()); } } this.extensionBundles=extensionBundles; } return extensionBundles.values(); } /** * get the extension bundle defintion not only from this context, get it from all contexts, including the server context * @return */ public abstract Collection<BundleDefinition> getAllExtensionBundleDefintions(); public abstract Collection<RHExtension> getAllRHExtensions(); protected void setJDBCDrivers(JDBCDriver[] drivers) { this.drivers=drivers; } public JDBCDriver[] getJDBCDrivers() { return drivers; } public JDBCDriver getJDBCDriverByClassName(String className, JDBCDriver defaultValue) { for(JDBCDriver d:drivers){ if(d.cd.getClassName().equals(className)) return d; } return defaultValue; } public JDBCDriver getJDBCDriverByBundle(String bundleName, Version version, JDBCDriver defaultValue) { for(JDBCDriver d:drivers){ if(d.cd.getName().equals(bundleName) && (version==null || version.equals(d.cd.getVersion()))) return d; } return defaultValue; } public JDBCDriver getJDBCDriverById(String id, JDBCDriver defaultValue) { for(JDBCDriver d:drivers){ if(d.cd.getId().equals(id)) return d; } return defaultValue; } public int getQueueMax() { return queueMax; } protected void setQueueMax(int queueMax) { this.queueMax = queueMax; } public long getQueueTimeout() { return queueTimeout; } protected void setQueueTimeout(long queueTimeout) { this.queueTimeout = queueTimeout; } public boolean getQueueEnable() { return queueEnable; } protected void setQueueEnable(boolean queueEnable) { this.queueEnable = queueEnable; } private boolean cgiScopeReadonly=true; public boolean getCGIScopeReadonly() { return cgiScopeReadonly; } protected void setCGIScopeReadonly(boolean cgiScopeReadonly) { this.cgiScopeReadonly = cgiScopeReadonly; } private Resource deployDir; public Resource getDeployDirectory() { if(deployDir==null) { // config web if(this instanceof ConfigWeb) { deployDir = getConfigDir().getRealResource("deploy"); if(!deployDir.exists())deployDir.mkdirs(); } // config server else { try { File file = new File(ConfigWebUtil.getEngine(this).getCFMLEngineFactory().getResourceRoot(),"deploy"); if(!file.exists()) file.mkdirs(); deployDir=ResourcesImpl.getFileResourceProvider() .getResource(file.getAbsolutePath()); } catch(IOException ioe) { deployDir = getConfigDir().getRealResource("deploy"); if(!deployDir.exists())deployDir.mkdirs(); } } } return deployDir; } private boolean allowLuceeDialect=false; public boolean allowLuceeDialect() { return allowLuceeDialect; } public void setAllowLuceeDialect(boolean allowLuceeDialect) { this. allowLuceeDialect=allowLuceeDialect; } public boolean installExtension(ExtensionDefintion ed) { return DeployHandler.deployExtension(this, ed, getLog("deploy"),true); } public abstract List<ExtensionDefintion> loadLocalExtensions(); private Map<String,ClassDefinition> cacheDefinitions; public void setCacheDefinitions(Map<String,ClassDefinition> caches) { this.cacheDefinitions=caches; } public Map<String,ClassDefinition> getCacheDefinitions() { return this.cacheDefinitions; } public ClassDefinition getCacheDefinition(String className) { return this.cacheDefinitions.get(className); } public Resource getAntiSamyPolicy() { return getConfigDir().getRealResource("security/antisamy-basic.xml"); } protected abstract void setGatewayEntries(Map<String, GatewayEntry> gatewayEntries); public abstract Map<String, GatewayEntry> getGatewayEntries(); }
package reb2sac; import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.prefs.Preferences; import javax.swing.*; import parser.*; import lhpn2sbml.gui.LHPNEditor; import lhpn2sbml.parser.Abstraction; import lhpn2sbml.parser.LhpnFile; import lhpn2sbml.parser.Translator; import gillespieSSAjava.GillespieSSAJavaSingleStep; import biomodelsim.*; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.parser.GCMFile; import gcm2sbml.util.GlobalConstants; import graph.*; import buttons.*; import sbmleditor.*; import stategraph.BuildStateGraphThread; import stategraph.PerfromSteadyStateMarkovAnalysisThread; import stategraph.PerfromTransientMarkovAnalysisThread; import stategraph.StateGraph; import verification.AbstPane; /** * This class creates the properties file that is given to the reb2sac program. * It also executes the reb2sac program. * * @author Curtis Madsen */ public class Run implements ActionListener { private Process reb2sac; private String separator; private Reb2Sac r2s; StateGraph sg; public Run(Reb2Sac reb2sac) { r2s = reb2sac; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } } /** * This method is given which buttons are selected and creates the * properties file from all the other information given. * * @param useInterval * * @param stem */ public void createProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, double absError, String outDir, long rndSeed, int run, String[] termCond, String[] intSpecies, String printer_id, String printer_track_quantity, String[] getFilename, String selectedButtons, Component component, String filename, double rap1, double rap2, double qss, int con, JCheckBox usingSSA, String ssaFile, JCheckBox usingSad, File sadFile, JList preAbs, JList loopAbs, JList postAbs, AbstPane abstPane) { Properties abs = new Properties(); if (selectedButtons.contains("abs") || selectedButtons.contains("nary")) { for (int i = 0; i < preAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.1." + (i + 1), (String) preAbs .getModel().getElementAt(i)); } for (int i = 0; i < loopAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.2." + (i + 1), (String) loopAbs .getModel().getElementAt(i)); } // abs.setProperty("reb2sac.abstraction.method.0.1", // "enzyme-kinetic-qssa-1"); // abs.setProperty("reb2sac.abstraction.method.0.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.0.3", // "multiple-products-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.4", // "multiple-reactants-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.5", // "single-reactant-product-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.6", // "dimer-to-monomer-substitutor"); // abs.setProperty("reb2sac.abstraction.method.0.7", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.1", // "modifier-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.2", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.1", // "operator-site-forward-binding-remover"); // abs.setProperty("reb2sac.abstraction.method.2.3", // "enzyme-kinetic-rapid-equilibrium-1"); // abs.setProperty("reb2sac.abstraction.method.2.4", // "irrelevant-species-remover"); // abs.setProperty("reb2sac.abstraction.method.2.5", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.2.6", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.7", // "similar-reaction-combiner"); // abs.setProperty("reb2sac.abstraction.method.2.8", // "modifier-constant-propagation"); } // if (selectedButtons.contains("abs")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction"); // else if (selectedButtons.contains("nary")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction-level-assignment"); for (int i = 0; i < postAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.3." + (i + 1), (String) postAbs.getModel() .getElementAt(i)); } abs.setProperty("simulation.printer", printer_id); abs.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); // if (selectedButtons.contains("monteCarlo")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "distribute-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.3", // "kinetic-law-constants-simplifier"); // else if (selectedButtons.contains("none")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "kinetic-law-constants-simplifier"); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); abs.setProperty("reb2sac.interesting.species." + (i + 1), split[0]); if (split.length > 1) { String[] levels = split[1].split(","); for (int j = 0; j < levels.length; j++) { abs.setProperty("reb2sac.concentration.level." + split[0] + "." + (j + 1), levels[j]); } } } } abs.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); abs.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); abs.setProperty("reb2sac.qssa.condition.1", "" + qss); abs.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); if (selectedButtons.contains("none")) { abs.setProperty("reb2sac.abstraction.method", "none"); } if (selectedButtons.contains("abs")) { abs.setProperty("reb2sac.abstraction.method", "abs"); } else if (selectedButtons.contains("nary")) { abs.setProperty("reb2sac.abstraction.method", "nary"); } if (abstPane != null) { for (Integer i = 0; i < abstPane.preAbsModel.size(); i++) { abs .setProperty("abstraction.transform." + abstPane.preAbsModel.getElementAt(i).toString(), "preloop" + i.toString()); } for (Integer i = 0; i < abstPane.loopAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.loopAbsModel.getElementAt(i))) { String value = abs .getProperty(abstPane.loopAbsModel.getElementAt(i).toString()); value = value + "mainloop" + i.toString(); abs.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), value); } else { abs.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), "mainloop" + i.toString()); } } for (Integer i = 0; i < abstPane.postAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.postAbsModel.getElementAt(i)) || abstPane.preAbsModel.contains(abstPane.postAbsModel.get(i))) { String value = abs .getProperty(abstPane.postAbsModel.getElementAt(i).toString()); value = value + "postloop" + i.toString(); abs.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), value); } else { abs.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), "postloop" + i.toString()); } } for (String s : abstPane.transforms) { if (!abstPane.preAbsModel.contains(s) && !abstPane.loopAbsModel.contains(s) && !abstPane.postAbsModel.contains(s)) { abs.remove(s); } } } if (selectedButtons.contains("ODE")) { abs.setProperty("reb2sac.simulation.method", "ODE"); } else if (selectedButtons.contains("monteCarlo")) { abs.setProperty("reb2sac.simulation.method", "monteCarlo"); } else if (selectedButtons.contains("markov")) { abs.setProperty("reb2sac.simulation.method", "markov"); } else if (selectedButtons.contains("sbml")) { abs.setProperty("reb2sac.simulation.method", "SBML"); } else if (selectedButtons.contains("dot")) { abs.setProperty("reb2sac.simulation.method", "Network"); } else if (selectedButtons.contains("xhtml")) { abs.setProperty("reb2sac.simulation.method", "Browser"); } else if (selectedButtons.contains("lhpn")) { abs.setProperty("reb2sac.simulation.method", "LPN"); } if (!selectedButtons.contains("monteCarlo")) { // if (selectedButtons.equals("none_ODE") || // selectedButtons.equals("abs_ODE")) { abs.setProperty("ode.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("ode.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs.setProperty("ode.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("ode.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("ode.simulation.time.step", "inf"); } else { abs.setProperty("ode.simulation.time.step", "" + timeStep); } abs.setProperty("ode.simulation.min.time.step", "" + minTimeStep); abs.setProperty("ode.simulation.absolute.error", "" + absError); abs.setProperty("ode.simulation.out.dir", outDir); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); } if (!selectedButtons.contains("ODE")) { // if (selectedButtons.equals("none_monteCarlo") || // selectedButtons.equals("abs_monteCarlo")) { abs.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs .setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("monte.carlo.simulation.time.step", "inf"); } else { abs.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } abs.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); abs.setProperty("monte.carlo.simulation.out.dir", outDir); if (usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "sad"); abs.setProperty("computation.analysis.sad.path", sadFile.getName()); } } if (!usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "constraint"); } if (usingSSA.isSelected() && selectedButtons.contains("monteCarlo")) { abs.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { abs .setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { if (!getFilename[getFilename.length - 1].contains(".")) { getFilename[getFilename.length - 1] += "."; filename += "."; } int cut = 0; for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) { if (getFilename[getFilename.length - 1].charAt(i) == '.') { cut = i; } } FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename .length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, cut) + ".properties")); abs.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for abstraction.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * This method is given what data is entered into the nary frame and creates * the nary properties file from that information. */ public void createNaryProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, String outDir, long rndSeed, int run, String printer_id, String printer_track_quantity, String[] getFilename, Component component, String filename, JRadioButton monteCarlo, String stopE, double stopR, String[] finalS, ArrayList<JTextField> inhib, ArrayList<JList> consLevel, ArrayList<String> getSpeciesProps, ArrayList<Object[]> conLevel, String[] termCond, String[] intSpecies, double rap1, double rap2, double qss, int con, ArrayList<Integer> counts, JCheckBox usingSSA, String ssaFile) { Properties nary = new Properties(); try { FileInputStream load = new FileInputStream(new File(outDir + separator + "species.properties")); nary.load(load); load.close(); } catch (Exception e) { JOptionPane.showMessageDialog(component, "Species Properties File Not Found!", "File Not Found", JOptionPane.ERROR_MESSAGE); } nary.setProperty("reb2sac.abstraction.method.0.1", "enzyme-kinetic-qssa-1"); nary .setProperty("reb2sac.abstraction.method.0.2", "reversible-to-irreversible-transformer"); nary.setProperty("reb2sac.abstraction.method.0.3", "multiple-products-reaction-eliminator"); nary .setProperty("reb2sac.abstraction.method.0.4", "multiple-reactants-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.5", "single-reactant-product-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.6", "dimer-to-monomer-substitutor"); nary.setProperty("reb2sac.abstraction.method.0.7", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.1", "modifier-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.1", "operator-site-forward-binding-remover"); nary.setProperty("reb2sac.abstraction.method.2.3", "enzyme-kinetic-rapid-equilibrium-1"); nary.setProperty("reb2sac.abstraction.method.2.4", "irrelevant-species-remover"); nary.setProperty("reb2sac.abstraction.method.2.5", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.2.6", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.7", "similar-reaction-combiner"); nary.setProperty("reb2sac.abstraction.method.2.8", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.2", "dimerization-reduction"); nary.setProperty("reb2sac.abstraction.method.3.1", "nary-order-unary-transformer"); nary.setProperty("reb2sac.abstraction.method.3.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.3.3", "absolute-inhibition-generator"); nary.setProperty("reb2sac.abstraction.method.3.4", "final-state-generator"); nary.setProperty("reb2sac.abstraction.method.3.5", "stop-flag-generator"); nary.setProperty("reb2sac.nary.order.decider", "distinct"); nary.setProperty("simulation.printer", printer_id); nary.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); nary.setProperty("reb2sac.analysis.stop.enabled", stopE); nary.setProperty("reb2sac.analysis.stop.rate", "" + stopR); for (int i = 0; i < getSpeciesProps.size(); i++) { if (!(inhib.get(i).getText().trim() != "<<none>>")) { nary.setProperty("reb2sac.absolute.inhibition.threshold." + getSpeciesProps.get(i), inhib.get(i).getText().trim()); } String[] consLevels = Buttons.getList(conLevel.get(i), consLevel.get(i)); for (int j = 0; j < counts.get(i); j++) { nary .remove("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1)); } for (int j = 0; j < consLevels.length; j++) { nary.setProperty("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1), consLevels[j]); } } if (monteCarlo.isSelected()) { nary.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { nary.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { nary.setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { nary.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { nary.setProperty("monte.carlo.simulation.time.step", "inf"); } else { nary.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } nary.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); nary.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); nary.setProperty("monte.carlo.simulation.runs", "" + run); nary.setProperty("monte.carlo.simulation.out.dir", "."); } for (int i = 0; i < finalS.length; i++) { if (finalS[i].trim() != "<<unknown>>") { nary.setProperty("reb2sac.final.state." + (i + 1), "" + finalS[i]); } } if (usingSSA.isSelected() && monteCarlo.isSelected()) { nary.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < intSpecies.length; i++) { if (intSpecies[i] != "") { nary.setProperty("reb2sac.interesting.species." + (i + 1), "" + intSpecies[i]); } } nary.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); nary.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); nary.setProperty("reb2sac.qssa.condition.1", "" + qss); nary.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { nary.setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { FileOutputStream store = new FileOutputStream(new File(filename.replace(".sbml", "") .replace(".xml", "") + ".properties")); nary.store(store, getFilename[getFilename.length - 1].replace(".sbml", "").replace( ".xml", "") + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for simulation.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * Executes the reb2sac program. If ODE, monte carlo, or markov is selected, * this method creates a Graph object. * * @param runTime */ public int execute(String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml, JRadioButton lhpn, Component component, JRadioButton ode, JRadioButton monteCarlo, String sim, String printer_id, String printer_track_quantity, String outDir, JRadioButton nary, int naryRun, String[] intSpecies, Log log, JCheckBox usingSSA, String ssaFile, BioSim biomodelsim, JTabbedPane simTab, String root, JProgressBar progress, String simName, GCM2SBMLEditor gcmEditor, String direct, double timeLimit, double runTime, String modelFile, AbstPane abstPane, JRadioButton abstraction, String lpnProperty, double absError, double timeStep, double printInterval, int runs) { Runtime exec = Runtime.getRuntime(); int exitValue = 255; while (outDir.split(separator)[outDir.split(separator).length - 1].equals(".")) { outDir = outDir.substring(0, outDir.length() - 1 - outDir.split(separator)[outDir.split(separator).length - 1].length()); } try { long time1; String directory = ""; String theFile = ""; String sbmlName = ""; String lhpnName = ""; 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); } if (nary.isSelected() && gcmEditor != null && (monteCarlo.isSelected() || xhtml.isSelected())) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(false) != null) { LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); lpnFile.save(root + separator + simName + separator + lpnName); time1 = System.nanoTime(); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate( root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + simName + separator + lpnName.replace(".lpn", ".sbml")); t1.outputSBML(); } else { return 0; } } if (nary.isSelected() && gcmEditor == null && !sim.contains("markov-chain-analysis") && !lhpn.isSelected() && naryRun == 1) { log.addText("Executing:\nreb2sac --target.encoding=nary-level " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=nary-level " + theFile, null, work); } else if (sbml.isSelected()) { sbmlName = JOptionPane.showInputDialog(component, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (sbmlName != null && !sbmlName.trim().equals("")) { sbmlName = sbmlName.trim(); if (sbmlName.length() > 4) { if (!sbmlName.substring(sbmlName.length() - 3).equals(".xml") || !sbmlName.substring(sbmlName.length() - 4).equals(".sbml")) { sbmlName += ".xml"; } } else { sbmlName += ".xml"; } File f = new File(root + separator + sbmlName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "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(root + separator + sbmlName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { progress.setIndeterminate(true); time1 = System.nanoTime(); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + modelFile); t1.BuildTemplate(root + separator + simName + separator + modelFile, lpnProperty); } else { t1.BuildTemplate(root + separator + modelFile, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); exitValue = 0; } else if (gcmEditor != null && nary.isSelected()) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "") .replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key) .put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(false) != null) { LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); lpnFile.save(root + separator + simName + separator + lpnName); time1 = System.nanoTime(); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate(root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); } else { time1 = System.nanoTime(); return 0; } exitValue = 0; } else { if (abstraction.isSelected() || nary.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + theFile, null, work); } else { log.addText("Outputting SBML file:\n" + root + separator + sbmlName + "\n"); time1 = System.nanoTime(); FileOutputStream fileOutput = new FileOutputStream(new File(root + separator + sbmlName)); FileInputStream fileInput = new FileInputStream(new File(filename)); int read = fileInput.read(); while (read != -1) { fileOutput.write(read); read = fileInput.read(); } fileInput.close(); fileOutput.close(); exitValue = 0; } } } else { time1 = System.nanoTime(); } } else if (lhpn.isSelected()) { lhpnName = JOptionPane.showInputDialog(component, "Enter LPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 4) { if (!lhpnName.substring(lhpnName.length() - 3).equals(".lpn")) { lhpnName += ".lpn"; } } else { lhpnName += ".lpn"; } File f = new File(root + separator + lhpnName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "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(root + separator + lhpnName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); lhpnFile.save(root + separator + lhpnName); time1 = System.nanoTime(); exitValue = 0; } else { ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key) .put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(false) != null) { LhpnFile lhpnFile = gcm.convertToLHPN(specs, conLevel); lhpnFile.save(root + separator + lhpnName); log.addText("Saving GCM file as LHPN:\n" + root + separator + lhpnName + "\n"); } else { return 0; } time1 = System.nanoTime(); exitValue = 0; } } else { time1 = System.nanoTime(); exitValue = 0; } } else if (dot.isSelected()) { if (nary.isSelected() && gcmEditor != null) { // String cmd = "atacs -cPllodpl " // + theFile.replace(".sbml", "").replace(".xml", "") + // ".lpn"; LhpnFile lhpnFile = new LhpnFile(log); lhpnFile.load(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn"); lhpnFile.printDot(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".dot"); time1 = System.nanoTime(); // Process ATACS = exec.exec(cmd, null, work); // ATACS.waitFor(); // log.addText("Executing:\n" + cmd); exitValue = 0; } else if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); lhpnFile.save(root + separator + simName + separator + modelFile); lhpnFile.printDot(root + separator + modelFile.replace(".lpn", ".dot")); // String cmd = "atacs -cPllodpl " + modelFile; // time1 = System.nanoTime(); // Process ATACS = exec.exec(cmd, null, work); // ATACS.waitFor(); // log.addText("Executing:\n" + cmd); time1 = System.nanoTime(); exitValue = 0; } else { log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + out + ".dot " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); } } else if (xhtml.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); } else if (usingSSA.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=ssa-with-user-update " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=ssa-with-user-update " + theFile, null, work); } else { if (sim.equals("atacs")) { log.addText("Executing:\nreb2sac --target.encoding=hse2 " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=hse2 " + theFile, null, work); } else if (sim.contains("markov-chain-analysis")) { time1 = System.nanoTime(); LhpnFile lhpnFile = null; if (modelFile.contains(".lpn")) { lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); } else { new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn").delete(); ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key) .put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(false) != null) { lhpnFile = gcm.convertToLHPN(specs, conLevel); lhpnFile.save(filename.replace(".gcm", "").replace(".sbml", "") .replace(".xml", "") + ".lpn"); log.addText("Saving GCM file as LHPN:\n" + filename.replace(".gcm", "").replace(".sbml", "").replace( ".xml", "") + ".lpn" + "\n"); } else { return 0; } } // gcmEditor.getGCM().createLogicalModel( // filename.replace(".gcm", "").replace(".sbml", // "").replace(".xml", "") // + ".lpn", // log, // biomodelsim, // theFile.replace(".gcm", "").replace(".sbml", // "").replace(".xml", "") // + ".lpn"); // LHPNFile lhpnFile = new LHPNFile(); // while (new File(filename.replace(".gcm", // "").replace(".sbml", "").replace( // ".xml", "") // + ".lpn.temp").exists()) { // if (new File(filename.replace(".gcm", // "").replace(".sbml", "").replace(".xml", // + ".lpn").exists()) { // lhpnFile.load(filename.replace(".gcm", // "").replace(".sbml", "").replace( // ".xml", "") // + ".lpn"); if (lhpnFile != null) { sg = new StateGraph(lhpnFile); BuildStateGraphThread buildStateGraph = new BuildStateGraphThread(sg); buildStateGraph.start(); buildStateGraph.join(); if (sim.equals("steady-state-markov-chain-analysis")) { if (!sg.getStop()) { log.addText("Performing steady state Markov chain analysis.\n"); PerfromSteadyStateMarkovAnalysisThread performMarkovAnalysis = new PerfromSteadyStateMarkovAnalysisThread( sg); time1 = System.nanoTime(); if (modelFile.contains(".lpn")) { performMarkovAnalysis.start(absError, null); } else { ArrayList<String> conditions = new ArrayList<String>(); for (int i = 0; i < gcmEditor.getGCM().getConditions().size(); i++) { if (gcmEditor.getGCM().getConditions().get(i).startsWith( "St")) { conditions.add(Translator .getProbpropExpression(gcmEditor.getGCM() .getConditions().get(i))); } } performMarkovAnalysis.start(absError, conditions); } performMarkovAnalysis.join(); if (!sg.getStop()) { String simrep = sg.getMarkovResults(); if (simrep != null) { FileOutputStream simrepstream = new FileOutputStream( new File(directory + separator + "sim-rep.txt")); simrepstream.write((simrep).getBytes()); simrepstream.close(); } sg.outputStateGraph(filename.replace(".gcm", "").replace( ".sbml", "").replace(".xml", "") + "_sg.dot", true); biomodelsim.enableTabMenu(biomodelsim.getTab() .getSelectedIndex()); } } } else if (sim.equals("transient-markov-chain-analysis")) { if (!sg.getStop()) { log .addText("Performing transient Markov chain analysis with uniformization.\n"); PerfromTransientMarkovAnalysisThread performMarkovAnalysis = new PerfromTransientMarkovAnalysisThread( sg, progress); time1 = System.nanoTime(); if (lpnProperty != null && !lpnProperty.equals("")) { performMarkovAnalysis.start(timeLimit, timeStep, absError, Translator.getProbpropParts(Translator .getProbpropExpression(lpnProperty))); } else { performMarkovAnalysis .start(timeLimit, timeStep, absError, null); } performMarkovAnalysis.join(); if (!sg.getStop()) { String simrep = sg.getMarkovResults(); if (simrep != null) { FileOutputStream simrepstream = new FileOutputStream( new File(directory + separator + "sim-rep.txt")); simrepstream.write((simrep).getBytes()); simrepstream.close(); } sg.outputStateGraph(filename.replace(".gcm", "").replace( ".sbml", "").replace(".xml", "") + "_sg.dot", true); if (sg.outputTSD(directory + separator + "percent-term-time.tsd")) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals( "TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } } } } biomodelsim.enableTabMenu(biomodelsim.getTab() .getSelectedIndex()); } // String simrep = sg.getMarkovResults(); // if (simrep != null) { // FileOutputStream simrepstream = new // FileOutputStream(new File( // directory + separator + "sim-rep.txt")); // simrepstream.write((simrep).getBytes()); // simrepstream.close(); // sg.outputStateGraph(filename.replace(".gcm", // "").replace(".sbml", // "").replace(".xml", "") // + "_sg.dot", true); // biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } // if (sg.getNumberOfStates() > 30) { // String[] options = { "Yes", "No" }; // int value = JOptionPane // .showOptionDialog( // BioSim.frame, // "The state graph contains more than 30 states and may not open well in dotty.\nOpen it with dotty anyway?", // "More Than 30 States", JOptionPane.YES_NO_OPTION, // JOptionPane.WARNING_MESSAGE, null, options, // options[0]); // if (value == JOptionPane.YES_OPTION) { // (System.getProperty("os.name").contentEquals("Linux")) // log.addText("Executing:\ndotty " // + filename.replace(".gcm", "").replace(".sbml", "") // .replace(".xml", "") + "_sg.dot" + "\n"); // exec.exec("dotty " // + theFile.replace(".gcm", "").replace(".sbml", // "").replace( // ".xml", "") + "_sg.dot", null, work); // else if // (System.getProperty("os.name").toLowerCase().startsWith( // "mac os")) { // log.addText("Executing:\nopen " // + filename.replace(".gcm", "").replace(".sbml", "") // .replace(".xml", "") + "_sg.dot" + "\n"); // exec.exec("open " // + theFile.replace(".gcm", "").replace(".sbml", // "").replace( // ".xml", "") + "_sg.dot", null, work); // else { // log.addText("Executing:\ndotty " // + filename.replace(".gcm", "").replace(".sbml", "") // .replace(".xml", "") + "_sg.dot" + "\n"); // exec.exec("dotty " // + theFile.replace(".gcm", "").replace(".sbml", // "").replace( // ".xml", "") + "_sg.dot", null, work); for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab .setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } exitValue = 0; } else { Preferences biosimrc = Preferences.userRoot(); if (sim.equals("gillespieJava")) { time1 = System.nanoTime(); // Properties props = new Properties(); // props.load(new FileInputStream(new File(directory + // separator + modelFile.substring(0, // modelFile.indexOf('.')) + ".properties"))); int index = -1; for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { simTab.setSelectedIndex(i); index = i; } } GillespieSSAJavaSingleStep javaSim = new GillespieSSAJavaSingleStep(); String SBMLFileName = directory + separator + theFile; javaSim.PerformSim(SBMLFileName, outDir, timeLimit, ((Graph) simTab .getComponentAt(index))); exitValue = 0; return exitValue; } else if (biosimrc.get("biosim.sim.command", "").equals("")) { time1 = System.nanoTime(); log.addText("Executing:\nreb2sac --target.encoding=" + sim + " " + filename + "\n"); reb2sac = exec.exec("reb2sac --target.encoding=" + sim + " " + theFile, null, work); } else { String command = biosimrc.get("biosim.sim.command", ""); String fileStem = theFile.replaceAll(".xml", ""); fileStem = fileStem.replaceAll(".sbml", ""); command = command.replaceAll("filename", fileStem); command = command.replaceAll("sim", sim); log.addText(command + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec(command, null, work); } } } String error = ""; try { InputStream reb = reb2sac.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); // int count = 0; String line; double time = 0; double oldTime = 0; int runNum = 0; int prog = 0; while ((line = br.readLine()) != null) { try { if (line.contains("Time")) { time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line .length())); if (oldTime > time) { runNum++; } oldTime = time; time += (runNum * timeLimit); double d = ((time * 100) / runTime); String s = d + ""; double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s .length())); if (decimal >= 0.5) { prog = (int) (Math.ceil(d)); } else { prog = (int) (d); } } } catch (Exception e) { } progress.setValue(prog); // if (steps > 0) { // count++; // progress.setValue(count); // log.addText(output); } InputStream reb2 = reb2sac.getErrorStream(); int read = reb2.read(); while (read != -1) { error += (char) read; read = reb2.read(); } br.close(); isr.close(); reb.close(); reb2.close(); } catch (Exception e) { } if (reb2sac != null) { exitValue = reb2sac.waitFor(); } long time2 = System.nanoTime(); long minutes; long hours; long days; double secs = ((time2 - time1) / 1000000000.0); long seconds = ((time2 - time1) / 1000000000); secs = secs - seconds; minutes = seconds / 60; secs = seconds % 60 + secs; hours = minutes / 60; minutes = minutes % 60; days = hours / 24; hours = hours % 60; String time; String dayLabel; String hourLabel; String minuteLabel; String secondLabel; if (days == 1) { dayLabel = " day "; } else { dayLabel = " days "; } if (hours == 1) { hourLabel = " hour "; } else { hourLabel = " hours "; } if (minutes == 1) { minuteLabel = " minute "; } else { minuteLabel = " minutes "; } if (seconds == 1) { secondLabel = " second"; } else { secondLabel = " seconds"; } if (days != 0) { time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (hours != 0) { time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (minutes != 0) { time = minutes + minuteLabel + secs + secondLabel; } else { time = secs + secondLabel; } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } log.addText("Total Simulation Time: " + time + " for " + simName + "\n\n"); if (exitValue != 0) { if (exitValue == 143) { JOptionPane.showMessageDialog(BioSim.frame, "The simulation was" + " canceled by the user.", "Canceled Simulation", JOptionPane.ERROR_MESSAGE); } else if (exitValue == 139) { JOptionPane.showMessageDialog(BioSim.frame, "The selected model is not a valid sbml file." + "\nYou must select an sbml file.", "Not An SBML File", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!\n" + "Bad Return Value!\n" + "The reb2sac program returned " + exitValue + " as an exit value.", "Error", JOptionPane.ERROR_MESSAGE); } } else { if (nary.isSelected() && gcmEditor == null && !lhpn.isSelected() && naryRun == 1) { } else if (sbml.isSelected()) { if (sbmlName != null && !sbmlName.trim().equals("")) { if (!biomodelsim.updateOpenSBML(sbmlName)) { biomodelsim.addTab(sbmlName, new SBML_Editor(root + separator + sbmlName, null, log, biomodelsim, null, null), "SBML Editor"); biomodelsim.addToTree(sbmlName); } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(sbmlName)); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } else if (lhpn.isSelected()) { if (lhpnName != null && !lhpnName.trim().equals("")) { if (!biomodelsim.updateOpenLHPN(lhpnName)) { biomodelsim.addTab(lhpnName, new LHPNEditor(root, lhpnName, null, biomodelsim, log), "LHPN Editor"); biomodelsim.addToTree(lhpnName); } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(lhpnName)); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } else if (dot.isSelected()) { 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); } } else if (xhtml.isSelected()) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ngnome-open " + directory + out + ".xhtml" + "\n"); exec.exec("gnome-open " + out + ".xhtml", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".xhtml" + "\n"); exec.exec("open " + out + ".xhtml", null, work); } else { log .addText("Executing:\ncmd /c start " + directory + out + ".xhtml" + "\n"); exec.exec("cmd /c start " + out + ".xhtml", null, work); } } else if (usingSSA.isSelected()) { if (!printer_id.equals("null.printer")) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id.length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add( data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab .setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id.length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add( data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } else if (sim.equals("atacs")) { log.addText("Executing:\natacs -T0.000001 -oqoflhsgllvA " + filename .substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "out.hse\n"); exec.exec("atacs -T0.000001 -oqoflhsgllvA out.hse", null, work); for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } // simTab.add("Probability Graph", new // Graph(printer_track_quantity, // outDir.split(separator)[outDir.split(separator).length - // simulation results", // printer_id, outDir, "time", biomodelsim, null, log, null, // false)); // simTab.getComponentAt(simTab.getComponentCount() - // 1).setName("ProbGraph"); } else { if (!printer_id.equals("null.printer")) { if (ode.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data .get(k) .add( data.get(k).get( data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data .get(k) .add( data.get(k).get( data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } else if (monteCarlo.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data .get(k) .add( data.get(k).get( data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data .get(k) .add( data.get(k).get( data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } } } } catch (InterruptedException e1) { JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!", "Error In Execution", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } catch (IOException e1) { JOptionPane.showMessageDialog(BioSim.frame, "File I/O Error!", "File I/O Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } return exitValue; } /** * This method is called if a button that cancels the simulation is pressed. */ public void actionPerformed(ActionEvent e) { if (reb2sac != null) { reb2sac.destroy(); } if (sg != null) { sg.stop(); } } }
package com.gelvt.gofdp; import com.gelvt.gofdp.singleton.ApplicationContext; import java.util.Date; public class App { public static void main(String[] args){ System.out.println("hello singleton!"); ApplicationContext ctx = ApplicationContext.getInstance(); ctx.setConfig("log.level", "warn"); ctx.setConfig("dal.printSQL", true); ctx.setConfig("author", "Elvin Zeng"); ctx.setConfig("version", "0.1.0"); ctx.setConfig("startTime", new Date()); System.out.println("dal.printSQL: " + ctx.removeConfig("dal.printSQL")); System.out.println("config list:"); for(String key : ctx.getConfigKeys()){ System.out.println(key + ": " + ctx.getConfig(key).toString()); } ApplicationContext ctx1 = ApplicationContext.getInstance(); ctx1.clearConfig(); ctx1.setConfig("stopTime", new Date()); System.out.println("config list:"); for(String key : ctx.getConfigKeys()){ System.out.println(key + ": " + ctx.getConfig(key).toString()); } } }
package therian.position.relative; import java.beans.FeatureDescriptor; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; import org.apache.commons.functor.UnaryPredicate; import org.apache.commons.functor.core.collection.FilteredIterable; import org.apache.commons.functor.generator.IteratorToGeneratorAdapter; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.reflect.TypeUtils; import therian.TherianContext; import therian.el.ELConstants; import therian.position.Position; import therian.position.Position.Readable; import therian.position.relative.RelativePosition.ReadWrite; import therian.util.Types; /** * Provides fluent access to {@link RelativePositionFactory} instances for {@link Map} keyed values. e.g. * Keyed.<MetasyntacticVariable> value().at("foo").of(Collections.singletonMap("foo", MetasyntacticVariable.FOO); */ public class Keyed { public static class PositionFactory<K, V> extends RelativePositionFactory<Map<K, V>, V> { private final K key; @SuppressWarnings("unchecked") protected PositionFactory(K key) { super(new GetTypeMixin<V>(key), new RelativePosition.Mixin.ELValue<V>(key)); this.key = key; } @Override public <P extends Map<K, V>> RelativePosition.ReadWrite<P, V> of(Readable<P> parentPosition) { return (ReadWrite<P, V>) super.of(parentPosition); } @Override public int hashCode() { int result = 53 << 4; result |= ObjectUtils.hashCode(key); return result; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof PositionFactory == false) { return false; } return ObjectUtils.equals(key, ((PositionFactory<?, ?>) obj).key); } } public static class Value<V> { public <K> PositionFactory<K, V> at(K key) { return new PositionFactory<K, V>(key); } } private static class GetTypeMixin<V> implements RelativePosition.GetType<V> { private final Object key; private GetTypeMixin(Object key) { super(); this.key = key; } public <P> Type getType(Readable<? extends P> parentPosition) { return Types.refine(getBasicType(parentPosition), parentPosition.getType()); } private <P> Type getBasicType(final Position.Readable<? extends P> parentPosition) { final TherianContext context = TherianContext.getInstance(); final P parent = parentPosition.getValue(); final UnaryPredicate<FeatureDescriptor> filter = new UnaryPredicate<FeatureDescriptor>() { public boolean test(FeatureDescriptor obj) { return String.valueOf(key).equals(obj.getName()); } }; final Iterable<FeatureDescriptor> featureDescriptors = parent == null ? Collections.<FeatureDescriptor> emptyList() : FilteredIterable.of( IteratorToGeneratorAdapter.adapt(context.getELResolver().getFeatureDescriptors(context, parent)) .toCollection()).retain(filter); for (FeatureDescriptor feature : featureDescriptors) { final Type fromGenericTypeAttribute = Type.class.cast(feature.getValue(ELConstants.GENERIC_TYPE)); if (fromGenericTypeAttribute != null) { return fromGenericTypeAttribute; } } return ObjectUtils.defaultIfNull( TypeUtils.getTypeArguments(parentPosition.getType(), Map.class).get(Map.class.getTypeParameters()[1]), Object.class); } } private Keyed() { } public static <V> Value<V> value() { return new Value<V>(); } }
package brooklyn.util; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; import java.util.NoSuchElementException; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import brooklyn.util.os.Os; import brooklyn.util.stream.Streams; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.io.Files; public class ResourceUtilsTest { private static final Logger log = LoggerFactory.getLogger(ResourceUtilsTest.class); private String tempFileContents = "abc"; private ResourceUtils utils; private File tempFile; @BeforeClass(alwaysRun=true) public void setUp() throws Exception { utils = ResourceUtils.create(this, "mycontext"); tempFile = Os.writeToTempFile(new ByteArrayInputStream(tempFileContents.getBytes()), "resourceutils-test", ".txt"); } @AfterClass(alwaysRun=true) public void tearDown() throws Exception { if (tempFile != null) tempFile.delete(); } @Test public void testWriteStreamToTempFile() throws Exception { File tempFileLocal = Os.writeToTempFile(new ByteArrayInputStream("mycontents".getBytes()), "resourceutils-test", ".txt"); try { List<String> lines = Files.readLines(tempFileLocal, Charsets.UTF_8); assertEquals(lines, ImmutableList.of("mycontents")); } finally { tempFileLocal.delete(); } } @Test public void testPropertiesStreamToTempFile() throws Exception { Properties props = new Properties(); props.setProperty("mykey", "myval"); File tempFileLocal = Os.writePropertiesToTempFile(props, "resourceutils-test", ".txt"); FileInputStream fis = null; try { fis = new FileInputStream(tempFileLocal); Properties props2 = new Properties(); props2.load(fis); assertEquals(props2.getProperty("mykey"), "myval"); } finally { Streams.closeQuietly(fis); tempFileLocal.delete(); } } @Test public void testGetResourceViaClasspathWithPrefix() throws Exception { InputStream stream = utils.getResourceFromUrl("classpath://brooklyn/config/sample.properties"); assertNotNull(stream); } @Test public void testGetResourceViaClasspathWithoutPrefix() throws Exception { InputStream stream = utils.getResourceFromUrl("/brooklyn/config/sample.properties"); assertNotNull(stream); } @Test public void testGetResourceViaFileWithPrefix() throws Exception { // on windows the correct syntax is file:///c:/path (note the extra /); // however our routines also accept file://c:/path so the following is portable InputStream stream = utils.getResourceFromUrl("file://"+tempFile.getAbsolutePath()); assertEquals(Streams.readFullyString(stream), tempFileContents); } @Test public void testGetResourceViaFileWithoutPrefix() throws Exception { InputStream stream = utils.getResourceFromUrl(tempFile.getAbsolutePath()); assertEquals(Streams.readFullyString(stream), tempFileContents); } @Test public void testClassLoaderDir() throws Exception { String d = utils.getClassLoaderDir(); log.info("Found resource "+this+" in: "+d); assertTrue(new File(d+"/brooklyn/util/").exists()); } @Test public void testClassLoaderDirFromJar() throws Exception { String d = utils.getClassLoaderDir("java/lang/Object.class"); log.info("Found Object in: "+d); assertTrue(d.toLowerCase().endsWith(".jar")); } @Test public void testClassLoaderDirFromJarWithSlash() throws Exception { String d = utils.getClassLoaderDir("/java/lang/Object.class"); log.info("Found Object in: "+d); assertTrue(d.toLowerCase().endsWith(".jar")); } @Test(expectedExceptions={NoSuchElementException.class}) public void testClassLoaderDirNotFound() throws Exception { String d = utils.getClassLoaderDir("/somewhere/not/found/XXX.xxx"); // above should fail log.warn("Uh oh found iamginary resource in: "+d); } @Test(groups="Integration") public void testGetResourceViaSftp() throws Exception { InputStream stream = utils.getResourceFromUrl("sftp://localhost:"+tempFile.getAbsolutePath()); assertEquals(Streams.readFullyString(stream), tempFileContents); } @Test(groups="Integration") public void testGetResourceViaSftpWithUsername() throws Exception { String user = System.getProperty("user.name"); InputStream stream = utils.getResourceFromUrl("sftp://"+user+"@localhost:"+tempFile.getAbsolutePath()); assertEquals(Streams.readFullyString(stream), tempFileContents); } @Test public void testDataUrl() throws Exception { assertEquals(utils.getResourceAsString("data:,hello"), "hello"); assertEquals(utils.getResourceAsString("data:,hello%20world"), "hello world"); // above is correct. below are not valid ... but we accept them anyway assertEquals(utils.getResourceAsString("data:hello"), "hello"); assertEquals(utils.getResourceAsString("data://hello"), "hello"); assertEquals(utils.getResourceAsString("data:hello world"), "hello world"); } @Test(groups={"Integration", "WIP"}) public void testResourceFromUrlFollowsRedirect() throws Exception { String contents = new ResourceUtils(this).getResourceAsString("http://bit.ly/brooklyn-visitors-creation-script"); assertFalse(contents.contains("bit.ly"), "contents="+contents); } }
package org.sakaiproject.evaluation.tool.reporting; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.evaluation.logic.EvalEvaluationService; import org.sakaiproject.evaluation.logic.ReportingPermissions; import org.sakaiproject.evaluation.logic.externals.EvalExternalLogic; import org.sakaiproject.evaluation.model.EvalEvaluation; import org.sakaiproject.evaluation.model.EvalTemplate; import org.sakaiproject.evaluation.tool.viewparams.CSVReportViewParams; import org.sakaiproject.evaluation.tool.viewparams.DownloadReportViewParams; import org.sakaiproject.evaluation.tool.viewparams.ExcelReportViewParams; import org.sakaiproject.evaluation.tool.viewparams.PDFReportViewParams; import uk.org.ponder.rsf.processor.HandlerHook; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.util.UniversalRuntimeException; /** * Handles the generation of files for exporting results * * @author Aaron Zeckoski (aaronz@vt.edu) * @author Rui Feng (fengr@vt.edu) * @author Will Humphries (whumphri@vt.edu) * @author Steven Githens */ public class ReportHandlerHook implements HandlerHook { private static Log log = LogFactory.getLog(ReportHandlerHook.class); private EvalExternalLogic externalLogic; public void setExternalLogic(EvalExternalLogic externalLogic) { this.externalLogic = externalLogic; } private EvalEvaluationService evaluationService; public void setEvaluationService(EvalEvaluationService evaluationService) { this.evaluationService = evaluationService; } private CSVReportExporter csvReportExporter; public void setCsvReportExporter(CSVReportExporter csvReportExporter) { this.csvReportExporter = csvReportExporter; } private XLSReportExporter xlsReportExporter; public void setXlsReportExporter(XLSReportExporter xlsReportExporter) { this.xlsReportExporter = xlsReportExporter; } private PDFReportExporter pdfReportExporter; public void setPdfReportExporter(PDFReportExporter pdfReportExporter) { this.pdfReportExporter = pdfReportExporter; } private ViewParameters viewparams; public void setViewparams(ViewParameters viewparams) { this.viewparams = viewparams; } private HttpServletResponse response; public void setResponse(HttpServletResponse response) { this.response = response; } private ReportingPermissions reportingPermissions; public void setReportingPermissions(ReportingPermissions perms) { this.reportingPermissions = perms; } /* (non-Javadoc) * @see uk.org.ponder.rsf.processor.HandlerHook#handle() */ public boolean handle() { // get viewparams so we know what to generate DownloadReportViewParams drvp; if (viewparams instanceof DownloadReportViewParams) { drvp = (DownloadReportViewParams) viewparams; } else { return false; } log.debug("Handling report"); // get evaluation and template from DAO EvalEvaluation evaluation = evaluationService.getEvaluationById(drvp.evalId); EvalTemplate template = evaluation.getTemplate(); String currentUserId = externalLogic.getCurrentUserId(); if (!reportingPermissions.canViewEvaluationResponses(evaluation, drvp.groupIds)) { throw new SecurityException("Invalid user attempting to access report downloads: " + currentUserId); } OutputStream resultsOutputStream = null; try { resultsOutputStream = response.getOutputStream(); } catch (IOException ioe) { throw UniversalRuntimeException.accumulate(ioe, "Unable to get response stream for Evaluation Results Export"); } // Response Headers that are the same for all Output types response.setHeader("Content-disposition", "inline"); if (drvp instanceof CSVReportViewParams) { response.setContentType("text/x-csv"); response.setHeader("filename", "report.csv"); csvReportExporter.formatResponses(evaluation, drvp.groupIds, resultsOutputStream); } else if (drvp instanceof ExcelReportViewParams) { response.setContentType("application/vnd.ms-excel"); response.setHeader("filename", "report.xls"); xlsReportExporter.formatResponses(evaluation, drvp.groupIds, resultsOutputStream); } else if (drvp instanceof PDFReportViewParams) { response.setContentType("application/pdf"); response.setHeader("filename", "report.pdf"); pdfReportExporter.formatResponses(evaluation, drvp.groupIds, resultsOutputStream); } return true; } }
package com.jediterm.terminal; import com.google.common.base.Ascii; import java.util.HashMap; import java.util.Map; import static java.awt.event.KeyEvent.*; /** * @author traff */ public class TerminalKeyEncoder { public static final int ESC = Ascii.ESC; public static final int DEL = Ascii.DEL; private final Map<Integer, byte[]> myKeyCodes = new HashMap<Integer, byte[]>(); public TerminalKeyEncoder() { putCode(VK_ENTER, Ascii.CR); arrowKeysApplicationSequences(); keypadApplicationSequences(); putCode(VK_F1, ESC, 'O', 'P'); putCode(VK_F2, ESC, 'O', 'Q'); putCode(VK_F3, ESC, 'O', 'R'); putCode(VK_F4, ESC, 'O', 'S'); putCode(VK_F5, ESC, 'O', 't'); putCode(VK_F6, ESC, '[', '1', '7', '~'); putCode(VK_F7, ESC, '[', '1', '8', '~'); putCode(VK_F8, ESC, '[', '1', '9', '~'); putCode(VK_F9, ESC, '[', '2', '0', '~'); putCode(VK_F10, ESC, '[', '2', '1', '~'); putCode(VK_F11, ESC, '[', '2', '3', '~', ESC); putCode(VK_F12, ESC, '[', '2', '4', '~', Ascii.BS); putCode(VK_INSERT, ESC, '[', '2', '~'); putCode(VK_DELETE, ESC, '[', '3', '~'); putCode(VK_PAGE_UP, ESC, '[', '5', '~'); putCode(VK_PAGE_DOWN, ESC, '[', '6', '~'); putCode(VK_HOME, ESC, '[', 'H'); putCode(VK_END, ESC, '[', 'F'); } public void arrowKeysApplicationSequences() { putCode(VK_UP, ESC, 'O', 'A'); putCode(VK_DOWN, ESC, 'O', 'B'); putCode(VK_RIGHT, ESC, 'O', 'C'); putCode(VK_LEFT, ESC, 'O', 'D'); } public void arrowKeysAnsiCursorSequences() { putCode(VK_UP, ESC, '[', 'A'); putCode(VK_DOWN, ESC, '[', 'B'); putCode(VK_RIGHT, ESC, '[', 'C'); putCode(VK_LEFT, ESC, '[', 'D'); } void putCode(final int code, final int... bytesAsInt) { myKeyCodes.put(code, CharacterUtils.makeCode(bytesAsInt)); } public byte[] getCode(final int key) { return myKeyCodes.get(key); } public void keypadApplicationSequences() { putCode(VK_KP_DOWN, ESC, 'O', 'r'); putCode(VK_KP_LEFT, ESC, 'O', 't'); putCode(VK_KP_RIGHT, ESC, 'O', 'v'); putCode(VK_KP_UP, ESC, 'O', 'x'); } public void normalKeypad() { putCode(VK_KP_DOWN, 2); putCode(VK_KP_LEFT, 4); putCode(VK_KP_RIGHT, 6); putCode(VK_KP_UP, 8); } }
package com.jediterm.terminal.display; import com.google.common.collect.Maps; import com.jediterm.terminal.*; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.Arrays; import java.util.BitSet; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Buffer for storing styled text data. * Stores only text that fit into one screen XxY, but has scrollBuffer to save history lines and textBuffer to restore * screen after resize. ScrollBuffer stores all lines before the first line currently shown on the screen. TextBuffer * stores lines that are shown currently on the screen and they have there(in TextBuffer) their initial length (even if * it doesn't fit to screen width). * <p/> * Also handles screen damage (TODO: write about it). */ public class BackBuffer implements StyledTextConsumer { private static final Logger LOG = Logger.getLogger(BackBuffer.class); private static final char EMPTY_CHAR = ' '; // (char) 0x0; private char[] myBuf; private TextStyle[] myStyleBuf; private BitSet myDamage; @NotNull private final StyleState myStyleState; private LinesBuffer myScrollBuffer = new LinesBuffer(); private LinesBuffer myTextBuffer = new LinesBuffer(); private int myWidth; private int myHeight; private final Lock myLock = new ReentrantLock(); private LinesBuffer myTextBufferBackup; // to store textBuffer after switching to alternate buffer private LinesBuffer myScrollBufferBackup; private boolean myAlternateBuffer = false; private boolean myUsingAlternateBuffer = false; public BackBuffer(final int width, final int height, @NotNull StyleState styleState) { myStyleState = styleState; myWidth = width; myHeight = height; allocateBuffers(); } private void allocateBuffers() { myBuf = new char[myWidth * myHeight]; Arrays.fill(myBuf, EMPTY_CHAR); myStyleBuf = new TextStyle[myWidth * myHeight]; Arrays.fill(myStyleBuf, TextStyle.EMPTY); myDamage = new BitSet(myWidth * myHeight); } public Dimension resize(@NotNull final Dimension pendingResize, @NotNull final RequestOrigin origin, final int cursorY, @NotNull JediTerminal.ResizeHandler resizeHandler, @Nullable TerminalSelection mySelection) { final char[] oldBuf = myBuf; final TextStyle[] oldStyleBuf = myStyleBuf; final int oldHeight = myHeight; final int oldWidth = myWidth; final int newWidth = pendingResize.width; final int newHeight = pendingResize.height; final int scrollLinesCountOld = myScrollBuffer.getLineCount(); final int textLinesCountOld = myTextBuffer.getLineCount(); boolean textBufferUpdated = false; if (newHeight < cursorY) { //we need to move lines from text buffer to the scroll buffer int count = cursorY - newHeight; if (!myAlternateBuffer) { myTextBuffer.moveTopLinesTo(count, myScrollBuffer); } if (mySelection != null) { mySelection.shiftY(-count); } } else if (newHeight > cursorY && myScrollBuffer.getLineCount() > 0) { //we need to move lines from scroll buffer to the text buffer if (!myAlternateBuffer) { myScrollBuffer.moveBottomLinesTo(newHeight - cursorY, myTextBuffer); textBufferUpdated = true; } if (mySelection != null) { mySelection.shiftY(newHeight - cursorY); } } myWidth = newWidth; myHeight = newHeight; allocateBuffers(); final int copyWidth = Math.min(oldWidth, myWidth); final int copyHeight = Math.min(oldHeight, myHeight); final int oldStart; final int start; if (myHeight > oldHeight) { oldStart = 0; start = Math.min(myHeight - copyHeight, scrollLinesCountOld); } else { oldStart = Math.max(0, cursorY - myHeight); start = 0; } // copying lines... for (int i = 0; i < copyHeight; i++) { System.arraycopy(oldBuf, (oldStart + i) * oldWidth, myBuf, (start + i) * myWidth, copyWidth); System.arraycopy(oldStyleBuf, (oldStart + i) * oldWidth, myStyleBuf, (start + i) * myWidth, copyWidth); } if (!myAlternateBuffer && (myWidth > oldWidth || textBufferUpdated)) { //we need to fill new space with data from the text buffer resetFromTextBuffer(); } if (myTextBuffer.getLineCount() >= myHeight) { myTextBuffer.moveTopLinesTo(myTextBuffer.getLineCount() - myHeight, myScrollBuffer); } int myCursorY = cursorY + (myTextBuffer.getLineCount() - textLinesCountOld); myDamage.set(0, myWidth * myHeight - 1, true); resizeHandler.sizeUpdated(myWidth, myHeight, myCursorY); return pendingResize; } private void resetFromTextBuffer() { clearArea(); myTextBuffer.processLines(0, getTextBufferLinesCount(), this, 0); } private void clearArea() { clearArea(0, 0, myWidth, myHeight); } private void clearArea(final int leftX, final int topY, final int rightX, final int bottomY) { clearArea(leftX, topY, rightX, bottomY, createEmptyStyleWithCurrentColor()); } private void clearArea(final int leftX, final int topY, final int rightX, final int bottomY, @NotNull TextStyle textStyle) { if (topY > bottomY) { LOG.error("Attempt to clear upside down area: top:" + topY + " > bottom:" + bottomY); return; } for (int y = topY; y < bottomY; y++) { if (y > myHeight - 1 || y < 0) { LOG.error("attempt to clear line " + y + "\n" + "args were x1:" + leftX + " y1:" + topY + " x2:" + rightX + " y2:" + bottomY); } else if (leftX > rightX) { LOG.error("Attempt to clear backwards area: left:" + leftX + " > right:" + rightX); } else { Arrays.fill(myBuf, y * myWidth + leftX, y * myWidth + rightX, EMPTY_CHAR); Arrays.fill(myStyleBuf, y * myWidth + leftX, y * myWidth + rightX, textStyle ); myDamage.set(y * myWidth + leftX, y * myWidth + rightX, true); } } } private TextStyle createEmptyStyleWithCurrentColor() { return myStyleState.getCurrent().createEmptyWithColors(); } public void deleteCharacters(final int x, final int y, final int count) { if (y > myHeight - 1 || y < 0) { LOG.error("attempt to delete in line " + y + "\n" + "args were x:" + x + " count:" + count); } else if (count < 0) { LOG.error("Attempt to delete negative chars number: count:" + count); } else if (count == 0) { //nothing to do return; } else { int to = y * myWidth + x; int from = to + count; int remain = myWidth - x - count; LOG.debug("About to delete " + count + " chars on line " + y + ", starting from " + x + " (from : " + from + " to : " + to + " remain : " + remain + ")"); System.arraycopy(myBuf, from, myBuf, to, remain); Arrays.fill(myBuf, to + remain, (y + 1) * myWidth, EMPTY_CHAR); System.arraycopy(myStyleBuf, from, myStyleBuf, to, remain); Arrays.fill(myStyleBuf, to + remain, (y + 1) * myWidth, createEmptyStyleWithCurrentColor()); myTextBuffer.deleteCharacters(x, y, count); myDamage.set(to, (y + 1) * myWidth, true); } } public void insertBlankCharacters(final int x, final int y, final int count) { if (y > myHeight - 1 || y < 0) { LOG.error("attempt to insert blank chars in line " + y + "\n" + "args were x:" + x + " count:" + count); } else if (count < 0) { LOG.error("Attempt to insert negative blank chars number: count:" + count); } else if (count == 0) { //nothing to do return; } else { int from = y * myWidth + x; int to = from + count; int remain = myWidth - x - count; LOG.debug("About to insert " + count + " blank chars on line " + y + ", starting from " + x + " (from : " + from + " to : " + to + " remain : " + remain + ")"); System.arraycopy(myBuf, from, myBuf, to, remain); Arrays.fill(myBuf, from, to, EMPTY_CHAR); System.arraycopy(myStyleBuf, from, myStyleBuf, to, remain); Arrays.fill(myStyleBuf, from, to, createEmptyStyleWithCurrentColor()); myTextBuffer.insertBlankCharacters(x, y, count, myWidth); myDamage.set(from, (y + 1) * myWidth, true); } } public void writeBytes(final int x, final int y, final char[] bytes, final int start, final int len) { final int adjY = y - 1; if (adjY >= myHeight || adjY < 0) { if (LOG.isDebugEnabled()) { StringBuilder sb = new StringBuilder("Attempt to draw line ") .append(adjY).append(" at (").append(x).append(",") .append(y).append(")"); CharacterUtils.appendBuf(sb, bytes, start, len); LOG.debug(sb); } return; } TextStyle style = myStyleState.getCurrent(); for (int i = 0; i < len; i++) { final int location = adjY * myWidth + x + i; myBuf[location] = bytes[start + i]; // Arraycopy does not convert myStyleBuf[location] = style; } myTextBuffer.writeString(x, adjY, new String(bytes, start, len), style); //TODO: make write bytes method myDamage.set(adjY * myWidth + x, adjY * myWidth + x + len); } public void writeString(final int x, final int y, @NotNull final String str) { writeString(x, y, str, myStyleState.getCurrent()); } private void writeString(int x, int y, @NotNull String str, @NotNull TextStyle style) { if (writeToBackBuffer(x, y, str, style)) return; myTextBuffer.writeString(x, y - 1, str, style); } private boolean writeToBackBuffer(int x, int y, @NotNull String str, @NotNull TextStyle style) { final int adjY = y - 1; if (adjY >= myHeight || adjY < 0) { LOG.debug("Attempt to draw line out of bounds: " + adjY + " at (" + x + "," + y + ")"); return true; } str.getChars(0, str.length(), myBuf, adjY * myWidth + x); for (int i = 0; i < str.length(); i++) { final int location = adjY * myWidth + x + i; myStyleBuf[location] = style; } myDamage.set(adjY * myWidth + x, adjY * myWidth + x + str.length()); return false; } public void scrollArea(final int scrollRegionTop, final int dy, int scrollRegionBottom) { if (dy == 0) { return; } if (dy > 0) { insertLines(scrollRegionTop - 1, dy, scrollRegionBottom); } else { LinesBuffer removed = deleteLines(scrollRegionTop - 1, -dy, scrollRegionBottom); if (scrollRegionTop == 1) { removed.moveTopLinesTo(removed.getLineCount(), myScrollBuffer); } } } private void moveLinesUp(int y, int dy, int lastLine) { if (dy >= 0) { LOG.error("dy should be negative"); } for (int line = y; line < lastLine; line++) { if (line >= myHeight) { // this is not necessary an error; simply skip it LOG.debug("Attempt to scroll line from below bottom of screen: " + line); continue; } if (line + dy < 0) { // this is not necessary an error; simply skip it LOG.debug("Attempt to scroll to line off top of screen: " + (line + dy)); continue; } System.arraycopy(myBuf, line * myWidth, myBuf, (line + dy) * myWidth, myWidth); System.arraycopy(myStyleBuf, line * myWidth, myStyleBuf, (line + dy) * myWidth, myWidth); myDamage.set((line + dy) * myWidth, (line + dy + 1) * myWidth); } } private void moveLinesDown(int y, int dy, int lastLine) { if (dy <= 0) { LOG.error("dy should be positive"); } for (int line = lastLine - dy; line >= y; line if (line < 0) { // this is not necessary an error; simply skip it LOG.debug("Attempt to scroll line from above top of screen: " + line); continue; } if (line + dy + 1 > myHeight) { // this is not necessary an error; simply skip it LOG.debug("Attempt to scroll line off bottom of screen: " + (line + dy)); continue; } System.arraycopy(myBuf, line * myWidth, myBuf, (line + dy) * myWidth, myWidth); System.arraycopy(myStyleBuf, line * myWidth, myStyleBuf, (line + dy) * myWidth, myWidth); myDamage.set((line + dy) * myWidth, (line + dy + 1) * myWidth); } } public String getStyleLines() { int count = 0; Map<Integer, Integer> hashMap = Maps.newHashMap(); myLock.lock(); try { final StringBuilder sb = new StringBuilder(); for (int row = 0; row < myHeight; row++) { for (int col = 0; col < myWidth; col++) { final TextStyle style = myStyleBuf[row * myWidth + col]; int styleNum = style == null ? 0 : style.getId(); if (!hashMap.containsKey(styleNum)) { hashMap.put(styleNum, count++); } sb.append(String.format("%02d ", hashMap.get(styleNum))); } sb.append("\n"); } return sb.toString(); } finally { myLock.unlock(); } } public TerminalLine getLine(int index) { if (index >= 0) { if (index >= getHeight()) { LOG.error("Attempt to get line out of bounds: " + index + " >= " + getHeight()); return TerminalLine.createEmpty(); } return myTextBuffer.getLine(index); } else { if (index < - myScrollBuffer.getLineCount()) { LOG.error("Attempt to get line out of bounds: " + index + " < " + -myScrollBuffer.getLineCount()); return TerminalLine.createEmpty(); } return myScrollBuffer.getLine(getScrollBufferLinesCount() + index); } } public String getLines() { myLock.lock(); try { final StringBuilder sb = new StringBuilder(); for (int row = 0; row < myHeight; row++) { sb.append(myBuf, row * myWidth, myWidth); sb.append('\n'); } return sb.toString(); } finally { myLock.unlock(); } } public String getDamageLines() { myLock.lock(); try { final StringBuilder sb = new StringBuilder(); for (int row = 0; row < myHeight; row++) { for (int col = 0; col < myWidth; col++) { boolean isDamaged = myDamage.get(row * myWidth + col); sb.append(isDamaged ? 'X' : '-'); } sb.append("\n"); } return sb.toString(); } finally { myLock.unlock(); } } public void resetDamage() { myLock.lock(); try { myDamage.clear(); } finally { myLock.unlock(); } } public void processTextBufferLines(final int yStart, final int yCount, @NotNull final StyledTextConsumer consumer, int startRow) { myTextBuffer.processLines(yStart - startRow, Math.min(yCount, myTextBuffer.getLineCount()), consumer, startRow); } public void processTextBufferLines(final int yStart, final int yCount, @NotNull final StyledTextConsumer consumer) { myTextBuffer.processLines(yStart - getTextBufferLinesCount(), Math.min(yCount, myTextBuffer.getLineCount()), consumer); } public void processBufferRows(final int startRow, final int height, final StyledTextConsumer consumer) { processBufferCells(0, startRow, myWidth, height, consumer); } public void processBufferCells(final int startCol, final int startRow, final int width, final int height, final StyledTextConsumer consumer) { final int endRow = startRow + height; final int endCol = startCol + width; myLock.lock(); try { for (int row = startRow; row < endRow; row++) { processBufferRow(row, startCol, endCol, consumer); } } finally { myLock.unlock(); } } public void processBufferRow(int row, StyledTextConsumer consumer) { processBufferRow(row, 0, myWidth, consumer); } public void processBufferRow(int row, int startCol, int endCol, StyledTextConsumer consumer) { TextStyle lastStyle = null; int beginRun = startCol; for (int col = startCol; col < endCol; col++) { final int location = row * myWidth + col; if (location < 0 || location >= myStyleBuf.length) { throw new IllegalStateException("Can't pump a char at " + row + "x" + col); } final TextStyle cellStyle = myStyleBuf[location]; if (lastStyle == null) { //begin line lastStyle = cellStyle; } else if (!cellStyle.equals(lastStyle)) { //start of new run consumer.consume(beginRun, row, lastStyle, new CharBuffer(myBuf, row * myWidth + beginRun, col - beginRun), 0); beginRun = col; lastStyle = cellStyle; } } //end row if (endCol == startCol) { // no run occurred : retrieve text style final int location = row * myWidth + startCol; if (location < 0 || location >= myStyleBuf.length) { throw new IllegalStateException("Can't pump a char at " + row + "x" + startCol); } lastStyle = myStyleBuf[location]; } if (lastStyle == null) { LOG.error("Style is null for run supposed to be from " + beginRun + " to " + endCol + " on row " + row); } else { consumer.consume(beginRun, row, lastStyle, new CharBuffer(myBuf, row * myWidth + beginRun, endCol - beginRun), 0); } } /** * Cell is a styled block of text * * @param consumer */ public void processDamagedCells(final StyledTextConsumer consumer) { final int startRow = 0; final int endRow = myHeight; final int startCol = 0; final int endCol = myWidth; myLock.lock(); try { for (int row = startRow; row < endRow; row++) { TextStyle lastStyle = null; int beginRun = startCol; for (int col = startCol; col < endCol; col++) { final int location = row * myWidth + col; if (location < 0 || location > myStyleBuf.length) { LOG.error("Requested out of bounds runs: pumpFromDamage"); continue; } final TextStyle cellStyle = myStyleBuf[location]; final boolean isDamaged = myDamage.get(location); if (!isDamaged) { if (lastStyle != null) { //flush previous run flushStyledText(consumer, row, lastStyle, beginRun, col); } lastStyle = null; } else { if (lastStyle == null) { //begin a new run beginRun = col; lastStyle = cellStyle; } else if (!cellStyle.equals(lastStyle)) { //flush prev run and start of a new one flushStyledText(consumer, row, lastStyle, beginRun, col); beginRun = col; lastStyle = cellStyle; } } } //flush the last run if (lastStyle != null) { flushStyledText(consumer, row, lastStyle, beginRun, endCol); } } } finally { myLock.unlock(); } } private void flushStyledText(StyledTextConsumer consumer, int row, TextStyle lastStyle, int beginRun, int col) { consumer.consume(beginRun, row, lastStyle, new CharBuffer(myBuf, row * myWidth + beginRun, col - beginRun), 0); } public boolean hasDamage() { return myDamage.nextSetBit(0) != -1; } public void lock() { myLock.lock(); } public void unlock() { myLock.unlock(); } public boolean tryLock() { return myLock.tryLock(); } private String getLineTrimTrailing(int row) { StringBuilder sb = new StringBuilder(); sb.append(myBuf, row * myWidth, myWidth); return Util.trimTrailing(sb.toString()); } @Override public void consume(int x, int y, @NotNull TextStyle style, @NotNull CharBuffer characters, int startRow) { int len = Math.min(myWidth - x, characters.getLength()); if (len > 0) { writeToBackBuffer(x, y - startRow + 1, new String(characters.getBuf(), characters.getStart(), len), style); } } public int getWidth() { return myWidth; } public int getHeight() { return myHeight; } public int getScrollBufferLinesCount() { return myScrollBuffer.getLineCount(); } public int getTextBufferLinesCount() { return myTextBuffer.getLineCount(); } public String getTextBufferLines() { return myTextBuffer.getLines(); } public boolean checkTextBufferIsValid(int row) { return myTextBuffer.getLineText(row).startsWith(getLineTrimTrailing(row));//in a row back buffer is always a prefix of text buffer } public char getCharAt(int x, int y) { return myBuf[x + myWidth * y]; } public char getBuffersCharAt(int x, int y) { String lineText = getLine(y).getText(); return x < lineText.length() ? lineText.charAt(x) : EMPTY_CHAR; } public TextStyle getStyleAt(int x, int y) { return myStyleBuf[x + myWidth * y]; } public void useAlternateBuffer(boolean enabled) { myAlternateBuffer = enabled; if (enabled) { if (!myUsingAlternateBuffer) { myTextBufferBackup = myTextBuffer; myScrollBufferBackup = myScrollBuffer; myTextBuffer = new LinesBuffer(); myScrollBuffer = new LinesBuffer(); clearArea(); myUsingAlternateBuffer = true; } } else { if (myUsingAlternateBuffer) { myTextBuffer = myTextBufferBackup; myScrollBuffer = myScrollBufferBackup; resetFromTextBuffer(); myUsingAlternateBuffer = false; } } } public LinesBuffer getScrollBuffer() { return myScrollBuffer; } public void insertLines(int y, int count, int scrollRegionBottom) { moveLinesDown(y, count, scrollRegionBottom - 1); clearArea(0, y, myWidth, Math.min(y + count, scrollRegionBottom)); myTextBuffer.insertLines(y, count, scrollRegionBottom - 1); } // returns deleted lines public LinesBuffer deleteLines(int y, int count, int scrollRegionBottom) { moveLinesUp(y + count, -count, scrollRegionBottom); clearArea(0, Math.max(y, scrollRegionBottom - count), myWidth, scrollRegionBottom); return myTextBuffer.deleteLines(y, count, scrollRegionBottom - 1); } public void clearLines(int startRow, int endRow) { TextStyle style = createEmptyStyleWithCurrentColor(); myTextBuffer.clearLines(startRow, endRow); clearArea(0, startRow, myWidth, endRow, style); } public void eraseCharacters(int leftX, int rightX, int y) { TextStyle style = createEmptyStyleWithCurrentColor(); if (y >= 0) { clearArea(leftX, y, rightX, y + 1, style); myTextBuffer.clearArea(leftX, y, rightX, y + 1, style); } else { LOG.error("Attempt to erase characters in line: " + y); } } public void clearAll() { clearArea(); myScrollBuffer.clearAll(); } }
package de.danielnaber.languagetool.rules.de; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import de.danielnaber.languagetool.AnalyzedSentence; import de.danielnaber.languagetool.AnalyzedTokenReadings; import de.danielnaber.languagetool.JLanguageTool; import de.danielnaber.languagetool.rules.Category; import de.danielnaber.languagetool.rules.RuleMatch; import de.danielnaber.languagetool.tagging.de.AnalyzedGermanToken; import de.danielnaber.languagetool.tagging.de.AnalyzedGermanTokenReadings; import de.danielnaber.languagetool.tagging.de.GermanTagger; import de.danielnaber.languagetool.tagging.de.GermanToken; import de.danielnaber.languagetool.tagging.de.GermanToken.POSType; import de.danielnaber.languagetool.tools.StringTools; /** * Check that adjectives and verbs are not written with an uppercase * first letter (except at the start of a sentence) and cases * like this: <tt>Das laufen f&auml;llt mir leicht.</tt> (<tt>laufen</tt> needs * to be uppercased). * * @author Daniel Naber */ public class CaseRule extends GermanRule { private GermanTagger tagger = new GermanTagger(); private static final Set<String> nounIndicators = new HashSet<String>(); static { nounIndicators.add("das"); nounIndicators.add("sein"); //indicator.add("seines"); // TODO: ? //nounIndicators.add("ihr"); // would cause false alarm e.g. "Auf ihr stehen die Ruinen..." nounIndicators.add("mein"); nounIndicators.add("dein"); nounIndicators.add("euer"); //indicator.add("ihres"); //indicator.add("ihren"); } private static final Set<String> sentenceStartExceptions = new HashSet<String>(); static { sentenceStartExceptions.add("("); sentenceStartExceptions.add(":"); sentenceStartExceptions.add("\""); sentenceStartExceptions.add("'"); sentenceStartExceptions.add("„"); sentenceStartExceptions.add("“"); sentenceStartExceptions.add("«"); sentenceStartExceptions.add("»"); } private static final Set<String> exceptions = new HashSet<String>(); static { exceptions.add("Nr"); exceptions.add("Sankt"); exceptions.add("Toter"); exceptions.add("Verantwortlicher"); exceptions.add("Wichtiges"); exceptions.add("Dr"); exceptions.add("Prof"); exceptions.add("Mr"); exceptions.add("Mrs"); exceptions.add("De"); // "De Morgan" etc exceptions.add("Le"); // "Le Monde" etc exceptions.add("Ihr"); exceptions.add("Ihre"); exceptions.add("Ihres"); exceptions.add("Ihren"); exceptions.add("Ihnen"); exceptions.add("Ihrem"); exceptions.add("Ihrer"); exceptions.add("Sie"); exceptions.add("Aus"); // "vor dem Aus stehen" exceptions.add("Oder"); // der Fluss exceptions.add("tun"); exceptions.add("St"); // Paris St. Germain exceptions.add("Las"); // Las Vegas, nicht "lesen" exceptions.add("Folgendes"); exceptions.add("besonderes"); exceptions.add("Hundert"); exceptions.add("Tausend"); exceptions.add("Übrigen"); exceptions.add("Unvorhergesehenes"); exceptions.add("Englisch"); // TODO: alle Sprachen exceptions.add("Deutsch"); exceptions.add("Französisch"); exceptions.add("Spanisch"); exceptions.add("Italienisch"); exceptions.add("Portugiesisch"); exceptions.add("Dänisch"); exceptions.add("Norwegisch"); exceptions.add("Schwedisch"); exceptions.add("Finnisch"); exceptions.add("Holländisch"); exceptions.add("Niederländisch"); exceptions.add("Polnisch"); exceptions.add("Tschechisch"); exceptions.add("Arabisch"); exceptions.add("Persisch"); exceptions.add("Schuld"); exceptions.add("Erwachsener"); exceptions.add("Jugendlicher"); exceptions.add("Link"); exceptions.add("Ausdrücke"); exceptions.add("Landwirtschaft"); exceptions.add("Flöße"); exceptions.add("Wild"); exceptions.add("Vorsitzender"); exceptions.add("Mrd"); exceptions.add("Links"); exceptions.add("Du"); exceptions.add("Dir"); exceptions.add("Dich"); exceptions.add("Deine"); exceptions.add("Deinen"); exceptions.add("Deinem"); exceptions.add("Deines"); exceptions.add("Deiner"); exceptions.add("Neuem"); exceptions.add("Weitem"); exceptions.add("Weiteres"); exceptions.add("Langem"); exceptions.add("Längerem"); exceptions.add("Kurzem"); exceptions.add("Schwarzes"); // Schwarzes Brett exceptions.add("Goldener"); // Goldener Schnitt // TODO: add more exceptions here } private static final Set<String> myExceptionPhrases = new HashSet<String>(); static { // use proper upper/lowercase spelling here: myExceptionPhrases.add("ohne Wenn und Aber"); myExceptionPhrases.add("Große Koalition"); myExceptionPhrases.add("Großen Koalition"); myExceptionPhrases.add("im Großen und Ganzen"); myExceptionPhrases.add("Im Großen und Ganzen"); myExceptionPhrases.add("im Guten wie im Schlechten"); myExceptionPhrases.add("Im Guten wie im Schlechten"); } private static final Set<String> substVerbenExceptions = new HashSet<String>(); static { substVerbenExceptions.add("gehören"); substVerbenExceptions.add("bedeutet"); // "und das bedeutet..." substVerbenExceptions.add("ermöglicht"); substVerbenExceptions.add("sollen"); substVerbenExceptions.add("werden"); substVerbenExceptions.add("dürfen"); substVerbenExceptions.add("müssen"); substVerbenExceptions.add("so"); substVerbenExceptions.add("ist"); substVerbenExceptions.add("können"); substVerbenExceptions.add("muss"); substVerbenExceptions.add("muß"); substVerbenExceptions.add("wollen"); substVerbenExceptions.add("habe"); substVerbenExceptions.add("ein"); // nicht "einen" (Verb) substVerbenExceptions.add("tun"); // "...dann wird er das tun." substVerbenExceptions.add("bestätigt"); substVerbenExceptions.add("bestätigte"); substVerbenExceptions.add("bestätigten"); substVerbenExceptions.add("bekommen"); } public CaseRule(final ResourceBundle messages) { if (messages != null) super.setCategory(new Category(messages.getString("category_case"))); } public String getId() { return "DE_CASE"; } public String getDescription() { return "Großschreibung von Nomen und substantivierten Verben"; } public RuleMatch[] match(final AnalyzedSentence text) { List<RuleMatch> ruleMatches = new ArrayList<RuleMatch>(); AnalyzedTokenReadings[] tokens = text.getTokensWithoutWhitespace(); int pos = 0; boolean prevTokenIsDas = false; for (int i = 0; i < tokens.length; i++) { //FIXME: defaulting to the first analysis //don't know if it's safe String posToken = tokens[i].getAnalyzedToken(0).getPOSTag(); if (posToken != null && posToken.equals(JLanguageTool.SENTENCE_START_TAGNAME)) continue; if (i == 1) { // don't care about first word, UppercaseSentenceStartRule does this already if (nounIndicators.contains(tokens[i].getToken().toLowerCase())) { prevTokenIsDas = true; } continue; } AnalyzedGermanTokenReadings analyzedToken = (AnalyzedGermanTokenReadings)tokens[i]; String token = analyzedToken.getToken(); List<AnalyzedGermanToken> readings = analyzedToken.getGermanReadings(); AnalyzedGermanTokenReadings analyzedGermanToken2 = null; boolean isBaseform = false; if (analyzedToken.getReadingsLength() > 1 && token.equals(analyzedToken.getAnalyzedToken(0).getLemma())) { isBaseform = true; } if ((readings == null || analyzedToken.getAnalyzedToken(0).getPOSTag() == null || analyzedToken.hasReadingOfType(GermanToken.POSType.VERB)) && isBaseform) { try { analyzedGermanToken2 = tagger.lookup(token.toLowerCase()); if (analyzedGermanToken2 != null) { readings = analyzedGermanToken2.getGermanReadings(); } } catch (IOException e) { throw new RuntimeException(e); } if (prevTokenIsDas) { // e.g. essen -> Essen String newToken = StringTools.uppercaseFirstChar(token); try { analyzedGermanToken2 = tagger.lookup(newToken); //analyzedGermanToken2.hasReadingOfType(GermanToken.POSType.VERB) } catch (IOException e) { throw new RuntimeException(e); } if (Character.isLowerCase(token.charAt(0)) && !substVerbenExceptions.contains(token)) { String msg = "Substantivierte Verben werden groß geschrieben."; RuleMatch ruleMatch = new RuleMatch(this, tokens[i].getStartPos(), tokens[i].getStartPos()+token.length(), msg); String word = tokens[i].getToken(); String fixedWord = StringTools.uppercaseFirstChar(word); ruleMatch.setSuggestedReplacement(fixedWord); ruleMatches.add(ruleMatch); } } } if (nounIndicators.contains(tokens[i].getToken().toLowerCase())) { prevTokenIsDas = true; } else { prevTokenIsDas = false; } if (readings == null) continue; boolean hasNounReading = analyzedToken.hasReadingOfType(GermanToken.POSType.NOMEN); if (hasNounReading) // it's the spell checker's task to check that nouns are uppercase continue; try { // TODO: this lookup should only happen once: analyzedGermanToken2 = tagger.lookup(token.toLowerCase()); } catch (IOException e) { throw new RuntimeException(e); } if (analyzedToken.getAnalyzedToken(0).getPOSTag() == null && analyzedGermanToken2 == null) { continue; } if (analyzedToken.getAnalyzedToken(0).getPOSTag() == null && analyzedGermanToken2 != null && analyzedGermanToken2.getAnalyzedToken(0).getPOSTag() == null) { // unknown word, probably a name etc continue; } if (Character.isUpperCase(token.charAt(0)) && token.length() > 1 && // length limit = ignore abbreviations !sentenceStartExceptions.contains(tokens[i-1].getToken()) && !StringTools.isAllUppercase(token) && !exceptions.contains(token) && !analyzedToken.hasReadingOfType(POSType.PROPER_NOUN) && !analyzedToken.isSentenceEnd() && !isExceptionPhrase(i, tokens)) { String msg = "Außer am Satzanfang werden nur Nomen und Eigennamen groß geschrieben"; RuleMatch ruleMatch = new RuleMatch(this, tokens[i].getStartPos(), tokens[i].getStartPos()+token.length(), msg); String word = tokens[i].getToken(); String fixedWord = Character.toLowerCase(word.charAt(0)) + word.substring(1); ruleMatch.setSuggestedReplacement(fixedWord); ruleMatches.add(ruleMatch); } pos += token.length(); } return toRuleMatchArray(ruleMatches); } private boolean isExceptionPhrase(int i, AnalyzedTokenReadings[] tokens) { // TODO: speed up? for (String exc : myExceptionPhrases) { String[] parts = exc.split(" "); for (int j = 0; j < parts.length; j++) { if (parts[j].equals(tokens[i].getToken())) { int startIndex = i-j; if (compareLists(tokens, startIndex, startIndex+parts.length-1, parts)) { return true; } } } } return false; } private boolean compareLists(AnalyzedTokenReadings[] tokens, int startIndex, int endIndex, String[] parts) { if (startIndex < 0) return false; int i = 0; for (int j = startIndex; j <= endIndex; j++) { //System.err.println("**" +tokens[j].getToken() + " <-> "+ parts[i]); if (i >= parts.length) return false; if (!tokens[j].getToken().equals(parts[i])) { return false; } i++; } return true; } public void reset() { // nothing } }
package de.danielnaber.languagetool.server; import java.util.HashSet; import java.util.List; import java.util.Set; import com.prolixtech.jaminid.ContentOracle; import com.prolixtech.jaminid.Daemon; import com.prolixtech.jaminid.ProtocolResponseHeader; import com.prolixtech.jaminid.Request; import com.prolixtech.jaminid.Response; import de.danielnaber.languagetool.JLanguageTool; import de.danielnaber.languagetool.Language; import de.danielnaber.languagetool.rules.RuleMatch; import de.danielnaber.languagetool.tools.StringTools; /** * A small embedded HTTP server that checks text. Returns XML, prints * debugging to stdout/stderr. * * @author Daniel Naber */ public class HTTPServer extends ContentOracle { /** * The default port on which the server is running (8081). */ public static final int DEFAULT_PORT = 8081; private static final int CONTEXT_SIZE = 40; // characters private static Daemon daemon; private int port = DEFAULT_PORT; private static final Set<String> allowedIPs = new HashSet<String>(); static { // accept only requests from localhost. // TODO: find a cleaner solution allowedIPs.add("/0:0:0:0:0:0:0:1"); // Suse Linux IPv6 stuff allowedIPs.add("/127.0.0.1"); } /** * Prepare a server - use run() to start it. */ public HTTPServer() { } /** * Prepare a server on the given port - use run() to start it. */ public HTTPServer(int port) { this.port = port; } /** * Start the server. */ public void run() { System.out.println("Starting server on port " + port + "..."); daemon = new Daemon(port, this); if (daemon.isRunning()) System.out.println("Server started"); else throw new RuntimeException("Server could not be started"); } public String demultiplex(Request connRequest, Response connResponse) { try { if ("".equals(connRequest.getLocation())) { connResponse.setStatus(403); throw new RuntimeException("Error: Access to " + connRequest.getLocation() + " denied"); } if (allowedIPs.contains(connRequest.getIPAddressString())) { String langParam = connRequest.getParamOrNull("language"); if (langParam == null) throw new IllegalArgumentException("Missing 'language' parameter"); Language lang = Language.getLanguageForShortName(langParam); if (lang == null) throw new IllegalArgumentException("Unknown language '" +langParam+ "'"); // TODO: create only once per language?! // TODO: how to take options from the client? JLanguageTool lt = new JLanguageTool(lang); lt.activateDefaultPatternRules(); lt.activateDefaultFalseFriendRules(); String text = connRequest.getParamOrNull("text"); if (text == null) throw new IllegalArgumentException("Missing 'text' parameter"); System.out.println("Checking text with length " + text.length()); List<RuleMatch> matches = lt.check(text); connResponse.setHeaderLine(ProtocolResponseHeader.Content_Type, "text/xml"); return StringTools.ruleMatchesToXML(matches, text, CONTEXT_SIZE); } else { connResponse.setStatus(403); throw new RuntimeException("Error: Access from " + connRequest.getIPAddressString() + " denied"); } } catch (Exception e) { e.printStackTrace(); connResponse.setStatus(500); return "Error: " + e.toString(); } } /** * Stop the server process. */ public void stop() { System.out.println("Stopping server..."); daemon.tearDown(); System.out.println("Server stopped"); } private static void printUsageAndExit() { System.out.println("Usage: HTTPServer [-p|--port port]"); System.exit(1); } /** * Start the server from command line. * Usage: <tt>HTTPServer [-p|--port port]</tt> */ public static void main(String[] args) { if (args.length == 1 || args.length > 2) { printUsageAndExit(); } int port = DEFAULT_PORT; if (args.length == 2) { if ("-p".equals(args[0]) || "--port".equals(args[0])) port = Integer.parseInt(args[1]); else printUsageAndExit(); } HTTPServer server = new HTTPServer(port); server.run(); } }
package org.commcare.android.tests.processing; import org.commcare.CommCareApp; import org.commcare.CommCareApplication; import org.commcare.android.CommCareTestRunner; import org.commcare.android.util.SavedFormLoader; import org.commcare.android.util.TestAppInstaller; import org.commcare.dalvik.BuildConfig; import org.commcare.tasks.PurgeStaleArchivedFormsTask; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.reference.ResourceReferenceFactory; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; import static org.junit.Assert.assertEquals; /** * Tests correctness of saved form purging logic. * * @author Phillip Mates (pmates@dimagi.com). */ @Config(application = CommCareApplication.class, constants = BuildConfig.class) @RunWith(CommCareTestRunner.class) public class ArchivedFormPurgeTest { @Before public void setup() { // needed to resolve "jr://resource" type references ReferenceManager._().addReferenceFactory(new ResourceReferenceFactory()); TestAppInstaller.setupPrototypeFactory(); TestAppInstaller appTestInstaller = new TestAppInstaller("jr://resource/commcare-apps/archive_form_tests/profile.ccpr", "test", "123"); appTestInstaller.installAppAndLogin(); SavedFormLoader.loadFormsFromPayload("/commcare-apps/archive_form_tests/saved_form_payload.xml"); } /** * Ensure that the correct number of forms are purged given different * validity ranges */ @Test public void testSavedFormPurge() { int SAVED_FORM_COUNT = 5; String firstFormCompletionDate = "Mon Oct 05 16:17:01 -0400 2015"; DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy"); DateTime startTestDate = dtf.parseDateTime(firstFormCompletionDate); DateTime twoMonthsLater = startTestDate.plusMonths(2); assertEquals("Only 1 form should remain if we're 2 months past the 1st form's create date.", SAVED_FORM_COUNT - 1, PurgeStaleArchivedFormsTask.getSavedFormsToPurge(twoMonthsLater).size()); DateTime twentyYearsLater = startTestDate.plusYears(20); assertEquals("All forms should be purged if we are way in the future.", SAVED_FORM_COUNT, PurgeStaleArchivedFormsTask.getSavedFormsToPurge(twentyYearsLater).size()); assertEquals("When the time is the 1st form's creation time, no forms should be purged", 0, PurgeStaleArchivedFormsTask.getSavedFormsToPurge(startTestDate).size()); } @Test public void testPurgeDateLoading() { CommCareApp ccApp = CommCareApplication._().getCurrentApp(); int daysFormValidFor = PurgeStaleArchivedFormsTask.getArchivedFormsValidityInDays(ccApp); assertEquals("App should try to keep forms for 31 days", 31, daysFormValidFor); } }
package io.vertigo.dashboard; import java.util.Optional; import org.h2.Driver; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import io.vertigo.AbstractTestCaseJU4; import io.vertigo.app.App; import io.vertigo.app.config.AppConfig; import io.vertigo.app.config.ModuleConfig; import io.vertigo.app.config.NodeConfig; import io.vertigo.commons.impl.CommonsFeatures; import io.vertigo.commons.plugins.analytics.log.SocketLoggerAnalyticsConnectorPlugin; import io.vertigo.commons.plugins.cache.memory.MemoryCachePlugin; import io.vertigo.core.param.Param; import io.vertigo.core.plugins.resource.classpath.ClassPathResourceResolverPlugin; import io.vertigo.database.DatabaseFeatures; import io.vertigo.database.impl.sql.vendor.h2.H2DataBase; import io.vertigo.database.plugins.sql.connection.c3p0.C3p0ConnectionProviderPlugin; import io.vertigo.dynamo.impl.DynamoFeatures; import io.vertigo.dynamo.plugins.search.elasticsearch.embedded.ESEmbeddedSearchServicesPlugin; import io.vertigo.dynamo.plugins.store.datastore.sql.SqlDataStorePlugin; import io.vertigo.dynamox.metric.domain.DomainMetricsProvider; import io.vertigo.vega.VegaFeatures; @RunWith(JUnitPlatform.class) public class DashboardLauncherTest extends AbstractTestCaseJU4 { @Override protected AppConfig buildAppConfig() { return AppConfig.builder() .beginBoot() .addPlugin(ClassPathResourceResolverPlugin.class) .withLocales("fr_FR") .endBoot() .addModule(new CommonsFeatures() .withRedisConnector("redis-pic.part.klee.lan.net", 6379, 0, Optional.empty()) .addAnalyticsConnectorPlugin(SocketLoggerAnalyticsConnectorPlugin.class) .withCache(MemoryCachePlugin.class) .build()) .addModule(new DatabaseFeatures() .withSqlDataBase() .addSqlConnectionProviderPlugin(C3p0ConnectionProviderPlugin.class, Param.of("dataBaseClass", H2DataBase.class.getCanonicalName()), Param.of("jdbcDriver", Driver.class.getCanonicalName()), Param.of("jdbcUrl", "jdbc:h2:mem:database")) .build()) .addModule(new DynamoFeatures() .withStore() .addDataStorePlugin(SqlDataStorePlugin.class, Param.of("sequencePrefix", "SEQ_")) .withSearch(ESEmbeddedSearchServicesPlugin.class, Param.of("home", "io/vertigo/dashboard/search/indexconfig"), Param.of("config.file", "io/vertigo/dashboard/search/indexconfig/elasticsearch.yml"), Param.of("envIndex", "TU_TEST"), Param.of("rowsPerQuery", "50")) .build()) .addModule(new VegaFeatures() .withEmbeddedServer(8080) .build()) .addModule(new DashboardFeatures() .withInfluxDb("http://analytica.part.klee.lan.net:8086", "analytica", "kleeklee") .build()) .addModule( ModuleConfig.builder("metrics") .addComponent(DomainMetricsProvider.class) .build()) .withNodeConfig(NodeConfig.builder() .withAppName("dashboardtest") .build()) .build(); } @Test public void server() { final App app = getApp(); Dashboard.start(app); // while (!Thread.interrupted()) { // try { // Thread.sleep(10 * 1000); // } catch (final InterruptedException e) { // e.printStackTrace(); } }
package io.vertx.ext.web.handler.sockjs.impl; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.ServerCookieDecoder; import io.netty.handler.codec.http.cookie.ServerCookieEncoder; import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.impl.StringEscapeUtils; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.core.shareddata.LocalMap; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.sockjs.SockJSHandlerOptions; import io.vertx.ext.web.handler.sockjs.SockJSSocket; import io.vertx.ext.web.handler.sockjs.Transport; import io.vertx.ext.web.impl.Utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.util.Set; import static io.vertx.core.http.HttpHeaders.*; class BaseTransport { private static final Logger log = LoggerFactory.getLogger(BaseTransport.class); protected final Vertx vertx; protected final LocalMap<String, SockJSSession> sessions; protected SockJSHandlerOptions options; protected static final String COMMON_PATH_ELEMENT_RE = "\\/[^\\/\\.]+\\/([^\\/\\.]+)\\/"; private static final long RAND_OFFSET = 2L << 30; public BaseTransport(Vertx vertx, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options) { this.vertx = vertx; this.sessions = sessions; this.options = options; } protected SockJSSession getSession(RoutingContext rc, long timeout, long heartbeatInterval, String sessionID, Handler<SockJSSocket> sockHandler) { SockJSSession session = sessions.computeIfAbsent(sessionID, s -> new SockJSSession(vertx, sessions, rc, s, timeout, heartbeatInterval, sockHandler)); return session; } protected void sendInvalidJSON(HttpServerResponse response) { if (log.isTraceEnabled()) log.trace("Broken JSON"); response.setStatusCode(500); response.end("Broken JSON encoding."); } protected String escapeForJavaScript(String str) { try { str = StringEscapeUtils.escapeJavaScript(str); } catch (Exception e) { log.error("Failed to escape", e); str = null; } return str; } protected static abstract class BaseListener implements TransportListener { protected final RoutingContext rc; protected final SockJSSession session; protected boolean closed; protected BaseListener(RoutingContext rc, SockJSSession session) { this.rc = rc; this.session = session; } protected void addCloseHandler(HttpServerResponse resp, final SockJSSession session) { resp.closeHandler(v -> { if (log.isTraceEnabled()) log.trace("Connection closed (from client?), closing session"); // Connection has been closed from the client or network error so // we remove the session session.shutdown(); closed = true; }); } @Override public void sessionClosed() { session.writeClosed(this); close(); } } static void setJSESSIONID(SockJSHandlerOptions options, RoutingContext rc) { String cookies = rc.request().getHeader("cookie"); if (options.isInsertJSESSIONID()) { //Preserve existing JSESSIONID, if any if (cookies != null) { String[] parts; if (cookies.contains(";")) { parts = cookies.split(";"); } else { parts = new String[] {cookies}; } for (String part: parts) { if (part.startsWith("JSESSIONID")) { cookies = part + "; path=/"; break; } } } if (cookies == null) { cookies = "JSESSIONID=dummy; path=/"; } rc.response().putHeader("Set-Cookie", cookies); } } static void setCORS(RoutingContext rc) { HttpServerRequest req = rc.request(); String origin = req.headers().get("origin"); if (origin == null || "null".equals(origin)) { origin = "*"; } Utils.addToMapIfAbsent(req.response().headers(), "Access-Control-Allow-Origin", origin); // https://developer.mozilla.org/En/HTTP_access_control#Requests_with_credentials if (!"*".equals(origin)) { Utils.addToMapIfAbsent(req.response().headers(), "Access-Control-Allow-Credentials", "true"); } String hdr = req.headers().get("Access-Control-Request-Headers"); if (hdr != null) { Utils.addToMapIfAbsent(req.response().headers(), "Access-Control-Allow-Headers", hdr); } } static Handler<RoutingContext> createInfoHandler(final SockJSHandlerOptions options) { return new Handler<RoutingContext>() { boolean websocket = !options.getDisabledTransports().contains(Transport.WEBSOCKET.toString()); public void handle(RoutingContext rc) { if (log.isTraceEnabled()) log.trace("In Info handler"); rc.response().putHeader("Content-Type", "application/json; charset=UTF-8"); setNoCacheHeaders(rc); JsonObject json = new JsonObject(); json.put("websocket", websocket); json.put("cookie_needed", options.isInsertJSESSIONID()); json.put("origins", new JsonArray().add("*:*")); // Java ints are signed, so we need to use a long and add the offset so // the result is not negative json.put("entropy", RAND_OFFSET + new Random().nextInt()); setCORS(rc); rc.response().end(json.encode()); } }; } static void setNoCacheHeaders(RoutingContext rc) { rc.response().putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"); } static Handler<RoutingContext> createCORSOptionsHandler(SockJSHandlerOptions options, String methods) { return rc -> { if (log.isTraceEnabled()) log.trace("In CORS options handler"); rc.response().putHeader("Cache-Control", "public,max-age=31536000"); long oneYearSeconds = 365 * 24 * 60 * 60; long oneYearms = oneYearSeconds * 1000; String expires = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date(System.currentTimeMillis() + oneYearms)); rc.response().putHeader("Expires", expires) .putHeader("Access-Control-Allow-Methods", methods) .putHeader("Access-Control-Max-Age", String.valueOf(oneYearSeconds)); setCORS(rc); setJSESSIONID(options, rc); rc.response().setStatusCode(204); rc.response().end(); }; } // Authorization static MultiMap removeCookieHeaders(MultiMap headers) { // We don't want to remove the JSESSION cookie. String cookieHeader = headers.get(COOKIE); if (cookieHeader != null) { headers.remove(COOKIE); Set<Cookie> nettyCookies = ServerCookieDecoder.STRICT.decode(cookieHeader); for (Cookie cookie: nettyCookies) { if (cookie.name().equals("JSESSIONID")) { headers.add(COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); break; } } } return headers; } }
package org.wdrp.core.algorithm.td; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Test; import org.wdrp.core.model.TDArc; import org.wdrp.core.model.TDGraph; public class TDDijkstraAlgorithmTest extends TDTestBase { @Test public void testTDEdgeCost() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int cost = a.getEdgeCost(g.getArc(0, 1), 0); assertEquals(cost, 4); cost = a.getEdgeCost(g.getArc(0, 1), 1); assertEquals(cost, 5); cost = a.getEdgeCost(g.getArc(0, 1), 2); assertEquals(cost, 6); cost = a.getEdgeCost(g.getArc(0, 1), 3); assertEquals(cost, 7); cost = a.getEdgeCost(g.getArc(0, 1), 4); assertEquals(cost, 8); cost = a.getEdgeCost(g.getArc(0, 1), 5); assertEquals(cost, 5+5); cost = a.getEdgeCost(g.getArc(0, 1), 6); assertEquals(cost, 5+6); cost = a.getEdgeCost(g.getArc(0, 1), 10); assertEquals(cost, 10+9); cost = a.getEdgeCost(g.getArc(0, 1), 19); assertEquals(cost, 19+4); cost = a.getEdgeCost(g.getArc(0, 1), 20); assertEquals(cost, Integer.MAX_VALUE); } @Test public void testTDEdgeCost1() { TDGraph tdg = new TDGraph(60,2); tdg.addNode(0); tdg.addNode(1); int[] costs = {10,20}; tdg.addEdge(0, new TDArc(1, costs)); TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(tdg); int cost; cost = a.getEdgeCost(tdg.getArc(0, 1), 0); assertEquals(10, cost); cost = a.getEdgeCost(tdg.getArc(0, 1), 30); assertEquals(40, cost); cost = a.getEdgeCost(tdg.getArc(0, 1), 59); assertEquals(69, cost); cost = a.getEdgeCost(tdg.getArc(0, 1), 60); assertEquals(80, cost); cost = a.getEdgeCost(tdg.getArc(0, 1), 90); assertEquals(110, cost); cost = a.getEdgeCost(tdg.getArc(0, 1), 119); assertEquals(139, cost); cost = a.getEdgeCost(tdg.getArc(0, 1), 120); assertEquals(Integer.MAX_VALUE, cost); cost = a.getEdgeCost(tdg.getArc(0, 1), 130); assertEquals(Integer.MAX_VALUE, cost); cost = a.getEdgeCost(tdg.getArc(0, 1), 180); assertEquals(Integer.MAX_VALUE, cost); } @Test public void computeSPSourceSourceValidDepartureTime() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,0,0); assertEquals(arrivalTime,0); } @Test public void computeSPSourceSourceInvalidDepartureTime() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,0,200); assertEquals(arrivalTime, 200); } @Test public void computeSPSourceTargetValidDepartureTime() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,1,0); assertEquals(arrivalTime, 4); assertEquals(a.getVisitedNodes().toString(), "{1, 0}"); } @Test public void computeSPSourceTargetInvalidDepartureTime() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,1,100); assertEquals(arrivalTime,-1); } @Test public void computeSPSourceTargetLateDepartureTime() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,1,19); assertEquals(arrivalTime,23); } @Test public void computeSPSourceTargetValidDepartureTime2() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,2,0); assertEquals(arrivalTime,7); } @Test public void computeSPSourceTargetValidDepartureTime3() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,2,1); assertEquals(arrivalTime,9); } @Test public void computeSPSourceTargetValidDepartureTime4() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,2,4); assertEquals(arrivalTime,12); } @Test public void computeSPSourceTargetValidDepartureTime5() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,5,0); assertEquals(arrivalTime,19); } @Test public void computeSPSourceTargetValidDepartureTime6() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,5,1); assertEquals(arrivalTime,25); } @Test public void computeSPSourceTargetValidDepartureTime7() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,5,2); assertEquals(arrivalTime,25); } @Test public void computeSPSourceTargetValidDepartureTime8() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,5,3); assertEquals(arrivalTime,26); } @Test public void computeSPSourceTargetValidDepartureTime9() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int arrivalTime = a.computeEarliestArrivalTime(0,5,5); assertEquals(arrivalTime,-1); } @Test public void computeEATimes() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int[] eaTimes = a.computeEarliestArrivalTimes(0, 5, 0, 3); assertEquals(Arrays.toString(eaTimes), "[19, 25, 25, 26]"); } @Test public void computeBestDepartureTime1() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int bestDepartureTime = a.computeBestDepartureTime(0, 5, 0, 5); assertEquals(bestDepartureTime, 0); } @Test public void computeBestDepartureTime2() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int bestDepartureTime = a.computeBestDepartureTime(0, 5, 1, 3); assertEquals(bestDepartureTime, 2); } @Test public void computeBestDepartureTime3() { TDDijkstraAlgorithm a = new TDDijkstraAlgorithm(g); int bestDepartureTime = a.computeBestDepartureTime(0, 5, 2, 3); assertEquals(bestDepartureTime, 2); } }
package de.martinreinhardt.owncloud.webtest.pages; import net.thucydides.core.annotations.Story; import net.thucydides.core.annotations.WithTag; import net.thucydides.core.annotations.findby.FindBy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import de.martinreinhardt.owncloud.webtest.OwnCloud; import de.martinreinhardt.owncloud.webtest.util.AbstractPage; @Story(OwnCloud.Apps.class) @WithTag("Apps") public class PortalPage extends AbstractPage { // OC7 app menu @FindBy(xpath = "//a[@class='menutoggle']") private WebElement appMenu; /** * @param pWebDriver */ public PortalPage(final WebDriver pWebDriver) { super(pWebDriver); } public void go_to_roundcube_app() { try { click(appMenu); } catch (final Exception e) { } click(roundcubeButton); } public void go_to_storage_charts_app() { try { click(appMenu); } catch (final Exception e) { } click(storageChartsButton); } public void open_settings_dropdown() { element(settingsDropdownButton).waitUntilVisible(); click(settingsDropdownButton); } public void go_to_admin_settings() { open_settings_dropdown(); element(adminSettingsDropdownButton).waitUntilVisible(); click(adminSettingsDropdownButton); } public void go_to_user_settings() { open_settings_dropdown(); element(userSettingsDropdownButton).waitUntilVisible(); click(userSettingsDropdownButton); } public void do_logout() { open_settings_dropdown(); element(logoutButton).waitUntilVisible(); click(logoutButton); } }
package org.duracloud.mill.manifest; import java.util.Date; import org.duracloud.audit.task.AuditTask; import org.duracloud.audit.task.AuditTask.ActionType; import org.duracloud.mill.workman.TaskExecutionFailedException; import org.duracloud.mill.workman.TaskProcessorBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ManifestWritingProcessor extends TaskProcessorBase { private static Logger log = LoggerFactory.getLogger(ManifestWritingProcessor.class); private AuditTask task; private ManifestStore manifestStore; /** * @param task * @param manifestStore */ public ManifestWritingProcessor(AuditTask task, ManifestStore manifestStore) { super(task); this.task = task; this.manifestStore = manifestStore; } /* (non-Javadoc) * @see org.duracloud.mill.workman.TaskProcessorBase#executeImpl() */ @Override protected void executeImpl() throws TaskExecutionFailedException { try { String account = task.getAccount(); String storeId = task.getStoreId(); String spaceId = task.getSpaceId(); String contentId = task.getContentId(); String action = task.getAction(); Date timeStamp = new Date(Long.parseLong(task.getDateTime())); if(ActionType.ADD_CONTENT.name().equals(action) || ActionType.COPY_CONTENT.name().equals(action) ){ String mimetype = task.getContentMimetype(); if(mimetype == null){ mimetype = "application/octet-stream"; } String size = task.getContentSize(); if(size == null){ size = "0"; } this.manifestStore.addUpdate(account, storeId, spaceId, contentId, task.getContentChecksum(), mimetype, size, timeStamp); }else if(ActionType.DELETE_CONTENT.name().equals(action)){ this.manifestStore.flagAsDeleted(account, storeId, spaceId, contentId, timeStamp); }else{ log.debug("action {} not handled by this processor: task={}", action,task); } log.info("audit task successfully processed: {}", task); } catch (Exception e) { String message = "Failed to execute " + task + ": " + e.getMessage(); log.debug(message, e); throw new TaskExecutionFailedException(message, e); } } }
package org.knowm.xchange.coinmate; import org.knowm.xchange.BaseExchange; import org.knowm.xchange.Exchange; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.coinmate.service.CoinmateAccountService; import org.knowm.xchange.coinmate.service.CoinmateMarketDataService; import org.knowm.xchange.coinmate.service.CoinmateTradeService; import org.knowm.xchange.utils.nonce.AtomicLongCurrentTimeIncrementalNonceFactory; import si.mazi.rescu.SynchronizedValueFactory; /** @author Martin Stachon */ public class CoinmateExchange extends BaseExchange implements Exchange { private final SynchronizedValueFactory<Long> nonceFactory = new AtomicLongCurrentTimeIncrementalNonceFactory(); @Override public SynchronizedValueFactory<Long> getNonceFactory() { return nonceFactory; } @Override protected void initServices() { this.marketDataService = new CoinmateMarketDataService(this); this.accountService = new CoinmateAccountService(this); this.tradeService = new CoinmateTradeService(this); } @Override public ExchangeSpecification getDefaultExchangeSpecification() { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass().getCanonicalName()); exchangeSpecification.setSslUri("https://coinmate.io"); exchangeSpecification.setHost("coinmate.io"); exchangeSpecification.setPort(80); exchangeSpecification.setExchangeName("CoinMate"); exchangeSpecification.setExchangeDescription("Bitcoin trading made simple."); return exchangeSpecification; } }
package com.intellij.xdebugger.impl.breakpoints; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.xmlb.annotations.Tag; import com.intellij.util.StringBuilderSpinAllocator; import com.intellij.xdebugger.*; import com.intellij.xdebugger.breakpoints.*; import com.intellij.xdebugger.impl.actions.ViewBreakpointsAction; import com.intellij.xdebugger.impl.XSourcePositionImpl; import com.intellij.xdebugger.impl.XDebugSessionImpl; import com.intellij.xdebugger.ui.DebuggerColors; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NonNls; import javax.swing.*; /** * @author nik */ public class XLineBreakpointImpl<P extends XBreakpointProperties> extends XBreakpointBase<XLineBreakpoint<P>, P, XLineBreakpointImpl.LineBreakpointState<P>> implements XLineBreakpoint<P> { private @Nullable RangeHighlighter myHighlighter; private final XLineBreakpointType<P> myType; private Icon myIcon; private XSourcePosition mySourcePosition; @NonNls private static final String BR_NBSP = "<br>&nbsp;"; public XLineBreakpointImpl(final XLineBreakpointType<P> type, XBreakpointManagerImpl breakpointManager, String url, int line, final @Nullable P properties) { super(type, breakpointManager, properties, new LineBreakpointState<P>(true, type.getId(), url, line)); myType = type; } private XLineBreakpointImpl(final XLineBreakpointType<P> type, XBreakpointManagerImpl breakpointManager, final LineBreakpointState<P> breakpointState) { super(type, breakpointManager, breakpointState); myType = type; } public void updateUI() { Document document = getDocument(); if (document == null) return; EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); TextAttributes attributes = scheme.getAttributes(DebuggerColors.BREAKPOINT_ATTRIBUTES); removeHighlighter(); MarkupModelEx markupModel = (MarkupModelEx)document.getMarkupModel(getProject()); RangeHighlighter highlighter = markupModel.addPersistentLineHighlighter(getLine(), DebuggerColors.BREAKPOINT_HIGHLIGHTER_LAYER, attributes); if (highlighter != null) { updateIcon(); setupGutterRenderer(highlighter); } myHighlighter = highlighter; } @Nullable public Document getDocument() { VirtualFile file = getFile(); if (file == null) return null; return FileDocumentManager.getInstance().getDocument(file); } @Nullable private VirtualFile getFile() { return VirtualFileManager.getInstance().findFileByUrl(getFileUrl()); } private void setupGutterRenderer(final RangeHighlighter highlighter) { highlighter.setGutterIconRenderer(new BreakpointGutterIconRenderer()); } @NotNull public XLineBreakpointType<P> getType() { return myType; } private void updateIcon() { myIcon = calculateIcon(); } @NotNull private Icon calculateIcon() { if (!isEnabled()) { return myType.getDisabledIcon(); } XDebugSessionImpl session = getBreakpointManager().getDebuggerManager().getCurrentSession(); if (session == null) { if (getBreakpointManager().getDependentBreakpointManager().getMasterBreakpoint(this) != null) { return myType.getDisabledDependentIcon(); } } else { if (session.isDisabledSlaveBreakpoint(this)) { return myType.getDisabledDependentIcon(); } CustomizedBreakpointPresentation presentation = session.getBreakpointPresentation(this); if (presentation != null) { Icon icon = presentation.getIcon(); if (icon != null) { return icon; } } } return myType.getEnabledIcon(); } @Nullable private CustomizedBreakpointPresentation getCustomizedPresentation() { final XDebugSessionImpl currentSession = getBreakpointManager().getDebuggerManager().getCurrentSession(); return currentSession != null ? currentSession.getBreakpointPresentation(this) : null; } public int getLine() { return getState().getLine(); } public String getFileUrl() { return getState().getFileUrl(); } @Nullable public RangeHighlighter getHighlighter() { return myHighlighter; } public XSourcePosition getSourcePosition() { if (mySourcePosition == null) { mySourcePosition = XSourcePositionImpl.create(getFile(), getLine()); } return mySourcePosition; } public boolean isValid() { return myHighlighter != null && myHighlighter.isValid(); } public void dispose() { removeHighlighter(); } private void removeHighlighter() { if (myHighlighter != null) { myHighlighter.getDocument().getMarkupModel(getProject()).removeHighlighter(myHighlighter); myHighlighter = null; } } private Icon getIcon() { if (myIcon == null) { updateIcon(); } return myIcon; } public String getDescription() { @NonNls StringBuilder builder = StringBuilderSpinAllocator.alloc(); try { builder.append("<html><body>"); builder.append(myType.getDisplayText(this)); String errorMessage = getErrorMessage(); if (errorMessage != null) { builder.append(BR_NBSP); builder.append("<font color=\"red\">"); builder.append(errorMessage); builder.append("</font>"); } SuspendPolicy suspendPolicy = getSuspendPolicy(); if (suspendPolicy == SuspendPolicy.THREAD) { builder.append(BR_NBSP).append(XDebuggerBundle.message("xbreakpoint.tooltip.suspend.policy.thread")); } else if (suspendPolicy == SuspendPolicy.NONE) { builder.append(BR_NBSP).append(XDebuggerBundle.message("xbreakpoint.tooltip.suspend.policy.none")); } String condition = getCondition(); if (condition != null) { builder.append(BR_NBSP); builder.append(XDebuggerBundle.message("xbreakpoint.tooltip.condition")); builder.append("&nbsp;"); builder.append(condition); } if (isLogMessage()) { builder.append(BR_NBSP).append(XDebuggerBundle.message("xbreakpoint.tooltip.log.message")); } String logExpression = getLogExpression(); if (logExpression != null) { builder.append(BR_NBSP); builder.append(XDebuggerBundle.message("xbreakpoint.tooltip.log.expression")); builder.append("&nbsp;"); builder.append(logExpression); } XBreakpoint<?> masterBreakpoint = getBreakpointManager().getDependentBreakpointManager().getMasterBreakpoint(this); if (masterBreakpoint != null) { builder.append(BR_NBSP); String str = XDebuggerBundle.message("xbreakpoint.tooltip.depends.on"); builder.append(str); builder.append("&nbsp;"); builder.append(XBreakpointUtil.getDisplayText(masterBreakpoint)); } builder.append("</body><html"); return builder.toString(); } finally { StringBuilderSpinAllocator.dispose(builder); } } @Nullable private String getErrorMessage() { CustomizedBreakpointPresentation presentation = getCustomizedPresentation(); return presentation != null ? presentation.getErrorMessage() : null; } public void updatePosition() { if (myHighlighter != null && myHighlighter.isValid()) { Document document = myHighlighter.getDocument(); setLine(document.getLineNumber(myHighlighter.getStartOffset())); } } private void setLine(final int line) { if (getLine() != line) { getState().setLine(line); fireBreakpointChanged(); } } @Tag("line-breakpoint") public static class LineBreakpointState<P extends XBreakpointProperties> extends XBreakpointBase.BreakpointState<XLineBreakpoint<P>, P, XLineBreakpointType<P>> { private String myFileUrl; private int myLine; public LineBreakpointState() { } public LineBreakpointState(final boolean enabled, final String typeId, final String fileUrl, final int line) { super(enabled, typeId); myFileUrl = fileUrl; myLine = line; } @Tag("url") public String getFileUrl() { return myFileUrl; } public void setFileUrl(final String fileUrl) { myFileUrl = fileUrl; } @Tag("line") public int getLine() { return myLine; } public void setLine(final int line) { myLine = line; } public XBreakpointBase<XLineBreakpoint<P>,P, ?> createBreakpoint(@NotNull final XLineBreakpointType<P> type, @NotNull XBreakpointManagerImpl breakpointManager) { return new XLineBreakpointImpl<P>(type, breakpointManager, this); } } private class BreakpointGutterIconRenderer extends GutterIconRenderer { @NotNull public Icon getIcon() { return XLineBreakpointImpl.this.getIcon(); } @Nullable public AnAction getClickAction() { return new MyRemoveBreakpointAction(); } @Nullable public AnAction getMiddleButtonClickAction() { return new MyToggleBreakpointAction(); } @Nullable public ActionGroup getPopupMenuActions() { DefaultActionGroup group = new DefaultActionGroup(); group.add(new MyRemoveBreakpointAction()); group.add(new MyToggleBreakpointAction()); group.add(new Separator()); group.add(new ViewBreakpointsAction(XDebuggerBundle.message("xdebugger.view.breakpoint.properties.action"), XLineBreakpointImpl.this)); return group; } @Nullable public String getTooltipText() { return getDescription(); } } private class MyRemoveBreakpointAction extends AnAction { private MyRemoveBreakpointAction() { super(XDebuggerBundle.message("xdebugger.remove.line.breakpoint.action.text")); } public void actionPerformed(final AnActionEvent e) { XDebuggerUtil.getInstance().removeBreakpoint(getProject(), XLineBreakpointImpl.this); } } private class MyToggleBreakpointAction extends AnAction { private MyToggleBreakpointAction() { super(isEnabled() ? XDebuggerBundle.message("xdebugger.disable.breakpoint.action.text") : XDebuggerBundle.message("xdebugger.enable.breakpoint.action.text")); } public void actionPerformed(final AnActionEvent e) { setEnabled(!isEnabled()); } } }
package com.xpn.xwiki.user.impl.xwiki; import java.io.IOException; import java.security.Principal; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.securityfilter.authenticator.Authenticator; import org.securityfilter.authenticator.FormAuthenticator; import org.securityfilter.filter.SecurityRequestWrapper; import org.securityfilter.filter.URLPatternMatcher; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.web.SavedRequestRestorerFilter; public class MyFormAuthenticator extends FormAuthenticator implements Authenticator, XWikiAuthenticator { private static final Log log = LogFactory.getLog(MyFormAuthenticator.class); /** * Show the login page. * * @param request the current request * @param response the current response */ public void showLogin(HttpServletRequest request, HttpServletResponse response, XWikiContext context) throws IOException { if ("1".equals(request.getParameter("basicauth"))) { String realmName = context.getWiki().Param("xwiki.authentication.realmname"); if (realmName == null) { realmName = "XWiki"; } MyBasicAuthenticator.showLogin(request, response, realmName); } else { showLogin(request, response); } } /** * {@inheritDoc} * * @see org.securityfilter.authenticator.Authenticator#showLogin(HttpServletRequest, HttpServletResponse) */ @Override public void showLogin(HttpServletRequest request, HttpServletResponse response) throws IOException { String savedRequestId = request.getParameter(SavedRequestRestorerFilter.SAVED_REQUESTS_IDENTIFIER); if (StringUtils.isEmpty(savedRequestId)) { // Save this request savedRequestId = SavedRequestRestorerFilter.saveRequest(request); } // Redirect to login page response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + this.loginPage + "?" + SavedRequestRestorerFilter.SAVED_REQUESTS_IDENTIFIER + "=" + savedRequestId)); return; } @Override public boolean processLogin(SecurityRequestWrapper request, HttpServletResponse response) throws Exception { return processLogin(request, response, null); } private String convertUsername(String username, XWikiContext context) { return context.getWiki().convertUsername(username, context); } /** * Process any login information that was included in the request, if any. Returns true if SecurityFilter should * abort further processing after the method completes (for example, if a redirect was sent as part of the login * processing). * * @param request * @param response * @return true if the filter should return after this method ends, false otherwise */ public boolean processLogin(SecurityRequestWrapper request, HttpServletResponse response, XWikiContext context) throws Exception { try { Principal principal = MyBasicAuthenticator.checkLogin(request, response, context); if (principal != null) { return false; } if ("1".equals(request.getParameter("basicauth"))) { return true; } } catch (Exception e) { // in case of exception we continue on Form Auth. // we don't want this to interfere with the most common behavior } // process any persistent login information, if user is not already logged in, // persistent logins are enabled, and the persistent login info is present in this request if (this.persistentLoginManager != null) { String username = convertUsername(this.persistentLoginManager.getRememberedUsername(request, response), context); String password = this.persistentLoginManager.getRememberedPassword(request, response); Principal principal = request.getUserPrincipal(); if (principal == null || !StringUtils.endsWith(principal.getName(), "XWiki." + username) || context.getWiki().ParamAsLong("xwiki.authentication.always", 0) == 1) { principal = authenticate(username, password, context); if (principal != null) { if (log.isDebugEnabled()) { log.debug("User " + principal.getName() + " has been authentified from cookie"); } request.setUserPrincipal(principal); } else { // Failed to authenticate, better cleanup the user stored in the session request.setUserPrincipal(null); if (username != null || password != null) { // Failed authentication with remembered login, better forget login now this.persistentLoginManager.forgetLogin(request, response); } } } } // process login form submittal if ((this.loginSubmitPattern != null) && request.getMatchableURL().endsWith(this.loginSubmitPattern)) { String username = convertUsername(request.getParameter(FORM_USERNAME), context); String password = request.getParameter(FORM_PASSWORD); String rememberme = request.getParameter(FORM_REMEMBERME); rememberme = (rememberme == null) ? "false" : rememberme; return processLogin(username, password, rememberme, request, response, context); } return false; } /** * Process any login information passed in parameter (username, password). Returns true if SecurityFilter should * abort further processing after the method completes (for example, if a redirect was sent as part of the login * processing). * * @param request * @param response * @return true if the filter should return after this method ends, false otherwise */ public boolean processLogin(String username, String password, String rememberme, SecurityRequestWrapper request, HttpServletResponse response, XWikiContext context) throws Exception { Principal principal = authenticate(username, password, context); if (principal != null) { // login successful if (log.isInfoEnabled()) { log.info("User " + principal.getName() + " has been logged-in"); } // invalidate old session if the user was already authenticated, and they logged in as a different user if (request.getUserPrincipal() != null && !username.equals(request.getRemoteUser())) { request.getSession().invalidate(); } // manage persistent login info, if persistent login management is enabled if (this.persistentLoginManager != null) { // did the user request that their login be persistent? if (rememberme != null) { // remember login this.persistentLoginManager.rememberLogin(request, response, username, password); } else { // forget login this.persistentLoginManager.forgetLogin(request, response); } } request.setUserPrincipal(principal); Boolean bAjax = (Boolean) context.get("ajax"); if ((bAjax == null) || (!bAjax.booleanValue())) { String continueToURL = getContinueToURL(request); // This is the url that the user was initially accessing before being prompted for login. response.sendRedirect(response.encodeRedirectURL(continueToURL)); } } else { // login failed // set response status and forward to error page if (log.isInfoEnabled()) { log.info("User " + username + " login has failed"); } String returnCode = context.getWiki().Param("xwiki.authentication.unauthorized_code"); int rCode = HttpServletResponse.SC_UNAUTHORIZED; if ((returnCode != null) && (!returnCode.equals(""))) { try { rCode = Integer.parseInt(returnCode); } catch (Exception e) { rCode = HttpServletResponse.SC_UNAUTHORIZED; } } response.setStatus(rCode); // TODO: Does this work? (200 in case of error) } return true; } /** * FormAuthenticator has a special case where the user should be sent to a default page if the user spontaneously * submits a login request. * * @param request * @return a URL to send the user to after logging in */ private String getContinueToURL(HttpServletRequest request) { String savedURL = request.getParameter("xredirect"); if (StringUtils.isEmpty(savedURL)) { savedURL = SavedRequestRestorerFilter.getOriginalUrl(request); } if (!StringUtils.isEmpty(savedURL)) { return savedURL; } return request.getContextPath() + this.defaultPage; } public static Principal authenticate(String username, String password, XWikiContext context) throws XWikiException { return context.getWiki().getAuthService().authenticate(username, password, context); } /** * {@inheritDoc} * * @see Authenticator#processLogout(SecurityRequestWrapper, HttpServletResponse, URLPatternMatcher) */ @Override public boolean processLogout(SecurityRequestWrapper securityRequestWrapper, HttpServletResponse httpServletResponse, URLPatternMatcher urlPatternMatcher) throws Exception { boolean result = super.processLogout(securityRequestWrapper, httpServletResponse, urlPatternMatcher); if (result == true) { if (this.persistentLoginManager != null) { this.persistentLoginManager.forgetLogin(securityRequestWrapper, httpServletResponse); } } return result; } }
package org.zanata.rest.client; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import org.jboss.resteasy.client.ClientExecutor; import org.jboss.resteasy.client.ClientRequestFactory; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.plugins.providers.RegisterBuiltin; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zanata.rest.RestConstant; import org.zanata.rest.dto.VersionInfo; import javax.ws.rs.core.Response; public class ZanataProxyFactory implements ITranslationResourcesFactory { static { ResteasyProviderFactory instance = ResteasyProviderFactory.getInstance(); RegisterBuiltin.register(instance); } private static final Logger log = LoggerFactory.getLogger(ZanataProxyFactory.class); private final ClientRequestFactory crf; private static final String RESOURCE_PREFIX = "rest"; public ZanataProxyFactory(String username, String apiKey, VersionInfo clientApiVersion) { this(null, username, apiKey, clientApiVersion); } public ZanataProxyFactory(URI base, String username, String apiKey, VersionInfo clientApiVersion) { this(base, username, apiKey, null, clientApiVersion, false); } public ZanataProxyFactory(URI base, String username, String apiKey, VersionInfo clientApiVersion, boolean logHttp) { this(base, username, apiKey, null, clientApiVersion, logHttp); } public ZanataProxyFactory(URI base, String username, String apiKey, ClientExecutor executor, VersionInfo clientApiVersion, boolean logHttp) { crf = new ClientRequestFactory(executor, null, fixBase(base)); registerPrefixInterceptor(new TraceDebugInterceptor(logHttp)); registerPrefixInterceptor(new ApiKeyHeaderDecorator(username, apiKey, clientApiVersion.getVersionNo())); String clientVer = clientApiVersion.getVersionNo(); String clientTimestamp = clientApiVersion.getBuildTimeStamp(); IVersionResource iversion = createIVersionResource(); ClientResponse<VersionInfo> versionResp = iversion.get(); VersionInfo serverVersionInfo = null; if( versionResp.getResponseStatus() == Response.Status.OK ) { serverVersionInfo = versionResp.getEntity(); } // unauthorized else if( versionResp.getResponseStatus() == Response.Status.UNAUTHORIZED ) { throw new RuntimeException("Incorrect username/password"); } String serverVer = serverVersionInfo.getVersionNo(); String serverTimestamp = serverVersionInfo.getBuildTimeStamp(); log.info("client API version: {}, server API version: {}", clientVer, serverVer); if (!serverVer.equals(clientVer)) { log.warn("client API version is {}, but server API version is {}", clientVer, serverVer); } else if (serverVer.contains(RestConstant.SNAPSHOT_VERSION) && !serverTimestamp.equalsIgnoreCase(clientTimestamp)) { log.warn("client API timestamp is {}, but server API timestamp is {}", clientTimestamp, serverTimestamp); } } public <T> T createProxy(Class<T> clazz, URI baseUri) { log.debug("{} proxy uri: {}", clazz.getSimpleName(), baseUri); T proxy = crf.createProxy(clazz, baseUri); // CacheFactory.makeCacheable(proxy); return proxy; } private static URI fixBase(URI base) { if (base != null) { String baseString = base.toString(); if (!baseString.endsWith("/")) { try { URI result = new URI(baseString + "/"); log.warn("Appending '/' to base URL '{}': using '{}'", baseString, result); return result; } catch (URISyntaxException e) { throw new RuntimeException(e); } } } return base; } public IGlossaryResource getGlossaryResource() { return createProxy(IGlossaryResource.class, getGlossaryResourceURI()); } public URI getGlossaryResourceURI() { try { URL url = new URL(crf.getBase().toURL(), RESOURCE_PREFIX + "/glossary"); return url.toURI(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public IAccountResource getAccount(String username) { return createProxy(IAccountResource.class, getAccountURI(username)); } public URI getAccountURI(String username) { try { URL url = new URL(crf.getBase().toURL(), RESOURCE_PREFIX + "/accounts/u/" + username); return url.toURI(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public IProjectResource getProject(String proj) { return createProxy(IProjectResource.class, getProjectURI(proj)); } public URI getProjectURI(String proj) { try { URL url = new URL(crf.getBase().toURL(), RESOURCE_PREFIX + "/projects/p/" + proj); return url.toURI(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public IProjectIterationResource getProjectIteration(String proj, String iter) { return createProxy(IProjectIterationResource.class, getProjectIterationURI(proj, iter)); } public URI getProjectIterationURI(String proj, String iter) { try { URL url = new URL(crf.getBase().toURL(), RESOURCE_PREFIX + "/projects/p/" + proj + "/iterations/i/" + iter); return url.toURI(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } } // NB IProjectsResource is not currently used in Java public IProjectsResource getProjects(final URI uri) { return createProxy(IProjectsResource.class, uri); } @Override public ITranslatedDocResource getTranslatedDocResource(String projectSlug, String versionSlug) { return createProxy(ITranslatedDocResource.class, getResourceURI(projectSlug, versionSlug)); } public ISourceDocResource getSourceDocResource(String projectSlug, String versionSlug) { return createProxy(ISourceDocResource.class, getResourceURI(projectSlug, versionSlug)); } @Override public URI getResourceURI(String projectSlug, String versionSlug) { String spec = RESOURCE_PREFIX + "/projects/p/" + projectSlug + "/iterations/i/" + versionSlug + "/r"; try { return new URL(crf.getBase().toURL(), spec).toURI(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { String msg = "URI Syntax error. Please make sure your project (project ID) and version are correct."; log.error(msg); log.error("part of your url: {}", spec); throw new RuntimeException(msg); } } /** * @see org.jboss.resteasy.client.core.ClientInterceptorRepositoryImpl#registerInterceptor(Object) * @param interceptor */ public void registerPrefixInterceptor(Object interceptor) { crf.getPrefixInterceptors().registerInterceptor(interceptor); } protected IVersionResource createIVersionResource() { URL url; try { url = new URL(crf.getBase().toURL(), RESOURCE_PREFIX + "/version"); return createProxy(IVersionResource.class, url.toURI()); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } } }
package com.salesforce.dva.argus.system; import com.google.inject.Singleton; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.nio.charset.Charset; import java.text.MessageFormat; import java.util.Properties; import static com.salesforce.dva.argus.system.SystemAssert.requireArgument; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; /** * Immutable system configuration information. * * @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com) */ @SuppressWarnings("serial") @Singleton public final class SystemConfiguration extends Properties { static final String LOCAL_CONFIG_LOCATION; static final String GLOBAL_CONFIG_LOCATION; static { LOCAL_CONFIG_LOCATION = "argus.config.public.location"; GLOBAL_CONFIG_LOCATION = "argus.config.private.location"; } /** * Creates a new SystemConfiguration object. * * @param props The properties used to configure the system. Cannot be null; */ public SystemConfiguration(Properties props) { super(); putAll(props); } /** * Interactively generates a local configuration file, prompting the user for input. * * @param input The input stream to read user responses from. Cannot be null. * @param output The output stream to prompt the user on. Cannot be null. * @param destination The destination file to write the configuration to. Cannot be null and cannot be an existing file. * * @throws IOException If an error writing the configuration occurs. */ public static void generateConfiguration(InputStream input, OutputStream output, File destination) throws IOException { requireArgument(input != null, "Input stream cannot be null."); requireArgument(output != null, "Output stream cannot be null."); requireArgument(destination != null, "Destination cannot be null."); requireArgument(!destination.exists(), "The destination file already exists."); BufferedReader in = new BufferedReader(new InputStreamReader(input, Charset.forName("UTF-8"))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(output, Charset.forName("UTF-8"))); SystemConfiguration config = new SystemConfiguration(new Properties()); for (Property property : Property.values()) { if (!Property.BUILD.equals(property) && !Property.VERSION.equals(property)) { String name = property.key(); do { String defaultValue = config.getValue(property); out.write(MessageFormat.format("Enter value for ''{0}'' ", name)); if (defaultValue != null) { out.write(MessageFormat.format("'(default = '{0}')': ", config.getValue(property))); } out.flush(); String value = in.readLine(); if (value != null && !value.trim().isEmpty()) { config.put(name, value); } else if (defaultValue != null) { config.put(name, defaultValue); } } while (config.getValue(property) == null); } } try(OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(destination), Charset.forName("UTF-8"))) { config.store(fileWriter, "Argus local configuration"); out.write(MessageFormat.format("Configuration saved to {0}.", destination.getAbsolutePath())); } } /** * Returns the host name of the system on which it is invoked. * * @return The system host name. */ public static String getHostname() { if (System.getProperty("os.name").startsWith("Windows")) { return System.getenv("COMPUTERNAME"); } else { String hostname = System.getenv("HOSTNAME"); if (hostname != null) { return hostname; } } try { return InetAddress.getLocalHost().getHostName(); } catch (Exception ex) { return "unknown-host"; } } /** * Returns the value of a configuration property. * * @param property The property to retrieve. Cannot be null. * * @return The configured value of the property. May be null for properties having no default. */ public String getValue(Property property) { return getProperty(property.key(), property.defaultValue()); } /** * Returns the value of a configuration property. * * @param key The key to retrieve. Cannot be null. * @param defaultValue The default value. * * @return The configured value of the property. May be null for properties having no default. */ public String getValue(String key, String defaultValue) { return getProperty(key, defaultValue); } /** * Returns the list of configured properties and their values. * * @return The list of configured properties and their values. */ @Override public synchronized String toString() { Properties allProperties = new Properties(); allProperties.putAll(this); for (Property property : Property.values()) { allProperties.putIfAbsent(property.key(), property.defaultValue()); } StringBuilder sb = new StringBuilder(); sb.append("Using the following configured values:\n"); Pattern pattern = Pattern.compile("pwd|secret|password|passwd|token"); Set<String> names = new TreeSet<>(allProperties.stringPropertyNames()); names.stream().forEach((name) -> { String value = pattern.matcher(name).find() ? "********" : allProperties.get(name).toString(); sb.append("\t").append(name).append(" : ").append(value).append("\n"); }); return sb.toString(); } /** * Supported properties. The target.environment property can be one of 'test' * * @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com) */ public enum Property { BUILD("system.property.build", "XXXX-XX"), LOG_LEVEL("system.property.log.level", "INFO"), VERSION("system.property.version", "X.X"), ADMIN_EMAIL("system.property.admin.email", "someone@mycompany.com"), EMAIL_ENABLED("system.property.mail.enabled", "false"), GOC_ENABLED("system.property.goc.enabled", "false"), GUS_ENABLED("system.property.gus.enabled", "false"), EMAIL_EXCEPTIONS("system.property.mail.exceptions", "false"), CLIENT_THREADS("system.property.client.threads", "2"), CLIENT_CONNECT_TIMEOUT("system.property.client.connect.timeout", "10000"), CACHE_SERVICE_IMPL_CLASS("service.binding.cache", "com.salesforce.dva.argus.service.cache.NoOperationCacheService"), CACHE_SERVICE_PROPERTY_FILE("service.config.cache","argus.properties"), MQ_SERVICE_IMPL_CLASS("service.binding.mq", "com.salesforce.dva.argus.service.mq.kafka.KafkaMessageService"), MQ_SERVICE_PROPERTY_FILE("service.config.mq","argus.properties"), ALERT_SERVICE_IMPL_CLASS("service.binding.alert", "com.salesforce.dva.argus.service.alert.DefaultAlertService"), ALERT_SERVICE_PROPERTY_FILE("service.config.alert","argus.properties"), NOTIFIER_PROPERTY_FILE("service.config.notifier","notifier.properties"), SCHEDULING_SERVICE_IMPL_CLASS("service.binding.scheduling", "com.salesforce.dva.argus.service.schedule.DefaultSchedulingService"), SCHEDULING_SERVICE_PROPERTY_FILE("service.config.scheduling","argus.properties"), MAIL_SERVICE_IMPL_CLASS("service.binding.mail", "com.salesforce.dva.argus.service.mail.DefaultMailService"), MAIL_SERVICE_PROPERTY_FILE("service.config.mail","argus.properties"), CALLBACK_SERVICE_IMPL_CLASS("service.binding.callback", "com.salesforce.dva.argus.service.callback.DefaultCallbackService"), CALLBACK_SERVICE_PROPPERTY_FILE("service.config.callback", "argus.properties"), AUTH_SERVICE_IMPL_CLASS("service.binding.auth", "com.salesforce.dva.argus.service.auth.LDAPAuthService"), AUTH_SERVICE_PROPERTY_FILE("service.config.auth","argus.properties"), SCHEMA_SERVICE_IMPL_CLASS("service.binding.schema", "com.salesforce.dva.argus.service.schema.AsyncHbaseSchemaService"), SCHEMA_SERVICE_PROPERTY_FILE("service.config.schema","argus.properties"), HISTORY_SERVICE_IMPL_CLASS("service.binding.history", "com.salesforce.dva.argus.service.history.HBaseHistoryService"), HISTORY_SERVICE_PROPERTY_FILE("service.config.history","argus.properties"), AUDIT_SERVICE_IMPL_CLASS("service.binding.audit", "com.salesforce.dva.argus.service.audit.DefaultAuditService"), AUDIT_SERVICE_PROPERTY_FILE("service.config.audit","argus.properties"), ASYNCHBASE_PROPERTY_FILE("service.config.asynchbase", "argus.properties"), TSDB_SERVICE_IMPL_CLASS("service.binding.tsdb", "com.salesforce.dva.argus.service.tsdb.DefaultTSDBService"), TSDB_SERVICE_PROPERTY_FILE("service.config.tsdb","argus.properties"), WARDEN_SERVICE_IMPL_CLASS("service.binding.warden", "com.salesforce.dva.argus.service.warden.DefaultWardenService"), WARDEN_SERVICE_PROPERTY_FILE("service.config.warden", "argus.properties"); private final String _name; private final String _defaultValue; private Property(String name, String defaultValue) { _name = name; _defaultValue = defaultValue; } private String defaultValue() { return _defaultValue; } private String key() { return _name; } } }
package mods.periodicraft; import java.util.Random; import java.util.logging.Level; import mods.periodicraft.World.EnumBlockRarity; import mods.periodicraft.World.PeriodicraftWorldGenerator; import mods.periodicraft.block.BlockOre; import mods.periodicraft.item.ItemDust; import mods.periodicraft.item.ItemIngot; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.MinecraftForge; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; @Mod(modid = "Periodicraft", name = "Periodicraft", version = "Beta 1.0.0") @NetworkMod(clientSideRequired = true, serverSideRequired = false) public class Periodicraft { // Ore Generator public static PeriodicraftWorldGenerator WGen; public static Random random = new Random(); protected static final int LightValue = 0; protected static final int LightOpacity = 0; // ingot public static ItemIngot ItemCopperIngot = new ItemIngot(ID.id(), "Copper Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemBronzeIngot = new ItemIngot(ID.id(), "Bronze Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemOsmiumIngot = new ItemIngot(ID.id(), "Osmium Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemPlatinumIngot = new ItemIngot(ID.id(), "Platinum Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemTungstenIngot = new ItemIngot(ID.id(), "Tungsten Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemTinIngot = new ItemIngot(ID.id(), "Tin Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemSilverIngot = new ItemIngot(ID.id(), "Silver Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemNeodymiumIngot = new ItemIngot(ID.id(), "Neodymium Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemNickelIngot = new ItemIngot(ID.id(), "Nickel Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemMagnesiumIngot = new ItemIngot(ID.id(), "Magnesium Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemBoronIngot = new ItemIngot(ID.id(), "Boron Ingot", Periodicraft.tabMaterials); public static ItemIngot ItemBerylliumIngot = new ItemIngot(ID.id(), "Beryllium Ingot", Periodicraft.tabMaterials); // dust public static ItemDust ItemCarbonDust = new ItemDust(ID.id(), "Carbon Dust", Periodicraft.tabMaterials); public static ItemDust ItemZincDust = new ItemDust(ID.id(), "Zinc Dust", Periodicraft.tabMaterials); public static ItemDust ItemMagnesiumDust = new ItemDust(ID.id(), "Magnesium Dust", Periodicraft.tabMaterials); // ore public static BlockOre BlockCopperOre = Periodicraft.CreateOreBlock( "Copper Ore", 3.5F, 4.5F, 1, LightValue, LightOpacity, 0, EnumBlockRarity.RARE); public static BlockOre BlockCarbonOre = Periodicraft.CreateOreBlock( "Carbon Ore", 5.4F, 4.3F, 2, LightValue, LightOpacity, 0, EnumBlockRarity.SUBTLE); public static BlockOre BlockOsmiumOre = Periodicraft.CreateOreBlock( "Osmium Ore", 8.7F, 5.4F, 4, LightValue, LightOpacity, 0, EnumBlockRarity.UNCOMMON); public static BlockOre BlockZincOre = Periodicraft.CreateOreBlock( "Zinc Ore", 5.5F, 3.2F, 3, LightValue, LightOpacity, 0, EnumBlockRarity.SUBTLE); public static BlockOre BlockPlatinumOre = Periodicraft.CreateOreBlock( "Platinum Ore", 7.5F, 5.5F, 3, LightValue, LightOpacity, 0, EnumBlockRarity.RARE); public static BlockOre BlockTungstenOre = Periodicraft.CreateOreBlock( "Tungsten Ore", 4.5F, 4.6F, 3, LightValue, LightOpacity, 0, EnumBlockRarity.RARE); public static BlockOre BlockTinOre = Periodicraft.CreateOreBlock("Tin Ore", 5.1F, 4.3F, 3, LightValue, LightOpacity, 0, EnumBlockRarity.SUBTLE); public static BlockOre BlockSilverOre = Periodicraft.CreateOreBlock( "Silver Ore", 3.2F, 3.9F, 3, LightValue, LightOpacity, 0, EnumBlockRarity.UNCOMMON); public static BlockOre BlockNeodymiumOre = Periodicraft.CreateOreBlock( "Neodymium Ore", 4.6F, 4.5F, 3, LightValue, LightOpacity, 0, EnumBlockRarity.COMMON); public static BlockOre BlockNickelOre = Periodicraft.CreateOreBlock( "Nickel Ore", 3.8F, 4.1F, 3, LightValue, LightOpacity, 0, EnumBlockRarity.SUBTLE); public static BlockOre BlockMagnesiumOre = Periodicraft.CreateOreBlock( "Magnesium Ore", 2.1F, 3.1F, 2, LightValue, LightOpacity, 0, EnumBlockRarity.UNCOMMON, Periodicraft.ItemMagnesiumDust.itemID, random.nextInt(3) + 3); public static BlockOre BlockBoronOre = Periodicraft.CreateOreBlock( "Boron Ore", 5.4F, 6.8F, 3, LightValue, LightOpacity, 0, EnumBlockRarity.SUBTLE); public static BlockOre BlockBerylliumOre = Periodicraft.CreateOreBlock( "Beryllium Ore", 6.4F, 5.3F, 3, LightValue, LightOpacity, 0, EnumBlockRarity.RARE); // Creative Tabs public static CreativeTabs tabBlocks = new CreativeTabs("tabBlocks") { public ItemStack getIconItemStack() { return new ItemStack(Item.pickaxeDiamond, 1, 0); } }; public static CreativeTabs tabMaterials = new CreativeTabs("tabMaterials") { public ItemStack getIconItemStack() { return new ItemStack(Item.pickaxeDiamond, 1, 0); } }; // The instance of your mod that Forge uses. @Instance("Periodicraft") public static Periodicraft instance; // Says where the client and server 'proxy' code is loaded. @SidedProxy(clientSide = "mods.periodicraft.client.ClientProxy", serverSide = "mods.periodicraft.CommonProxy") public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent event) { // Stub Method FMLLog.log( Level.INFO, "=======================================================Pre-Initalizing Periodicraft======================================================="); } @EventHandler public void load(FMLInitializationEvent event) { proxy.registerRenderers(); FMLLog.log( Level.INFO, "=======================================================Initalizing Periodicraft======================================================="); // CreativeTabs LanguageRegistry.instance().addStringLocalization("itemGroup.tabArmor", "en_US", "Armor"); LanguageRegistry.instance().addStringLocalization("itemGroup.tabTools", "en_US", "Tools"); LanguageRegistry.instance().addStringLocalization( "itemGroup.tabElements", "en_US", "Elements"); LanguageRegistry.instance().addStringLocalization("itemGroup.tabFood", "en_US", "Food"); LanguageRegistry.instance().addStringLocalization( "itemGroup.tabBlocks", "en_US", "Blocks"); LanguageRegistry.instance().addStringLocalization( "itemGroup.tabMaterials", "en_US", "Materials"); LanguageRegistry.instance().addStringLocalization( "itemGroup.tabWeapons", "en_US", "Weapons"); LanguageRegistry.instance().addStringLocalization("itemGroup.tabSpace", "en_US", "Space Travel"); WGen = new PeriodicraftWorldGenerator(); GameRegistry.registerWorldGenerator(WGen); GameRegistry.addShapelessRecipe(new ItemStack(Block.cobblestone), Block.sand, Block.gravel, Block.dirt); BlockCopperOre.addSmeltingRecipe(ItemCopperIngot, 2.1F); BlockPlatinumOre.addSmeltingRecipe(ItemPlatinumIngot, 5.1F); BlockTungstenOre.addSmeltingRecipe(ItemTungstenIngot, 2.1F); BlockOsmiumOre.addSmeltingRecipe(ItemOsmiumIngot, 6.3F); BlockTinOre.addSmeltingRecipe(ItemTinIngot, 2.1F); BlockSilverOre.addSmeltingRecipe(ItemSilverIngot, 2.1F); BlockNeodymiumOre.addSmeltingRecipe(ItemNeodymiumIngot, 4.1F); BlockNickelOre.addSmeltingRecipe(ItemNickelIngot, 2.1F); BlockBoronOre.addSmeltingRecipe(ItemBoronIngot, 2.1F); BlockBerylliumOre.addSmeltingRecipe(ItemBerylliumIngot, 2.1F); GameRegistry.addShapelessRecipe(new ItemStack( Periodicraft.ItemMagnesiumIngot), Periodicraft.ItemMagnesiumDust, Periodicraft.ItemMagnesiumDust, Periodicraft.ItemMagnesiumDust, Periodicraft.ItemMagnesiumDust); BlockBoronOre.setCreativeTab(Periodicraft.tabBlocks); } @EventHandler public void postInit(FMLPostInitializationEvent event) { // Stub Method FMLLog.log( Level.INFO, "=======================================================Starting Periodicraft======================================================="); } public static BlockOre CreateOreBlock(String UnlocalizedName, float Hardness, float Resistance, int HarvestLevel, float LightValue, int LightOpacity, int dimension, EnumBlockRarity rarity, int Drop, int count) { BlockOre block = Periodicraft.CreateOreBlock(UnlocalizedName, Hardness, Resistance, HarvestLevel, LightValue, LightOpacity, dimension, rarity); block.setDropAndCount(Drop, count); return block; } public static BlockOre CreateOreBlock(String UnlocalizedName, float Hardness, float Resistance, int HarvestLevel, float LightValue, int LightOpacity, int dimension, EnumBlockRarity rarity) { BlockOre block = new BlockOre(ID.id()); block.setUnlocalizedName(UnlocalizedName).setHardness(Hardness) .setResistance(Resistance) .setCreativeTab(Periodicraft.tabBlocks) .setLightValue(LightValue) .setTextureName("periodicraft:" + UnlocalizedName) .setLightOpacity(LightOpacity); MinecraftForge.setBlockHarvestLevel(block, "pickaxe", HarvestLevel); LanguageRegistry.addName(block, UnlocalizedName); GameRegistry.registerBlock(block, UnlocalizedName); block.addToSurfaceGen(rarity); block.setDropAndCount(block.blockID, 1); return block; } public static PeriodicraftBlock CreateSimpleBlock(Material par2Material, String UnlocalizedName) { } public static ItemIngot CreateItemIngot(String UnlocalizedName, CreativeTabs CreativeTab) { ItemIngot ingot = new ItemIngot(ID.id(), UnlocalizedName, CreativeTab); ingot.setTextureName("periodicraft:" + UnlocalizedName); return ingot; } }
package net.fortuna.ical4j.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.StringTokenizer; import net.fortuna.ical4j.util.CompatibilityHints; /** * Defines a list of days. * * @author Ben Fortuna */ public class WeekDayList extends ArrayList implements Serializable { private static final long serialVersionUID = 1243262497035300445L; /** * Default constructor. */ public WeekDayList() { } /** * Creates a new instance with the specified initial capacity. * @param initialCapacity the initial capacity of the list */ public WeekDayList(final int initialCapacity) { super(initialCapacity); } /** * Constructor. * @param aString a string representation of a day list */ public WeekDayList(final String aString) { boolean outlookCompatibility = CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY); for (StringTokenizer t = new StringTokenizer(aString, ","); t .hasMoreTokens();) { if (outlookCompatibility) { add(new WeekDay(t.nextToken().replaceAll(" ", ""))); } else { add(new WeekDay(t.nextToken())); } } } /** * @param weekDay a day to add to the list * @return */ public final boolean add(final WeekDay weekDay) { return add((Object) weekDay); } public final boolean add(final Object arg0) { if (!(arg0 instanceof WeekDay)) { throw new IllegalArgumentException("Argument not a " + WeekDay.class.getName()); } return super.add(arg0); } /** * @param weekDay a day to remove from the list * @return */ public final boolean remove(final WeekDay weekDay) { return remove((Object) weekDay); } /** * @see java.lang.Object#toString() */ public final String toString() { StringBuffer b = new StringBuffer(); for (Iterator i = iterator(); i.hasNext();) { b.append(i.next()); if (i.hasNext()) { b.append(','); } } return b.toString(); } }
package net.fortuna.ical4j.util; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.property.Uid; public class UidGenerator { private String pid; private InetAddress hostAddress; private static long lastMillis; /** * Default constructor. */ public UidGenerator(String pid) throws SocketException { this(findNonLoopbackAddress(), pid); } /** * @param hostAddress */ public UidGenerator(InetAddress hostAddress, String pid) { this.hostAddress = hostAddress; this.pid = pid; } /** * @return */ public Uid generateUid() { final StringBuffer b = new StringBuffer(); b.append(uniqueTimestamp()); b.append('-'); b.append(pid); if (hostAddress != null) { b.append('@'); b.append(hostAddress.getHostName()); } return new Uid(b.toString()); } /** * Generates a timestamp guaranteed to be unique for the current JVM instance. * @return a {@link DateTime} instance representing a unique timestamp */ private static DateTime uniqueTimestamp() { long currentMillis; synchronized (UidGenerator.class) { currentMillis = System.currentTimeMillis(); // guarantee uniqueness by ensuring timestamp is always greater // than the previous.. if (currentMillis < lastMillis) { currentMillis = lastMillis; } if (currentMillis - lastMillis < Dates.MILLIS_PER_SECOND) { currentMillis += Dates.MILLIS_PER_SECOND; } lastMillis = currentMillis; } final DateTime timestamp = new DateTime(currentMillis); timestamp.setUtc(true); return timestamp; } /** * Find a non loopback address for this machine on which to start the server. * @return a non loopback address * @throws SocketException if a socket error occurs */ private static InetAddress findNonLoopbackAddress() throws SocketException { final Enumeration enumInterfaceAddress = NetworkInterface.getNetworkInterfaces(); while (enumInterfaceAddress.hasMoreElements()) { final NetworkInterface netIf = (NetworkInterface) enumInterfaceAddress.nextElement(); // Iterate over inet address final Enumeration enumInetAdress = netIf.getInetAddresses(); while (enumInetAdress.hasMoreElements()) { final InetAddress address = (InetAddress) enumInetAdress.nextElement(); if (!address.isLoopbackAddress()) { return address; } } } return null; } }
package org.jfree.chart.block; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.StandardEntityCollection; import org.jfree.chart.util.ParamChecks; import org.jfree.ui.Size2D; import org.jfree.util.PublicCloneable; /** * A container for a collection of {@link Block} objects. The container uses * an {@link Arrangement} object to handle the position of each block. */ public class BlockContainer extends AbstractBlock implements Block, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 8199508075695195293L; /** The blocks within the container. */ private List blocks; /** The object responsible for laying out the blocks. */ private Arrangement arrangement; /** * Creates a new instance with default settings. */ public BlockContainer() { this(new BorderArrangement()); } /** * Creates a new instance with the specified arrangement. * * @param arrangement the arrangement manager (<code>null</code> not * permitted). */ public BlockContainer(Arrangement arrangement) { ParamChecks.nullNotPermitted(arrangement, "arrangement"); this.arrangement = arrangement; this.blocks = new ArrayList(); } /** * Returns the arrangement (layout) manager for the container. * * @return The arrangement manager (never <code>null</code>). */ public Arrangement getArrangement() { return this.arrangement; } /** * Sets the arrangement (layout) manager. * * @param arrangement the arrangement (<code>null</code> not permitted). */ public void setArrangement(Arrangement arrangement) { ParamChecks.nullNotPermitted(arrangement, "arrangement"); this.arrangement = arrangement; } /** * Returns <code>true</code> if there are no blocks in the container, and * <code>false</code> otherwise. * * @return A boolean. */ public boolean isEmpty() { return this.blocks.isEmpty(); } /** * Returns an unmodifiable list of the {@link Block} objects managed by * this arrangement. * * @return A list of blocks. */ public List getBlocks() { return Collections.unmodifiableList(this.blocks); } /** * Adds a block to the container. * * @param block the block (<code>null</code> permitted). */ public void add(Block block) { add(block, null); } /** * Adds a block to the container. * * @param block the block (<code>null</code> permitted). * @param key the key (<code>null</code> permitted). */ public void add(Block block, Object key) { this.blocks.add(block); this.arrangement.add(block, key); } /** * Clears all the blocks from the container. */ public void clear() { this.blocks.clear(); this.arrangement.clear(); } /** * Arranges the contents of the block, within the given constraints, and * returns the block size. * * @param g2 the graphics device. * @param constraint the constraint (<code>null</code> not permitted). * * @return The block size (in Java2D units, never <code>null</code>). */ public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) { return this.arrangement.arrange(this, g2, constraint); } /** * Draws the container and all the blocks within it. * * @param g2 the graphics device. * @param area the area. */ public void draw(Graphics2D g2, Rectangle2D area) { draw(g2, area, null); } /** * Draws the block within the specified area. * * @param g2 the graphics device. * @param area the area. * @param params passed on to blocks within the container * (<code>null</code> permitted). * * @return An instance of {@link EntityBlockResult}, or <code>null</code>. */ public Object draw(Graphics2D g2, Rectangle2D area, Object params) { // check if we need to collect chart entities from the container EntityBlockParams ebp; StandardEntityCollection sec = null; if (params instanceof EntityBlockParams) { ebp = (EntityBlockParams) params; if (ebp.getGenerateEntities()) { sec = new StandardEntityCollection(); } } Rectangle2D contentArea = (Rectangle2D) area.clone(); contentArea = trimMargin(contentArea); drawBorder(g2, contentArea); contentArea = trimBorder(contentArea); contentArea = trimPadding(contentArea); Iterator iterator = this.blocks.iterator(); while (iterator.hasNext()) { Block block = (Block) iterator.next(); Rectangle2D bounds = block.getBounds(); Rectangle2D drawArea = new Rectangle2D.Double(bounds.getX() + area.getX(), bounds.getY() + area.getY(), bounds.getWidth(), bounds.getHeight()); Object r = block.draw(g2, drawArea, params); if (sec != null) { if (r instanceof EntityBlockResult) { EntityBlockResult ebr = (EntityBlockResult) r; EntityCollection ec = ebr.getEntityCollection(); sec.addAll(ec); } } } BlockResult result = null; if (sec != null) { result = new BlockResult(); result.setEntityCollection(sec); } return result; } /** * Tests this container for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof BlockContainer)) { return false; } if (!super.equals(obj)) { return false; } BlockContainer that = (BlockContainer) obj; if (!this.arrangement.equals(that.arrangement)) { return false; } if (!this.blocks.equals(that.blocks)) { return false; } return true; } /** * Returns a clone of the container. * * @return A clone. * * @throws CloneNotSupportedException if there is a problem cloning. */ public Object clone() throws CloneNotSupportedException { BlockContainer clone = (BlockContainer) super.clone(); // TODO : complete this return clone; } }
package com.doos.update; public class AppVersion { private String version; private String downloadUrl; private int size; public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version.replace("v", ""); } public int getSize() { return size; } public void setSize(int size) { this.size = size; } @Override public String toString() { return "AppVersion: {" + version + "\ndownload:[" + downloadUrl + "], size: " + size / 1024 + "kb}"; } }
package com.braintreepayments.cardform.view; import android.text.Editable; import com.braintreepayments.cardform.R; import com.braintreepayments.cardform.test.TestActivity; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.braintreepayments.cardform.test.Assertions.assertBitmapsEqual; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; @RunWith(RobolectricTestRunner.class) public class CardEditTextTest { private CardEditText mView; @Before public void setup() { mView = (CardEditText) Robolectric.setupActivity(TestActivity.class) .findViewById(R.id.bt_card_form_card_number); } @Test public void testVisa() { helper("4", "111 1111 1111 1111", R.drawable.bt_ic_visa, 4, 8, 12); } @Test public void testMasterCard() { helper("55", "55 5555 5555 4444", R.drawable.bt_ic_mastercard, 4, 8, 12); } @Test public void testDiscover() { helper("6011", "1111 1111 1117", R.drawable.bt_ic_discover, 4, 8, 12); } @Test public void testAmex() { helper("37", "82 822463 10005", R.drawable.bt_ic_amex, 4, 10); } @Test public void testJcb() { helper("35", "30 1113 3330 0000", R.drawable.bt_ic_jcb, 4, 8, 12); } @Test public void testDiners() { helper("3000", "0000 0000 04", R.drawable.bt_ic_diners_club, 4, 8, 12); } @Test public void testMaestro() { helper("5018", "0000 0000 0000122", R.drawable.bt_ic_maestro, 4, 8, 12); } @Test public void testUnionPay() { helper("62", "40 8888 8888 8885127", R.drawable.bt_ic_unionpay, 4, 8, 12); } @Test public void testUnknown() { helper("1", "111 1111 1111 1111111", R.drawable.bt_card_highlighted, 4, 8, 12); } @Test public void showsCardTypeIconsByDefault() { assertCardIconIs(R.drawable.bt_card_highlighted); } @Test public void doesNotShowCardTypeIconsWhenDisabled() { mView.setDisplayCardTypeIcon(false); assertNull(mView.getCompoundDrawables()[0]); assertNull(mView.getCompoundDrawables()[1]); assertNull(mView.getCompoundDrawables()[2]); assertNull(mView.getCompoundDrawables()[3]); type("4"); assertNull(mView.getCompoundDrawables()[0]); assertNull(mView.getCompoundDrawables()[1]); assertNull(mView.getCompoundDrawables()[2]); assertNull(mView.getCompoundDrawables()[3]); } @Test public void getErrorMessage_returnsErrorMessageWhenEmpty() { assertEquals(RuntimeEnvironment.application.getString(R.string.bt_card_number_required), mView.getErrorMessage()); } @Test public void getErrorMessage_returnsErrorMessageWhenNotEmpty() { type("4"); assertEquals(RuntimeEnvironment.application.getString(R.string.bt_card_number_invalid), mView.getErrorMessage()); } private void helper(String start, String end, int drawable, int... spans) { assertCardIconIs(R.drawable.bt_card_highlighted); type(start).assertCardIconIs(drawable); type(end).assertSpansAt(spans); assertCharacterMaxLengthHit(); } private void assertCharacterMaxLengthHit() { Editable text = mView.getText(); int maxLength = text.length(); type("1111"); assertEquals("Able to write more characters than max length", maxLength, text.length()); } private void assertSpansAt(int... indices) { Editable text = mView.getText(); List<SpaceSpan> allSpans = Arrays.asList(text.getSpans(0, text.length(), SpaceSpan.class)); List<SpaceSpan> foundSpans = new ArrayList<SpaceSpan>(); for (int i : indices) { SpaceSpan[] span = text.getSpans(i - 1, i, SpaceSpan.class); assertEquals(1, span.length); foundSpans.add(span[0]); } assertEquals(allSpans, foundSpans); } private void assertCardIconIs(int resId) { assertBitmapsEqual(RuntimeEnvironment.application.getResources().getDrawable(resId), mView.getCompoundDrawables()[2]); } private CardEditTextTest type(String text) { Editable editable = mView.getText(); for (char c : text.toCharArray()) { if (c != ' ') { editable.append(c); } } return this; } }
package Model; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * * @author Ruben */ public class Opleiding implements Entiteit{ private int ID; private String naam; private int contact_id; public Opleiding() {}; public Opleiding(int ID, int contact_id, String naam) { this.ID = ID; this.naam = naam; this.contact_id = contact_id; } public int getOpleidingID() { return ID; } public String getOpleidingNaam() { return naam; } public String InsertOpleiding() { return "INSERT INTO Opleiding VALUES('" + this.getOpleidingID() + "', '" + this.getOpleidingNaam() + "');"; } @Override public String getInsertSQL() { return "INSERT INTO Opleiding (naam) VALUES (?);"; } @Override public PreparedStatement getInsertStatement(PreparedStatement stmt, Connection con) throws SQLException { stmt.setString(1, this.naam); return stmt; } @Override public String getUpdateSQL() { return "UPDATE Opleiding SET naam = ?, contact_id = ? WHERE opleiding_id = ?"; } @Override public PreparedStatement getUpdateStatement(PreparedStatement stmt, Connection con) throws SQLException { stmt.setString(1, this.naam); stmt.setInt(2, this.contact_id); stmt.setInt(3, this.ID); return stmt; } @Override public String getDeleteSQL() { return "DELETE from Opleiding WHERE opleiding_id = ?"; } @Override public PreparedStatement getDeleteStatement(PreparedStatement stmt, Connection con, int keyValue) throws SQLException { stmt.setInt(1, keyValue); return stmt; } @Override public String getSelectSQL(String columnName) { String SQL = ""; if (columnName.isEmpty()) { SQL = "SELECT * FROM Opleiding"; } else { SQL = "SELECT * FROM Opleiding WHERE " + columnName + " LIKE ?"; } return SQL; } @Override public PreparedStatement getSelectStatement(PreparedStatement stmt, String columnInput) throws SQLException { stmt.setString(1, "%" + columnInput + "%"); return stmt; } }
package de.uka.ipd.sdq.beagle.core.testutil; import static de.uka.ipd.sdq.beagle.core.testutil.ExceptionThrownMatcher.throwsException; import org.apache.commons.lang3.ArrayUtils; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.function.Consumer; public final class NullHandlingMatchers { /** * Enclosing instance. */ private static final NullHandlingMatchers THIZ = new NullHandlingMatchers(); /** * A matcher matching if a method throws a NullPointerException. */ private static final Matcher<ThrowingMethod> THROWS_NPE = throwsException(NullPointerException.class); private static final Matcher<ThrowingMethod> THROWS_IAE = throwsException(IllegalArgumentException.class); /** * This is a utility class and not meant to be instantiated. */ private NullHandlingMatchers() { } public static <CONSUMED_TYPE> Matcher<Consumer<CONSUMED_TYPE[]>> notAcceptingNull( final CONSUMED_TYPE[] testValues) { final NotAcceptingNullInListMatcher<CONSUMED_TYPE> listMatcher = THIZ.new NotAcceptingNullInListMatcher<>(Arrays.asList(testValues)); // hack to get an empty array of CONSUMED_TYPE without SurpressWarnings final CONSUMED_TYPE[] copyInstance = ArrayUtils.clone(testValues); ArrayUtils.removeElements(copyInstance, copyInstance); return new TypeSafeDiagnosingMatcher<Consumer<CONSUMED_TYPE[]>>() { @Override public void describeTo(final Description description) { listMatcher.describeTo(description); } @Override protected boolean matchesSafely(final Consumer<CONSUMED_TYPE[]> item, final Description mismatchDescription) { return listMatcher.matchesSafely((list) -> item.accept(list.toArray(copyInstance)), mismatchDescription); } }; } public static <CONSUMED_TYPE> Matcher<Consumer<Collection<CONSUMED_TYPE>>> notAcceptingNull( final Collection<CONSUMED_TYPE> testValues) { return THIZ.new NotAcceptingNullInListMatcher<CONSUMED_TYPE>(new ArrayList<>(testValues)); } private static <T> List<T> withNull(final List<T> list, final int index) { final List<T> result = new ArrayList<>(list); result.add(index, null); return result; } private static <T> List<T> withNull(final List<T> list) { final List<T> result = new ArrayList<>(list); result.add(null); return result; } private final class NotAcceptingNullInListMatcher<CONSUMED_TYPE> extends TypeSafeDiagnosingMatcher<Consumer<Collection<CONSUMED_TYPE>>> { /** * Description of what was expected. */ private String expectedDescription; /** * A list of values that are accepted by the examined lambda. */ private final List<CONSUMED_TYPE> testValues; /** * Creates this matcher with values that can safely be passed to the examined * lambda. * * * @param testValues A list of valid values that can be passed to the examined * lambda without it throwing an exception. */ private NotAcceptingNullInListMatcher(final List<CONSUMED_TYPE> testValues) { this.testValues = testValues; } @Override public void describeTo(final Description description) { description.appendText(this.expectedDescription); } @Override protected boolean matchesSafely(final Consumer<Collection<CONSUMED_TYPE>> consumer, final Description mismatchDescription) { ThrowingMethod nullApplied; // feed null this.expectedDescription = "a method throwing a NullPointerException if a passed collection is null"; nullApplied = () -> consumer.accept(null); if (!THROWS_NPE.matches(nullApplied)) { THROWS_NPE.describeMismatch(nullApplied, mismatchDescription); mismatchDescription.appendText(" when passing null as argument"); return false; } // insert null at start, middle and end final List<List<CONSUMED_TYPE>> inputsWithNull = Arrays.asList(withNull(this.testValues, 0), withNull(this.testValues, this.testValues.size() / 2), withNull(this.testValues)); this.expectedDescription = "a method throwing an IllegalArgumentException if a passed collection contains null"; // feed the lists containing null for (final List<CONSUMED_TYPE> testInputsWithNull : inputsWithNull) { nullApplied = () -> consumer.accept(testInputsWithNull); if (!THROWS_IAE.matches(nullApplied)) { THROWS_IAE.describeMismatch(nullApplied, mismatchDescription); mismatchDescription.appendText(" when passing null in the argument"); return false; } } return true; } } }
import base.Count; import base.Tempo; import base.TimeSignature; import form.Note; import form.Part; import form.Passage; import io.Writer; import javax.sound.midi.*; import java.io.IOException; import java.util.Iterator; import java.util.TreeMap; /** * MidiWriter is a class which does exactly what you'd expect. * form.Note that each MidiWriter composes exactly *one* midi Sequence. * This means that the MidiTools class instantiates one for every * single form.Passage to be written. This class could potentially be * absorbed into MidiTools, but is separated for the code cleanness. */ class MidiWriter { /* The "resolution," i.e. the number of ticks per measure. */ private static int resolution = 24; /* The passage that we're reading from. */ private Passage passage = null; /* The sequence that we're writing to. */ private Sequence sequence = null; /* A series of floats mapped to Longs representing different measures' start times in ticks. */ private TreeMap<Float,Long> timePoints; // Writes the information contained in a passage down to a sequence public Sequence run(Passage passage) { try { // Initialize our variables this.passage = passage; this.sequence = new Sequence(javax.sound.midi.Sequence.PPQ,resolution); this.timePoints = new TreeMap<>(); // Constantly reused variables MetaMessage metaMessage; MidiEvent event; // Create and initialize the control track (for tempi and time signatures) Track controlTrack = sequence.createTrack(); initTrack(controlTrack); // Set the default time signature... should be removed metaMessage = new MetaMessage(); byte[] bt = {0x04, 0x04, (byte)resolution, (byte)8}; // Should work... should. metaMessage.setMessage(0x58 ,bt, 3); event = new MidiEvent(metaMessage,(long)resolution); controlTrack.add(event); writeTimeSignatures(controlTrack); writeTempoChanges(controlTrack); System.out.println("MIDI READER:\tAdded a new track (from a Part)"); // For every part in the passage, create a track, and fill it with all the notes in that track for(Part line : passage) { Track track = sequence.createTrack(); initTrack(track); for(Note note : line) { addNote(note, track); } //endTrack(track); } } catch (InvalidMidiDataException e) { e.printStackTrace(); } return sequence; } private void init(Track track) throws InvalidMidiDataException { } private void initTrack(Track track) throws InvalidMidiDataException { // Set the instrument to piano ShortMessage instChange = new ShortMessage(); instChange.setMessage(ShortMessage.PROGRAM_CHANGE, 0, 0, 0); track.add(new MidiEvent(instChange, 0)); } private void addNote(Note note, Track track) throws InvalidMidiDataException { //System.out.println("Added note"); ShortMessage on = new ShortMessage(); ShortMessage off = new ShortMessage(); on.setMessage(ShortMessage.NOTE_ON, 0, note.getPitch().getValue(), 60); off.setMessage(ShortMessage.NOTE_OFF, 0, note.getPitch().getValue(), 0); track.add(new MidiEvent(on, interpolate(note.getStart().toFloat()))); track.add(new MidiEvent(off, interpolate(note.getEnd().toFloat()))); } private void endTrack(Track track) throws InvalidMidiDataException { System.out.println("Ending track"); MetaMessage mt = new MetaMessage(); byte[] bet = {}; // empty array mt.setMessage(0x2F,bet,0); MidiEvent me = new MidiEvent(mt, (long)10000000); // TEMPORARY track.add(me); } private long interpolate(float time) { // Get the time points before and after this tick float earlierTime = timePoints.floorKey(time); float laterTime = timePoints.ceilingKey(time); // If we're right on the time point we want if(Float.compare(earlierTime,laterTime) == 0) { System.out.println("Interpolated "+time+" to exactly "+(timePoints.get(earlierTime))); return timePoints.get(earlierTime); } // If we have to interpolate else { // Figure out what fractions-of-a-measure those time points // represent, and lerp between them to figure out where "tick" is long earlierTimePoint = timePoints.get(earlierTime); long laterTimePoint = timePoints.get(laterTime); float relativePosition = ((time - earlierTime) / (laterTime - earlierTime)); System.out.println("Interpolated "+time+" to "+(relativePosition * (laterTimePoint - earlierTimePoint )) + earlierTimePoint); return (long)(relativePosition * (laterTimePoint - earlierTimePoint )) + earlierTimePoint; } } private void writeTimeSignatures(Track track) throws InvalidMidiDataException { // Put a starting point in timePoints.put(0f,(long)0); // The measure that the time signature last changed int lastTimeSigChange = 0; // The size of those measures in ticks long lastMeasureSize = 0; // The iterator over all the passage's time signatures Iterator<Integer> timeSigItr = passage.timeSignatureIterator(); // Add all of the timeSignature changes while(timeSigItr.hasNext()) { int curMeasure = timeSigItr.next(); int measuresPassed = curMeasure - lastTimeSigChange; TimeSignature timeSignature = passage.getTimeSignatureAt(new Count(curMeasure)); long newTimePoint = timePoints.lastEntry().getValue() + measuresPassed * lastMeasureSize; timePoints.put((float)curMeasure,newTimePoint); System.out.println(curMeasure + " " + newTimePoint + " " + timeSignature); int cc = 0; switch(timeSignature.getDenominator()) { case 1: cc = 0; break; case 2: cc = 1; break; case 4: cc = 2; break; case 8: cc = 3; break; case 16: cc = 4; break; } byte[] bytes = {(byte)timeSignature.getNumerator(), (byte)cc, (byte)resolution, (byte)8}; // Create a time signature change event MetaMessage metaMessage = new MetaMessage(); metaMessage.setMessage(0x58 ,bytes, 3); MidiEvent event = new MidiEvent(metaMessage,newTimePoint); track.add(event); lastMeasureSize = resolution*timeSignature.getNumerator()/timeSignature.getDenominator(); lastTimeSigChange = curMeasure; } // Create a time point waaaaaaay after the end of the piece to ensure our interpolator can work timePoints.put((float)lastTimeSigChange+10000,timePoints.lastEntry().getValue()+lastMeasureSize*10000); } private void writeTempoChanges(Track track) throws InvalidMidiDataException { // Add all of the tempo changes Iterator<Count> tempoItr = passage.tempoChangeIterator(); while(tempoItr.hasNext()) { Count time = tempoItr.next(); Tempo tempo = passage.getTempoAt(time); int ppqn = 60000000 / tempo.getBPM(); // Set tempo MetaMessage metaMessage = new MetaMessage(); byte[] bytes = new byte[]{(byte) (ppqn >> 16), (byte) (ppqn >> 8), (byte) (ppqn)}; // Should work... should. metaMessage.setMessage(0x51, bytes, 3); MidiEvent event = new MidiEvent(metaMessage,interpolate(time.toFloat())); track.add(event); } } public static void main(String argv[]) throws IOException, InvalidMidiDataException, MidiUnavailableException { Sequence sequence = MidiTools.download("https: Passage passage = MidiTools.parse(sequence); Writer.write(passage,"input"); Sequence out = MidiTools.write(passage); Passage outputPassage = MidiTools.parse(out); Writer.write(outputPassage,"output"); MidiTools.play(out); } }
package Pkutils; public class Console { private static int indentionLevel; /** * Prints out Object in the console. * * @param object The Object that's to be printed */ public static void print(Object object) { System.out.print(object); } /** * Prints out Object in a new line in the console. * * @param object The Object that's to be printed */ public static void println(Object object) { System.out.println(object); } }
package net.sf.cglib; import java.io.ObjectStreamException; import java.lang.reflect.*; import java.util.*; /*package*/ class EnhancerGenerator extends CodeGenerator { private static final String INTERCEPTOR_FIELD = "CGLIB$INTERCEPTOR"; private static final String DELEGATE_FIELD = "CGLIB$DELEGATE"; private static final String CONSTRUCTOR_PROXY_MAP = "CGLIB$CONSTRUCTOR_PROXY_MAP"; private static final int PRIVATE_FINAL_STATIC = Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC; private static final Method NORMAL_NEW_INSTANCE = ReflectUtils.findMethod("Factory.newInstance(MethodInterceptor)"); private static final Method DELEGATE_NEW_INSTANCE = ReflectUtils.findMethod("Factory.newInstance(MethodInterceptor, Object)"); private static final Method AROUND_ADVICE = ReflectUtils.findMethod("MethodInterceptor.aroundAdvice(Object, Method, Object[], MethodProxy)"); private static final Method MAKE_PROXY = ReflectUtils.findMethod("MethodProxy.create(Method)"); private static final Method MAKE_CONSTRUCTOR_PROXY = ReflectUtils.findMethod("ConstructorProxy.create(Constructor)"); private static final Method INTERNAL_WRITE_REPLACE = ReflectUtils.findMethod("Enhancer$InternalReplace.writeReplace(Object)"); private static final Method NEW_CLASS_KEY = ReflectUtils.findMethod("ConstructorProxy.newClassKey(Class[])"); private static final Method PROXY_NEW_INSTANCE = ReflectUtils.findMethod("ConstructorProxy.newInstance(Object[])"); private static final Method MULTIARG_NEW_INSTANCE = ReflectUtils.findMethod("Factory.newInstance(Class[], Object[], MethodInterceptor)"); private static final Method SET_DELEGATE = ReflectUtils.findMethod("Factory.setDelegate(Object)"); private static final Method GET_DELEGATE = ReflectUtils.findMethod("Factory.getDelegate()"); private static final Method GET_INTERCEPTOR = ReflectUtils.findMethod("Factory.getInterceptor()"); private static final Method SET_INTERCEPTOR = ReflectUtils.findMethod("Factory.setInterceptor(MethodInterceptor)"); private Class[] interfaces; private Method wreplace; private boolean delegating; private MethodFilter filter; private Constructor cstruct; private List constructorList; /* package */ EnhancerGenerator( String className, Class clazz, Class[] interfaces, ClassLoader loader, Method wreplace, boolean delegating, MethodFilter filter) { super(className, clazz, loader); this.interfaces = interfaces; this.wreplace = wreplace; this.delegating = delegating; this.filter = filter; if (wreplace != null && (!Modifier.isStatic(wreplace.getModifiers()) || !Modifier.isPublic(wreplace.getModifiers()) || wreplace.getReturnType() != Object.class || wreplace.getParameterTypes().length != 1 || wreplace.getParameterTypes()[0] != Object.class)) { throw new IllegalArgumentException(wreplace.toString()); } try { VisibilityFilter vis = new VisibilityFilter(clazz); try { cstruct = clazz.getDeclaredConstructor(Constants.TYPES_EMPTY); if (!vis.accept(cstruct)) { cstruct = null; } } catch (NoSuchMethodException ignore) { } constructorList = new ArrayList(Arrays.asList(clazz.getDeclaredConstructors())); filterMembers(constructorList, vis); if (constructorList.size() == 0) { throw new IllegalArgumentException("No visible constructors in " + clazz); } if (wreplace != null) { loader.loadClass(wreplace.getDeclaringClass().getName()); } loader.loadClass(clazz.getName()); if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { if (!interfaces[i].isInterface()) { throw new IllegalArgumentException(interfaces[i] + " is not an interface"); } loader.loadClass(interfaces[i].getName()); } } } catch (ClassNotFoundException e) { throw new CodeGenerationException(e); } } protected void generate() throws NoSuchMethodException { if (wreplace == null) { wreplace = INTERNAL_WRITE_REPLACE; } declare_interface(Factory.class); declare_field(Modifier.PRIVATE, MethodInterceptor.class, INTERCEPTOR_FIELD); if (delegating) { declare_field(Modifier.PRIVATE, getSuperclass(), DELEGATE_FIELD); } generateConstructors(); generateFactory(); // Order is very important: must add superclass, then // its superclass chain, then each interface and // its superinterfaces. List methods = new ArrayList(); addDeclaredMethods(methods, getSuperclass()); Set forcePublic; if (interfaces != null) { declare_interfaces(interfaces); List interfaceMethods = new ArrayList(); for (int i = 0; i < interfaces.length; i++) { addDeclaredMethods(interfaceMethods, interfaces[i]); } forcePublic = MethodWrapper.createSet(interfaceMethods); methods.addAll(interfaceMethods); } else { forcePublic = Collections.EMPTY_SET; } filterMembers(methods, new VisibilityFilter(getSuperclass())); if (delegating) { filterMembers(methods, new ModifierFilter(Modifier.PROTECTED, 0)); } filterMembers(methods, new DuplicatesFilter()); filterMembers(methods, new ModifierFilter(Modifier.FINAL, 0)); if (filter != null) { filterMembers(methods, filter); } boolean declaresWriteReplace = false; for (int i = 0; i < methods.size(); i++) { Method method = (Method)methods.get(i); if (method.getName().equals("writeReplace") && method.getParameterTypes().length == 0) { declaresWriteReplace = true; } String fieldName = getFieldName(i); String accessName = getAccessName(method, i); declare_field(PRIVATE_FINAL_STATIC, Method.class, fieldName); declare_field(PRIVATE_FINAL_STATIC, MethodProxy.class, accessName); generateAccessMethod(method, accessName); generateAroundMethod(method, fieldName, accessName, forcePublic.contains(MethodWrapper.create(method))); } generateClInit(methods); if (!declaresWriteReplace) { generateWriteReplace(); } } private void filterMembers(List members, MethodFilter filter) { Iterator it = members.iterator(); while (it.hasNext()) { if (!filter.accept((Member)it.next())) { it.remove(); } } } private String getFieldName(int index) { return "METHOD_" + index; } private String getAccessName(Method method, int index) { return "CGLIB$ACCESS_" + index + "_" + method.getName(); } private void generateConstructors() throws NoSuchMethodException { for (Iterator i = constructorList.iterator(); i.hasNext();) { Constructor constructor = (Constructor)i.next(); begin_constructor(constructor); load_this(); load_args(); super_invoke(constructor); return_value(); end_method(); } } private void generateFactory() { begin_method(GET_INTERCEPTOR); load_this(); getfield(INTERCEPTOR_FIELD); return_value(); end_method(); begin_method(SET_INTERCEPTOR); load_this(); load_arg(0); putfield(INTERCEPTOR_FIELD); return_value(); end_method(); if (delegating) { throwWrongType(NORMAL_NEW_INSTANCE); throwWrongType(MULTIARG_NEW_INSTANCE); generateFactoryHelper(DELEGATE_NEW_INSTANCE); generateSetDelegate(); } else { throwWrongType(DELEGATE_NEW_INSTANCE); throwWrongType(SET_DELEGATE); generateFactoryHelper(NORMAL_NEW_INSTANCE); generateMultiArgFactory(); } } private void generateFactoryHelper(Method method) { begin_method(method); new_instance_this(); dup(); invoke_constructor_this(); dup(); load_arg(0); putfield(INTERCEPTOR_FIELD); if (method == DELEGATE_NEW_INSTANCE) { dup(); load_arg(1); invoke(SET_DELEGATE); } return_value(); end_method(); } private void generateSetDelegate() { begin_method(SET_DELEGATE); load_this(); load_arg(0); checkcast(getSuperclass()); putfield(DELEGATE_FIELD); return_value(); end_method(); } private void generateMultiArgFactory() { declare_field(PRIVATE_FINAL_STATIC, Map.class, CONSTRUCTOR_PROXY_MAP); begin_method(MULTIARG_NEW_INSTANCE); getfield(CONSTRUCTOR_PROXY_MAP); load_arg(0);// Class[] types invoke(NEW_CLASS_KEY);//key invoke(MethodConstants.MAP_GET);// PROXY_MAP.get( key(types) ) checkcast(ConstructorProxy.class); dup(); ifnull("fail"); load_arg(1); invoke(PROXY_NEW_INSTANCE); checkcast_this(); dup(); load_arg(2); putfield(INTERCEPTOR_FIELD); return_value(); nop("fail"); throw_exception(IllegalArgumentException.class, "Constructor not found "); end_method(); } private void throwWrongType(Method method) { begin_method(method); throw_exception(UnsupportedOperationException.class, "Using a delegating enhanced class as non-delegating, or the reverse"); return_value(); end_method(); } private void generateWriteReplace() { begin_method(Modifier.PRIVATE, Object.class, "writeReplace", Constants.TYPES_EMPTY, new Class[]{ ObjectStreamException.class }); load_this(); invoke(wreplace); return_value(); end_method(); } private static void addDeclaredMethods(List methodList, Class clazz) { methodList.addAll(java.util.Arrays.asList(clazz.getDeclaredMethods())); if (clazz.isInterface()) { Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { addDeclaredMethods(methodList, interfaces[i]); } } else { Class superclass = clazz.getSuperclass(); if (superclass != null) { addDeclaredMethods(methodList, superclass); } } } private void generateAccessMethod(Method method, String accessName) { begin_method(Modifier.FINAL, method.getReturnType(), accessName, method.getParameterTypes(), method.getExceptionTypes()); if (delegating) { load_this(); getfield(DELEGATE_FIELD); load_args(); invoke(method); } else if (Modifier.isAbstract(method.getModifiers())) { throw_exception(AbstractMethodError.class, method.toString() + " is abstract" ); } else { load_this(); load_args(); super_invoke(method); } return_value(); end_method(); } private void generateAroundMethod(Method method, String fieldName, String accessName, boolean forcePublic) { int modifiers = getDefaultModifiers(method); if (forcePublic) { modifiers = (modifiers & ~Modifier.PROTECTED) | Modifier.PUBLIC; } begin_method(method, modifiers); Object handler = begin_handler(); load_this(); getfield(INTERCEPTOR_FIELD); dup(); ifnull("null_interceptor"); load_this(); getfield(fieldName); create_arg_array(); getfield(accessName); invoke(AROUND_ADVICE); if (isProxy()) { unbox(method.getReturnType()); } else { unbox_or_zero(method.getReturnType()); } return_value(); nop("null_interceptor"); load_this(); load_args(); super_invoke(method); return_value(); end_handler(); generateHandleUndeclared(method, handler); end_method(); } private boolean isProxy() { Class clazz = getSuperclass(); while (clazz != null) { if (clazz.getName().equals("net.sf.cglib.Proxy")) { return true; } clazz = clazz.getSuperclass(); } return false; } private void generateHandleUndeclared(Method method, Object handler) { /* generates: } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (<DeclaredException> e) { throw e; } catch (Throwable e) { throw new UndeclaredThrowableException(e); } */ Class[] exceptionTypes = method.getExceptionTypes(); Set exceptionSet = new HashSet(Arrays.asList(exceptionTypes)); if (!(exceptionSet.contains(Exception.class) || exceptionSet.contains(Throwable.class))) { if (!exceptionSet.contains(RuntimeException.class)) { handle_exception(handler, RuntimeException.class); athrow(); } if (!exceptionSet.contains(Error.class)) { handle_exception(handler, Error.class); athrow(); } for (int i = 0; i < exceptionTypes.length; i++) { handle_exception(handler, exceptionTypes[i]); athrow(); } // e -> eo -> oeo -> ooe -> o handle_exception(handler, Throwable.class); new_instance(UndeclaredThrowableException.class); dup_x1(); swap(); invoke_constructor(UndeclaredThrowableException.class, Constants.TYPES_THROWABLE); athrow(); } } private void generateClInit(List methodList) throws NoSuchMethodException { /* generates: static { Class [] args; Class cls = findClass("java.lang.Object"); args = new Class[0]; METHOD_1 = cls.getDeclaredMethod("toString", args); Class thisClass = findClass("NameOfThisClass"); Method proxied = thisClass.getDeclaredMethod("CGLIB$ACCESS_O", args); CGLIB$ACCESS_0 = MethodProxy.create(proxied); } */ begin_static(); Object args = make_local(); for (int i = 0, size = methodList.size(); i < size; i++) { Method method = (Method)methodList.get(i); String fieldName = getFieldName(i); load_class(method.getDeclaringClass()); push(method.getName()); push_object(method.getParameterTypes()); dup(); store_local(args); invoke(MethodConstants.GET_DECLARED_METHOD); putfield(fieldName); String accessName = getAccessName(method, i); load_class_this(); push(accessName); load_local(args); invoke(MethodConstants.GET_DECLARED_METHOD); invoke(MAKE_PROXY); putfield(accessName); } if (!delegating) { new_instance(HashMap.class); dup(); dup(); invoke_constructor(HashMap.class); putfield(CONSTRUCTOR_PROXY_MAP); Object map = make_local(); store_local(map); for (int i = 0, size = constructorList.size(); i < size; i++) { Constructor constructor = (Constructor)constructorList.get(i); Class[] types = constructor.getParameterTypes(); load_local(map); push(types); invoke(NEW_CLASS_KEY);//key load_class_this(); push(types); invoke(MethodConstants.GET_DECLARED_CONSTRUCTOR); invoke(MAKE_CONSTRUCTOR_PROXY);//value invoke(MethodConstants.MAP_PUT);// put( key( agrgTypes[] ), proxy ) } } return_value(); end_method(); } }
package org.waterforpeople.mapping.dataexport.service; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.TreeMap; import java.util.zip.GZIPInputStream; import com.gallatinsystems.common.util.MD5Util; import com.gallatinsystems.framework.rest.RestRequest; import com.gallatinsystems.survey.domain.SurveyGroup.ProjectType; import com.fasterxml.jackson.core.type.TypeReference; import org.akvo.flow.util.FlowJsonObjectReader; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.waterforpeople.mapping.app.gwt.client.devicefiles.DeviceFilesDto; import org.waterforpeople.mapping.app.gwt.client.survey.OptionContainerDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDependencyDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto; import org.waterforpeople.mapping.app.gwt.client.survey.QuestionOptionDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto; import org.waterforpeople.mapping.app.gwt.client.survey.TranslationDto; import org.waterforpeople.mapping.app.gwt.client.surveyinstance.SurveyInstanceDto; import org.waterforpeople.mapping.app.web.dto.DataBackoutRequest; import org.waterforpeople.mapping.app.web.dto.InstanceDataDto; import org.waterforpeople.mapping.app.web.dto.SurveyRestRequest; import static org.waterforpeople.mapping.app.web.dto.SurveyInstanceRequest.*; /** * client code for calling the apis for data processing on the server * * @author Christopher Fagiani */ public class BulkDataServiceClient { private static final Logger log = Logger.getLogger(BulkDataServiceClient.class); private static final String DATA_SERVLET_PATH = "/databackout"; public static final String RESPONSE_KEY = "dtoList"; private static final String SURVEY_SERVLET_PATH = "/surveyrestapi"; private static final String INSTANCE_DATA_SERVLET_PATH = "/instancedata"; private static final String DEVICE_FILES_SERVLET_PATH = "/devicefilesrestapi?action="; /** * lists all responses from the server for a surveyInstance submission as a map of values keyed * on questionId and iteration * * @param instanceId * @param serverBase * @return * @throws Exception */ public static Map<Long, Map<Long, String>> fetchQuestionResponses(String instanceId, String serverBase, String apiKey) throws Exception { String instanceValues = fetchDataFromServer(serverBase + DATA_SERVLET_PATH, "?action=" + DataBackoutRequest.LIST_INSTANCE_RESPONSE_ACTION + "&" + DataBackoutRequest.SURVEY_INSTANCE_ID_PARAM + "=" + instanceId, true, apiKey); return parseSurveyInstanceResponse(instanceValues); } /** * survey instance ids and their submission dates. Map keys are the instances and values are the * dates. * * @param surveyId * @param serverBase * @return * @throws Exception */ public static Map<String, String> fetchInstanceIds(String surveyId, String serverBase, String apiKey, boolean lastCollection, String from, String to, String limit) throws Exception { Map<String, String> values = new HashMap<String, String>(); String instanceString = fetchDataFromServer(serverBase + DATA_SERVLET_PATH, "?action=" + DataBackoutRequest.LIST_INSTANCE_ACTION + "&" + DataBackoutRequest.SURVEY_ID_PARAM + "=" + surveyId + "&" + DataBackoutRequest.INCLUDE_DATE_PARAM + "=true" + "&" + DataBackoutRequest.LAST_COLLECTION_PARAM + "=" + lastCollection + "&" + DataBackoutRequest.FROM_DATE_PARAM + "=" + from + "&" + DataBackoutRequest.TO_DATE_PARAM + "=" + to + "&" + DataBackoutRequest.LIMIT_PARAM + "=" + limit, true, apiKey); if (instanceString != null && instanceString.trim().length() != 0) { StringTokenizer strTok = new StringTokenizer(instanceString, ","); while (strTok.hasMoreTokens()) { String instanceId = strTok.nextToken(); String dateString = ""; if (instanceId.contains("|")) { dateString = instanceId .substring(instanceId.indexOf("|") + 1); instanceId = instanceId.substring(0, instanceId.indexOf("|")); } values.put(instanceId, dateString.replaceAll("\n", " ").trim()); } } return values; } /** * form instance count for a single form. * * @param formId * @param serverBase * @return count * @throws Exception */ public static Long fetchInstanceCount(String formId, String serverBase, String apiKey, String from, String to) throws Exception { String instanceString = fetchDataFromServer(serverBase + DATA_SERVLET_PATH, "?action=" + DataBackoutRequest.COUNT_INSTANCE_ACTION + "&" + DataBackoutRequest.SURVEY_ID_PARAM + "=" + formId + "&" + DataBackoutRequest.FROM_DATE_PARAM + "=" + from + "&" + DataBackoutRequest.TO_DATE_PARAM + "=" + to, true, apiKey); Long count = null; if (instanceString != null) { try { count = Long.parseLong(instanceString.trim()); //remove trailing newline } catch (Exception e) { log.error("Unparsable instance count " + e.getMessage()); // Leave it as null } } return count; } public static void main(String[] args) { try { Map<String, String> results = BulkDataServiceClient .fetchInstanceIds(args[1], args[0], args[2], false, null, null, null); if (results != null) { log.info(results); } } catch (Exception e) { log.error("Error: " + e.getMessage(), e); } } /** * Parse a survey instance response into a map of answers keyed first by question id and then by * iteration * * @param responseData * @return */ private static final Map<Long, Map<Long, String>> parseSurveyInstanceResponse( String responseData) { Map<Long, Map<Long, String>> result = new HashMap<>(); StringTokenizer lines = new StringTokenizer(responseData, "\n"); while (lines.hasMoreTokens()) { String line = lines.nextToken(); String[] tokens = line.split(",", 3); Long questionId = Long.valueOf(tokens[0]); Long iteration = Long.valueOf(tokens[1]); String value = new String(Base64.decodeBase64(tokens[2]), StandardCharsets.UTF_8) .trim(); Map<Long, String> iterationMap = result.get(questionId); if (iterationMap != null) { assert iterationMap.get(iteration) == null; iterationMap.put(iteration, value); } else { Map<Long, String> newIterationMap = new HashMap<>(); newIterationMap.put(iteration, value); result.put(questionId, newIterationMap); } } return result; } /** * loads full details for a single question (options, translations, etc) * * @param serverBase * @param questionId * @return */ public static QuestionDto loadQuestionDetails(String serverBase, Long questionId, String apiKey) throws Exception { List<QuestionDto> dtoList = null; dtoList = parseQuestions(fetchDataFromServer(serverBase + SURVEY_SERVLET_PATH, "?action=" + SurveyRestRequest.GET_QUESTION_DETAILS_ACTION + "&" + SurveyRestRequest.QUESTION_ID_PARAM + "=" + questionId, true, apiKey)); if (dtoList != null && dtoList.size() > 0) { return dtoList.get(0); } else { return null; } } /** * returns an array containing 2 elements: the first is an ordered list of questionIds (in the * order they appear in the survey) and the second element is a map of questions (keyed on id) * * @param surveyId * @param serverBase * @return * @throws Exception */ public static Object[] loadQuestions(String surveyId, String serverBase, String apiKey) throws Exception { Object[] results = new Object[2]; Map<String, QuestionDto> questions = new HashMap<String, QuestionDto>(); List<QuestionGroupDto> groups = fetchQuestionGroups(serverBase, surveyId, apiKey); List<String> keyList = new ArrayList<String>(); if (groups != null) { for (QuestionGroupDto group : groups) { List<QuestionDto> questionDtos = fetchQuestions(serverBase, group.getKeyId(), apiKey); if (questionDtos != null) { for (QuestionDto question : questionDtos) { keyList.add(question.getKeyId().toString()); questions.put(question.getKeyId().toString(), question); } } } } results[0] = keyList; results[1] = questions; return results; } /** * gets questions from the server for a specific question group * * @param serverBase * @param groupId * @return * @throws Exception */ public static List<QuestionDto> fetchQuestions(String serverBase, Long groupId, String apiKey) throws Exception { return parseQuestions(fetchDataFromServer(serverBase + SURVEY_SERVLET_PATH, "?action=" + SurveyRestRequest.LIST_QUESTION_ACTION + "&" + SurveyRestRequest.QUESTION_GROUP_ID_PARAM + "=" + groupId, true, apiKey)); } /** * gets question options for a list of questions * @param surveyId * @param serverBase * @param apiKey * @param questionIds * @return * @throws Exception */ public static Map<Long, List<QuestionOptionDto>> fetchOptionNodes(String surveyId, String serverBase, String apiKey, List<Long> questionIds) throws Exception { Map<Long, List<QuestionOptionDto>> result = new HashMap<>(); //this loop is inefficient when there are many option questions (possibly hundreds) //if all options for a survey are needed, use fetchSurveyQuestionOptions() for (Long questionId : questionIds) { List<QuestionOptionDto> questionOptions = parseQuestionOptions(fetchDataFromServer(serverBase + SURVEY_SERVLET_PATH, "?action=" + SurveyRestRequest.LIST_QUESTION_OPTIONS_ACTION + "&" + SurveyRestRequest.QUESTION_ID_PARAM + "=" + questionId, true, apiKey)); result.put(questionId, questionOptions); } return result; } /** * gets all question options for an entire survey * @param surveyId * @param serverBase * @param apiKey * @return list of option nodes * @throws Exception */ public static List<QuestionOptionDto> fetchSurveyQuestionOptions( String surveyId, String serverBase, String apiKey) throws Exception { return parseQuestionOptions( fetchDataFromServer(serverBase + SURVEY_SERVLET_PATH, "?action=" + SurveyRestRequest.LIST_SURVEY_QUESTION_OPTIONS_ACTION + "&" + SurveyRestRequest.SURVEY_ID_PARAM + "=" + surveyId, true, apiKey)); } /** * gets a surveyInstance from the server for a specific id * * @param id * @param serverBase * @return * @throws Exception */ public static SurveyInstanceDto findSurveyInstance(Long id, String serverBase, String apiKey) throws Exception { return parseSurveyInstance(fetchDataFromServer(serverBase + SURVEY_SERVLET_PATH, "?action=" + SurveyRestRequest.GET_SURVEY_INSTANCE_ACTION + "&" + SurveyRestRequest.INSTANCE_PARAM + "=" + id, true, apiKey)); } public static InstanceDataDto fetchInstanceData(Long surveyInstanceId, String serverBase, String apiKey) throws Exception { final String baseUrl = serverBase + INSTANCE_DATA_SERVLET_PATH; final String urlQueryString = new StringBuilder() .append("?action=").append(GET_INSTANCE_DATA_ACTION) .append("&") .append(SURVEY_INSTANCE_ID_PARAM).append("=").append(surveyInstanceId) .toString(); final String instanceDataResponse = fetchDataFromServer(baseUrl, urlQueryString, true, apiKey); return parseInstanceData(instanceDataResponse); } private static InstanceDataDto parseInstanceData(String instanceDataResponse) { FlowJsonObjectReader jsonReader = new FlowJsonObjectReader(); TypeReference<InstanceDataDto> typeReference = new TypeReference<InstanceDataDto>() {}; try { InstanceDataDto instanceData = jsonReader.readObject(instanceDataResponse, typeReference); return instanceData; } catch (IOException e) { log.error("Error while parsing: ", e); } return new InstanceDataDto(); } /** * gets question groups from the server for a specific survey * * @param serverBase * @param surveyId * @return * @throws Exception */ public static List<QuestionGroupDto> fetchQuestionGroups(String serverBase, String surveyId, String apiKey) throws Exception { return parseQuestionGroups(fetchDataFromServer(serverBase + SURVEY_SERVLET_PATH, "?action=" + SurveyRestRequest.LIST_GROUP_ACTION + "&" + SurveyRestRequest.SURVEY_ID_PARAM + "=" + surveyId, true, apiKey)); } /** * Fetch a single SurveyGroup based for the surveyId provided * * @param surveyId * @param serverBase * @param apiKey * @return * @throws Exception */ public static SurveyGroupDto fetchSurveyGroup(String surveyId, String serverBase, String apiKey) { SurveyGroupDto surveyGroupDto = null; try { final String surveyGroupResponse = fetchDataFromServer( serverBase + SURVEY_SERVLET_PATH, "action=" + SurveyRestRequest.GET_SURVEY_GROUP_ACTION + "&" + SurveyRestRequest.SURVEY_ID_PARAM + "=" + surveyId, true, apiKey); log.debug("response: " + surveyGroupResponse); final FlowJsonObjectReader jsonDeserialiser = new FlowJsonObjectReader(); final TypeReference<SurveyGroupDto> listItemTypeReference = new TypeReference<SurveyGroupDto>(){}; final List<SurveyGroupDto> surveyGroupList = jsonDeserialiser.readDtoListObject(surveyGroupResponse, listItemTypeReference); if (surveyGroupList != null && !surveyGroupList.isEmpty()) { surveyGroupDto = surveyGroupList.get(0); } } catch (Exception e) { log.error(e); } return surveyGroupDto; } /** * gets survey groups from the server * * @param serverBase * @param apiKey * @return * @throws Exception */ public static List<SurveyGroupDto> fetchSurveyGroups(String serverBase, String apiKey) throws Exception { final List<SurveyGroupDto> result = new ArrayList<SurveyGroupDto>(); String cursor = null; do { String qs = "?action=" + SurveyRestRequest.LIST_SURVEY_GROUPS_ACTION; if (cursor != null && !"".equals(cursor)) { qs = qs + "&cursor=" + cursor; } String resp = fetchDataFromServer(serverBase + SURVEY_SERVLET_PATH, qs, true, apiKey); try { JSONObject jsonResp = new JSONObject(resp); cursor = jsonResp.isNull("cursor") ? null : jsonResp.getString("cursor"); } catch (JSONException e) { cursor = null; } result.addAll(parseSurveyGroups(resp)); } while (cursor != null); return result; } /** * gets survey list from the server for a specific survey group * * @param serverBase * @param surveyGroupId * @return * @throws Exception */ public static List<SurveyDto> fetchSurveys(Long surveyGroupId, String serverBase, String apiKey) throws Exception { return parseSurveys(fetchDataFromServer(serverBase + SURVEY_SERVLET_PATH, "?action=" + SurveyRestRequest.LIST_SURVEYS_ACTION + "&" + SurveyRestRequest.SURVEY_GROUP_ID_PARAM + "=" + surveyGroupId, true, apiKey)); } public static List<SurveyDto> fetchSurvey(Long surveyId, String serverBase, String apiKey) throws Exception { return parseSurveys(fetchDataFromServer(serverBase + SURVEY_SERVLET_PATH, "?action=" + SurveyRestRequest.GET_SURVEY_ACTION + "&" + SurveyRestRequest.SURVEY_ID_PARAM + "=" + surveyId, true, apiKey)); } /** * parses a single SurveyInstanceDto from a json response string * * @param response * @return * @throws Exception */ private static SurveyInstanceDto parseSurveyInstance(String response) throws Exception { SurveyInstanceDto dto = null; if (response != null) { JSONArray arr = getJsonArray(response); if (arr != null && arr.length() > 0) { JSONObject json = arr.getJSONObject(0); if (json != null) { dto = new SurveyInstanceDto(); if (json.has("keyId")) { dto.setKeyId(json.getLong("keyId")); } if (json.has("surveyId")) { dto.setSurveyId(json.getLong("surveyId")); } if (json.has("userID") && !json.isNull("userID")) { dto.setUserID(json.getLong("userID")); } if (json.has("surveyalTime") && !json.isNull("surveyalTime")) { dto.setSurveyalTime(json.getLong("surveyalTime")); } if (json.has("submitterName")) { dto.setSubmitterName(json.getString("submitterName")); } if (json.has("approvedFlag")) { dto.setApprovedFlag(json.getString("approvedFlag")); } if (json.has("deviceIdentifier")) { dto.setDeviceIdentifier(json .getString("deviceIdentifier")); } if (json.has("surveyedLocaleId") && !json.isNull("surveyedLocaleId")) { dto.setSurveyedLocaleId(json.getLong("surveyedLocaleId")); } if (json.has("surveyedLocaleDisplayName") && !json.isNull("surveyedLocaleDisplayName")) { dto.setSurveyedLocaleDisplayName(json .getString("surveyedLocaleDisplayName")); } if (json.has("surveyedLocaleIdentifier") && !json.isNull("surveyedLocaleIdentifier")) { dto.setSurveyedLocaleIdentifier(json.getString("surveyedLocaleIdentifier")); } if (json.has("collectionDate")) { dto.setCollectionDate(new Date(json.getLong("collectionDate"))); } if (!json.has("formVersion")) { dto.setFormVersion(json.getDouble("formVersion")); } } } } return dto; } /** * parses the question group response and forms DTOs * * @param response * @return * @throws Exception */ private static List<QuestionGroupDto> parseQuestionGroups(String response) throws Exception { List<QuestionGroupDto> dtoList = new ArrayList<QuestionGroupDto>(); JSONArray arr = getJsonArray(response); if (arr != null) { for (int i = 0; i < arr.length(); i++) { JSONObject json = arr.getJSONObject(i); if (json != null) { QuestionGroupDto dto = new QuestionGroupDto(); try { if (!json.isNull("code")) { dto.setCode(json.getString("code")); } if (!json.isNull("keyId")) { dto.setKeyId(json.getLong("keyId")); } if (!json.isNull("displayName")) { dto.setName(json.getString("displayName")); } if (!json.isNull("order")) { dto.setOrder(json.getInt("order")); } if (!json.isNull("path")) { dto.setPath(json.getString("path")); } if (!json.isNull("surveyId")) { dto.setSurveyId(json.getLong("surveyId")); } if (!json.isNull("repeatable")) { dto.setRepeatable(json.getBoolean("repeatable")); } dtoList.add(dto); } catch (Exception e) { log.error("Error in json parsing: " + e.getMessage(), e); } } } } return dtoList; } /** * parses the survey group response and forms DTOs * * @param response * @return * @throws Exception */ private static List<SurveyGroupDto> parseSurveyGroups(String response) throws Exception { List<SurveyGroupDto> dtoList = new ArrayList<SurveyGroupDto>(); JSONArray arr = getJsonArray(response); if (arr != null) { for (int i = 0; i < arr.length(); i++) { JSONObject json = arr.getJSONObject(i); if (json != null) { SurveyGroupDto dto = new SurveyGroupDto(); try { if (!json.isNull("code")) { dto.setCode(json.getString("code")); } if (!json.isNull("keyId")) { dto.setKeyId(json.getLong("keyId")); } if (!json.isNull("displayName")) { dto.setName(json.getString("displayName")); } if (!json.isNull("description")) { dto.setDescription(json.getString("description")); } if (!json.isNull("projectType")) { dto.setProjectType(ProjectType.valueOf(json.getString("projectType"))); } if (!json.isNull("parentId")) { dto.setParentId(json.getLong("parentId")); } if (!json.isNull("path")) { dto.setPath(json.getString("path")); } if (!json.isNull("ancestorIds")) { JSONArray idArr = json.getJSONArray("ancestorIds"); List<Long> ancestorIds = new ArrayList<Long>(); for (int ix = 0; ix < idArr.length(); ix++) { ancestorIds.add(idArr.getLong(ix)); } dto.setAncestorIds(ancestorIds); } if (!json.isNull("defaultLanguageCode")) { dto.setDefaultLanguageCode(json.getString("defaultLanguageCode")); } if (!json.isNull("monitoringGroup")) { dto.setMonitoringGroup(json.getBoolean("monitoringGroup")); } if (!json.isNull("newLocaleSurveyId")) { dto.setNewLocaleSurveyId(json.getLong("newLocaleSurveyId")); } dtoList.add(dto); } catch (Exception e) { log.error("Error in json parsing: " + e.getMessage(), e); } } } } return dtoList; } /** * parses the survey group response and forms DTOs * * @param response * @return * @throws Exception */ private static List<SurveyDto> parseSurveys(String response) throws Exception { List<SurveyDto> dtoList = new ArrayList<SurveyDto>(); JSONArray arr = getJsonArray(response); if (arr != null) { for (int i = 0; i < arr.length(); i++) { JSONObject json = arr.getJSONObject(i); if (json != null) { SurveyDto dto = new SurveyDto(); try { if (!json.isNull("code")) { dto.setCode(json.getString("code")); } if (!json.isNull("defaultLanguageCode")) { dto.setDefaultLanguageCode(json.getString("defaultLanguageCode")); } if (!json.isNull("description")) { dto.setDescription(json.getString("description")); } if (!json.isNull("keyId")) { dto.setKeyId(json.getLong("keyId")); } if (!json.isNull("name")) { dto.setName(json.getString("name")); } if (!json.isNull("path")) { dto.setPath(json.getString("path")); } if (!json.isNull("requireApproval")) { dto.setRequireApproval(json.getBoolean("requireApproval")); } if (!json.isNull("status")) { dto.setStatus(json.getString("status")); } if (!json.isNull("surveyGroupId")) { dto.setSurveyGroupId(json.getLong("surveyGroupId")); } if (!json.isNull("version")) { dto.setVersion(json.getString("version")); } if (!json.isNull("ancestorIds")) { JSONArray idArr = json.getJSONArray("ancestorIds"); List<Long> ancestorIds = new ArrayList<Long>(); for (int ix = 0; ix < idArr.length(); ix++) { ancestorIds.add(idArr.getLong(ix)); } dto.setAncestorIds(ancestorIds); } dtoList.add(dto); } catch (Exception e) { log.error("Error in json parsing: " + e.getMessage(), e); } } } } return dtoList; } private static List<DeviceFilesDto> parseDeviceFiles(String response) throws Exception { if (response.startsWith("{")) { List<DeviceFilesDto> dtoList = new ArrayList<DeviceFilesDto>(); JSONArray arr = getJsonArray(response); if (arr != null) { for (int i = 0; i < arr.length(); i++) { JSONObject json = arr.getJSONObject(i); dtoList.add(parseDeviceFile(json)); } return dtoList; } return null; } return null; } public static DeviceFilesDto parseDeviceFile(JSONObject json) throws JSONException { DeviceFilesDto dto = new DeviceFilesDto(); if (json != null) { if (json.has("processingMessage")) { String x = json.getString("processingMessage"); dto.setProcessingMessage(x); } if (json.has("phoneNumber")) { String x = json.getString("phoneNumber"); dto.setPhoneNumber(x); } if (json.has("processedStatus")) { String x = json.getString("processedStatus"); dto.setProcessedStatus(x); } if (json.has("checksum")) { String x = json.getString("checksum"); dto.setChecksum(x); } if (json.has("processDate")) { String x = json.getString("processDate"); dto.setProcessDate(x); } if (json.has("URI")) { String x = json.getString("URI"); dto.setURI(x); } if (json.has("surveyInstanceId")) { String x = json.getString("surveyInstanceId"); dto.setSurveyInstanceId(Long.parseLong(x)); } } return dto; } /** * parses question responses into QuestionDto objects * * @param response * @return * @throws Exception */ private static List<QuestionDto> parseQuestions(String response) throws Exception { if (response.startsWith("{")) { List<QuestionDto> dtoList = new ArrayList<QuestionDto>(); JSONArray arr = getJsonArray(response); if (arr != null) { for (int i = 0; i < arr.length(); i++) { JSONObject json = arr.getJSONObject(i); if (json != null) { QuestionDto dto = new QuestionDto(); try { if (json.has("surveyId")) { if (json.getString("surveyId") != null) { String numberC = json.getString("surveyId"); try { dto.setSurveyId(Long.parseLong(numberC)); } catch (NumberFormatException nex) { dto.setSurveyId(null); } } } if (!json.isNull("allowMultipleFlag")) { dto.setAllowMultipleFlag(json.getBoolean("allowMultipleFlag")); } if (!json.isNull("allowOtherFlag")) { dto.setAllowOtherFlag(json.getBoolean("allowOtherFlag")); } if (!json.isNull("order")) { dto.setOrder(json.getInt("order")); } if (!json.isNull("questionGroupId")) { dto.setQuestionGroupId(json.getLong("questionGroupId")); } if (!json.isNull("tip")) { dto.setTip(json.optString("tip")); } if (!json.isNull("variableName")) { dto.setVariableName(json.optString("variableName")); } if (!json.isNull("path")) { dto.setPath(json.getString("path")); } if (!json.isNull("text")) { dto.setText(json.getString("text")); } if (!json.isNull("keyId")) { dto.setKeyId(json.getLong("keyId")); } if (!json.isNull("collapseable")) { dto.setCollapseable(json.getBoolean("collapseable")); } if (!json.isNull("dependentFlag")) { dto.setDependentFlag(json.getBoolean("dependentFlag")); } if (!json.isNull("dependentQuestionAnswer")) { dto.setDependentQuestionAnswer(json .optString("dependentQuestionAnswer")); } if (json.has("dependentQuestionId")) { try { dto.setDependentQuestionId(json.getLong("dependentQuestionId")); } catch (Exception e) { dto.setDependentQuestionId(null); } } if (!json.isNull("geoLocked")) { dto.setGeoLocked(json.getBoolean("geoLocked")); } if (!json.isNull("caddisflyResourceUuid")) { dto.setCaddisflyResourceUuid( json.getString("caddisflyResourceUuid")); } if (!json.isNull("immutable")) { dto.setImmutable(json.getBoolean("immutable")); } if (!json.isNull("isName")) { dto.setName(json.getBoolean("isName")); } if (!json.isNull("localeNameFlag")) { dto.setLocaleNameFlag(json.getBoolean("localeNameFlag")); } if (!json.isNull("mandatoryFlag")) { dto.setMandatoryFlag(json.getBoolean("mandatoryFlag")); } if (json.has("metricId")) { try { dto.setMetricId(json.getLong("metricId")); } catch (Exception e) { dto.setMetricId(null); } } if (!json.isNull("requireDoubleEntry")) { dto.setRequireDoubleEntry(json.getBoolean("requireDoubleEntry")); } if (json.has("sourceId")) { try { dto.setSourceId(json.getLong("sourceId")); } catch (Exception e) { dto.setSourceId(null); } } if (!json.isNull("allowDecimal")) { dto.setAllowDecimal(json.getBoolean("allowDecimal")); } if (!json.isNull("allowSign")) { dto.setAllowSign(json.getBoolean("allowSign")); } if (json.has("minVal")) { try { dto.setMinVal(json.getDouble("minVal")); } catch (Exception e) { dto.setMinVal(null); } } if (json.has("maxVal")) { try { dto.setMaxVal(json.getDouble("maxVal")); } catch (Exception e) { dto.setMaxVal(null); } } if (!json.isNull("translationMap")) { dto.setTranslationMap(parseTranslations(json .getJSONObject("translationMap"))); } if (!json.isNull("type")) { dto.setType(QuestionDto.QuestionType.valueOf(json .getString("type"))); } if (!json.isNull("allowPoints")) { dto.setAllowPoints(json.getBoolean("allowPoints")); } if (!json.isNull("allowLine")) { dto.setAllowLine(json.getBoolean("allowLine")); } if (!json.isNull("allowPolygon")) { dto.setAllowPolygon(json.getBoolean("allowPolygon")); } if (!json.isNull("optionContainerDto")) { OptionContainerDto container = new OptionContainerDto(); JSONObject contJson = json.getJSONObject("optionContainerDto"); if (!contJson.isNull("optionsList")) { JSONArray optArray = contJson.getJSONArray("optionsList"); if (optArray != null) { for (int j = 0; j < optArray.length(); j++) { JSONObject optJson = optArray.getJSONObject(j); QuestionOptionDto opt = new QuestionOptionDto(); opt.setKeyId(optJson.getLong("keyId")); opt.setText(optJson.getString("text")); if (!optJson.isNull("code")) { // getString on null gives String "null" opt.setCode(optJson.getString("code")); } opt.setOrder(optJson.getInt("order")); if (!optJson.isNull("translationMap")) { opt.setTranslationMap(parseTranslations(optJson .getJSONObject("translationMap"))); } container.addQuestionOption(opt); } } dto.setOptionContainerDto(container); } } // The questionDependency check below is related to the // previous if statements dependentFlag, dependentQuestionId, // dependentQuestionAnswer i.e. checks whether question is // dependent on another if (!json.isNull("questionDependency")) { QuestionDependencyDto dep = new QuestionDependencyDto(); JSONObject depJson = json.getJSONObject("questionDependency"); dep.setQuestionId(depJson.getLong("questionId")); dep.setAnswerValue(depJson.getString("answerValue")); dto.setQuestionDependency(dep); } if (!json.isNull("levelNames")) { final List<String> levelNames = new ArrayList<String>(); final JSONArray array = json.getJSONArray("levelNames"); for (int c = 0; c < array.length(); c++) { levelNames.add(array.getString(c)); } dto.setLevelNames(levelNames); } dtoList.add(dto); } catch (Exception e) { log.error("Error in json parsing: " + e.getMessage(), e); } } } } return dtoList; } else return null; } /** * @param response * @return */ private static List<QuestionOptionDto> parseQuestionOptions(String response) { List<QuestionOptionDto> dtoList = new ArrayList<>(); try { JSONArray jsonArray = getJsonArray(response); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); if (json != null) { QuestionOptionDto dto = new QuestionOptionDto(); dto.setQuestionId(json.getLong("questionId")); dto.setText(json.optString("text", null)); dto.setCode(json.optString("code", null)); dtoList.add(dto); } } } } catch (Exception e) { log.warn("Could not parse question options: " + response, e); } return dtoList; } @SuppressWarnings("unchecked") private static TreeMap<String, TranslationDto> parseTranslations( JSONObject translationMapJson) throws Exception { Iterator<String> keyIter = translationMapJson.keys(); TreeMap<String, TranslationDto> translationMap = null; if (keyIter != null) { translationMap = new TreeMap<String, TranslationDto>(); //Iterate on all the languages while (keyIter.hasNext()) { String lang = keyIter.next(); JSONObject transObj = translationMapJson.getJSONObject(lang); if (transObj != null) { TranslationDto tDto = new TranslationDto(); tDto.setKeyId(transObj.getLong("keyId")); tDto.setParentId(transObj.getLong(("parentId"))); tDto.setParentType(transObj.getString("parentType")); tDto.setLangCode(lang); tDto.setText(transObj.getString("text")); translationMap.put(lang, tDto); } } } return translationMap; } /** * invokes a remote REST api using the base and query string passed in. If shouldSign is true, * the queryString will be augmented with a timestamp and hash parameter. * @throws Exception */ public static String fetchDataFromServer(String baseUrl, String queryString, boolean shouldSign, String apiKey) throws Exception { if (shouldSign && apiKey != null) { if (queryString == null) { queryString = new String(); } else { if (queryString.trim().startsWith("?")) { queryString = queryString.trim().substring(1); } queryString += "&"; } DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("GMT")); queryString += RestRequest.TIMESTAMP_PARAM + "=" + URLEncoder.encode(df.format(new Date()), "UTF-8"); queryString = sortQueryString(queryString); queryString += "&" + RestRequest.HASH_PARAM + "=" + MD5Util.generateHMAC(queryString, apiKey); } return fetchDataFromServer(baseUrl + ((queryString != null && queryString.trim().length() > 0) ? "?" + queryString : "")); } /** * invokes a remote REST api. If the url is longer than 1900 characters, this method will use * POST since that is too long for a GET * @throws Exception */ public static String fetchDataFromServer(String fullUrl) throws Exception { if (fullUrl != null) { if (fullUrl.length() > 1900) { return fetchDataFromServerPOST(fullUrl); } else { return fetchDataFromServerGET(fullUrl); } } else { return null; } } /** * executes a post to invoke a rest api */ private static String fetchDataFromServerPOST(String fullUrl) throws Exception { BufferedReader reader = null; String result = null; try { String baseUrl = fullUrl; String queryString = null; if (fullUrl.contains("?")) { baseUrl = fullUrl.substring(0, fullUrl.indexOf("?")); queryString = fullUrl.substring(fullUrl.indexOf("?") + 1); } else { queryString = ""; } URL url = new URL(baseUrl); log.debug("Calling: " + baseUrl + " with params: " + queryString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Content-Length", "" + Integer.toString(queryString.getBytes().length)); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoInput(true); conn.setDoOutput(true); conn.addRequestProperty("Accept-Encoding", "gzip"); conn.addRequestProperty("User-Agent", "gzip"); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(queryString); wr.flush(); wr.close(); InputStream instream = conn.getInputStream(); String contentEncoding = conn.getHeaderField("Content-Encoding"); if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { reader = new BufferedReader(new InputStreamReader( new GZIPInputStream(instream), "UTF-8")); } else { reader = new BufferedReader(new InputStreamReader(instream, "UTF-8")); } StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } finally { if (reader != null) { reader.close(); } } return result; } /** * executes a GET to invoke a rest api */ private static String fetchDataFromServerGET(String fullUrl) throws Exception { BufferedReader reader = null; String result = null; try { URL url = new URL(fullUrl); log.debug("Calling: " + url.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.addRequestProperty("Accept-Encoding", "gzip"); conn.addRequestProperty("User-Agent", "gzip"); InputStream instream = conn.getInputStream(); String contentEncoding = conn.getHeaderField("Content-Encoding"); if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { reader = new BufferedReader(new InputStreamReader( new GZIPInputStream(instream), "UTF-8")); } else { reader = new BufferedReader(new InputStreamReader(instream, "UTF-8")); } StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } finally { if (reader != null) { reader.close(); } } return result; } private static String sortQueryString(String queryString) throws UnsupportedEncodingException { String[] parts = queryString.split("&"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (int i = 0; i < parts.length; i++) { String[] nvp = parts[i].split("="); if (nvp.length > 1) { if (nvp.length == 2) { pairs.add(new NameValuePair(nvp[0], nvp[1])); } else { // if we're here, we have multiple "=" so we need to merge // parts 1..n StringBuilder builder = new StringBuilder(); for (int j = 1; j < nvp.length; j++) { if (builder.length() > 0) { builder.append("="); } builder.append(nvp[j]); } pairs.add(new NameValuePair(nvp[0], builder.toString())); } } } // now sort the names Collections.sort(pairs); StringBuilder result = new StringBuilder(); for (NameValuePair nvp : pairs) { if (result.length() > 0) { result.append("&"); } result.append(nvp.getName()).append("="); if (nvp.getName().equals(RestRequest.TIMESTAMP_PARAM)) { result.append(nvp.getValue()); } else { result.append(URLEncoder.encode(nvp.getValue(), "UTF-8")); } } return result.toString(); } /** * converts the string into a JSON array object. */ public static JSONArray getJsonArray(String response) throws Exception { log.debug("response: " + response); if (response != null) { JSONObject json = new JSONObject(response); if (json != null) { return json.getJSONArray(RESPONSE_KEY); } } return null; } }
package com.elmakers.mine.bukkit.magic.listener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.bukkit.Chunk; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.PistonMoveReaction; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.FallingBlock; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockFadeEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.event.world.WorldInitEvent; import org.bukkit.event.world.WorldSaveEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import com.elmakers.mine.bukkit.api.batch.Batch; import com.elmakers.mine.bukkit.api.batch.SpellBatch; import com.elmakers.mine.bukkit.api.block.UndoList; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MaterialSet; import com.elmakers.mine.bukkit.batch.UndoBatch; import com.elmakers.mine.bukkit.block.DefaultMaterials; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.tasks.CheckChunkTask; import com.elmakers.mine.bukkit.tasks.UndoBlockTask; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.elmakers.mine.bukkit.utility.NMSUtils; import com.elmakers.mine.bukkit.wand.Wand; import com.elmakers.mine.bukkit.world.MagicWorld; public class BlockController implements Listener, ChunkLoadListener { private final MagicController controller; private boolean undoOnWorldSave = false; private int creativeBreakFrequency = 0; private boolean dropOriginalBlock = true; private boolean applySpawnerData = true; private boolean disableSpawnerData = false; // This is used only for the BlockBurn event, in other cases we get a source block to check. static final List<BlockFace> blockBurnDirections = Arrays.asList( BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN ); public BlockController(MagicController controller) { this.controller = controller; } public void loadProperties(ConfigurationSection properties) { undoOnWorldSave = properties.getBoolean("undo_on_world_save", false); creativeBreakFrequency = properties.getInt("prevent_creative_breaking", 0); dropOriginalBlock = properties.getBoolean("drop_original_block", true); applySpawnerData = properties.getBoolean("apply_spawner_data", true); if (disableSpawnerData) { applySpawnerData = false; } } public void finalizeIntegration() { final PluginManager pluginManager = controller.getPlugin().getServer().getPluginManager(); if (pluginManager.isPluginEnabled("SilkSpawners")) { applySpawnerData = false; disableSpawnerData = true; controller.getLogger().info("SilkSpawners detected, forcing apply_spawner_data to false"); } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { Block block = event.getBlock(); Player player = event.getPlayer(); if (creativeBreakFrequency > 0 && player.getGameMode() == GameMode.CREATIVE) { com.elmakers.mine.bukkit.magic.Mage mage = controller.getMage(event.getPlayer()); if (mage.checkLastClick(creativeBreakFrequency)) { event.setCancelled(true); return; } } if (controller.areLocksProtected() && controller.isContainer(block) && !controller.hasBypassPermission(event.getPlayer())) { String lockKey = CompatibilityUtils.getLock(block); if (lockKey != null && !lockKey.isEmpty()) { Inventory inventory = player.getInventory(); Mage mage = controller.getRegisteredMage(event.getPlayer()); if (mage != null) { inventory = mage.getInventory(); } if (!InventoryUtils.hasItem(inventory, lockKey)) { String message = controller.getMessages().get("general.locked_chest"); if (mage != null) { mage.sendMessage(message); } else { player.sendMessage(message); } event.setCancelled(true); return; } } } if (controller.checkAutomatonBreak(block)) { event.setCancelled(true); return; } com.elmakers.mine.bukkit.api.block.BlockData modifiedBlock = com.elmakers.mine.bukkit.block.UndoList.getBlockData(block.getLocation()); if (modifiedBlock != null) { UndoList undoList = modifiedBlock.getUndoList(); if (undoList != null) { if (undoList.isUnbreakable()) { event.setCancelled(true); return; } if (!undoList.isConsumed()) { event.setCancelled(true); Collection<ItemStack> items = null; if (dropOriginalBlock) { while (modifiedBlock.getPriorState() != null) { modifiedBlock = modifiedBlock.getPriorState(); } modifiedBlock.modify(block); items = block.getDrops(); } if (items != null) { Location location = block.getLocation(); for (ItemStack item : items) { if (!CompatibilityUtils.isEmpty(item)) { location.getWorld().dropItemNaturally(location, item); } } } block.setType(Material.AIR); } modifiedBlock.commit(); } } } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); ItemStack itemStack = event.getItemInHand(); if (NMSUtils.isTemporary(itemStack)) { event.setCancelled(true); player.getInventory().setItemInMainHand(null); return; } if (NMSUtils.isUnplaceable(itemStack) || Wand.isSpecial(itemStack)) { event.setCancelled(true); return; } com.elmakers.mine.bukkit.magic.Mage mage = controller.getMage(player); if (mage.getBlockPlaceTimeout() > System.currentTimeMillis()) { event.setCancelled(true); } if (Wand.isSpecial(itemStack)) { event.setCancelled(true); } if (!event.isCancelled()) { Block block = event.getBlock(); com.elmakers.mine.bukkit.api.block.BlockData modifiedBlock = com.elmakers.mine.bukkit.block.UndoList.getBlockData(block.getLocation()); if (modifiedBlock != null) { // Replacing a permanently-changed block will act as normal while silently // committing the change. // Replacing a temporarily-changed block will force the block to undo while preventing the place UndoList undoList = modifiedBlock.getUndoList(); if (undoList != null && undoList.isScheduled()) { event.setCancelled(true); Plugin plugin = controller.getPlugin(); plugin.getServer().getScheduler().runTaskLater(plugin, new UndoBlockTask(modifiedBlock), 1); } else { modifiedBlock.commit(); // Prevent creating waterlogged blocks accidentally, since these can be exploited for water, even in the nether if (event.getBlockReplacedState().getType() == Material.WATER) { CompatibilityUtils.setWaterlogged(block, false); } } } if (!event.isCancelled() && applySpawnerData && DefaultMaterials.isMobSpawner(block.getType()) && event.getItemInHand() != null && DefaultMaterials.isMobSpawner(event.getItemInHand().getType()) && player.hasPermission("Magic.spawners")) { CompatibilityUtils.applyItemData(event.getItemInHand(), block); } } } @EventHandler public void onBlockFade(BlockFadeEvent event) { Block block = event.getBlock(); UndoList undoList = controller.getPendingUndo(block.getLocation()); if (undoList != null) { undoList.add(block); } } @EventHandler public void onPistonRetract(BlockPistonRetractEvent event) { Block piston = event.getBlock(); Block block = piston.getRelative(event.getDirection()); UndoList undoList = controller.getPendingUndo(block.getLocation()); if (undoList != null) { // This block is the piston head undoList.add(block); // This block stores the state of the piston (er, I think?) undoList.add(piston); block = piston.getRelative(event.getDirection()); // This is the block we will pull if it's not empty if (!DefaultMaterials.isAir(block.getType())) { undoList.add(block); } } } @EventHandler public void onPistonExtend(BlockPistonExtendEvent event) { Block piston = event.getBlock(); Block block = piston.getRelative(event.getDirection()); // See if this block is going to get pushed or broken or what PistonMoveReaction reaction = block.getPistonMoveReaction(); if (reaction == PistonMoveReaction.BLOCK) { return; } UndoList undoList = controller.getPendingUndo(block.getLocation()); if (undoList == null) { undoList = controller.getPendingUndo(piston.getLocation()); } if (undoList != null) { // This block stores the state of the piston, maybe undoList.add(piston); if (reaction == PistonMoveReaction.BREAK) { // This block is about to be broken, we will break it but avoid dropping an item. undoList.add(block); NMSUtils.clearItems(block.getLocation()); DeprecatedUtils.setTypeAndData(block, Material.AIR, (byte) 0, false); } else { // This block is about to become the piston head undoList.add(block); // Continue to look for more solid blocks we'll push block = block.getRelative(event.getDirection()); undoList.add(block); // We need to store the final air block since we'll be pushing a block into that // But after that, we can quit int maxBlocks = 14; while (maxBlocks-- > 0 && !DefaultMaterials.isAir(block.getType())) { block = block.getRelative(event.getDirection()); undoList.add(block); } } } } @EventHandler public void onBlockFromTo(BlockFromToEvent event) { Block targetBlock = event.getToBlock(); Block sourceBlock = event.getBlock(); UndoList undoList = controller.getPendingUndo(sourceBlock.getLocation()); if (undoList != null) { undoList.add(targetBlock); } else { undoList = controller.getPendingUndo(targetBlock.getLocation()); if (undoList != null) { undoList.add(targetBlock); } } if (undoList != null && undoList.isScheduled()) { // Avoid dropping broken items! MaterialSet doubles = com.elmakers.mine.bukkit.block.UndoList.attachablesDouble; if (doubles.testBlock(targetBlock)) { Block upBlock = targetBlock.getRelative(BlockFace.UP); while (doubles.testBlock(upBlock)) { undoList.add(upBlock); DeprecatedUtils.setTypeAndData(upBlock, Material.AIR, (byte) 0, false); upBlock = upBlock.getRelative(BlockFace.UP); } Block downBlock = targetBlock.getRelative(BlockFace.DOWN); while (doubles.testBlock(downBlock)) { undoList.add(downBlock); DeprecatedUtils.setTypeAndData(downBlock, Material.AIR, (byte) 0, false); downBlock = downBlock.getRelative(BlockFace.DOWN); } } if (!CompatibilityUtils.isWaterLoggable(targetBlock)) { NMSUtils.clearItems(targetBlock.getLocation()); DeprecatedUtils.setTypeAndData(targetBlock, Material.AIR, (byte) 0, false); } event.setCancelled(true); } } @EventHandler public void onBlockBurn(BlockBurnEvent event) { Block targetBlock = event.getBlock(); UndoList undoList = controller.getPendingUndo(targetBlock.getLocation()); if (undoList == null) { // TODO: Use BlockBurnEvent.getIgnitingBlock to avoid this mess, 1.11 and up // This extra check is necessary to prevent a very specific condition that is not necessarily unique to // burning, but happens much more frequently. This may be a sign that the attachment-watching code in UndoList // needs review, and perhaps in general instead of watching neighbor blocks we should check all neighbor blocks // for block flow and attachable break events. // The specific problem here has to do with overlapping spells with paced undo. Take 2 Fire casts as an example: // 1) Fire A casts and begins to burn some blocks, which turn to air // 2) Fire B casts and registers nearby combustible blocks. // 3) Some blocks already burnt by Fire A are adjacent to blocks burning from Fire B, and are not registered // for watching because they are currently air and non-combustible. // 4) Fire A rolls back, restoring blocks that were air when Fire B cast to something combustible // 5) Rolled back blocks from Fire A start to burn, but are not tracked since they were registered for // watching by Fire B. // 6) Fire B rolls back, leaving burning blocks that continue to spread. for (BlockFace face : blockBurnDirections) { Block sourceBlock = targetBlock.getRelative(face); if (sourceBlock.getType() != Material.FIRE) continue; undoList = controller.getPendingUndo(sourceBlock.getLocation()); if (undoList != null) { break; } } } if (undoList != null) { undoList.add(targetBlock); } } @EventHandler public void onBlockIgnite(BlockIgniteEvent event) { BlockIgniteEvent.IgniteCause cause = event.getCause(); if (cause == BlockIgniteEvent.IgniteCause.ENDER_CRYSTAL || cause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL) { return; } Entity entity = event.getIgnitingEntity(); UndoList entityList = controller.getEntityUndo(entity); if (entityList != null) { entityList.add(event.getBlock()); return; } Block ignitingBlock = event.getIgnitingBlock(); Block targetBlock = event.getBlock(); if (ignitingBlock != null) { UndoList undoList = controller.getPendingUndo(ignitingBlock.getLocation()); if (undoList != null) { undoList.add(event.getBlock()); return; } } UndoList undoList = controller.getPendingUndo(targetBlock.getLocation()); if (undoList != null) { undoList.add(targetBlock); } } @EventHandler public void onBlockDamage(BlockDamageEvent event) { Player damager = event.getPlayer(); Mage damagerMage = controller.getRegisteredMage(damager); if (damagerMage != null) { com.elmakers.mine.bukkit.api.wand.Wand activeWand = damagerMage.getActiveWand(); if (activeWand != null) { activeWand.playEffects("hit_block"); } } } @EventHandler public void onEntityChangeBlockEvent(EntityChangeBlockEvent event) { Entity entity = event.getEntity(); if (entity instanceof FallingBlock) { if (event.getTo() == Material.AIR) { // Block is falling, register it controller.registerFallingBlock(entity, event.getBlock()); } else { // Block is landing, convert it UndoList blockList = com.elmakers.mine.bukkit.block.UndoList.getUndoList(entity); if (blockList != null) { com.elmakers.mine.bukkit.api.action.CastContext context = blockList.getContext(); if (context != null && !context.hasBuildPermission(entity.getLocation().getBlock())) { event.setCancelled(true); } else { Block block = event.getBlock(); blockList.convert(entity, block); if (!blockList.getApplyPhysics()) { FallingBlock falling = (FallingBlock)entity; DeprecatedUtils.setTypeAndData(block, falling.getMaterial(), NMSUtils.getBlockData(falling), false); event.setCancelled(true); } } } } } } private void undoPending(World world, String logType) { Collection<Mage> mages = controller.getMages(); for (Mage mage : mages) { Collection<Batch> pending = new ArrayList<>(mage.getPendingBatches()); int cancelled = 0; int fastForwarded = 0; for (Batch batch : pending) { if (batch instanceof SpellBatch) { SpellBatch spellBatch = (SpellBatch)batch; UndoList undoList = spellBatch.getUndoList(); if (undoList != null && undoList.isScheduled() && undoList.affectsWorld(world)) { spellBatch.cancel(); cancelled++; } } else if (batch instanceof UndoBatch) { UndoBatch undoBatch = (UndoBatch)batch; UndoList undoList = undoBatch.getUndoList(); if (undoList != null && undoList.affectsWorld(world)) { undoBatch.complete(); fastForwarded++; } } } if (cancelled > 0) { controller.info("Cancelled " + cancelled + " pending spells for " + mage.getName() + " prior to " + logType + " of world " + world.getName()); } if (fastForwarded > 0) { controller.info("Fast-forwarded " + fastForwarded + " pending undo tasks for " + mage.getName() + " prior to " + logType + " of world " + world.getName()); } } Collection<UndoList> pending = new ArrayList<>(controller.getPendingUndo()); int undone = 0; for (UndoList list : pending) { if (list.isScheduled() && list.affectsWorld(world)) { list.undoScheduled(true); undone++; } } if (undone > 0) { controller.info("Undid " + undone + " spells prior to " + logType + " of world " + world.getName()); } } @EventHandler public void onWorldSaveEvent(WorldSaveEvent event) { World world = event.getWorld(); MagicWorld magicWorld = controller.getMagicWorld(world.getName()); boolean undo = undoOnWorldSave; if (undo && magicWorld != null && !magicWorld.isCancelSpellsOnSave()) { undo = false; } if (undo) { undoPending(world, "save"); } Collection<Player> players = world.getPlayers(); for (Player player : players) { Mage mage = controller.getRegisteredMage(player); if (mage != null) { controller.saveMage(mage, true); } } } @EventHandler public void onWorldUnload(WorldUnloadEvent event) { World world = event.getWorld(); undoPending(world, "unload"); } @Override public void onChunkLoad(Chunk chunk) { controller.resumeAutomata(chunk); controller.restoreNPCs(chunk); } @EventHandler public void onChunkLoad(ChunkLoadEvent event) { Chunk chunk = event.getChunk(); if (!controller.isDataLoaded()) { CheckChunkTask.defer(controller.getPlugin(), this, chunk); } else { onChunkLoad(chunk); } } @EventHandler public void onWorldInit(WorldInitEvent e) { controller.checkAutomata(e.getWorld()); controller.checkNPCs(e.getWorld()); } @EventHandler public void onChunkUnload(ChunkUnloadEvent e) { controller.pauseAutomata(e.getChunk()); } }
package com.facebook.react.uimanager; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.common.ReactConstants; import com.facebook.react.uimanager.TouchTargetHelper.ViewTarget; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.react.uimanager.events.PointerEvent; import com.facebook.react.uimanager.events.PointerEventHelper; import com.facebook.react.uimanager.events.PointerEventHelper.EVENT; import com.facebook.react.uimanager.events.TouchEvent; import com.facebook.react.uimanager.events.TouchEventCoalescingKeyHelper; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * JSPointerDispatcher handles dispatching pointer events to JS from RootViews. If you implement * RootView you need to call handleMotionEvent from onTouchEvent, onInterceptTouchEvent, * onHoverEvent, onInterceptHoverEvent. It will correctly find the right view to handle the touch * and also dispatch the appropriate event to JS */ public class JSPointerDispatcher { private static final int UNSET_POINTER_ID = -1; private static final float ONMOVE_EPSILON = 0.1f; private static final String TAG = "POINTER EVENTS"; private final TouchEventCoalescingKeyHelper mTouchEventCoalescingKeyHelper = new TouchEventCoalescingKeyHelper(); private List<ViewTarget> mLastHitPath = Collections.emptyList(); private final float[] mLastEventCoordinates = new float[2]; private final float[] mTargetCoordinates = new float[2]; private int mChildHandlingNativeGesture = -1; private int mPrimaryPointerId = UNSET_POINTER_ID; private long mDownStartTime = TouchEvent.UNSET; private long mHoverInteractionKey = TouchEvent.UNSET; private final ViewGroup mRootViewGroup; // Set globally for hover interactions, referenced for coalescing hover events public JSPointerDispatcher(ViewGroup viewGroup) { mRootViewGroup = viewGroup; } public void onChildStartedNativeGesture( View childView, MotionEvent motionEvent, EventDispatcher eventDispatcher) { if (mChildHandlingNativeGesture != -1 || childView == null) { // This means we previously had another child start handling this native gesture and now a // different native parent of that child has decided to intercept the touch stream and handle // the gesture itself. Example where this can happen: HorizontalScrollView in a ScrollView. return; } List<ViewTarget> hitPath = TouchTargetHelper.findTargetPathAndCoordinatesForTouch( motionEvent.getX(), motionEvent.getY(), mRootViewGroup, mTargetCoordinates); dispatchCancelEvent(hitPath, motionEvent, eventDispatcher); mChildHandlingNativeGesture = childView.getId(); } public void onChildEndedNativeGesture() { // There should be only one child gesture at any given time. We can safely turn off the flag. mChildHandlingNativeGesture = -1; } private void onUp( int activeTargetTag, List<ViewTarget> hitPath, int surfaceId, MotionEvent motionEvent, EventDispatcher eventDispatcher) { if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) { // End of a "down" coalescing key mTouchEventCoalescingKeyHelper.removeCoalescingKey(mDownStartTime); mDownStartTime = TouchEvent.UNSET; } else { mTouchEventCoalescingKeyHelper.incrementCoalescingKey(mDownStartTime); } boolean supportsHover = PointerEventHelper.supportsHover(motionEvent); boolean listeningForUp = isAnyoneListeningForBubblingEvent(hitPath, EVENT.UP, EVENT.UP_CAPTURE); if (listeningForUp) { eventDispatcher.dispatchEvent( PointerEvent.obtain( PointerEventHelper.POINTER_UP, surfaceId, activeTargetTag, motionEvent, mTargetCoordinates, mPrimaryPointerId)); } if (!supportsHover) { boolean listeningForOut = isAnyoneListeningForBubblingEvent(hitPath, EVENT.OUT, EVENT.OUT_CAPTURE); if (listeningForOut) { eventDispatcher.dispatchEvent( PointerEvent.obtain( PointerEventHelper.POINTER_OUT, surfaceId, activeTargetTag, motionEvent, mTargetCoordinates, mPrimaryPointerId)); } List<ViewTarget> leaveViewTargets = filterByShouldDispatch(hitPath, EVENT.LEAVE, EVENT.LEAVE_CAPTURE, false); // target -> root dispatchEventForViewTargets( PointerEventHelper.POINTER_LEAVE, leaveViewTargets, eventDispatcher, surfaceId, motionEvent); } if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) { mPrimaryPointerId = UNSET_POINTER_ID; } return; } private void onDown( int activeTargetTag, List<ViewTarget> hitPath, int surfaceId, MotionEvent motionEvent, EventDispatcher eventDispatcher) { if (motionEvent.getActionMasked() == MotionEvent.ACTION_DOWN) { mPrimaryPointerId = motionEvent.getPointerId(0); mDownStartTime = motionEvent.getEventTime(); mTouchEventCoalescingKeyHelper.addCoalescingKey(mDownStartTime); } else { mTouchEventCoalescingKeyHelper.incrementCoalescingKey(mDownStartTime); } boolean supportsHover = PointerEventHelper.supportsHover(motionEvent); if (!supportsHover) { // Indirect OVER event dispatches before ENTER boolean listeningForOver = isAnyoneListeningForBubblingEvent(hitPath, EVENT.OVER, EVENT.OVER_CAPTURE); if (listeningForOver) { eventDispatcher.dispatchEvent( PointerEvent.obtain( PointerEventHelper.POINTER_OVER, surfaceId, activeTargetTag, motionEvent, mTargetCoordinates, mPrimaryPointerId)); } List<ViewTarget> enterViewTargets = filterByShouldDispatch(hitPath, EVENT.ENTER, EVENT.ENTER_CAPTURE, false); // Dispatch root -> target, we need to reverse order of enterViewTargets Collections.reverse(enterViewTargets); dispatchEventForViewTargets( PointerEventHelper.POINTER_ENTER, enterViewTargets, eventDispatcher, surfaceId, motionEvent); } boolean listeningForDown = isAnyoneListeningForBubblingEvent(hitPath, EVENT.DOWN, EVENT.DOWN_CAPTURE); if (listeningForDown) { eventDispatcher.dispatchEvent( PointerEvent.obtain( PointerEventHelper.POINTER_DOWN, surfaceId, activeTargetTag, motionEvent, mTargetCoordinates, mPrimaryPointerId)); } } public void handleMotionEvent(MotionEvent motionEvent, EventDispatcher eventDispatcher) { int action = motionEvent.getActionMasked(); // Ignore hover enter/exit because we determine this ourselves if (action == MotionEvent.ACTION_HOVER_EXIT || action == MotionEvent.ACTION_HOVER_ENTER) { return; } boolean supportsHover = PointerEventHelper.supportsHover(motionEvent); int surfaceId = UIManagerHelper.getSurfaceId(mRootViewGroup); // Only relevant for POINTER_UP/POINTER_DOWN actions, otherwise 0 int actionIndex = motionEvent.getActionIndex(); List<ViewTarget> hitPath = TouchTargetHelper.findTargetPathAndCoordinatesForTouch( motionEvent.getX(actionIndex), motionEvent.getY(actionIndex), mRootViewGroup, mTargetCoordinates); if (hitPath.isEmpty()) { return; } TouchTargetHelper.ViewTarget activeViewTarget = hitPath.get(0); int activeTargetTag = activeViewTarget.getViewId(); if (action == MotionEvent.ACTION_HOVER_MOVE) { onMove(motionEvent, eventDispatcher, surfaceId, hitPath); return; } // TODO(luwe) - Update this to properly handle native gesture handling for non-hover move events // If the touch was intercepted by a child, we've already sent a cancel event to JS for this // gesture, so we shouldn't send any more pointer events related to it. if (mChildHandlingNativeGesture != -1) { return; } switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: onDown(activeTargetTag, hitPath, surfaceId, motionEvent, eventDispatcher); break; case MotionEvent.ACTION_MOVE: // TODO(luwe) - converge this with ACTION_HOVER_MOVE int coalescingKey = mTouchEventCoalescingKeyHelper.getCoalescingKey(mDownStartTime); boolean listeningForMove = isAnyoneListeningForBubblingEvent(hitPath, EVENT.MOVE, EVENT.MOVE_CAPTURE); if (listeningForMove) { eventDispatcher.dispatchEvent( PointerEvent.obtain( PointerEventHelper.POINTER_MOVE, surfaceId, activeTargetTag, motionEvent, mTargetCoordinates, coalescingKey, mPrimaryPointerId)); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: onUp(activeTargetTag, hitPath, surfaceId, motionEvent, eventDispatcher); break; case MotionEvent.ACTION_CANCEL: dispatchCancelEvent(hitPath, motionEvent, eventDispatcher); break; default: FLog.w( ReactConstants.TAG, "Warning : Motion Event was ignored. Action=" + action + " Target=" + activeTargetTag + " Supports Hover=" + supportsHover); return; } } private static boolean isAnyoneListeningForBubblingEvent( List<ViewTarget> hitPath, EVENT event, EVENT captureEvent) { for (ViewTarget viewTarget : hitPath) { if (PointerEventHelper.isListening(viewTarget.getView(), event) || PointerEventHelper.isListening(viewTarget.getView(), captureEvent)) { return true; } } return false; } /** * Returns list of view targets that we should be dispatching events from * * @param viewTargets, ordered from target -> root * @param bubble, name of event that bubbles. Should only ever be enter or leave * @param capture, name of event that captures. Should only ever be enter or leave * @param forceDispatch, if true, all viewTargets should dispatch * @return list of viewTargets filtered from target -> root */ private static List<ViewTarget> filterByShouldDispatch( List<ViewTarget> viewTargets, EVENT bubble, EVENT capture, boolean forceDispatch) { List<ViewTarget> dispatchableViewTargets = new ArrayList<>(viewTargets); if (forceDispatch) { return dispatchableViewTargets; } boolean ancestorListening = false; // Start to filter which viewTargets may not need to dispatch an event for (int i = viewTargets.size() - 1; i >= 0; i ViewTarget viewTarget = viewTargets.get(i); View view = viewTarget.getView(); if (!ancestorListening && !PointerEventHelper.isListening(view, capture) && !PointerEventHelper.isListening(view, bubble)) { dispatchableViewTargets.remove(i); } else if (!ancestorListening && PointerEventHelper.isListening(view, capture)) { ancestorListening = true; } } return dispatchableViewTargets; } private void dispatchEventForViewTargets( String eventName, List<ViewTarget> viewTargets, EventDispatcher dispatcher, int surfaceId, MotionEvent motionEvent) { for (ViewTarget viewTarget : viewTargets) { int viewId = viewTarget.getViewId(); dispatcher.dispatchEvent( PointerEvent.obtain( eventName, surfaceId, viewId, motionEvent, mTargetCoordinates, mPrimaryPointerId)); } } // called on hover_move motion events only private void onMove( MotionEvent motionEvent, EventDispatcher eventDispatcher, int surfaceId, List<ViewTarget> hitPath) { int action = motionEvent.getActionMasked(); if (action != MotionEvent.ACTION_HOVER_MOVE) { return; } float x = motionEvent.getX(); float y = motionEvent.getY(); boolean qualifiedMove = (Math.abs(mLastEventCoordinates[0] - x) > ONMOVE_EPSILON || Math.abs(mLastEventCoordinates[1] - y) > ONMOVE_EPSILON); // Early exit if (!qualifiedMove) { return; } // Set the interaction key if unset, to be used as a coalescing key for hover interactions if (mHoverInteractionKey < 0) { mHoverInteractionKey = motionEvent.getEventTime(); mTouchEventCoalescingKeyHelper.addCoalescingKey(mHoverInteractionKey); } // If child is handling, eliminate target tags under handling child if (mChildHandlingNativeGesture > 0) { int index = 0; for (ViewTarget viewTarget : hitPath) { if (viewTarget.getViewId() == mChildHandlingNativeGesture) { hitPath.subList(0, index).clear(); break; } index++; } } int targetTag = hitPath.isEmpty() ? -1 : hitPath.get(0).getViewId(); // If targetTag is empty, we should bail? if (targetTag == -1) { return; } // hitState is list ordered from inner child -> parent tag // Traverse hitState back-to-front to find the first divergence with mLastHitState // FIXME: this may generate incorrect events when view collapsing changes the hierarchy boolean nonDivergentListeningToEnter = false; boolean nonDivergentListeningToLeave = false; int firstDivergentIndexFromBack = 0; while (firstDivergentIndexFromBack < Math.min(hitPath.size(), mLastHitPath.size()) && hitPath .get(hitPath.size() - 1 - firstDivergentIndexFromBack) .equals(mLastHitPath.get(mLastHitPath.size() - 1 - firstDivergentIndexFromBack))) { // Track if any non-diverging views are listening to enter/leave View nonDivergentViewTargetView = hitPath.get(hitPath.size() - 1 - firstDivergentIndexFromBack).getView(); if (!nonDivergentListeningToEnter && PointerEventHelper.isListening(nonDivergentViewTargetView, EVENT.ENTER_CAPTURE)) { nonDivergentListeningToEnter = true; } if (!nonDivergentListeningToLeave && PointerEventHelper.isListening(nonDivergentViewTargetView, EVENT.LEAVE_CAPTURE)) { nonDivergentListeningToLeave = true; } firstDivergentIndexFromBack++; } boolean hasDiverged = firstDivergentIndexFromBack < Math.max(hitPath.size(), mLastHitPath.size()); if (hasDiverged) { // If something has changed in either enter/exit, let's start a new coalescing key mTouchEventCoalescingKeyHelper.incrementCoalescingKey(mHoverInteractionKey); // Out, Leave events if (mLastHitPath.size() > 0) { int lastTargetTag = mLastHitPath.get(0).getViewId(); boolean listeningForOut = isAnyoneListeningForBubblingEvent(mLastHitPath, EVENT.OUT, EVENT.OUT_CAPTURE); if (listeningForOut) { eventDispatcher.dispatchEvent( PointerEvent.obtain( PointerEventHelper.POINTER_OUT, surfaceId, lastTargetTag, motionEvent, mTargetCoordinates, mPrimaryPointerId)); } // target -> root List<ViewTarget> leaveViewTargets = filterByShouldDispatch( mLastHitPath.subList(0, mLastHitPath.size() - firstDivergentIndexFromBack), EVENT.LEAVE, EVENT.LEAVE_CAPTURE, nonDivergentListeningToLeave); if (leaveViewTargets.size() > 0) { // We want to dispatch from target -> root, so no need to reverse dispatchEventForViewTargets( PointerEventHelper.POINTER_LEAVE, leaveViewTargets, eventDispatcher, surfaceId, motionEvent); } } boolean listeningForOver = isAnyoneListeningForBubblingEvent(hitPath, EVENT.OVER, EVENT.OVER_CAPTURE); if (listeningForOver) { eventDispatcher.dispatchEvent( PointerEvent.obtain( PointerEventHelper.POINTER_OVER, surfaceId, targetTag, motionEvent, mTargetCoordinates, mPrimaryPointerId)); } // target -> root List<ViewTarget> enterViewTargets = filterByShouldDispatch( hitPath.subList(0, hitPath.size() - firstDivergentIndexFromBack), EVENT.ENTER, EVENT.ENTER_CAPTURE, nonDivergentListeningToEnter); if (enterViewTargets.size() > 0) { // We want to iterate these from root -> target so we need to reverse Collections.reverse(enterViewTargets); dispatchEventForViewTargets( PointerEventHelper.POINTER_ENTER, enterViewTargets, eventDispatcher, surfaceId, motionEvent); } } int coalescingKey = mTouchEventCoalescingKeyHelper.getCoalescingKey(mHoverInteractionKey); boolean listeningToMove = isAnyoneListeningForBubblingEvent(hitPath, EVENT.MOVE, EVENT.MOVE_CAPTURE); if (listeningToMove) { eventDispatcher.dispatchEvent( PointerEvent.obtain( PointerEventHelper.POINTER_MOVE, surfaceId, targetTag, motionEvent, mTargetCoordinates, coalescingKey, mPrimaryPointerId)); } mLastHitPath = hitPath; mLastEventCoordinates[0] = x; mLastEventCoordinates[1] = y; } private void dispatchCancelEvent( List<ViewTarget> hitPath, MotionEvent motionEvent, EventDispatcher eventDispatcher) { // This means the gesture has already ended, via some other CANCEL or UP event. This is not // expected to happen very often as it would mean some child View has decided to intercept the // touch stream and start a native gesture only upon receiving the UP/CANCEL event. Assertions.assertCondition( mChildHandlingNativeGesture == -1, "Expected to not have already sent a cancel for this gesture"); int surfaceId = UIManagerHelper.getSurfaceId(mRootViewGroup); if (!hitPath.isEmpty()) { boolean listeningForCancel = isAnyoneListeningForBubblingEvent(hitPath, EVENT.CANCEL, EVENT.CANCEL_CAPTURE); if (listeningForCancel) { int targetTag = hitPath.get(0).getViewId(); Assertions.assertNotNull(eventDispatcher) .dispatchEvent( PointerEvent.obtain( PointerEventHelper.POINTER_CANCEL, surfaceId, targetTag, motionEvent, mTargetCoordinates, mPrimaryPointerId)); } List<ViewTarget> leaveViewTargets = filterByShouldDispatch(hitPath, EVENT.LEAVE, EVENT.LEAVE_CAPTURE, false); // dispatch from target -> root dispatchEventForViewTargets( PointerEventHelper.POINTER_LEAVE, leaveViewTargets, eventDispatcher, surfaceId, motionEvent); mTouchEventCoalescingKeyHelper.removeCoalescingKey(mDownStartTime); mDownStartTime = TouchEvent.UNSET; mPrimaryPointerId = UNSET_POINTER_ID; } } private void debugPrintHitPath(List<ViewTarget> hitPath) { StringBuilder builder = new StringBuilder("hitPath: "); for (ViewTarget viewTarget : hitPath) { builder.append(String.format("%d, ", viewTarget.getViewId())); } FLog.d(TAG, builder.toString()); } }
package wycliffeassociates.recordingapp; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.media.AudioFormat; import android.os.Bundle; import android.os.Environment; import android.text.InputType; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.UUID; public class CanvasScreen extends Activity { //Constants for WAV format private static final int RECORDER_BPP = 16; private static final String AUDIO_RECORDER_FILE_EXT_WAV = ".wav"; private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder"; private static final String AUDIO_RECORDER_TEMP_FILE = "record_temp.raw"; private static final int RECORDER_SAMPLERATE = 44100; private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO; private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT; private String recordedFilename = null; private WavRecorder recorder = null; final Context context = this; private String outputName = null; private CanvasView mainCanvas; private CanvasView minimap; private float userScale; private float xTranslation; private ScaleGestureDetector SGD; private GestureDetector gestureDetector; private boolean paused = false; private boolean isSaved = false; private boolean isPlaying = false; private boolean isRecording = false; private PreferencesManager pref; RotateAnimation anim; public boolean onTouchEvent(MotionEvent ev) { if(ev.getPointerCount() > 1.0){ SGD.onTouchEvent(ev); } else { //gestureDetector.onTouchEvent(ev); } return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); pref = new PreferencesManager(this); outputName = (String)pref.getPreferences("fileName")+"-" +pref.getPreferences("fileCounter").toString(); //recordedFilename = savedInstanceState.getString("outputFileName", null); //make sure the tablet does not go to sleep while on the recording screen getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.recording_screen); userScale = 1.f; GestureDetector.SimpleOnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { xTranslation += distanceX; mainCanvas.setXTranslation(xTranslation); mainCanvas.invalidate(); return true; } }; ScaleGestureDetector.SimpleOnScaleGestureListener scaleListener = new ScaleGestureDetector.SimpleOnScaleGestureListener(){ @Override public boolean onScale(ScaleGestureDetector detector) { userScale *= detector.getScaleFactor(); mainCanvas.setUserScale(userScale); return true; } }; //gestureDetector = new GestureDetector(this, gestureListener); SGD = new ScaleGestureDetector(this, scaleListener); mainCanvas = (CanvasView) findViewById(R.id.main_canvas); minimap = (CanvasView) findViewById(R.id.minimap); findViewById(R.id.volumeBar).setVisibility(View.VISIBLE); findViewById(R.id.volumeBar).setBackgroundResource(R.drawable.min); minimap.setIsMinimap(true); setButtonHandlers(); enableButtons(false); anim = new RotateAnimation(0f, 350f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); anim.setInterpolator(new LinearInterpolator()); anim.setRepeatCount(Animation.INFINITE); anim.setDuration(1500); } private void setButtonHandlers() { findViewById(R.id.btnRecording).setOnClickListener(btnClick); findViewById(R.id.btnStop).setOnClickListener(btnClick); findViewById(R.id.btnPlay).setOnClickListener(btnClick); findViewById(R.id.btnSave).setOnClickListener(btnClick); findViewById(R.id.btnPauseRecording).setOnClickListener(btnClick); findViewById(R.id.btnPause).setOnClickListener(btnClick); } private void enableButton(int id,boolean isEnable){ findViewById(id).setEnabled(isEnable); } private void enableButtons(boolean isRecording) { enableButton(R.id.btnRecording, !isRecording); enableButton(R.id.btnStop, true); enableButton(R.id.btnPlay, true); enableButton(R.id.btnSave, !isRecording); enableButton(R.id.btnPauseRecording, isRecording); enableButton(R.id.btnPause, true); } private void saveRecording(){ try { getSaveName(context); } catch (Exception e) { e.printStackTrace(); } } public boolean getSaveName(Context c){ final EditText toSave = new EditText(c); toSave.setInputType(InputType.TYPE_CLASS_TEXT); //pref.getPreferences("fileName"); toSave.setText(outputName, TextView.BufferType.EDITABLE); //prepare the dialog AlertDialog.Builder builder = new AlertDialog.Builder(c); builder.setTitle("Save as"); builder.setView(toSave); builder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setName(toSave.getText().toString()); //SAVE FILE HERE } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); return true; } public void setName(String newName){ outputName = newName; isSaved = true; recordedFilename = saveFile(outputName); } public String getName(){return outputName;} private void pauseRecording(){ paused = true; isRecording = false; findViewById(R.id.btnRecording).setVisibility(View.VISIBLE); findViewById(R.id.btnPauseRecording).setVisibility(View.INVISIBLE); findViewById(R.id.btnPauseRecording).setAnimation(null); stopService(new Intent(this, WavRecorder.class)); try { RecordingQueues.writingQueue.put(new RecordingMessage(null, true, false)); RecordingQueues.UIQueue.put(new RecordingMessage(null, true, false)); } catch (InterruptedException e) { e.printStackTrace(); } } private void pausePlayback(){ paused = true; findViewById(R.id.btnPause).setVisibility(View.INVISIBLE); findViewById(R.id.btnPlay).setVisibility(View.VISIBLE); WavPlayer.pause(); } private void startRecording(){ findViewById(R.id.volumeBar).setVisibility(View.VISIBLE); findViewById(R.id.btnPauseRecording).setVisibility(View.VISIBLE); findViewById(R.id.btnRecording).setVisibility(View.INVISIBLE); findViewById(R.id.btnPauseRecording).setAnimation(anim); if(!paused) { isRecording = true; isSaved = false; RecordingQueues.writingQueue.clear(); Intent intent = new Intent(this, WavFileWriter.class); intent.putExtra("audioFileName", getFilename()); startService(new Intent(this, WavRecorder.class)); System.out.println("Started the service"); startService(intent); mainCanvas.listenForRecording(this); } else { paused = false; isRecording = true; startService(new Intent(this, WavRecorder.class)); } } private void stopRecording() { if(!isRecording && !isPlaying){ return; } isRecording = false; if (isPlaying) { isPlaying = false; WavPlayer.stop(); } else { findViewById(R.id.volumeBar).setVisibility(View.INVISIBLE); findViewById(R.id.linearLayout10).setVisibility(View.VISIBLE); findViewById(R.id.toolbar).setVisibility(View.INVISIBLE); stopService(new Intent(this, WavRecorder.class)); try { RecordingQueues.UIQueue.put(new RecordingMessage(null, false, true)); RecordingQueues.writingQueue.put(new RecordingMessage(null, false, true)); } catch (InterruptedException e) { e.printStackTrace(); } try { Boolean done = RecordingQueues.doneWriting.take(); if (done.booleanValue()) { mainCanvas.loadWavFromFile(recordedFilename); final int base = -mainCanvas.getWidth()/8; mainCanvas.setXTranslation(base); mainCanvas.displayWaveform(10); mainCanvas.shouldDrawMaker(true); minimap.loadWavFromFile(recordedFilename); minimap.getMinimap(); minimap.invalidate(); } } catch (InterruptedException e) { e.printStackTrace(); } } } private void playRecording(){ findViewById(R.id.btnPlay).setVisibility(View.INVISIBLE); findViewById(R.id.btnPause).setVisibility(View.VISIBLE); Toast.makeText(getApplicationContext(), "Playing Audio", Toast.LENGTH_LONG).show(); WavPlayer.play(recordedFilename); isPlaying = true; final int base = -mainCanvas.getWidth()/8; mainCanvas.setXTranslation(base); mainCanvas.invalidate(); Thread playback = new Thread(new Runnable() { @Override public void run() { int translation = 0; double scaleFactor = (WavPlayer.getDuration() / 10000.0) * mainCanvas.getWidth(); while(WavPlayer.isPlaying()){ int location = WavPlayer.getLocation(); double locPercentage = (double)location/ (double)WavPlayer.getDuration(); translation = (int)(userScale*(int)(locPercentage * scaleFactor)); mainCanvas.resample(WavFileLoader.positionToWindowStart(location)); mainCanvas.setXTranslation(base+translation); minimap.setMiniMarkerLoc((float) (locPercentage * minimap.getWidth())); minimap.shouldDrawMiniMarker(true); runOnUiThread(new Runnable() { @Override public void run() { mainCanvas.invalidate(); minimap.invalidate(); } }); } } }); playback.start(); } @Override public void onBackPressed() { if(!isSaved) { exitdialog dialog = new exitdialog(this, R.style.Theme_UserDialog); if(isRecording){ dialog.setIsRecording(true); } dialog.show(); } else super.onBackPressed(); } private View.OnClickListener btnClick = new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("Pressed something"); switch(v.getId()){ case R.id.btnRecording:{ System.out.println("Pressed Record"); enableButtons(true); startRecording(); break; } case R.id.btnStop:{ enableButtons(false); stopRecording(); break; } case R.id.btnPlay:{ enableButtons(false); playRecording(); break; } case R.id.btnSave:{ saveRecording(); break; } case R.id.btnPause:{ enableButtons(true); pausePlayback(); break; } case R.id.btnPauseRecording:{ enableButtons(false); pauseRecording(); break; } } } }; /** * Names the currently recorded .wav file. * * @param name a string with the desired output filename. Should not include the .wav extension. * @return the absolute path of the file created */ public String saveFile(String name) { File dir = new File(pref.getPreferences("fileDirectory").toString()); // System.out.println(recordedFilename); File from = new File(recordedFilename); File to = new File(dir, name + AUDIO_RECORDER_FILE_EXT_WAV); Boolean out = from.renameTo(to); recordedFilename = to.getAbsolutePath(); pref.setPreferences("fileCounter", ((int)pref.getPreferences("fileCounter")+1)); return to.getAbsolutePath(); } /** * Retrieves the filename of the recorded audio file. * If the AudioRecorder folder does not exist, it is created. * * @return the absolute filepath to the recorded .wav file */ public String getFilename() { String filepath = Environment.getExternalStorageDirectory().getPath(); File file = new File(filepath, AUDIO_RECORDER_FOLDER); if (!file.exists()) { file.mkdirs(); } if(recordedFilename != null) return (file.getAbsolutePath() + "/" + recordedFilename); else { recordedFilename = (file.getAbsolutePath() + "/" + UUID.randomUUID().toString() + AUDIO_RECORDER_FILE_EXT_WAV); System.out.println("filename is " + recordedFilename); return recordedFilename; } } }
package com.bouye.gw2.sab.query; import com.bouye.gw2.sab.SABConstants; import com.bouye.gw2.sab.db.DBStorage; import java.lang.ref.SoftReference; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javafx.scene.image.Image; public enum ImageCache { /** * The unique instance of this class. */ INSTANCE; /** * The icon cache. * <br>The cache uses soft references that may be garbaged when the VM runs out of memory. */ private final Map<String, SoftReference<Image>> cache = Collections.synchronizedMap(new HashMap()); /** * Retrieves an image from the cache. * <br>If the image is not in the cache, an empty image is returned and the data of the image is loaded in the background. * @param url The URL of the image. * @return An {@code Image} instance, may be {@code null}. * @throws NullPointerException If {@code url} is {@code null}. */ public Image getImage(final String url) throws NullPointerException { return getImage(url, true); } /** * Retrieves an image from the cache. * @param url The URL of the image. * @param backgroundLoading If {@code true}, the image is loaded in background. * @return An {@code Image} instance, may be {@code null}. * @throws NullPointerException If {@code url} is {@code null}. */ public Image getImage(final String url, final boolean backgroundLoading) throws NullPointerException { Objects.requireNonNull(url); Image result = null; synchronized (cache) { SoftReference<Image> imageRef = cache.get(url); result = (imageRef == null) ? null : imageRef.get(); if (result == null && !cache.containsKey(url)) { try { // For local images, access the data base and ignore the background loading parameter. if (!url.startsWith("https://")) { // NOI18N. result = DBStorage.INSTANCE.getImageFromCache(url); } // Remote image. else if (!SABConstants.INSTANCE.isOffline()) { result = new Image(url, backgroundLoading); } else { // @todo Return a local (as embededed within the app) default non-null image when in offline mode. } imageRef = new SoftReference<>(result); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.WARNING, ex.getMessage(), ex); cache.put(url, null); } // Storing the key upon failure should prevent from further retrieval attempts. cache.put(url, imageRef); } } return result; } }
package gov.niarl.hisAppraiser.hibernate.util; import gov.niarl.hisAppraiser.hibernate.dao.AttestDao; import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; import gov.niarl.hisAppraiser.hibernate.domain.PCRManifest; import gov.niarl.hisAppraiser.hibernate.domain.PcrWhiteList; import gov.niarl.hisAppraiser.hibernate.util.ResultConverter.AttestResult; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.ws.rs.core.GenericEntity; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; public class AttestService { /** * validate PCR value of a request. Here is 4 cases, that is timeout, unknown, trusted and untrusted. * case1 (timeout): attest's time is greater than default timeout of attesting from OpenAttestation.properties. In generally, it is usually set as 60 seconds; * case2 (unknown): machine is not enrolled in attest server. Just check whether active machineCert is existed. * case3 (trusted): all hosts has attested and their pcrs has matched with PCRManifest table; * case4 (untrusted): all hosts has attested, but their pcrs cannot match with PCRManifest table. * @param attestRequest of intending to validate. * @return */ public static AttestRequest validatePCRReport(AttestRequest attestRequest,String machineNameInput){ String analysisOutput = ""; attestRequest.getAuditLog(); List<PcrWhiteList> whiteList = new ArrayList<PcrWhiteList>(); AttestDao dao = new AttestDao(); boolean flag = true; whiteList = dao.getPcrValue(machineNameInput); System.out.println(attestRequest.getId() +":" +attestRequest.getAuditLog().getId()); if(attestRequest.getAuditLog()!= null && attestRequest.getIsConsumedByPollingWS()){ AuditLog auditLog = attestRequest.getAuditLog(); HashMap<Integer,String> pcrs = new HashMap<Integer, String>(); pcrs = generatePcrsByAuditId(auditLog); if (whiteList!=null && whiteList.size() != 0){ for(int i=0; i<whiteList.size(); i++){ int pcrNumber = Integer.valueOf(whiteList.get(i).getPcrName()).intValue(); if(!whiteList.get(i).getPcrDigest().equalsIgnoreCase(pcrs.get(pcrNumber))){ analysisOutput += "PCR #" + whiteList.get(i).getPcrName() + " mismatch. "; flag = false; } } } else { analysisOutput += "No PCR in white list."; flag = false; } if (!flag){ attestRequest.setResult(ResultConverter.getIntFromResult(AttestResult.UN_TRUSTED)); } attestRequest = updateAnalysisResult(attestRequest, "VALIDATE_PCR", flag, "ANALYSIS_COMPLETED", analysisOutput.trim()); } return attestRequest; } /** * Receives the current content of field analysisResult of table * AttestRequest and updates it with received information * about the analysis: name, result, status and output. * @param prevAnalysisResult Previous content of field analysisResult * @param analysis The analysis to be added to analysisResult * @param result Result of the analysis to be added to analysisResult * @param status Status of the analysis to be added to analysisResult * @param output Output of the analysis to be added to analysisResult * @return The updated content of field analysisResult */ public static AttestRequest updateAnalysisResult(AttestRequest attestRequest, String analysis, boolean result, String status, String output) { String analysisResult = (attestRequest.getAnalysisResults() == null) ? "" : attestRequest.getAnalysisResults(); analysisResult += analysis + "|" + result + "|" + status + "|" + output.length() + "|" + output + ";"; attestRequest.setAnalysisResults(analysisResult); return attestRequest; } /* * compare request's PCR with PCRManifest in DB. * @Param needs to compare request. * At first convert request string from AttestRequest to List<Manifest>. * A request may contain several pcrs, so needs parse a List of PCRmanifest. * @Return null string if PCR not exists, else not null string * with different pcrs' number and separating them with '|' like this '2|20' */ public static String compareManifestPCR(List<PCRManifest> manifestPcrs){ GenericEntity<List<PCRManifest>> entity = new GenericEntity<List<PCRManifest>>(manifestPcrs) {}; AttestUtil.loadProp(); //manifestPcrs. WebResource resource = AttestUtil.getClient(AttestUtil.getManifestWebServicesUrl()); ClientResponse res = resource.path("/Validate").type("application/json"). accept("application/json").post(ClientResponse.class,entity); return res.getEntity(String.class); } /** * generate a hashMap of pcrs for a given auditlog. The hashMap key is pcr's number and value is pcr's value. * @param auditlog of interest * @return contain key-values of pcrs like {<'1','11111111111'>,<'2','111111111111111111111'>,...} */ public static HashMap<Integer,String> generatePcrsByAuditId(AuditLog auditlog){ HashMap<Integer,String> pcrs = new HashMap<Integer, String>(); pcrs.put(0, auditlog.getPcr0()); pcrs.put(1, auditlog.getPcr1()); pcrs.put(2, auditlog.getPcr2()); pcrs.put(3, auditlog.getPcr3()); pcrs.put(4, auditlog.getPcr4()); pcrs.put(5, auditlog.getPcr5()); pcrs.put(6, auditlog.getPcr6()); pcrs.put(7, auditlog.getPcr7()); pcrs.put(8, auditlog.getPcr8()); pcrs.put(9, auditlog.getPcr9()); pcrs.put(10, auditlog.getPcr10()); pcrs.put(11, auditlog.getPcr11()); pcrs.put(12, auditlog.getPcr12()); pcrs.put(13, auditlog.getPcr13()); pcrs.put(14, auditlog.getPcr14()); pcrs.put(15, auditlog.getPcr15()); pcrs.put(16, auditlog.getPcr16()); pcrs.put(17, auditlog.getPcr17()); pcrs.put(18, auditlog.getPcr18()); pcrs.put(19, auditlog.getPcr19()); pcrs.put(20, auditlog.getPcr20()); pcrs.put(21, auditlog.getPcr21()); pcrs.put(22, auditlog.getPcr22()); pcrs.put(23, auditlog.getPcr23()); return pcrs; } }
package com.option_u.stolpersteine.activities.cards; import java.util.ArrayList; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.option_u.stolpersteine.R; import com.option_u.stolpersteine.StolpersteineApplication; import com.option_u.stolpersteine.activities.description.DescriptionActivity; import com.option_u.stolpersteine.api.model.Stolperstein; public class CardsActivity extends Activity { private static final String EXTRA_NAME = "stolpersteine"; public static Intent createIntent(Context context, ArrayList<Stolperstein> stolpersteine) { Intent intent = new Intent(context, CardsActivity.class); intent.putParcelableArrayListExtra(EXTRA_NAME, stolpersteine); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); setContentView(R.layout.activity_info); final ListView listView = (ListView) findViewById(R.id.list); Intent intent = getIntent(); if (intent.hasExtra(EXTRA_NAME)) { ArrayList<Stolperstein> stolpersteine = intent.getParcelableArrayListExtra(EXTRA_NAME); Integer numStolpersteine = stolpersteine.size(); int resourceID = (numStolpersteine > 1) ? R.string.app_stolpersteine_plural : R.string.app_stolpersteine_singular; String title = getResources().getString(resourceID); actionBar.setTitle(Integer.toString(numStolpersteine) + " " + title); StolpersteineAdapter stolpersteinAdapter = new StolpersteineAdapter(this, stolpersteine); listView.setAdapter(stolpersteinAdapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Stolperstein stolperstein = (Stolperstein) listView.getItemAtPosition(position); String bioUrl = stolperstein.getPerson().getBiographyUri().toString(); startActivity(DescriptionActivity.createIntent(CardsActivity.this, bioUrl)); } }); } } @Override protected void onResume() { super.onResume(); StolpersteineApplication stolpersteineApplication = (StolpersteineApplication) getApplication(); stolpersteineApplication.trackView(this.getClass()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.info, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); } return true; } }
package edu.wustl.catissuecore.bizlogic; import java.util.HashSet; import java.util.List; import java.util.Set; import edu.wustl.catissuecore.dao.DAO; import edu.wustl.catissuecore.domain.AbstractDomainObject; import edu.wustl.catissuecore.domain.ClinicalReport; import edu.wustl.catissuecore.domain.CollectionProtocolEvent; import edu.wustl.catissuecore.domain.CollectionProtocolRegistration; import edu.wustl.catissuecore.domain.Participant; import edu.wustl.catissuecore.domain.ParticipantMedicalIdentifier; import edu.wustl.catissuecore.domain.Site; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.security.SecurityManager; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.security.exceptions.UserNotAuthorizedException; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; /** * UserHDAO is used to add user information into the database using Hibernate. * @author kapil_kaveeshwar */ public class SpecimenCollectionGroupBizLogic extends DefaultBizLogic { /** * Saves the user object in the database. * @param obj The user object to be saved. * @param session The session in which the object is saved. * @throws DAOException */ protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { SpecimenCollectionGroup specimenCollectionGroup = (SpecimenCollectionGroup) obj; Object siteObj = dao.retrieve(Site.class.getName(), specimenCollectionGroup.getSite().getSystemIdentifier()); if (siteObj != null) { // check for closed Site checkStatus(dao,specimenCollectionGroup.getSite(), "Site" ); specimenCollectionGroup.setSite((Site)siteObj); } Object collectionProtocolEventObj = dao.retrieve(CollectionProtocolEvent.class.getName(), specimenCollectionGroup.getCollectionProtocolEvent().getSystemIdentifier()); if(collectionProtocolEventObj!=null) { CollectionProtocolEvent cpe = (CollectionProtocolEvent)collectionProtocolEventObj; //check for closed CollectionProtocol checkStatus(dao, cpe.getCollectionProtocol(), "Collection Protocol" ); specimenCollectionGroup.setCollectionProtocolEvent(cpe); } setClinicalReport(dao, specimenCollectionGroup); setCollectionProtocolRegistration(dao, specimenCollectionGroup, null); dao.insert(specimenCollectionGroup,sessionDataBean, true, true); if(specimenCollectionGroup.getClinicalReport()!=null) dao.insert(specimenCollectionGroup.getClinicalReport(),sessionDataBean, true, true); try { SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null,getProtectionObjects(specimenCollectionGroup),getDynamicGroups(specimenCollectionGroup)); } catch (SMException e) { Logger.out.error("Exception in Authorization: "+e.getMessage(),e); } } public Set getProtectionObjects(AbstractDomainObject obj) { Set protectionObjects = new HashSet(); SpecimenCollectionGroup specimenCollectionGroup = (SpecimenCollectionGroup) obj; protectionObjects.add(specimenCollectionGroup); Participant participant = null; // //Case of registering Participant on its participant ID // if(specimenCollectionGroup.getClinicalReport()!=null) // protectionObjects.add(specimenCollectionGroup.getClinicalReport()); Logger.out.debug(protectionObjects.toString()); return protectionObjects; } public String[] getDynamicGroups(AbstractDomainObject obj) { String[] dynamicGroups=null; SpecimenCollectionGroup specimenCollectionGroup = (SpecimenCollectionGroup) obj; dynamicGroups = new String[1]; try { dynamicGroups[0] = SecurityManager.getInstance(this.getClass()).getProtectionGroupByName(specimenCollectionGroup.getCollectionProtocolRegistration(),Constants.getCollectionProtocolPGName(null)); } catch (SMException e) { Logger.out.error("Exception in Authorization: "+e.getMessage(),e); } Logger.out.debug("Dynamic Group name: "+dynamicGroups[0]); return dynamicGroups; } /** * Updates the persistent object in the database. * @param obj The object to be updated. * @param session The session in which the object is saved. * @throws DAOException */ protected void update(DAO dao, Object obj, Object oldObj,SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { SpecimenCollectionGroup specimenCollectionGroup = (SpecimenCollectionGroup) obj; SpecimenCollectionGroup oldspecimenCollectionGroup = (SpecimenCollectionGroup) oldObj; // Check for different closed site if(!specimenCollectionGroup.getSite().getSystemIdentifier().equals( oldspecimenCollectionGroup.getSite().getSystemIdentifier())) { checkStatus(dao,specimenCollectionGroup.getSite(), "Site" ); } // -- check for closed CollectionProtocol List list = dao.retrieve(CollectionProtocolEvent.class.getName(), Constants.SYSTEM_IDENTIFIER, specimenCollectionGroup.getCollectionProtocolEvent().getSystemIdentifier()); if(!list.isEmpty()) { // check for closed CollectionProtocol CollectionProtocolEvent cpe = (CollectionProtocolEvent)list.get(0); if(!cpe.getCollectionProtocol().getSystemIdentifier().equals(oldspecimenCollectionGroup.getCollectionProtocolEvent().getCollectionProtocol().getSystemIdentifier())) checkStatus(dao,cpe.getCollectionProtocol(), "Collection Protocol" ); specimenCollectionGroup.setCollectionProtocolEvent((CollectionProtocolEvent)list.get(0)); } setCollectionProtocolRegistration(dao, specimenCollectionGroup, oldspecimenCollectionGroup); dao.update(specimenCollectionGroup, sessionDataBean, true, true, false); dao.update(specimenCollectionGroup.getClinicalReport(), sessionDataBean, true, true, false); //Audit. dao.audit(obj, oldObj, sessionDataBean, true); SpecimenCollectionGroup oldSpecimenCollectionGroup = (SpecimenCollectionGroup) oldObj; dao.audit(specimenCollectionGroup.getClinicalReport(), oldspecimenCollectionGroup.getClinicalReport(), sessionDataBean, true); //Disable the related specimens to this specimen group Logger.out.debug("specimenCollectionGroup.getActivityStatus() "+specimenCollectionGroup.getActivityStatus()); if(specimenCollectionGroup.getActivityStatus().equals(Constants.ACTIVITY_STATUS_DISABLED)) { Logger.out.debug("specimenCollectionGroup.getActivityStatus() "+specimenCollectionGroup.getActivityStatus()); Long specimenCollectionGroupIDArr[] = {specimenCollectionGroup.getSystemIdentifier()}; NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic)BizLogicFactory.getBizLogic(Constants.NEW_SPECIMEN_FORM_ID); bizLogic.disableRelatedObjectsForSpecimenCollectionGroup(dao,specimenCollectionGroupIDArr); } } private void setCollectionProtocolRegistration(DAO dao, SpecimenCollectionGroup specimenCollectionGroup,SpecimenCollectionGroup oldSpecimenCollectionGroup) throws DAOException { String sourceObjectName = CollectionProtocolRegistration.class.getName(); String[] selectColumnName = null; String[] whereColumnName = new String[2]; String[] whereColumnCondition = {"=","="}; Object[] whereColumnValue = new Object[2]; String joinCondition = Constants.AND_JOIN_CONDITION; whereColumnName[0]="collectionProtocol."+Constants.SYSTEM_IDENTIFIER; whereColumnValue[0]=specimenCollectionGroup.getCollectionProtocolRegistration().getCollectionProtocol().getSystemIdentifier(); if(specimenCollectionGroup.getCollectionProtocolRegistration().getParticipant()!=null) { // check for closed Participant Participant participantObject = (Participant)specimenCollectionGroup.getCollectionProtocolRegistration().getParticipant() ; if(oldSpecimenCollectionGroup!=null) { Participant participantObjectOld =oldSpecimenCollectionGroup.getCollectionProtocolRegistration().getParticipant(); if(!participantObject.getSystemIdentifier().equals(participantObjectOld.getSystemIdentifier())) checkStatus(dao,participantObject, "Participant" ); } else checkStatus(dao,participantObject, "Participant" ); whereColumnName[1]="participant."+Constants.SYSTEM_IDENTIFIER; whereColumnValue[1]=specimenCollectionGroup.getCollectionProtocolRegistration().getParticipant().getSystemIdentifier(); } else { whereColumnName[1] = "protocolParticipantIdentifier"; whereColumnValue[1] = specimenCollectionGroup.getCollectionProtocolRegistration().getProtocolParticipantIdentifier(); System.out.println("Value returned:"+whereColumnValue[1]); } List list = dao.retrieve( sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); if(!list.isEmpty()) { //check for closed CollectionProtocolRegistration CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration)list.get(0); if(oldSpecimenCollectionGroup!=null) { CollectionProtocolRegistration collectionProtocolRegistrationOld =oldSpecimenCollectionGroup.getCollectionProtocolRegistration(); if(!collectionProtocolRegistration.getSystemIdentifier().equals(collectionProtocolRegistrationOld.getSystemIdentifier())) checkStatus(dao,collectionProtocolRegistration, "Collection Protocol Registration" ); } else checkStatus(dao,collectionProtocolRegistration, "Collection Protocol Registration" ); specimenCollectionGroup.setCollectionProtocolRegistration((CollectionProtocolRegistration)list.get(0)); } } private void setClinicalReport(DAO dao, SpecimenCollectionGroup specimenCollectionGroup) throws DAOException { ClinicalReport clinicalReport = specimenCollectionGroup.getClinicalReport(); ParticipantMedicalIdentifier participantMedicalIdentifier = clinicalReport.getParticipantMedicalIdentifier(); if(participantMedicalIdentifier!=null) { List list = dao.retrieve(ParticipantMedicalIdentifier.class.getName(), Constants.SYSTEM_IDENTIFIER, participantMedicalIdentifier.getSystemIdentifier()); if(!list.isEmpty()) { specimenCollectionGroup.getClinicalReport().setParticipantMedicalIdentifier((ParticipantMedicalIdentifier)list.get(0)); } } } public void disableRelatedObjects(DAO dao, Long collProtRegIDArr[])throws DAOException { List listOfSubElement = super.disableObjects(dao, SpecimenCollectionGroup.class, "collectionProtocolRegistration", "CATISSUE_SPECIMEN_COLLECTION_GROUP", "COLLECTION_PROTOCOL_REGISTRATION_ID", collProtRegIDArr); if(!listOfSubElement.isEmpty()) { NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic)BizLogicFactory.getBizLogic(Constants.NEW_SPECIMEN_FORM_ID); bizLogic.disableRelatedObjectsForSpecimenCollectionGroup(dao,Utility.toLongArray(listOfSubElement)); } } /** * @param dao * @param privilegeName * @param objectIds * @param assignToUser * @param roleId * @param longs * @throws DAOException * @throws SMException */ public void assignPrivilegeToRelatedObjects(DAO dao, String privilegeName, Long[] objectIds, Long userId, String roleId, boolean assignToUser) throws SMException, DAOException { List listOfSubElement = super.getRelatedObjects(dao, SpecimenCollectionGroup.class,"collectionProtocolRegistration", objectIds); if(!listOfSubElement.isEmpty()) { super.setPrivilege(dao,privilegeName,SpecimenCollectionGroup.class,Utility.toLongArray(listOfSubElement),userId, roleId, assignToUser); NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic)BizLogicFactory.getBizLogic(Constants.NEW_SPECIMEN_FORM_ID); bizLogic.assignPrivilegeToRelatedObjectsForSCG(dao,privilegeName,Utility.toLongArray(listOfSubElement),userId, roleId, assignToUser); } } /** * @see AbstractBizLogic#setPrivilege(DAO, String, Class, Long[], Long, String, boolean) */ public void setPrivilege(DAO dao, String privilegeName, Class objectType, Long[] objectIds, Long userId, String roleId, boolean assignToUser) throws SMException, DAOException { super.setPrivilege(dao,privilegeName,objectType,objectIds,userId, roleId, assignToUser); NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic)BizLogicFactory.getBizLogic(Constants.NEW_SPECIMEN_FORM_ID); bizLogic.assignPrivilegeToRelatedObjectsForSCG(dao,privilegeName,objectIds,userId, roleId, assignToUser); } }
package edu.wustl.catissuecore.bizlogic; import java.io.Serializable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import net.sf.ehcache.CacheException; import edu.wustl.catissuecore.domain.CheckInCheckOutEventParameter; import edu.wustl.catissuecore.domain.CollectionEventParameters; import edu.wustl.catissuecore.domain.DisposalEventParameters; import edu.wustl.catissuecore.domain.EmbeddedEventParameters; import edu.wustl.catissuecore.domain.FixedEventParameters; import edu.wustl.catissuecore.domain.FrozenEventParameters; import edu.wustl.catissuecore.domain.ReceivedEventParameters; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenEventParameters; import edu.wustl.catissuecore.domain.StorageContainer; import edu.wustl.catissuecore.domain.TissueSpecimenReviewEventParameters; import edu.wustl.catissuecore.domain.TransferEventParameters; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.ApiSearchUtil; import edu.wustl.catissuecore.util.CatissueCoreCacheManager; import edu.wustl.catissuecore.util.StorageContainerUtil; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.DefaultBizLogic; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.dao.DAO; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.security.exceptions.UserNotAuthorizedException; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.Validator; /** * @author mandar_deshmukh</p> * This class contains the Business Logic for all EventParameters Classes. * This will be the class which will be used for data transactions of the EventParameters. */ public class SpecimenEventParametersBizLogic extends DefaultBizLogic { /** * Saves the FrozenEventParameters object in the database. * @param obj The FrozenEventParameters object to be saved. * @param session The session in which the object is saved. * @throws DAOException */ protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { try { SpecimenEventParameters specimenEventParametersObject = (SpecimenEventParameters) obj; List list = dao.retrieve(User.class.getName(), Constants.SYSTEM_IDENTIFIER, specimenEventParametersObject.getUser().getId()); if (!list.isEmpty()) { User user = (User) list.get(0); // check for closed User checkStatus(dao, user, "User"); specimenEventParametersObject.setUser(user); } Specimen specimen = (Specimen) dao.retrieve(Specimen.class.getName(), specimenEventParametersObject.getSpecimen().getId()); // check for closed Specimen checkStatus(dao, specimen, "Specimen"); if (specimen != null) { specimenEventParametersObject.setSpecimen(specimen); if (specimenEventParametersObject instanceof TransferEventParameters) { TransferEventParameters transferEventParameters = (TransferEventParameters) specimenEventParametersObject; /*specimen.setPositionDimensionOne(transferEventParameters.getToPositionDimensionOne()); specimen.setPositionDimensionTwo(transferEventParameters.getToPositionDimensionTwo());*/ // StorageContainer storageContainer = (StorageContainer) dao.retrieve(StorageContainer.class.getName(), transferEventParameters // .getToStorageContainer().getId()); StorageContainer storageContainerObj = new StorageContainer(); storageContainerObj.setId(transferEventParameters.getToStorageContainer().getId()); String sourceObjectName = StorageContainer.class.getName(); String[] selectColumnName = {"name"}; String[] whereColumnName = {"id"}; //"storageContainer."+Constants.SYSTEM_IDENTIFIER String[] whereColumnCondition = {"="}; Object[] whereColumnValue = {transferEventParameters.getToStorageContainer().getId()}; String joinCondition = null; List stNamelist = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); if (!stNamelist.isEmpty()) { storageContainerObj.setName((String) stNamelist.get(0)); } // check for closed StorageContainer checkStatus(dao, storageContainerObj, "Storage Container"); StorageContainerBizLogic storageContainerBizLogic = (StorageContainerBizLogic) BizLogicFactory.getInstance().getBizLogic( Constants.STORAGE_CONTAINER_FORM_ID); storageContainerBizLogic.checkContainer(dao, storageContainerObj.getId().toString(), transferEventParameters .getToPositionDimensionOne().toString(), transferEventParameters.getToPositionDimensionTwo().toString(), sessionDataBean); // if (storageContainer != null) // NewSpecimenBizLogic newSpecimenBizLogic = (NewSpecimenBizLogic) BizLogicFactory.getInstance().getBizLogic( // Constants.NEW_SPECIMEN_FORM_ID); //newSpecimenBizLogic.chkContainerValidForSpecimen(storageContainer, specimen); specimen.setStorageContainer(storageContainerObj); specimen.setPositionDimensionOne(transferEventParameters.getToPositionDimensionOne()); specimen.setPositionDimensionTwo(transferEventParameters.getToPositionDimensionTwo()); dao.update(specimen, sessionDataBean, true, true, false); } if (specimenEventParametersObject instanceof DisposalEventParameters) { DisposalEventParameters disposalEventParameters = (DisposalEventParameters) specimenEventParametersObject; if (disposalEventParameters.getActivityStatus().equals(Constants.ACTIVITY_STATUS_DISABLED)) { disableSubSpecimens(dao, specimen.getId().toString()); } Map disabledCont = new TreeMap(); if (specimen.getStorageContainer() != null) { addEntriesInDisabledMap(specimen, specimen.getStorageContainer(), disabledCont); } specimen.setPositionDimensionOne(null); specimen.setPositionDimensionTwo(null); specimen.setStorageContainer(null); specimen.setAvailable(new Boolean(false)); specimen.setActivityStatus(disposalEventParameters.getActivityStatus()); dao.update(specimen, sessionDataBean, true, true, false); try { CatissueCoreCacheManager catissueCoreCacheManager = CatissueCoreCacheManager.getInstance(); catissueCoreCacheManager.addObjectToCache(Constants.MAP_OF_CONTAINER_FOR_DISABLED_SPECIEN, (Serializable) disabledCont); } catch (CacheException e) { } } } dao.insert(specimenEventParametersObject, sessionDataBean, true, true); } catch (SMException e) { throw handleSMException(e); } } private void addEntriesInDisabledMap(Specimen specimen, StorageContainer container, Map disabledConts) { String contNameKey = "StorageContName"; String contIdKey = "StorageContIdKey"; String pos1Key = "pos1"; String pos2Key = "pos2"; Map containerDetails = new TreeMap(); containerDetails.put(contNameKey, container.getName()); containerDetails.put(contIdKey, container.getId()); containerDetails.put(pos1Key, specimen.getPositionDimensionOne()); containerDetails.put(pos2Key, specimen.getPositionDimensionTwo()); disabledConts.put(container.getId().toString(), containerDetails); } public void postInsert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { SpecimenEventParameters specimenEventParametersObject = (SpecimenEventParameters) obj; try { if (specimenEventParametersObject instanceof TransferEventParameters) { TransferEventParameters transferEventParameters = (TransferEventParameters) specimenEventParametersObject; Map containerMap = StorageContainerUtil.getContainerMapFromCache(); if (transferEventParameters.getFromStorageContainer() != null) { StorageContainer storageContainerFrom = (StorageContainer) dao.retrieve(StorageContainer.class.getName(), transferEventParameters .getFromStorageContainer().getId()); StorageContainerUtil.insertSinglePositionInContainerMap(storageContainerFrom, containerMap, transferEventParameters .getFromPositionDimensionOne().intValue(), transferEventParameters.getFromPositionDimensionTwo().intValue()); } StorageContainer storageContainerTo = (StorageContainer) dao.retrieve(StorageContainer.class.getName(), transferEventParameters .getToStorageContainer().getId()); StorageContainerUtil.deleteSinglePositionInContainerMap(storageContainerTo, containerMap, transferEventParameters .getToPositionDimensionOne().intValue(), transferEventParameters.getToPositionDimensionTwo().intValue()); } if (specimenEventParametersObject instanceof DisposalEventParameters) { DisposalEventParameters disposalEventParameters = (DisposalEventParameters) specimenEventParametersObject; Map containerMap = StorageContainerUtil.getContainerMapFromCache(); if (disposalEventParameters.getSpecimen() != null) { Map disabledConts = getContForDisabledSpecimenFromCache(); Set keySet = disabledConts.keySet(); Iterator itr = keySet.iterator(); while (itr.hasNext()) { String Id = (String) itr.next(); Map disabledContDetails = (TreeMap) disabledConts.get(Id); String contNameKey = "StorageContName"; //String contIdKey = "StorageContIdKey"; String pos1Key = "pos1"; String pos2Key = "pos2"; StorageContainer cont = new StorageContainer(); cont.setId(new Long(Id)); cont.setName((String) disabledContDetails.get(contNameKey)); int x = ((Integer) disabledContDetails.get(pos1Key)).intValue(); int y = ((Integer) disabledContDetails.get(pos2Key)).intValue(); StorageContainerUtil.insertSinglePositionInContainerMap(cont, containerMap, x, y); } /*StorageContainer storageContainer = disposalEventParameters.getSpecimen().getStorageContainer(); if (storageContainer != null) { storageContainerBizLogic.insertSinglePositionInContainerMap(storageContainer, containerMap, storageContainer .getPositionDimensionOne().intValue(), storageContainer.getPositionDimensionTwo().intValue()); }*/ } } } catch (Exception e) { } } /** * Updates the persistent object in the database. * @param obj The object to be updated. * @param session The session in which the object is saved. * @throws DAOException */ protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { SpecimenEventParameters specimenEventParameters = (SpecimenEventParameters) obj; SpecimenEventParameters oldSpecimenEventParameters = (SpecimenEventParameters) oldObj; //Check for Closed Specimen //checkStatus(dao, specimenEventParameters.getSpecimen(), "Specimen" ); // Check for different User if (!specimenEventParameters.getUser().getId().equals(oldSpecimenEventParameters.getUser().getId())) { checkStatus(dao, specimenEventParameters.getUser(), "User"); } // check for transfer event // if (specimenEventParameters.getSpecimen() != null) // if (specimenEventParameters instanceof TransferEventParameters) // TransferEventParameters transferEventParameters = (TransferEventParameters)specimenEventParameters; // TransferEventParameters oldTransferEventParameters = (TransferEventParameters)oldSpecimenEventParameters; // StorageContainer storageContainer = transferEventParameters.getToStorageContainer(); // StorageContainer oldstorageContainer = oldTransferEventParameters.getToStorageContainer(); // Logger.out.debug("StorageContainer match : " + storageContainer.equals(oldstorageContainer ) ); // // check for closed StorageContainer // if(!storageContainer.getId().equals(oldstorageContainer.getId()) ) // checkStatus(dao, storageContainer, "Storage Container" ); //Update registration dao.update(specimenEventParameters, sessionDataBean, true, true, false); //Audit. dao.audit(obj, oldObj, sessionDataBean, true); } /** * Overriding the parent class's method to validate the enumerated attribute values */ protected boolean validate(Object obj, DAO dao, String operation) throws DAOException { SpecimenEventParameters eventParameter = (SpecimenEventParameters) obj; ApiSearchUtil.setEventParametersDefault(eventParameter); //End:- Change for API Search switch (Utility.getEventParametersFormId(eventParameter)) { case Constants.CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID : String storageStatus = ((CheckInCheckOutEventParameter) eventParameter).getStorageStatus(); if (!Validator.isEnumeratedValue(Constants.STORAGE_STATUS_ARRAY, storageStatus)) { throw new DAOException(ApplicationProperties.getValue("events.storageStatus.errMsg")); } break; case Constants.COLLECTION_EVENT_PARAMETERS_FORM_ID : String procedure = ((CollectionEventParameters) eventParameter).getCollectionProcedure(); List procedureList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null); if (!Validator.isEnumeratedValue(procedureList, procedure)) { throw new DAOException(ApplicationProperties.getValue("events.collectionProcedure.errMsg")); } String container = ((CollectionEventParameters) eventParameter).getContainer(); List containerList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null); if (!Validator.isEnumeratedOrNullValue(containerList, container)) { throw new DAOException(ApplicationProperties.getValue("events.container.errMsg")); } break; case Constants.EMBEDDED_EVENT_PARAMETERS_FORM_ID : String embeddingMedium = ((EmbeddedEventParameters) eventParameter).getEmbeddingMedium(); List embeddingMediumList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_EMBEDDING_MEDIUM, null); if (!Validator.isEnumeratedValue(embeddingMediumList, embeddingMedium)) { throw new DAOException(ApplicationProperties.getValue("events.embeddingMedium.errMsg")); } break; case Constants.FIXED_EVENT_PARAMETERS_FORM_ID : String fixationType = ((FixedEventParameters) eventParameter).getFixationType(); List fixationTypeList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_FIXATION_TYPE, null); if (!Validator.isEnumeratedValue(fixationTypeList, fixationType)) { throw new DAOException(ApplicationProperties.getValue("events.fixationType.errMsg")); } break; case Constants.FROZEN_EVENT_PARAMETERS_FORM_ID : String method = ((FrozenEventParameters) eventParameter).getMethod(); List methodList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_METHOD, null); if (!Validator.isEnumeratedValue(methodList, method)) { throw new DAOException(ApplicationProperties.getValue("events.method.errMsg")); } break; case Constants.RECEIVED_EVENT_PARAMETERS_FORM_ID : String quality = ((ReceivedEventParameters) eventParameter).getReceivedQuality(); List qualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null); if (!Validator.isEnumeratedValue(qualityList, quality)) { throw new DAOException(ApplicationProperties.getValue("events.receivedQuality.errMsg")); } break; case Constants.TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID : String histQuality = ((TissueSpecimenReviewEventParameters) eventParameter).getHistologicalQuality(); List histologicalQualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_HISTOLOGICAL_QUALITY, null); if (!Validator.isEnumeratedOrNullValue(histologicalQualityList, histQuality)) { throw new DAOException(ApplicationProperties.getValue("events.histologicalQuality.errMsg")); } break; case Constants.TRANSFER_EVENT_PARAMETERS_FORM_ID : if (Constants.EDIT.equals(operation)) { //validateTransferEventParameters(eventParameter); } break; } return true; } private void validateTransferEventParameters(SpecimenEventParameters eventParameter) throws DAOException { TransferEventParameters parameter = (TransferEventParameters) eventParameter; List list = (List) retrieve(TransferEventParameters.class.getName(), Constants.SYSTEM_IDENTIFIER, parameter.getId()); if (list.size() != 0) { TransferEventParameters parameterCopy = (TransferEventParameters) list.get(0); String positionDimensionOne = parameterCopy.getToPositionDimensionOne().toString(); String positionDimensionTwo = parameterCopy.getToPositionDimensionTwo().toString(); String storageContainer = parameterCopy.getToStorageContainer().getId().toString(); if (!positionDimensionOne.equals(parameter.getToPositionDimensionOne().toString()) || !positionDimensionTwo.equals(parameter.getToPositionDimensionTwo().toString()) || !storageContainer.equals(parameter.getToStorageContainer().getId().toString())) { throw new DAOException(ApplicationProperties.getValue("events.toPosition.errMsg")); } } } private void setDisableToSubSpecimen(Specimen specimen) { if (specimen != null) { Iterator iterator = specimen.getChildrenSpecimen().iterator(); while (iterator.hasNext()) { Specimen childSpecimen = (Specimen) iterator.next(); childSpecimen.setActivityStatus(Constants.ACTIVITY_STATUS_DISABLED); setDisableToSubSpecimen(childSpecimen); } } } private void disableSubSpecimens(DAO dao, String speID) throws DAOException { String sourceObjectName = Specimen.class.getName(); String[] selectColumnName = {Constants.SYSTEM_IDENTIFIER}; String[] whereColumnName = {"parentSpecimen", Constants.ACTIVITY_STATUS}; String[] whereColumnCondition = {"=", "!="}; String[] whereColumnValue = {speID, Constants.ACTIVITY_STATUS_DISABLED}; String joinCondition = Constants.AND_JOIN_CONDITION; List listOfSpecimenIDs = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); listOfSpecimenIDs = Utility.removeNull(listOfSpecimenIDs); //getRelatedObjects(dao, Specimen.class, "parentSpecimen", speIDArr); if (!listOfSpecimenIDs.isEmpty()) { throw new DAOException(ApplicationProperties.getValue("errors.specimen.contains.subspecimen")); } else { return; } } public List getRelatedObjects(DAO dao, Class sourceClass, String[] whereColumnName, String[] whereColumnValue, String[] whereColumnCondition) throws DAOException { String sourceObjectName = sourceClass.getName(); String joinCondition = Constants.AND_JOIN_CONDITION; String selectColumnName[] = {Constants.SYSTEM_IDENTIFIER}; List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); list = Utility.removeNull(list); return list; } public Map getContForDisabledSpecimenFromCache() throws Exception { // TODO if map is null // TODO move all code to common utility // getting instance of catissueCoreCacheManager and getting participantMap from cache CatissueCoreCacheManager catissueCoreCacheManager = CatissueCoreCacheManager.getInstance(); Map disabledconts = (TreeMap) catissueCoreCacheManager.getObjectFromCache(Constants.MAP_OF_CONTAINER_FOR_DISABLED_SPECIEN); return disabledconts; } }
// This file is part of MuPDF. // MuPDF is free software: you can redistribute it and/or modify it under the // any later version. // MuPDF is distributed in the hope that it will be useful, but WITHOUT ANY // details. // Alternative licensing terms are available from the licensor. // Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, // CA 94945, U.S.A., +1(415)492-9861, for further information. package com.artifex.mupdf.fitz; public class Link { public Rect bounds; public String uri; public Link(Rect bounds, String uri) { this.bounds = bounds; this.uri = uri; } public boolean isExternal() { char c = uri.charAt(0); if (!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z')) return false; for (int i = 1; i < uri.length(); i++) { c = uri.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.') continue; else return c == ':'; } return false; } public String toString() { return "Link(bounds="+bounds+",uri="+uri+")"; } }
package sg.ncl.adapter.deterlab; import org.springframework.boot.context.properties.ConfigurationProperties; import static sg.ncl.adapter.deterlab.ConnectionProperties.PREFIX; @ConfigurationProperties(prefix = PREFIX) public class ConnectionProperties { public static final String PREFIX = "ncl.deterlab.adapter"; private String ip; private String port; private String bossUrl; private String userUrl; private String mode; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String login() { return "http://" + ip + ":" + port + "/login"; } public String getJoinProjectNewUsers() { return "http://" + ip + ":" + port + "/joinProjectNewUsers"; } public String getJoinProject() { return "http://" + ip + ":" + port + "/joinProject"; } public String getApplyProjectNewUsers() { return "http://" + ip + ":" + port + "/applyProjectNewUsers"; } public String getCreateExperiment() { return "http://" + ip + ":" + port + "/createExperiment"; } public String startExperiment() { return "http://" + ip + ":" + port + "/startExperiment"; } public String stopExperiment() { return "http://" + ip + ":" + port + "/stopExperiment"; } public String deleteExperiment() { return "http://" + ip + ":" + port + "/deleteExperiment"; } public String getUpdateCredentials() { return "http://" + ip + ":" + port + "/changePassword"; } public String getApproveJoinRequest() { return "http://" + ip + ":" + port + "/approveJoinRequest"; } public String getRejectJoinRequest() { return "http://" + ip + ":" + port + "/rejectJoinRequest"; } public String getApplyProject() { return "http://" + ip + ":" + port + "/applyProject"; } public String getApproveProject() { return "http://" + ip + ":" + port + "/approveProject"; } public String getRejectProject() { return "http://" + ip + ":" + port + "/rejectProject"; } public String getExpStatus() { return "http://" + ip + ":" + port + "/getExpStatus"; } public String getBossUrl() { return bossUrl; } public void setBossUrl(String bossUrl) { this.bossUrl = bossUrl; } public String getUserUrl() { return userUrl; } public void setUserUrl(String userUrl) { this.userUrl = userUrl; } public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } public boolean isProd() { return mode.equalsIgnoreCase("prod"); } }
package org.springframework.roo.addon.gwt; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.List; import java.util.Set; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.osgi.service.component.ComponentContext; import org.springframework.roo.addon.web.mvc.controller.UrlRewriteOperations; import org.springframework.roo.addon.web.mvc.controller.WebMvcOperations; import org.springframework.roo.file.monitor.event.FileDetails; import org.springframework.roo.metadata.MetadataService; import org.springframework.roo.model.JavaType; import org.springframework.roo.process.manager.FileManager; import org.springframework.roo.process.manager.MutableFile; import org.springframework.roo.project.Dependency; import org.springframework.roo.project.Path; import org.springframework.roo.project.PathResolver; import org.springframework.roo.project.Plugin; import org.springframework.roo.project.ProjectMetadata; import org.springframework.roo.project.ProjectOperations; import org.springframework.roo.project.Repository; import org.springframework.roo.support.osgi.UrlFindingUtils; import org.springframework.roo.support.util.Assert; import org.springframework.roo.support.util.FileCopyUtils; import org.springframework.roo.support.util.TemplateUtils; import org.springframework.roo.support.util.WebXmlUtils; import org.springframework.roo.support.util.XmlElementBuilder; import org.springframework.roo.support.util.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Provides GWT installation services. * * @author Ben Alex * @author Alan Stewart * @author Stefan Schmidt * @author Ray Cromwell * @author Amit Manjhi * @since 1.1 */ @Component @Service public class GwtOperationsImpl implements GwtOperations { @Reference private FileManager fileManager; @Reference private PathResolver pathResolver; @Reference private MetadataService metadataService; @Reference private ProjectOperations projectOperations; @Reference private UrlRewriteOperations urlRewriteOperations; @Reference private WebMvcOperations mvcOperations; private ComponentContext context; boolean isGaeEnabled; protected void activate(ComponentContext context) { this.context = context; } private ProjectMetadata getProjectMetadata() { return (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier()); } public boolean isSetupGwtAvailable() { ProjectMetadata projectMetadata = getProjectMetadata(); if (projectMetadata == null) { return false; } // Do not permit installation if they have a gwt package already in their project String root = GwtPath.GWT_ROOT.canonicalFileSystemPath(projectMetadata); return !fileManager.exists(root); } public void setupGwt() { ProjectMetadata projectMetadata = getProjectMetadata(); Assert.notNull(projectMetadata, "Project could not be retrieved"); isGaeEnabled = isGaeEnabled(); // Install web pieces if not already installed if (!fileManager.exists(pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "/WEB-INF/web.xml"))) { mvcOperations.installAllWebMvcArtifacts(); } // Add GWT natures and builder names to maven eclipse plugin updateMavenEclipsePlugin(); Element configuration = getConfiguration(); // Add dependencies List<Element> dependencies = XmlUtils.findElements("/configuration/dependencies/dependency", configuration); for (Element dependency : dependencies) { projectOperations.dependencyUpdate(new Dependency(dependency)); } if (isGaeEnabled) { // Add GAE SDK specific JARs using systemPath to make AppEngineLauncher happy for (Element dependency : XmlUtils.findElements("/configuration/gae-dependencies/dependency", configuration)) { projectOperations.dependencyUpdate(new Dependency(dependency)); } } // Add POM plugin List<Element> plugins = XmlUtils.findElements(isGaeEnabled ? "/configuration/gae-plugins/plugin" : "/configuration/plugins/plugin", configuration); for (Element plugin : plugins) { projectOperations.addBuildPlugin(new Plugin(plugin)); } updateRepositories(); // Update web.xml updateWebXml(projectMetadata); // Update urlrewrite.xml updateUrlRewriteXml(); // Copy "static" directories for (GwtPath path : GwtPath.values()) { copyDirectoryContents(path, projectMetadata); } // Do a "get" for every .java file, thus ensuring the metadata is fired FileDetails srcRoot = new FileDetails(new File(pathResolver.getRoot(Path.SRC_MAIN_JAVA)), null); String antPath = pathResolver.getRoot(Path.SRC_MAIN_JAVA) + File.separatorChar + "**" + File.separatorChar + "*.java"; for (FileDetails fd : fileManager.findMatchingAntPath(antPath)) { String fullPath = srcRoot.getRelativeSegment(fd.getCanonicalPath()); fullPath = fullPath.substring(1, fullPath.lastIndexOf(".java")).replace(File.separatorChar, '.'); // ditch the first / and .java JavaType javaType = new JavaType(fullPath); String id = GwtMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA); metadataService.get(id); } } private void copyDirectoryContents(GwtPath gwtPath, ProjectMetadata projectMetadata) { String sourceAntPath = gwtPath.sourceAntPath(); String targetDirectory = gwtPath.canonicalFileSystemPath(projectMetadata); if (!targetDirectory.endsWith("/")) { targetDirectory += "/"; } if (!fileManager.exists(targetDirectory)) { fileManager.createDirectory(targetDirectory); } String path = TemplateUtils.getTemplatePath(getClass(), sourceAntPath); Set<URL> urls = UrlFindingUtils.findMatchingClasspathResources(context.getBundleContext(), path); Assert.notNull(urls, "Could not search bundles for resources for Ant Path '" + path + "'"); for (URL url : urls) { String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1); fileName = fileName.replace("-template", ""); if (fileName.contains("GaeUserInformation") && !isGaeEnabled()) { continue; } String targetFilename = targetDirectory + fileName; if (!fileManager.exists(targetFilename)) { try { if (targetFilename.endsWith("png")) { FileCopyUtils.copy(url.openStream(), fileManager.createFile(targetFilename).getOutputStream()); } else { // Read template and insert the user's package String input = FileCopyUtils.copyToString(new InputStreamReader(url.openStream())); input = input.replace("__TOP_LEVEL_PACKAGE__", projectMetadata.getTopLevelPackage().getFullyQualifiedPackageName()); input = input.replace("__PROJECT_NAME__", projectMetadata.getProjectName()); // Output the file for the user MutableFile mutableFile = fileManager.createFile(targetFilename); FileCopyUtils.copy(input.getBytes(), mutableFile.getOutputStream()); } } catch (IOException ioe) { throw new IllegalStateException("Unable to create '" + targetFilename + "'", ioe); } } } } private Element getConfiguration() { InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "configuration.xml"); Assert.notNull(templateInputStream, "Could not acquire configuration.xml file"); Document dependencyDoc; try { dependencyDoc = XmlUtils.getDocumentBuilder().parse(templateInputStream); } catch (Exception e) { throw new IllegalStateException(e); } return (Element) dependencyDoc.getFirstChild(); } private void updateMavenEclipsePlugin() { String pom = pathResolver.getIdentifier(Path.ROOT, "pom.xml"); Assert.isTrue(fileManager.exists(pom), "pom.xml not found; cannot continue"); Document pomDoc; InputStream is = null; MutableFile mutablePom = null; try { mutablePom = fileManager.updateFile(pom); is = mutablePom.getInputStream(); pomDoc = XmlUtils.getDocumentBuilder().parse(is); } catch (Exception e) { throw new IllegalStateException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new IllegalStateException(e); } } } Element pomRoot = (Element) pomDoc.getFirstChild(); List<Element> pluginElements = XmlUtils.findElements("/project/build/plugins/plugin", pomRoot); for (Element pluginElement : pluginElements) { Plugin plugin = new Plugin(pluginElement); if ("maven-eclipse-plugin".equals(plugin.getArtifactId().getSymbolName()) && "org.apache.maven.plugins".equals(plugin.getGroupId().getFullyQualifiedPackageName())) { // Add in the builder configuration Element newEntry = new XmlElementBuilder("buildCommand", pomDoc).addChild(new XmlElementBuilder("name", pomDoc).setText("com.google.gwt.eclipse.core.gwtProjectValidator").build()).build(); Element ctx = XmlUtils.findRequiredElement("configuration/additionalBuildcommands/buildCommand[last()]", pluginElement); ctx.getParentNode().appendChild(newEntry); // Add in the additional nature newEntry = new XmlElementBuilder("projectnature", pomDoc).setText("com.google.gwt.eclipse.core.gwtNature").build(); ctx = XmlUtils.findRequiredElement("configuration/additionalProjectnatures/projectnature[last()]", pluginElement); ctx.getParentNode().appendChild(newEntry); // If gae plugin configured, add gaeNature if (isGaeEnabled) { newEntry = new XmlElementBuilder("projectnature", pomDoc).setText("com.google.appengine.eclipse.core.gaeNature").build(); ctx.getParentNode().appendChild(newEntry); } plugin = new Plugin(pluginElement); projectOperations.removeBuildPlugin(plugin); projectOperations.addBuildPlugin(plugin); } } // Fix output directory Element outputDirectory = XmlUtils.findFirstElement("/project/build/outputDirectory", pomRoot); if (outputDirectory != null) { outputDirectory.setTextContent("${project.build.directory}/${project.build.finalName}/WEB-INF/classes"); } else { Element newEntry = new XmlElementBuilder("outputDirectory", pomDoc).setText("${project.build.directory}/${project.build.finalName}/WEB-INF/classes").build(); Element ctx = XmlUtils.findRequiredElement("/project/build", pomRoot); ctx.appendChild(newEntry); } // TODO CD is there a better way of doing this here? XmlUtils.writeXml(mutablePom.getOutputStream(), pomDoc); } private boolean isGaeEnabled() { ProjectMetadata projectMetadata = getProjectMetadata(); Assert.notNull(projectMetadata, "Project could not be retrieved"); return projectMetadata.isGaeEnabled(); } private void updateRepositories() { Element configuration = getConfiguration(); List<Element> repositories = XmlUtils.findElements("/configuration/repositories/repository", configuration); for (Element repositoryElement : repositories) { projectOperations.addRepository(new Repository(repositoryElement)); } List<Element> pluginRepositories = XmlUtils.findElements("/configuration/pluginRepositories/pluginRepository", configuration); for (Element repositoryElement : pluginRepositories) { projectOperations.addPluginRepository(new Repository(repositoryElement)); } } private void updateWebXml(ProjectMetadata projectMetadata) { String webXml = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/web.xml"); Assert.isTrue(fileManager.exists(webXml), "web.xml not found; cannot continue"); MutableFile mutableWebXml = null; Document webXmlDoc; try { mutableWebXml = fileManager.updateFile(webXml); webXmlDoc = XmlUtils.getDocumentBuilder().parse(mutableWebXml.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element webXmlRoot = webXmlDoc.getDocumentElement(); WebXmlUtils.WebXmlParam initParams = null; if (isGaeEnabled()) { String userClass = projectMetadata.getTopLevelPackage().getFullyQualifiedPackageName() + ".gwt.GaeUserInformation"; initParams = new WebXmlUtils.WebXmlParam("userInfoClass", userClass); WebXmlUtils.addServlet("requestFactory", "com.google.gwt.requestfactory.server.RequestFactoryServlet", "/gwtRequest", null, webXmlDoc, null, initParams); } else { WebXmlUtils.addServlet("requestFactory", "com.google.gwt.requestfactory.server.RequestFactoryServlet", "/gwtRequest", null, webXmlDoc, null); } removeIfFound("/web-app/welcome-file-list/welcome-file", webXmlRoot); WebXmlUtils.addWelcomeFile("ApplicationScaffold.html", webXmlDoc, "Changed by 'gwt setup' command"); XmlUtils.writeXml(mutableWebXml.getOutputStream(), webXmlDoc); } private void updateUrlRewriteXml() { Document urlRewriteDoc = urlRewriteOperations.getUrlRewriteDocument(); Element root = urlRewriteDoc.getDocumentElement(); Element firstRule = XmlUtils.findRequiredElement("/urlrewrite/rule", root); root.insertBefore(new XmlElementBuilder("rule", urlRewriteDoc)
package com.rgi.common.test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.function.Function; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.junit.Test; import com.rgi.common.Range; @SuppressWarnings({"javadoc", "static-method"}) public class RangeTest { Comparator<Number> numberComparartor = new Comparator<Number>() { @Override public int compare(Number o1, Number o2) { Double value1 = o1.doubleValue(); Double value2 = o2.doubleValue(); return value1.compareTo(value2); } }; @Test public void verifyRange() { double minimum = 80.0; double maximum = 100.0; Range<Double> range = new Range<>(minimum, maximum); assertRangeValues(range, minimum, maximum); } @Test public void verifyRange2() { List<Double> listValues = new ArrayList<>(Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0)); Range<Double> range = new Range<>(listValues, this.numberComparartor); assertRangeValues(range, 0.0, 12.0); } @Test public void verifyRange3() { List<Double> listValues = Arrays.asList(2.0, 0.0, 1.0, 5.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0); try(Stream<Double> stream = StreamSupport.stream(listValues.spliterator(), false);) { Range<Double> range = new Range<>(stream, this.numberComparartor); assertRangeValues(range, 0.0, 12.0); } } @Test public void verifyRange4() { List<Double> listValues = new ArrayList<>(Arrays.asList(11.0, 12.5, -1.0, -1.15, -1.0, -1.15, 2.0, 5.0, 10.0, 12.5, 12.5)); Function<Double, Double> function = new Function<Double, Double>(){ @Override public Double apply(Double t) { return t*-1.0; }}; double expectedMin = -12.5; double expectedMax = 1.15; Range<Double> range = new Range<>(listValues, function, this.numberComparartor); assertRangeValues(range, expectedMin, expectedMax); } @Test public void verifyRange5() { List<Number> listValues = new ArrayList<>(Arrays.asList(11, 12.5, -1.0, -1.15, -1.0, -1.15, 2.0, 5.0, 10.0, 12.5, 12.5, 7.82912381)); Function<Number, Integer> function = new Function<Number, Integer>(){ @Override public Integer apply(Number t) { return (int) Math.floor(t.doubleValue()); }}; int expectedMin = -2; int expectedMax = 12; Range<Number> range = new Range<>(listValues, function, this.numberComparartor); assertRangeValues(expectedMin, expectedMax, range); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void illegalArgumentException() { List<Number> listValues = new ArrayList<>(Arrays.asList(11.0, 12.5, -1.0, -1.15, -1.0, -1.15, 2.0, 5.0, 10.0, 12.5, 12.5)); Function<Number, Integer> function = new Function<Number, Integer>(){ @Override public Integer apply(Number t) { return (int) Math.floor(t.doubleValue()); }}; new Range<>(null, function, this.numberComparartor); fail("Expected Range to throw an IllegalArgumentException when the Iterable is null"); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void illegalArgumentException2() { List<Number> listValues = new ArrayList<>(); Function<Number, Integer> function = new Function<Number, Integer>(){ @Override public Integer apply(Number t) { return (int) Math.floor(t.doubleValue()); }}; new Range<>(listValues, function, this.numberComparartor); fail("Expected Range to throw an IllegalArgumentException when the Iterable is empty"); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void illegalArgumentException3() { List<Number> listValues = new ArrayList<>(Arrays.asList(10.0, 100, -12)); Function<Number, Integer> function = null; new Range<>(listValues, function, this.numberComparartor); fail("Expected Range to throw an IllegalArgumentException when the Function is null"); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void illegalArgumentException4() { List<Number> listValues = new ArrayList<>(Arrays.asList(10.0, 100, -12)); Function<Number, Integer> function = new Function<Number, Integer>(){ @Override public Integer apply(Number t) { return (int) Math.floor(t.doubleValue()); }}; new Range<>(listValues, function, null); fail("Expected Range to throw an IllegalArgumentException when the Comparator is null"); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void illegalArgumentException5() { List<Number> listValues = new ArrayList<>(); new Range<>(listValues, this.numberComparartor); fail("Expected Range to throw an IllegalArgumentException when the Iterable is empty"); } @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void illegalArgumentException6() { List<Number> listValues = new ArrayList<>(Arrays.asList(12, 2.74, 8.0)); new Range<>(listValues, null); fail("Expected Range to throw an IllegalArgumentException when the Iterable is empty"); } private void assertRangeValues(Range<Double> range, double expectedMinimum, double expectedMaximum) { assertTrue(String.format("The range did not return the expected values.\nActual: %s.\nExpected: [%s, %s].", range.toString(), expectedMinimum, expectedMaximum), range.getMinimum() == expectedMinimum && range.getMaximum() == expectedMaximum); } private void assertRangeValues(Number expectedMinimum, Number expectedMaximum, Range<Number> range) { assertTrue(String.format("The range did not return the expected values.\nActual: %s.\nExpected: [%s, %s].", range.toString(), expectedMinimum, expectedMaximum), range.getMinimum() == expectedMinimum && range.getMaximum() == expectedMaximum); } }
package com.onegini.model; import android.os.Build; import com.google.gson.annotations.SerializedName; import com.onegini.mobile.sdk.android.library.model.OneginiClientConfigModel; public class ConfigModel implements OneginiClientConfigModel { @SerializedName("shouldGetIdToken") private boolean shouldGetIdToken; @SerializedName("kOGAppIdentifier") private String appIdentifier; @SerializedName("kOGAppPlatform") private String appPlatform; @SerializedName("kOGAppScheme") private String appScheme; @SerializedName("kOGAppVersion") private String appVersion; @SerializedName("kAppBaseURL") private String baseUrl; @SerializedName("kOGMaxPinFailures") private int maxPinFailures; @SerializedName("kOGResourceBaseURL") private String resourceBaseUrl; @SerializedName("kOGShouldConfirmNewPin") private boolean shouldConfirmNewPin; @SerializedName("kOGShouldDirectlyShowPushMessage") private boolean shouldDirectlyShowPushMessage; @SerializedName("kOGdebugDetectionEnabled") private boolean debugDetectionEnabled; @SerializedName("kOGrootDetectionEnabled") private boolean rootDetectionEnabled; @SerializedName("kOGUseEmbeddedWebview") private boolean useEmbeddedWebview; private int certificatePinningKeyStore; private String keyStoreHash; @Override public String getAppIdentifier() { return appIdentifier; } @Override public String getAppPlatform() { return appPlatform; } @Override public String getAppScheme() { return appScheme; } @Override public String getAppVersion() { return appVersion; } @Override public String getBaseUrl() { return baseUrl; } @Override public int getMaxPinFailures() { return maxPinFailures; } @Override public String getResourceBaseUrl() { return resourceBaseUrl; } @Override public boolean shouldConfirmNewPin() { return shouldConfirmNewPin; } @Override public boolean shouldDirectlyShowPushMessage() { return shouldDirectlyShowPushMessage; } @Override public int getCertificatePinningKeyStore() { return certificatePinningKeyStore; } public void setCertificatePinningKeyStore(int certificatePinningKeyStore) { this.certificatePinningKeyStore = certificatePinningKeyStore; } @Override public String getKeyStoreHash() { return keyStoreHash; } public void setKeyStoreHash(String keyStoreHash) { this.keyStoreHash = keyStoreHash; } @Override public String getDeviceName() { return Build.BRAND + " " + Build.MODEL; } @Override public boolean shouldGetIdToken() { return shouldGetIdToken; } @Override public boolean shouldStoreCookies() { return true; } @Override public int getHttpClientTimeout() { return 0; } @Override public boolean debugDetectionEnabled() { return debugDetectionEnabled; } @Override public boolean rootDetectionEnabled() { return rootDetectionEnabled; } public boolean useEmbeddedWebview() { return useEmbeddedWebview; } @Override public String toString() { return "ConfigModel{" + " appIdentifier='" + appIdentifier + "'" + ", appPlatform='" + appPlatform + "'" + ", appScheme='" + appScheme + "'" + ", appVersion='" + appVersion + "'" + ", baseURL='" + baseUrl + "'" + ", confirmNewPin='" + shouldConfirmNewPin + "'" + ", directlyShowPushMessage='" + shouldDirectlyShowPushMessage + "'" + ", maxPinFailures='" + maxPinFailures + "'" + ", resourceBaseURL='" + resourceBaseUrl + "'" + ", keyStoreHash='" + getKeyStoreHash() + "'" + ", idTokenRequested='" + shouldGetIdToken + "'" + "}"; } }
package verification.platu.stategraph; import java.io.*; import java.util.*; import lpn.parser.LhpnFile; import lpn.parser.Transition; import verification.platu.common.PlatuObj; import verification.platu.lpn.DualHashMap; import verification.platu.lpn.LPN; import verification.platu.lpn.LpnTranList; import verification.platu.lpn.VarSet; import verification.timed_state_exploration.zone.TimedState; /** * State * @author Administrator */ public class State extends PlatuObj { public static int[] counts = new int[15]; protected int[] marking; protected int[] vector; protected boolean[] tranVector; // indicator vector to record whether each transition is enabled or not. private int hashVal = 0; private LhpnFile lpn = null; private int index; private boolean localEnabledOnly; protected boolean failure = false; // The TimingState that extends this state with a zone. Null if untimed. protected TimedState timeExtension; @Override public String toString() { // String ret=Arrays.toString(marking)+""+ // Arrays.toString(vector); // return "["+ret.replace("[", "{").replace("]", "}")+"]"; return this.print(); } public State(final LhpnFile lpn, int[] new_marking, int[] new_vector, boolean[] new_isTranEnabled) { this.lpn = lpn; this.marking = new_marking; this.vector = new_vector; this.tranVector = new_isTranEnabled; if (marking == null || vector == null || tranVector == null) { new NullPointerException().printStackTrace(); } //Arrays.sort(this.marking); this.index = 0; localEnabledOnly = false; counts[0]++; } public State(State other) { if (other == null) { new NullPointerException().printStackTrace(); } this.lpn = other.lpn; this.marking = new int[other.marking.length]; System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length); this.vector = new int[other.vector.length]; System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length); this.tranVector = new boolean[other.tranVector.length]; System.arraycopy(other.tranVector, 0, this.tranVector, 0, other.tranVector.length); // this.hashVal = other.hashVal; this.hashVal = 0; this.index = other.index; this.localEnabledOnly = other.localEnabledOnly; counts[0]++; } // TODO: (temp) Two Unused constructors, State() and State(Object otherState) // public State() { // this.marking = new int[0]; // this.vector = new int[0];//EMPTY_VECTOR.clone(); // this.hashVal = 0; // this.index = 0; // localEnabledOnly = false; // counts[0]++; //static PrintStream out = System.out; // public State(Object otherState) { // State other = (State) otherState; // if (other == null) { // new NullPointerException().printStackTrace(); // this.lpnModel = other.lpnModel; // this.marking = new int[other.marking.length]; // System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length); // // this.vector = other.getVector().clone(); // this.vector = new int[other.vector.length]; // System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length); // this.hashVal = other.hashVal; // this.index = other.index; // this.localEnabledOnly = other.localEnabledOnly; // counts[0]++; public void setLpn(final LhpnFile thisLpn) { this.lpn = thisLpn; } public LhpnFile getLpn() { return this.lpn; } public void setLabel(String lbl) { } public String getLabel() { return null; } /** * This method returns the boolean array representing the status (enabled/disabled) of each transition in an LPN. * @return */ public boolean[] getTranVector() { return tranVector; } public void setIndex(int newIndex) { this.index = newIndex; } public int getIndex() { return this.index; } public boolean hasNonLocalEnabled() { return this.localEnabledOnly; } public void hasNonLocalEnabled(boolean nonLocalEnabled) { this.localEnabledOnly = nonLocalEnabled; } public boolean isFailure() { return false;// getType() != getType().NORMAL || getType() != // getType().TERMINAL; } public static long tSum = 0; @Override public State clone() { counts[6]++; State s = new State(this); return s; } public String print() { DualHashMap<String, Integer> VarIndexMap = this.lpn.getVarIndexMap(); String message = "Marking: ["; for (int i : marking) { message += i + ","; } message += "]\n" + "Vector: ["; for (int i = 0; i < vector.length; i++) { message += VarIndexMap.getKey(i) + "=>" + vector[i]+", "; } message += "]\n" + "Transition Vector: ["; for (int i = 0; i < tranVector.length; i++) { message += tranVector[i] + ","; } message += "]\n"; return message; } @Override public int hashCode() { if(hashVal == 0){ final int prime = 31; int result = 1; result = prime * result + ((lpn == null) ? 0 : lpn.getLabel().hashCode()); result = prime * result + Arrays.hashCode(marking); result = prime * result + Arrays.hashCode(vector); result = prime * result + Arrays.hashCode(tranVector); hashVal = result; } return hashVal; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; State other = (State) obj; if (lpn == null) { if (other.lpn != null) return false; } else if (!lpn.equals(other.lpn)) return false; if (!Arrays.equals(marking, other.marking)) return false; if (!Arrays.equals(vector, other.vector)) return false; if (!Arrays.equals(tranVector, other.tranVector)) return false; return true; } public void print(DualHashMap<String, Integer> VarIndexMap) { System.out.print("Marking: ["); for (int i : marking) { System.out.print(i + ","); } System.out.println("]"); System.out.print("Vector: ["); for (int i = 0; i < vector.length; i++) { System.out.print(VarIndexMap.getKey(i) + "=>" + vector[i]+", "); } System.out.println("]"); System.out.print("Transition vector: ["); for (boolean bool : tranVector) { System.out.print(bool + ","); } System.out.println("]"); } /** * @return the marking */ public int[] getMarking() { return marking; } public void setMarking(int[] newMarking) { marking = newMarking; } /** * @return the vector */ public int[] getVector() { // new Exception("StateVector getVector(): "+s).printStackTrace(); return vector; } public HashMap<String, Integer> getOutVector(VarSet outputs, DualHashMap<String, Integer> VarIndexMap) { HashMap<String, Integer> outVec = new HashMap<String, Integer>(); for(int i = 0; i < vector.length; i++) { String var = VarIndexMap.getKey(i); if(outputs.contains(var) == true) outVec.put(var, vector[i]); } return outVec; } public State getLocalState() { //VarSet lpnOutputs = this.lpnModel.getOutputs(); //VarSet lpnInternals = this.lpnModel.getInternals(); Set<String> lpnOutputs = this.lpn.getAllOutputs().keySet(); Set<String> lpnInternals = this.lpn.getAllInternals().keySet(); DualHashMap<String,Integer> varIndexMap = this.lpn.getVarIndexMap(); int[] outVec = new int[this.vector.length]; /* * Create a copy of the vector of mState such that the values of inputs are set to 0 * and the values for outputs/internal variables remain the same. */ for(int i = 0; i < this.vector.length; i++) { String curVar = varIndexMap.getKey(i); if(lpnOutputs.contains(curVar) ==true || lpnInternals.contains(curVar)==true) outVec[i] = this.vector[i]; else outVec[i] = 0; } // TODO: (??) Need to create outTranVector as well? return new State(this.lpn, this.marking, outVec, this.tranVector); } /** * @return the enabledSet */ public int[] getEnabledSet() { return null;// enabledSet; } public LpnTranList getEnabledTransitions() { LpnTranList enabledTrans = new LpnTranList(); for (int i=0; i<tranVector.length; i++) { if (tranVector[i]) { enabledTrans.add(this.lpn.getTransition(i)); } } return enabledTrans; } public String getEnabledSetString() { String ret = ""; // for (int i : enabledSet) { // ret += i + ", "; return ret; } /** * Return a new state if the newVector leads to a new state from this state; otherwise return null. * @param newVector * @param VarIndexMap * @return */ public State update(StateGraph SG,HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap) { int[] newStateVector = new int[this.vector.length]; boolean newState = false; for(int index = 0; index < vector.length; index++) { String var = VarIndexMap.getKey(index); int this_val = this.vector[index]; Integer newVal = newVector.get(var); if(newVal != null) { if(this_val != newVal) { newState = true; newStateVector[index] = newVal; } else newStateVector[index] = this.vector[index]; } else newStateVector[index] = this.vector[index]; } boolean[] newEnabledTranVector = SG.updateEnabledTranVector(this.getTranVector(), this.marking, newStateVector, null); if(newState == true) return new State(this.lpn, this.marking, newStateVector, newEnabledTranVector); return null; } /** * Return a new state if the newVector leads to a new state from this state; otherwise return null. * States considered here include a vector indicating enabled/disabled state of each transition. * @param newVector * @param VarIndexMap * @return */ public State update(HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap, boolean[] newTranVector) { int[] newStateVector = new int[this.vector.length]; boolean newState = false; for(int index = 0; index < vector.length; index++) { String var = VarIndexMap.getKey(index); int this_val = this.vector[index]; Integer newVal = newVector.get(var); if(newVal != null) { if(this_val != newVal) { newState = true; newStateVector[index] = newVal; } else newStateVector[index] = this.vector[index]; } else newStateVector[index] = this.vector[index]; } if (!this.tranVector.equals(newTranVector)) newState = true; if(newState == true) return new State(this.lpn, this.marking, newStateVector, newTranVector); return null; } static public void printUsageStats() { System.out.printf("%-20s %11s\n", "State", counts[0]); System.out.printf("\t%-20s %11s\n", "State", counts[10]); // System.out.printf("\t%-20s %11s\n", "State", counts[11]); // System.out.printf("\t%-20s %11s\n", "merge", counts[1]); System.out.printf("\t%-20s %11s\n", "update", counts[2]); // System.out.printf("\t%-20s %11s\n", "compose", counts[3]); System.out.printf("\t%-20s %11s\n", "equals", counts[4]); // System.out.printf("\t%-20s %11s\n", "conjunction", counts[5]); System.out.printf("\t%-20s %11s\n", "clone", counts[6]); System.out.printf("\t%-20s %11s\n", "hashCode", counts[7]); // System.out.printf("\t%-20s %11s\n", "resembles", counts[8]); // System.out.printf("\t%-20s %11s\n", "digest", counts[9]); } //TODO: (original) try database serialization public File serialize(String filename) throws FileNotFoundException, IOException { File f = new File(filename); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f)); os.writeObject(this); os.close(); return f; } public static State deserialize(String filename) throws FileNotFoundException, IOException, ClassNotFoundException { File f = new File(filename); ObjectInputStream os = new ObjectInputStream(new FileInputStream(f)); State zone = (State) os.readObject(); os.close(); return zone; } public static State deserialize(File f) throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream os = new ObjectInputStream(new FileInputStream(f)); State zone = (State) os.readObject(); os.close(); return zone; } public boolean failure(){ return this.failure; } public void setFailure(){ this.failure = true; } public void print(LhpnFile lpn) { System.out.print("Marking: ["); // for (int i : marking) { // System.out.print(i + ","); for (int i=0; i < marking.length; i++) { System.out.print(lpn.getPlaceList().clone()[i] + "=" + marking[i] + ", "); } System.out.println("]"); System.out.print("Vector: ["); for (int i = 0; i < vector.length; i++) { System.out.print(lpn.getVarIndexMap().getKey(i) + "=>" + vector[i]+", "); } System.out.println("]"); System.out.print("Transition vector: ["); for (boolean bool : tranVector) { System.out.print(bool + ","); } System.out.println("]"); } /** * Getter for the TimingState that extends this state. * @return * The TimingState that extends this state if it has been set. Null, otherwise. */ public TimedState getTimeExtension(){ return timeExtension; } /** * Setter for the TimingState that extends this state. * @param s * The TimingState that exteds this state. */ public void setTimeExtension(TimedState s){ timeExtension = s; } }
package ar.glyphsets; import java.awt.Color; import java.util.Map; public interface Painter<T> { public java.awt.Color from(T item); public static final class Constant<T> implements Painter<T> { private final Color c; public Constant() {this.c = Color.red;} public Constant(Color c) {this.c = c;} public Color from(T item) {return c;} } /**Coloring scheme when the full set of values is known.**/ public static final class Listing<T> implements Painter<T> { private final Map<T, Color> mappings; private final Color other; public Listing(Map<T,Color> mappings, Color other) {this.mappings=mappings; this.other = other;} public Color from(T item) { Color c = mappings.get(item); if (c == null) {return other;} else {return c;} } } /**Binary coloring scheme. * If an item equals the stored value, return color 'a'. * Otherwise return color 'b'. */ public static final class AB<T> implements Painter<T> { private final Color a; private final Color b; private final T v; public AB(T v, Color a, Color b) {this.v = v; this.a = a; this.b=b;} public Color from(T item) { if (item == v || (v != null && v.equals(item))) {return a;} return b; } } }
import java.util.*; public class OxygenFiller { public OxygenFiller (Maze theMaze, boolean debug) { _theMap = theMaze; _debug = debug; _currentLocation = theMaze.getOxygenStation(); // start at the oxygen station _trackTaken = new Stack<Integer>(); } // trace through the maze until we get back to the start public int fillWithOxygen () { int steps = 0; fill(); return steps; } /* * If we run into a wall then try a different direction. * If we can't move other than backwards then do that. * Don't move into areas we've already been. */ private boolean fill () { boolean response = false; boolean needToBackup = false; /* * We search N, E, S and then W. */ if (!tryToFill(DroidMovement.NORTH, DroidMovement.getNextPosition(_currentLocation, DroidMovement.NORTH))) { //if (_debug) System.out.println("\n"+_theMap); if (!tryToFill(DroidMovement.EAST, DroidMovement.getNextPosition(_currentLocation, DroidMovement.EAST))) { //if (_debug) System.out.println("\n"+_theMap); if (!tryToFill(DroidMovement.SOUTH, DroidMovement.getNextPosition(_currentLocation, DroidMovement.SOUTH))) { //if (_debug) System.out.println("\n"+_theMap); if (!tryToFill(DroidMovement.WEST, DroidMovement.getNextPosition(_currentLocation, DroidMovement.WEST))) { //if (_debug) System.out.println("\n"+_theMap); /* * At this point we've exhausted all of the options for moving from * the current location. Therefore, we need to backtrack. */ System.out.println("BACKTRACK"); backtrack(); } } } } return response; } private boolean tryToFill (int direction, Coordinate to) { //if (_debug) System.out.println("Trying to fill from: "+_currentLocation+" to "+to+" with direction "+DroidMovement.toString(direction)); if (_theMap.isWall(to)) { System.out.println("**IS WALL"); return false; } /* * Oxygen filled space. */ _theMap.updateTile(_currentLocation, TileId.OXYGEN_STATION); _currentLocation = to; System.out.println("\n"+_theMap); recordJourney(direction); return fill(); } private boolean backtrack () { boolean status = false; if (_trackTaken.size() > 0) { int backupDirection = DroidMovement.backupDirection(_trackTaken.pop()); //if (_debug) System.out.println("Trying to backup from: "+_currentLocation+" with direction "+DroidMovement.toString(backupDirection)); _currentLocation = DroidMovement.getNextPosition(_currentLocation, backupDirection); status = true; } return status; } private void recordJourney (int direction) { _trackTaken.push(direction); } private Maze _theMap; private boolean _debug; private Coordinate _currentLocation; private Stack<Integer> _trackTaken; }
package org.spash; import static java.util.Collections.sort; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Set; import org.spash.ray.Ray; import org.spash.ray.RayBodyIntersector; import org.spash.ray.RayBroadPhase; import org.spash.ray.RayContact; /** * Brings broad phase and narrow phase together to find overlapping bodies. */ public class Space { private BodyOverlapper overlapper; private BroadPhase broadPhase; private List<OverlapListener> listeners; private List<PairFilter> filters; private RayBroadPhase rayBroadPhase; private RayBodyIntersector intersector; /** * Creates a space. * * @param broadPhase Broadphase to find pairs of bodies, cannot be null * @param overlapper Overlapper for narrow phase checks, cannot be null */ public Space(BroadPhase broadPhase, BodyOverlapper overlapper) { if(overlapper == null) throw new IllegalArgumentException("overlapper cannot be null"); if(broadPhase == null) throw new IllegalArgumentException("broadPhase cannot be null"); this.overlapper = overlapper; this.broadPhase = broadPhase; listeners = new ArrayList<OverlapListener>(); filters = new ArrayList<PairFilter>(); intersector = noIntersector(); rayBroadPhase = noRayBroadPhase(); } private RayBroadPhase noRayBroadPhase() { return new RayBroadPhase() { public Set<Body> potentialBodies(Ray ray) { throw new IllegalStateException("This space has not been equipped for ray queries, see Space#equipForRays"); } public void add(Body body) {} public void clear() {} }; } private RayBodyIntersector noIntersector() { return new RayBodyIntersector() { public ROVector2f intersect(Ray ray, Body body) { throw new IllegalStateException("This space has not been equipped for ray queries, see Space#equipForRays"); } }; } /** * Finds overlaps and notifies listeners. */ public void processOverlaps() { for(Pair pair : broadPhase.findPairs()) { if(shouldDoNarrowPhase(pair)) { Translation minTranslation = doNarrowPhase(pair); if(minTranslation != null) { overlapFound(pair, minTranslation); } } } } private boolean shouldDoNarrowPhase(Pair pair) { for(PairFilter filter : filters) { if(filter.shouldSkipNarrowPhase(pair)) { return false; } } return true; } private Translation doNarrowPhase(Pair pair) { return overlapper.getMinTranslation(pair.getBodyA(), pair.getBodyB()); } private void overlapFound(Pair pair, Translation minTranslation) { notifyBodies(pair.getBodyA(), pair.getBodyB()); notifyListeners(new OverlapEvent(pair, minTranslation)); } private void notifyBodies(Body bodyA, Body bodyB) { bodyA.overlapping(bodyB); bodyB.overlapping(bodyA); } private void notifyListeners(OverlapEvent event) { for(OverlapListener listener : listeners) { listener.onOverlap(event); } } public void addBodies(Collection<? extends Body> bodies) { for(Body body : bodies) { if(body == null) throw new IllegalArgumentException("bodies cannot contain null"); broadPhase.add(body); } } public void clearBodies() { broadPhase.clear(); } public void addOverlapListener(OverlapListener listener) { listeners.add(listener); } public void removeOverlapListener(OverlapListener listener) { listeners.remove(listener); } public void addPairFilter(PairFilter filter) { filters.add(filter); } public void removePairFilter(PairFilter filter) { filters.remove(filter); } /** * Gives this space the stuff to do ray queries. * * @param rayBroadPhase * @param intersector */ public void equipForRays(RayBroadPhase rayBroadPhase, RayBodyIntersector intersector) { if(rayBroadPhase == null) throw new IllegalArgumentException("rayBroadPhase cannot be null"); if(intersector == null) throw new IllegalArgumentException("intersector cannot be null"); this.rayBroadPhase = rayBroadPhase; this.intersector = intersector; } /** * Returns all contacts made by a ray. * * @param ray * @return Ray contacts, never null */ public List<RayContact> allReached(Ray ray) { List<RayContact> contacts = new ArrayList<RayContact>(); for(Body body : rayBroadPhase.potentialBodies(ray)) { RayContact contact = isReached(body, ray); if(contact != null) { contacts.add(contact); } } sort(contacts, byAscendingDistanceFromRayStart()); return contacts; } private Comparator<RayContact> byAscendingDistanceFromRayStart() { return new Comparator<RayContact>() { public int compare(RayContact c1, RayContact c2) { if(c1.distanceFromRayStart() < c2.distanceFromRayStart()) { return -1; } else if(c1.distanceFromRayStart() > c2.distanceFromRayStart()) { return 1; } return 0; } }; } /** * Tells if a body is reached by a ray. * * @param body * @param ray * @return Ray contact if the ray reaches the body, null otherwise */ public RayContact isReached(Body body, Ray ray) { ROVector2f point = intersector.intersect(ray, body); if(point != null) { return new RayContact(ray, body, point); } return null; } }
package com.appstax.android; import com.appstax.Ax; import com.appstax.AxObject; import com.appstax.AxUser; import java.util.List; import java.util.Map; public abstract class Appstax extends Ax { public static void save(final AxObject object, final Callback<AxObject> callback) { new Request<AxObject>(callback) { protected AxObject run() { return Ax.save(object); } }; } public static void remove(final AxObject object, final Callback<AxObject> callback) { new Request<AxObject>(callback) { protected AxObject run() { return Ax.remove(object); } }; } public static void refresh(final AxObject object, final Callback<AxObject> callback) { new Request<AxObject>(callback) { protected AxObject run() { return Ax.refresh(object); } }; } public static void find(final String collection, final String id, final Callback<AxObject> callback) { new Request<AxObject>(callback) { protected AxObject run() { return Ax.find(collection, id); } }; } public static void find(final String collection, final Callback<List<AxObject>> callback) { new Request<List<AxObject>>(callback) { protected List<AxObject> run() { return Ax.find(collection); } }; } public static void filter(final String collection, final String filter, final Callback<List<AxObject>> callback) { new Request<List<AxObject>>(callback) { protected List<AxObject> run() { return Ax.filter(collection, filter); } }; } public static void filter(final String collection, final Map<String, String> properties, final Callback<List<AxObject>> callback) { new Request<List<AxObject>>(callback) { protected List<AxObject> run() { return Ax.filter(collection, properties); } }; } public static void signup(final String username, final String password, final Callback<AxUser> callback) { new Request<AxUser>(callback) { protected AxUser run() { return Ax.signup(username, password); } }; } public static void login(final String username, final String password, final Callback<AxUser> callback) { new Request<AxUser>(callback) { protected AxUser run() { return Ax.login(username, password); } }; } public static void logout(final Callback<Void> callback) { new Request<Void>(callback) { protected Void run() { Ax.logout(); return null; } }; } public static void save(final AxUser user, final Callback<AxUser> callback) { new Request<AxUser>(callback) { protected AxUser run() { return Ax.save(user); } }; } public static void refresh(final AxUser user, final Callback<AxUser> callback) { new Request<AxUser>(callback) { protected AxUser run() { return Ax.refresh(user); } }; } }
package bzh.plealog.bioinfo.ui.carto.core; import bzh.plealog.bioinfo.api.data.feature.Feature; import bzh.plealog.bioinfo.ui.carto.data.FGraphics; import bzh.plealog.bioinfo.ui.carto.painter.FeaturePainter; /** * This class can be used to associate a feature to a graphical object. * * @author Patrick G. Durand */ public class FeatureGraphics { private boolean visible = true; private Feature feature; private FGraphics fGraphics; private FeaturePainter fPainter; /** * Standard constructor. * * @param feature a feature * @param graphics the associated graphic object */ public FeatureGraphics(Feature feature, FGraphics graphics, FeaturePainter painter) { super(); this.feature = feature; fGraphics = graphics; fPainter = painter; } public Feature getFeature() { return feature; } public FGraphics getFGraphics() { return fGraphics; } public void setFeature(Feature feature) { this.feature = feature; } public void setFGraphics(FGraphics graphics) { fGraphics = graphics; } public FeaturePainter getFPainter() { return fPainter; } public void setFPainter(FeaturePainter fPainter) { this.fPainter = fPainter; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } }
package ch.ethz.inf.vs.californium.dtls; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import java.util.logging.Logger; import javax.crypto.KeyAgreement; import javax.crypto.SecretKey; import sun.security.ec.ECParameters; /** * A helper class to execute the ECDHE key agreement and key generation. * * @author Stefan Jucker * */ public class ECDHECryptography { // Logging //////////////////////////////////////////////////////// protected static final Logger LOG = Logger.getLogger(ECDHECryptography.class.getName()); // Static members ///////////////////////////////////////////////// private static final String KEYPAIR_GENERATOR_INSTANCE = "EC"; private static final String KEY_AGREEMENT_INSTANCE = "ECDH"; // Members //////////////////////////////////////////////////////// private PrivateKey privateKey; private ECPublicKey publicKey; // Constructors /////////////////////////////////////////////////// /** * Called by Server, create ephemeral key ECDH keypair. * * @param key * the server's private key. */ public ECDHECryptography(PrivateKey key) { // create ephemeral key pair try { // get the curve name by the parameters of the private key ECParameterSpec parameters = ((ECPrivateKey) key).getParams(); // namedCurve will look like this: secp192k1 (1.3.132.0.31) String namedCurve = parameters.toString(); // we only need secp192k1 the namedCurve = namedCurve.substring(0, 9); // initialize the key pair generator KeyPairGenerator kpg; kpg = KeyPairGenerator.getInstance(KEYPAIR_GENERATOR_INSTANCE); ECGenParameterSpec params = new ECGenParameterSpec(namedCurve); kpg.initialize(params, new SecureRandom()); KeyPair kp = kpg.generateKeyPair(); privateKey = kp.getPrivate(); publicKey = (ECPublicKey) kp.getPublic(); } catch (GeneralSecurityException e) { LOG.severe("Could not generate the ECDHE keypair."); e.printStackTrace(); } } /** * Called by client, with parameters provided by server. * * @param params * the parameters provided by the server's ephemeral public key. */ public ECDHECryptography(ECParameterSpec params) { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEYPAIR_GENERATOR_INSTANCE); keyPairGenerator.initialize(params, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); privateKey = keyPair.getPrivate(); publicKey = (ECPublicKey) keyPair.getPublic(); } catch (GeneralSecurityException e) { LOG.severe("Could not generate the ECDHE keypair."); e.printStackTrace(); } } public PrivateKey getPrivateKey() { return privateKey; } public void setPrivateKey(PrivateKey privateKey) { this.privateKey = privateKey; } public ECPublicKey getPublicKey() { return publicKey; } public void setPublicKey(ECPublicKey publicKey) { this.publicKey = publicKey; } /** * Called by the server. Extracts the client's public key from the encoded * point and then runs the specified key agreement algorithm (ECDH) to * generate the premaster secret. * * @param encodedPoint * the client's public key (encoded) * @return the premaster secret */ public SecretKey getSecret(byte[] encodedPoint) { SecretKey secretKey = null; try { // extract public key ECParameterSpec params = publicKey.getParams(); ECPoint point = ECParameters.decodePoint(encodedPoint, params.getCurve()); KeyFactory keyFactory = KeyFactory.getInstance(KEYPAIR_GENERATOR_INSTANCE); ECPublicKeySpec keySpec = new ECPublicKeySpec(point, params); PublicKey peerPublicKey = keyFactory.generatePublic(keySpec); secretKey = getSecret(peerPublicKey); } catch (Exception e) { LOG.severe("Could not generate the premaster secret."); e.printStackTrace(); } return secretKey; } /** * Runs the specified key agreement algorithm (ECDH) to generate the * premaster secret. * * @param peerPublicKey * the peer's ephemeral public key. * @return the premaster secret. */ public SecretKey getSecret(PublicKey peerPublicKey) { SecretKey secretKey = null; try { KeyAgreement keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_INSTANCE); keyAgreement.init(privateKey); keyAgreement.doPhase(peerPublicKey, true); secretKey = keyAgreement.generateSecret("TlsPremasterSecret"); // TODO } catch (Exception e) { e.printStackTrace(); } return secretKey; } }
package com.beepscore.android.spotifystreamer; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.List; import kaaes.spotify.webapi.android.models.Artist; import kaaes.spotify.webapi.android.models.Image; public class ArtistsArrayAdapter extends ArrayAdapter<Artist> { /** * Custom constructor (it doesn't mirror a superclass constructor). * @param context The current context. Used to inflate the layout file. * @param artistsList A List of Artist objects to display */ public ArtistsArrayAdapter(Activity context, List<Artist> artistsList) { // Initialize the ArrayAdapter's internal storage for the context and the list. // ArrayAdapter uses the second argument when populating a single TextView. // ArtistsArrayAdapter is not going to use the second argument, so it can be any value. Here, we used 0. super(context, 0, artistsList); } /** * Provides a view for an AdapterView (ListView, GridView, etc.) * * @param position The AdapterView position that is requesting a view * @param convertView The recycled view to populate. * (search online for "android view recycling" to learn more) * @param parent The parent ViewGroup that is used for inflation. * @return The View for the position in the AdapterView. */ @Override public View getView(int position, View convertView, ViewGroup parent) { // Gets the Artist object from the ArrayAdapter at the appropriate position Artist artist = getItem(position); // Adapters recycle views to AdapterViews. // If this is a new View object we're getting, then inflate the layout. // If not, this view already has the layout inflated from a previous call to getView, // and we modify the View widgets as usual. if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false); } ImageView imageView = (ImageView) convertView.findViewById(R.id.list_item_imageview); loadArtistImageView(artist, imageView); TextView artistNameView = (TextView) convertView.findViewById(R.id.list_item_textview); artistNameView.setText(artist.name); return convertView; } private void loadArtistImageView(Artist artist, ImageView imageView) { if (artist.images.size() > 0) { // get the last image because images is sorted decreasing size Image artistLastImage = artist.images.get(artist.images.size() - 1); String artistLastImageUrlString = artistLastImage.url; Picasso.with(getContext()).load(artistLastImageUrlString).into(imageView); } } }
package com.oklab.githubjourney.asynctasks; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.oklab.githubjourney.data.GitHubUserLocationDataEntry; import com.oklab.githubjourney.data.GitHubUsersDataEntry; import com.oklab.githubjourney.data.LocationConstants; import com.oklab.githubjourney.services.FetchAddressIntentService; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; public class LocationsReadyCallback implements OnMapReadyCallback, FollowersAsyncTask.OnFollowersLoadedListener,FollowingAsyncTask.OnFollowingLoadedListener, UserProfileAsyncTask.OnProfilesLoadedListener { private static final String TAG = LocationsReadyCallback.class.getSimpleName(); private final Context context; private int currentPage = 1; private int count = 0; private int followersCount = 0; private List<GitHubUsersDataEntry> followersLocationsList; private List<GitHubUsersDataEntry> followingsLocationsList; private ArrayList<GitHubUserLocationDataEntry> locationsDataList; private AddressResultReceiver mResultReceiver; private GoogleMap map; public LocationsReadyCallback(Context context) { this.context = context; } @Override public void onMapReady(GoogleMap googleMap) { new FollowersAsyncTask(context, this).execute(1); mResultReceiver = new AddressResultReceiver(new Handler()); map = googleMap; } protected void startIntentService() { Intent intent = new Intent(context, FetchAddressIntentService.class); Log.v(TAG, "locationsDataList = " + locationsDataList.size()); intent.putParcelableArrayListExtra(LocationConstants.LOCATION_DATA_EXTRA, locationsDataList); intent.putExtra(LocationConstants.RECEIVER, mResultReceiver); context.startService(intent); } @Override public void OnFollowersLoaded(List<GitHubUsersDataEntry> followersDataEntry) { followersLocationsList = followersDataEntry !=null ? followersDataEntry: Collections.emptyList(); Log.v(TAG, "followersLocationsList = " + followersLocationsList.size()); new FollowingAsyncTask(context, this).execute(1); } @Override public void onFollowingLoaded(List<GitHubUsersDataEntry> followingDataEntry) { followingsLocationsList = followingDataEntry !=null ? followingDataEntry: Collections.emptyList(); Log.v(TAG, "followingsLocationsList = " + followingsLocationsList.size()); HashSet<String> set = new HashSet<>(); ArrayList<GitHubUsersDataEntry> list = new ArrayList<>(followingsLocationsList.size() + followersLocationsList.size()); for(GitHubUsersDataEntry entry: followersLocationsList) { set.add(entry.getName()); list.add(entry); } for(GitHubUsersDataEntry entry: followingsLocationsList) { if(!set.contains(entry.getName())) { set.add(entry.getName()); list.add(entry); } } count = list.size(); Log.v(TAG, "list = " + list.size()); locationsDataList = new ArrayList<>(count); for(GitHubUsersDataEntry entry: list) { new UserProfileAsyncTask(context, this).execute(entry.getName()); } } @Override public void OnProfilesLoaded(GitHubUserLocationDataEntry locationDataEntry) { count if (locationDataEntry != null && locationDataEntry.getLocation()!=null && !locationDataEntry.getLocation().isEmpty()) { locationsDataList.add(locationDataEntry); } if(count == 0) { startIntentService(); } } class AddressResultReceiver extends ResultReceiver { public AddressResultReceiver(Handler handler) { super(handler); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { Log.v(TAG, "onReceiveResult"); ArrayList<GitHubUserLocationDataEntry> locationsList = resultData.getParcelableArrayList(LocationConstants.LOCATION_DATA_EXTRA); Log.v(TAG, "ArrayList.size() = " + locationsList.size()); for(GitHubUserLocationDataEntry entry: locationsList) { if(entry.getLatitude() != 0.0 || entry.getLongitude() != 0.0) { Log.v(TAG, "getLatitude = " + entry.getLatitude()); LatLng position = new LatLng (entry.getLatitude(), entry.getLongitude()); MarkerOptions options= new MarkerOptions().position(position).title(entry.getName()); map.addMarker(options); } } } } }
package de.cs.fau.mad.quickshop.android.view; //import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.support.v4.app.Fragment; import com.nhaarman.listviewanimations.itemmanipulation.DynamicListView; import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.OnDismissCallback; import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.SimpleSwipeUndoAdapter; import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.TimedUndoAdapter; import java.util.ArrayList; import cs.fau.mad.quickshop_android.R; import de.cs.fau.mad.quickshop.android.common.Item; import de.cs.fau.mad.quickshop.android.common.ShoppingList; import de.cs.fau.mad.quickshop.android.model.ListStorage; import de.cs.fau.mad.quickshop.android.model.messages.ItemChangeType; import de.cs.fau.mad.quickshop.android.model.messages.ItemChangedEvent; import de.cs.fau.mad.quickshop.android.model.messages.ShoppingListChangedEvent; import de.cs.fau.mad.quickshop.android.model.ListStorageFragment; import de.cs.fau.mad.quickshop.android.util.StringHelper; import de.greenrobot.event.EventBus; public class ShoppingListFragment extends Fragment { //region Constants private static final String ARG_LISTID = "list_id"; //endregion //region Fields private ShoppingListAdapter shoppingListAdapter; private ShoppingListAdapter shoppingListAdapterBought; private ListStorage listStorage; private ShoppingList shoppingList = null; private int listID; private TextView textView_QuickAdd; //endregion //region Construction public static ShoppingListFragment newInstance(int listID) { ShoppingListFragment fragment = new ShoppingListFragment(); Bundle args = new Bundle(); args.putInt(ARG_LISTID, listID); fragment.setArguments(args); return fragment; } //endregion //region Overrides @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { listID = getArguments().getInt(ARG_LISTID); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { EventBus.getDefault().register(this); new ListStorageFragment().SetupLocalListStorageFragment(getActivity()); listStorage = ListStorageFragment.getLocalListStorage(); View rootView = inflater.inflate(R.layout.fragment_shoppinglist, container, false); DynamicListView shoppingListView = (DynamicListView) rootView.findViewById(R.id.list_shoppingList); DynamicListView shoppingListViewBought = (DynamicListView) rootView.findViewById(R.id.list_shoppingListBought); try { shoppingList = listStorage.loadList(listID); } catch (IllegalArgumentException ex) { //TODO: we should probably introduce our own exception types showToast(ex.getMessage()); Intent intent = new Intent(getActivity(), ShoppingListActivity.class); startActivity(intent); } if (shoppingList != null) { // Upper list for Items that are not yet bought shoppingListAdapter = new ShoppingListAdapter(getActivity(), R.id.list_shoppingList, generateData(shoppingList, false), shoppingList); SimpleSwipeUndoAdapter swipeUndoAdapter = new TimedUndoAdapter(shoppingListAdapter, getActivity(), new OnDismissCallback() { @Override public void onDismiss(@NonNull final ViewGroup listView, @NonNull final int[] reverseSortedPositions) { for (int position : reverseSortedPositions) { shoppingListAdapter.removeByPosition(position); UpdateLists(); } } } ); swipeUndoAdapter.setAbsListView(shoppingListView); shoppingListView.setAdapter(swipeUndoAdapter); shoppingListView.enableSimpleSwipeUndo(); // Lower list for Items that are already bought shoppingListAdapterBought = new ShoppingListAdapter(getActivity(), R.id.list_shoppingListBought, generateData(shoppingList, true), shoppingList); shoppingListViewBought.enableSwipeToDismiss( new OnDismissCallback() { @Override public void onDismiss(@NonNull final ViewGroup listView, @NonNull final int[] reverseSortedPositions) { for (int position : reverseSortedPositions) { shoppingListAdapterBought.removeByPosition(position); UpdateLists(); } } } ); shoppingListViewBought.setAdapter(shoppingListAdapterBought); // OnClickListener to open the item details view /*shoppingListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Open item details view Toast.makeText(getActivity(), "ID: " + id + " - PID: " + parent.getItemIdAtPosition(position), Toast.LENGTH_LONG).show(); fm.beginTransaction().replace(BaseActivity.frameLayout.getId() , ItemDetailsFragment.newInstance(listID, (int) id)) .addToBackStack(null).commit(); } });*/ View fab = rootView.findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Fragment newItemFragment = ItemDetailsFragment.newInstance(listID); getActivity().getSupportFragmentManager() .beginTransaction() .replace(BaseActivity.frameLayout.getId(), newItemFragment) .addToBackStack(null).commit(); } }); textView_QuickAdd = (TextView) rootView.findViewById(R.id.textView_quickAdd); View button_QuickAdd = rootView.findViewById(R.id.button_quickAdd); button_QuickAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //adding empty items without a name is not supported if (!StringHelper.isNullOrWhiteSpace(textView_QuickAdd.getText())) { Item newItem = new Item(); newItem.setName(textView_QuickAdd.getText().toString()); shoppingList.addItem(newItem); listStorage.saveList(shoppingList); EventBus.getDefault().post(new ItemChangedEvent(ItemChangeType.Added, shoppingList.getId(), newItem.getId())); //reset quick add text textView_QuickAdd.setText(""); } } }); //Setting spinner adapter to sort by button Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.sort_by_array, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner spinner.setAdapter(adapter); } return rootView; } @Override public void onDestroyView() { super.onDestroyView(); EventBus.getDefault().unregister(this); } //endregion //region Event Handlers public void onEvent(ShoppingListChangedEvent event) { if (event.getListId() == this.listID && this.shoppingListAdapter != null) { UpdateLists(); } } public void onEvent(ItemChangedEvent event) { if (event.getShoppingListId() == this.listID && this.shoppingListAdapter != null) { UpdateLists(); } } //endregion //region Private Methods private void UpdateLists() { shoppingListAdapter.clear(); shoppingListAdapter.addAll(generateData(listStorage.loadList(listID), false)); shoppingListAdapter.notifyDataSetChanged(); shoppingListAdapterBought.clear(); shoppingListAdapterBought.addAll(generateData(listStorage.loadList(listID), true)); shoppingListAdapterBought.notifyDataSetChanged(); } private ArrayList<Integer> generateData(ShoppingList shoppingList, boolean isBought) { ArrayList<Integer> items = new ArrayList<>(); for (Item item : shoppingList.getItems()) { if(item.isBought() == isBought) items.add(item.getId()); } return items; } //region Private Methods private void showToast(String text) { int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(getActivity(), text, duration); toast.show(); } //endregion }
package de.fau.amos.virtualledger.android.dagger.module; import android.app.Application; import android.util.Log; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import org.apache.commons.lang3.math.NumberUtils; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; @Module public class NetModule { private String baseUrl; /** * @param baseUrl * @methodtype constructor */ public NetModule(String baseUrl) { this.baseUrl = baseUrl; } /** * @param application * @return cache */ @Provides Cache provideHttpCache(Application application) { int cacheSize = 10 * 1024 * 1024; Cache cache = new Cache(application.getCacheDir(), cacheSize); return cache; } /** * @return Gson */ @Provides Gson provideGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { //FIXME Quick fix to parse two different date formats. Should make sure the server only returns one format instead! final String jsonString = json.getAsJsonPrimitive().getAsString(); if(NumberUtils.isParsable(jsonString)) { return new Date(NumberUtils.createLong(jsonString)); } else { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH); try { return dateFormat.parse(jsonString.replaceAll("Z$", "+0000")); } catch (ParseException e) { Log.e("", "Failed parsing date"); return null; } } } }); return gsonBuilder.create(); } /** * @param cache * @return OkHttpClient */ @Provides OkHttpClient provideOkhttpClient(Cache cache) { OkHttpClient.Builder client = new OkHttpClient.Builder(); client.cache(cache); return client.build(); } /** * @param gson * @param okHttpClient * @return Retrofit */ @Provides Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(baseUrl) .client(okHttpClient) .build(); } }
package de.markusfisch.android.shadereditor.opengl; import de.markusfisch.android.shadereditor.app.ShaderEditorApplication; import de.markusfisch.android.shadereditor.fragment.SamplerPropertiesFragment; import de.markusfisch.android.shadereditor.hardware.AccelerometerListener; import de.markusfisch.android.shadereditor.hardware.GyroscopeListener; import de.markusfisch.android.shadereditor.hardware.MagneticFieldListener; import de.markusfisch.android.shadereditor.hardware.LightListener; import de.markusfisch.android.shadereditor.hardware.PressureListener; import de.markusfisch.android.shadereditor.hardware.ProximityListener; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.Matrix; import android.hardware.SensorManager; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.os.BatteryManager; import android.view.MotionEvent; import java.io.ByteArrayOutputStream; import java.lang.IllegalArgumentException; import java.lang.InterruptedException; import java.nio.ByteBuffer; import java.nio.IntBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11ExtensionPack; import java.util.ArrayList; import java.util.Calendar; import java.util.regex.Pattern; import java.util.regex.Matcher; public class ShaderRenderer implements GLSurfaceView.Renderer { public interface OnRendererListener { void onInfoLog(String error); void onFramesPerSecond(int fps); } public static final String BACKBUFFER = "backbuffer"; private static final int TEXTURE_UNITS[] = { GLES20.GL_TEXTURE0, GLES20.GL_TEXTURE1, GLES20.GL_TEXTURE2, GLES20.GL_TEXTURE3, GLES20.GL_TEXTURE4, GLES20.GL_TEXTURE5, GLES20.GL_TEXTURE6, GLES20.GL_TEXTURE7, GLES20.GL_TEXTURE8, GLES20.GL_TEXTURE9, GLES20.GL_TEXTURE10, GLES20.GL_TEXTURE11, GLES20.GL_TEXTURE12, GLES20.GL_TEXTURE13, GLES20.GL_TEXTURE14, GLES20.GL_TEXTURE15, GLES20.GL_TEXTURE16, GLES20.GL_TEXTURE17, GLES20.GL_TEXTURE18, GLES20.GL_TEXTURE19, GLES20.GL_TEXTURE20, GLES20.GL_TEXTURE21, GLES20.GL_TEXTURE22, GLES20.GL_TEXTURE23, GLES20.GL_TEXTURE24, GLES20.GL_TEXTURE25, GLES20.GL_TEXTURE26, GLES20.GL_TEXTURE27, GLES20.GL_TEXTURE28, GLES20.GL_TEXTURE29, GLES20.GL_TEXTURE30, GLES20.GL_TEXTURE31}; private static final int CUBE_MAP_TARGETS[] = { // all sides of a cube are stored in a single // rectangular source image for compactness: // /| -Z | | -X | -Z | // |/ -Y / | -Y | | -X | -Z | // > | +Y | -Y | // / +Y /| | +Y | | +Z | +X | // | +Z |/ | +Z | +X | // so, from left to right, top to bottom: GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_POSITIVE_X}; private static final float NS_PER_SECOND = 1000000000f; private static final long FPS_UPDATE_FREQUENCY_NS = 200000000L; private static final long BATTERY_UPDATE_INTERVAL = 10000000000L; private static final long DATE_UPDATE_INTERVAL = 1000000000L; private static final Pattern PATTERN_SAMPLER = Pattern.compile( String.format( "uniform[ \t]+sampler(2D|Cube)+[ \t]+(%s);[ \t]*(.*)", SamplerPropertiesFragment.TEXTURE_NAME_PATTERN)); private static final Pattern PATTERN_FTIME = Pattern.compile( "^#define[ \\t]+FTIME_PERIOD[ \\t]+([0-9\\.]+)[ \\t]*$", Pattern.MULTILINE); private static final String VERTEX_SHADER = "attribute vec2 position;" + "void main()" + "{" + "gl_Position = vec4( position, 0., 1. );" + "}"; private static final String FRAGMENT_SHADER = "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" + "precision highp float;\n" + "#else\n" + "precision mediump float;\n" + "#endif\n" + "uniform vec2 resolution;" + "uniform sampler2D frame;" + "void main( void )" + "{" + "gl_FragColor = texture2D( " + "frame," + "gl_FragCoord.xy/resolution.xy ).rgba;" + "}"; private final TextureBinder textureBinder = new TextureBinder(); private final ArrayList<String> textureNames = new ArrayList<>(); private final ArrayList<TextureParameters> textureParameters = new ArrayList<>(); private final TextureParameters backBufferTextureParams = new TextureParameters( GLES20.GL_NEAREST, GLES20.GL_NEAREST, GLES20.GL_CLAMP_TO_EDGE, GLES20.GL_CLAMP_TO_EDGE); private final Matrix flipMatrix = new Matrix(); private final int fb[] = new int[]{0, 0}; private final int tx[] = new int[]{0, 0}; private final int textureLocs[] = new int[32]; private final int textureTargets[] = new int[32]; private final int textureIds[] = new int[32]; private final float surfaceResolution[] = new float[]{0, 0}; private final float resolution[] = new float[]{0, 0}; private final float touch[] = new float[]{0, 0}; private final float mouse[] = new float[]{0, 0}; private final float pointers[] = new float[30]; private final float offset[] = new float[]{0, 0}; private final float dateTime[] = new float[]{0, 0, 0, 0}; private final float rotationMatrix[] = new float[9]; private final float orientation[] = new float[]{0, 0, 0}; private final Context context; private final ByteBuffer vertexBuffer; private AccelerometerListener accelerometerListener; private GyroscopeListener gyroscopeListener; private MagneticFieldListener magneticFieldListener; private LightListener lightListener; private PressureListener pressureListener; private ProximityListener proximityListener; private OnRendererListener onRendererListener; private String fragmentShader; private int surfaceProgram = 0; private int surfacePositionLoc; private int surfaceResolutionLoc; private int surfaceFrameLoc; private int program = 0; private int positionLoc; private int timeLoc; private int secondLoc; private int subSecondLoc; private int fTimeLoc; private int resolutionLoc; private int touchLoc; private int mouseLoc; private int pointerCountLoc; private int pointersLoc; private int gravityLoc; private int linearLoc; private int rotationLoc; private int magneticLoc; private int orientationLoc; private int lightLoc; private int pressureLoc; private int proximityLoc; private int offsetLoc; private int batteryLoc; private int dateTimeLoc; private int startRandomLoc; private int backBufferLoc; private int numberOfTextures = 0; private int pointerCount; private int frontTarget = 0; private int backTarget = 1; private long startTime; private long lastRender; private long lastBatteryUpdate; private long lastDateUpdate; private float batteryLevel; private float quality = 1f; private float startRandom; private float fTimeMax; private volatile byte thumbnail[] = new byte[1]; private volatile long nextFpsUpdate = 0; private volatile float sum; private volatile float samples; private volatile int lastFps; public ShaderRenderer(Context context) { this.context = context; flipMatrix.postScale(1f, -1f); vertexBuffer = ByteBuffer.allocateDirect(8); vertexBuffer.put(new byte[]{ -1, 1, -1, -1, 1, 1, 1, -1}).position(0); } public void setFragmentShader(String source, float quality) { setQuality(quality); setFragmentShader(source); } public void setFragmentShader(String source) { fTimeMax = parseFTime(source); resetFps(); fragmentShader = source; indexTextureNames(source); } public void setQuality(float quality) { this.quality = quality; } public void setOnRendererListener(OnRendererListener listener) { onRendererListener = listener; } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { GLES20.glDisable(GLES20.GL_CULL_FACE); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glClearColor(0f, 0f, 0f, 1f); if (surfaceProgram != 0) { // Don't glDeleteProgram( surfaceProgram ) because // GLSurfaceView::onPause() destroys the GL context // what also deletes all programs. // With glDeleteProgram(): // <core_glDeleteProgram:594>: GL_INVALID_VALUE surfaceProgram = 0; } if (program != 0) { // Don't glDeleteProgram( program ); // same as above program = 0; deleteTargets(); } if (fragmentShader != null && fragmentShader.length() > 0) { resetFps(); createTextures(); loadPrograms(); indexLocations(); enableAttribArrays(); registerListeners(); } } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { startTime = lastRender = System.nanoTime(); startRandom = (float) Math.random(); surfaceResolution[0] = width; surfaceResolution[1] = height; float w = Math.round(width * quality); float h = Math.round(height * quality); if (w != resolution[0] || h != resolution[1]) { deleteTargets(); } resolution[0] = w; resolution[1] = h; resetFps(); } @Override public void onDrawFrame(GL10 gl) { if (surfaceProgram == 0 || program == 0) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); return; } final long now = System.nanoTime(); GLES20.glUseProgram(program); GLES20.glVertexAttribPointer( positionLoc, 2, GLES20.GL_BYTE, false, 0, vertexBuffer); float delta = (now - startTime) / NS_PER_SECOND; if (timeLoc > -1) { GLES20.glUniform1f( timeLoc, delta); } if (secondLoc > -1) { GLES20.glUniform1i( secondLoc, (int) delta); } if (subSecondLoc > -1) { GLES20.glUniform1f( subSecondLoc, delta - (int) delta); } if (fTimeLoc > -1) { GLES20.glUniform1f( fTimeLoc, ((delta % fTimeMax) / fTimeMax * 2f - 1f)); } if (resolutionLoc > -1) { GLES20.glUniform2fv( resolutionLoc, 1, resolution, 0); } if (touchLoc > -1) { GLES20.glUniform2fv( touchLoc, 1, touch, 0); } if (mouseLoc > -1) { GLES20.glUniform2fv( mouseLoc, 1, mouse, 0); } if (pointerCountLoc > -1) { GLES20.glUniform1i( pointerCountLoc, pointerCount); } if (pointersLoc > -1) { GLES20.glUniform3fv( pointersLoc, pointerCount, pointers, 0); } if (gravityLoc > -1 && accelerometerListener != null) { GLES20.glUniform3fv( gravityLoc, 1, accelerometerListener.gravity, 0); } if (linearLoc > -1 && accelerometerListener != null) { GLES20.glUniform3fv( linearLoc, 1, accelerometerListener.linear, 0); } if (rotationLoc > -1 && gyroscopeListener != null) { GLES20.glUniform3fv( rotationLoc, 1, gyroscopeListener.rotation, 0); } if (magneticLoc > -1 && magneticFieldListener != null) { GLES20.glUniform3fv( magneticLoc, 1, magneticFieldListener.values, 0); } if (orientationLoc > -1 && accelerometerListener != null && magneticFieldListener != null) { SensorManager.getRotationMatrix( rotationMatrix, null, accelerometerListener.values, magneticFieldListener.values); SensorManager.getOrientation(rotationMatrix, orientation); GLES20.glUniform3fv( orientationLoc, 1, orientation, 0); } if (lightLoc > -1 && lightListener != null) { GLES20.glUniform1f( lightLoc, lightListener.ambient); } if (pressureLoc > -1 && pressureListener != null) { GLES20.glUniform1f( pressureLoc, pressureListener.pressure); } if (proximityLoc > -1 && proximityListener != null) { GLES20.glUniform1f( proximityLoc, proximityListener.centimeters); } if (offsetLoc > -1) { GLES20.glUniform2fv( offsetLoc, 1, offset, 0); } if (batteryLoc > -1) { if (now - lastBatteryUpdate > BATTERY_UPDATE_INTERVAL) { // profiled getBatteryLevel() on slow/old devices // and it can take up to 6ms, so better do that // not for every frame but only once in a while batteryLevel = getBatteryLevel(); lastBatteryUpdate = now; } GLES20.glUniform1f( batteryLoc, batteryLevel); } if (dateTimeLoc > -1) { if (now - lastDateUpdate > DATE_UPDATE_INTERVAL) { Calendar calendar = Calendar.getInstance(); dateTime[0] = calendar.get(Calendar.YEAR); dateTime[1] = calendar.get(Calendar.MONTH); dateTime[2] = calendar.get(Calendar.DAY_OF_MONTH); dateTime[3] = calendar.get(Calendar.HOUR_OF_DAY) * 3600f + calendar.get(Calendar.MINUTE) * 60f + calendar.get(Calendar.SECOND); lastDateUpdate = now; } GLES20.glUniform4fv( dateTimeLoc, 1, dateTime, 0); } if (startRandomLoc > -1) { GLES20.glUniform1f( startRandomLoc, startRandom); } if (fb[0] == 0) { createTargets( (int) resolution[0], (int) resolution[1]); } // first draw custom shader in framebuffer GLES20.glViewport( 0, 0, (int) resolution[0], (int) resolution[1]); textureBinder.reset(); if (backBufferLoc > -1) { textureBinder.bind( backBufferLoc, GLES20.GL_TEXTURE_2D, tx[backTarget]); } for (int i = 0; i < numberOfTextures; ++i) { textureBinder.bind( textureLocs[i], textureTargets[i], textureIds[i]); } GLES20.glBindFramebuffer( GLES20.GL_FRAMEBUFFER, fb[frontTarget]); GLES20.glDrawArrays( GLES20.GL_TRIANGLE_STRIP, 0, 4); // then draw framebuffer on screen GLES20.glBindFramebuffer( GLES20.GL_FRAMEBUFFER, 0); GLES20.glViewport( 0, 0, (int) surfaceResolution[0], (int) surfaceResolution[1]); GLES20.glUseProgram(surfaceProgram); GLES20.glVertexAttribPointer( surfacePositionLoc, 2, GLES20.GL_BYTE, false, 0, vertexBuffer); GLES20.glUniform2fv( surfaceResolutionLoc, 1, surfaceResolution, 0); GLES20.glUniform1i(surfaceFrameLoc, 0); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture( GLES20.GL_TEXTURE_2D, tx[frontTarget]); GLES20.glClear( GLES20.GL_COLOR_BUFFER_BIT); GLES20.glDrawArrays( GLES20.GL_TRIANGLE_STRIP, 0, 4); // swap buffers so the next image will be rendered // over the current backbuffer and the current image // will be the backbuffer for the next image int t = frontTarget; frontTarget = backTarget; backTarget = t; if (thumbnail == null) { thumbnail = saveThumbnail(); } if (onRendererListener != null) { updateFps(now); } } public void unregisterListeners() { if (accelerometerListener != null) { accelerometerListener.unregister(); } if (gyroscopeListener != null) { gyroscopeListener.unregister(); } if (magneticFieldListener != null) { magneticFieldListener.unregister(); } if (lightListener != null) { lightListener.unregister(); } if (pressureListener != null) { pressureListener.unregister(); } if (proximityListener != null) { proximityListener.unregister(); } } public void touchAt(MotionEvent e) { float x = e.getX() * quality; float y = e.getY() * quality; touch[0] = x; touch[1] = resolution[1] - y; mouse[0] = x / resolution[0]; mouse[1] = 1 - y / resolution[1]; switch (e.getActionMasked()) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: pointerCount = 0; return; } pointerCount = Math.min( e.getPointerCount(), pointers.length / 3); for (int i = 0, offset = 0; i < pointerCount; ++i) { pointers[offset++] = e.getX(i) * quality; pointers[offset++] = resolution[1] - e.getY(i) * quality; pointers[offset++] = e.getTouchMajor(i); } } public void setOffset(float x, float y) { offset[0] = x; offset[1] = y; } public byte[] getThumbnail() { // settings thumbnail to null triggers // the capture on the OpenGL thread in // onDrawFrame() thumbnail = null; try { for (int trys = 10; trys-- > 0 && program > 0 && thumbnail == null; ) { Thread.sleep(100); } } catch (InterruptedException e) { // thread got interrupted, ignore that } // don't clone() because the data doesn't need to be // protected from modification what means copying would // only mean using more memory than necessary return thumbnail; } private void resetFps() { sum = samples = 0; lastFps = 0; nextFpsUpdate = 0; } private void loadPrograms() { if (((surfaceProgram = Program.loadProgram( VERTEX_SHADER, FRAGMENT_SHADER)) == 0 || (program = Program.loadProgram( VERTEX_SHADER, fragmentShader)) == 0) && onRendererListener != null) { onRendererListener.onInfoLog(Program.getInfoLog()); } } private void indexLocations() { surfacePositionLoc = GLES20.glGetAttribLocation( surfaceProgram, "position"); surfaceResolutionLoc = GLES20.glGetUniformLocation( surfaceProgram, "resolution"); surfaceFrameLoc = GLES20.glGetUniformLocation( surfaceProgram, "frame"); positionLoc = GLES20.glGetAttribLocation( program, "position"); timeLoc = GLES20.glGetUniformLocation( program, "time"); secondLoc = GLES20.glGetUniformLocation( program, "second"); subSecondLoc = GLES20.glGetUniformLocation( program, "subsecond"); fTimeLoc = GLES20.glGetUniformLocation( program, "ftime"); resolutionLoc = GLES20.glGetUniformLocation( program, "resolution"); touchLoc = GLES20.glGetUniformLocation( program, "touch"); mouseLoc = GLES20.glGetUniformLocation( program, "mouse"); pointerCountLoc = GLES20.glGetUniformLocation( program, "pointerCount"); pointersLoc = GLES20.glGetUniformLocation( program, "pointers"); gravityLoc = GLES20.glGetUniformLocation( program, "gravity"); linearLoc = GLES20.glGetUniformLocation( program, "linear"); rotationLoc = GLES20.glGetUniformLocation( program, "rotation"); magneticLoc = GLES20.glGetUniformLocation( program, "magnetic"); orientationLoc = GLES20.glGetUniformLocation( program, "orientation"); lightLoc = GLES20.glGetUniformLocation( program, "light"); pressureLoc = GLES20.glGetUniformLocation( program, "pressure"); proximityLoc = GLES20.glGetUniformLocation( program, "proximity"); offsetLoc = GLES20.glGetUniformLocation( program, "offset"); batteryLoc = GLES20.glGetUniformLocation( program, "battery"); dateTimeLoc = GLES20.glGetUniformLocation( program, "date"); startRandomLoc = GLES20.glGetUniformLocation( program, "startRandom"); backBufferLoc = GLES20.glGetUniformLocation( program, BACKBUFFER); for (int i = numberOfTextures; i textureLocs[i] = GLES20.glGetUniformLocation( program, textureNames.get(i)); } } private void enableAttribArrays() { GLES20.glEnableVertexAttribArray(surfacePositionLoc); GLES20.glEnableVertexAttribArray(positionLoc); } private void registerListeners() { if (gravityLoc > -1 || linearLoc > -1 || orientationLoc > -1) { if (accelerometerListener == null) { accelerometerListener = new AccelerometerListener(context); } accelerometerListener.register(); } if (rotationLoc > -1) { if (gyroscopeListener == null) { gyroscopeListener = new GyroscopeListener(context); } gyroscopeListener.register(); } if (magneticLoc > -1 || orientationLoc > -1) { if (magneticFieldListener == null) { magneticFieldListener = new MagneticFieldListener(context); } magneticFieldListener.register(); } if (lightLoc > -1) { if (lightListener == null) { lightListener = new LightListener(context); } lightListener.register(); } if (pressureLoc > -1) { if (pressureListener == null) { pressureListener = new PressureListener(context); } pressureListener.register(); } if (proximityLoc > -1) { if (proximityListener == null) { proximityListener = new ProximityListener(context); } proximityListener.register(); } } private byte[] saveThumbnail() { final int min = (int) Math.min( surfaceResolution[0], surfaceResolution[1]); final int pixels = min * min; final int rgba[] = new int[pixels]; final int bgra[] = new int[pixels]; final IntBuffer colorBuffer = IntBuffer.wrap(rgba); GLES20.glReadPixels( 0, 0, min, min, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, colorBuffer); for (int i = 0, e = pixels; i < pixels; ) { e -= min; for (int x = min, b = e; x-- > 0; ++i, ++b) { final int c = rgba[i]; bgra[b] = ((c >> 16) & 0xff) | ((c << 16) & 0xff0000) | (c & 0xff00ff00); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); Bitmap.createScaledBitmap( Bitmap.createBitmap( bgra, min, min, Bitmap.Config.ARGB_8888), 144, 144, true).compress( Bitmap.CompressFormat.PNG, 100, out); return out.toByteArray(); } catch (IllegalArgumentException e) { // will never happen because neither // width nor height <= 0 return null; } } private void updateFps(long now) { long delta = now - lastRender; // because sum and samples are volatile synchronized (this) { sum += Math.min(NS_PER_SECOND / delta, 60f); if (++samples > 0xffff) { sum = sum / samples; samples = 1; } } if (now > nextFpsUpdate) { int fps = Math.round(sum / samples); if (fps != lastFps) { onRendererListener.onFramesPerSecond(fps); lastFps = fps; } nextFpsUpdate = now + FPS_UPDATE_FREQUENCY_NS; } lastRender = now; } private void deleteTargets() { if (fb[0] == 0) { return; } GLES20.glDeleteFramebuffers(2, fb, 0); GLES20.glDeleteTextures(2, tx, 0); fb[0] = 0; } private void createTargets(int width, int height) { deleteTargets(); GLES20.glGenFramebuffers(2, fb, 0); GLES20.glGenTextures(2, tx, 0); createTarget(frontTarget, width, height, backBufferTextureParams); createTarget(backTarget, width, height, backBufferTextureParams); // unbind textures that were bound in createTarget() GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); } private void createTarget( int idx, int width, int height, TextureParameters tp) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tx[idx]); GLES20.glTexImage2D( GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null); tp.set(GLES20.GL_TEXTURE_2D); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); GLES20.glBindFramebuffer( GLES20.GL_FRAMEBUFFER, fb[idx]); GLES20.glFramebufferTexture2D( GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, tx[idx], 0); // clear texture because some drivers // don't initialize texture memory GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); } private void deleteTextures() { if (textureIds[0] == 1 || numberOfTextures < 1) { return; } GLES20.glDeleteTextures(numberOfTextures, textureIds, 0); } private void createTextures() { deleteTextures(); GLES20.glGenTextures(numberOfTextures, textureIds, 0); for (int i = 0; i < numberOfTextures; ++i) { Bitmap bitmap = ShaderEditorApplication .dataSource .getTextureBitmap(textureNames.get(i)); if (bitmap == null) { continue; } switch (textureTargets[i]) { default: continue; case GLES20.GL_TEXTURE_2D: createTexture(textureIds[i], bitmap, textureParameters.get(i)); break; case GLES20.GL_TEXTURE_CUBE_MAP: createCubeTexture(textureIds[i], bitmap, textureParameters.get(i)); break; } bitmap.recycle(); } } private void createTexture( int id, Bitmap bitmap, TextureParameters tp) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, id); tp.set(GLES20.GL_TEXTURE_2D); // flip bitmap because 0/0 is bottom left in OpenGL Bitmap flippedBitmap = Bitmap.createBitmap( bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), flipMatrix, true); GLUtils.texImage2D( GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, flippedBitmap, GLES20.GL_UNSIGNED_BYTE, 0); flippedBitmap.recycle(); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); } private void createCubeTexture( int id, Bitmap bitmap, TextureParameters tp) { GLES20.glBindTexture(GLES20.GL_TEXTURE_CUBE_MAP, id); tp.set(GLES20.GL_TEXTURE_CUBE_MAP); int bitmapWidth = bitmap.getWidth(); int bitmapHeight = bitmap.getHeight(); int sideWidth = (int) Math.ceil(bitmapWidth / 2f); int sideHeight = Math.round(bitmapHeight / 3f); int sideLength = Math.min(sideWidth, sideHeight); int x = 0; int y = 0; for (int target : CUBE_MAP_TARGETS) { Bitmap side = Bitmap.createBitmap( bitmap, x, y, // cube textures need to be quadratic sideLength, sideLength, // don't flip cube textures null, true); GLUtils.texImage2D( target, 0, GLES20.GL_RGBA, side, GLES20.GL_UNSIGNED_BYTE, 0); side.recycle(); if ((x += sideWidth) >= bitmapWidth) { x = 0; y += sideHeight; } } GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_CUBE_MAP); } private static float parseFTime(String source) { if (source != null) { Matcher m = PATTERN_FTIME.matcher(source); if (m.find() && m.groupCount() > 0) { return Float.parseFloat(m.group(1)); } } return 3f; } private void indexTextureNames(String source) { if (source == null) { return; } textureNames.clear(); textureParameters.clear(); numberOfTextures = 0; final int maxTextures = textureIds.length; for (Matcher m = PATTERN_SAMPLER.matcher(source); m.find() && numberOfTextures < maxTextures; ) { String type = m.group(1); String name = m.group(2); String params = m.group(3); if (type == null || name == null) { continue; } if (name.equals(BACKBUFFER)) { backBufferTextureParams.parse(params); continue; } int target; switch (type) { case "2D": target = GLES20.GL_TEXTURE_2D; break; case "Cube": target = GLES20.GL_TEXTURE_CUBE_MAP; break; default: continue; } textureTargets[numberOfTextures++] = target; textureNames.add(name); textureParameters.add(new TextureParameters(params)); } } private float getBatteryLevel() { Intent batteryStatus = context.registerReceiver( null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); if (batteryStatus == null) { return 0; } int level = batteryStatus.getIntExtra( BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra( BatteryManager.EXTRA_SCALE, -1); return (float) level / scale; } private static class TextureBinder { private int index; private void reset() { index = 0; } private void bind(int loc, int target, int textureId) { if (loc < 0 || index >= TEXTURE_UNITS.length) { return; } GLES20.glUniform1i(loc, index); GLES20.glActiveTexture(TEXTURE_UNITS[index]); GLES20.glBindTexture(target, textureId); ++index; } } }
package de.markusfisch.android.shadereditor.opengl; import de.markusfisch.android.shadereditor.app.ShaderEditorApp; import de.markusfisch.android.shadereditor.fragment.AbstractSamplerPropertiesFragment; import de.markusfisch.android.shadereditor.hardware.AccelerometerListener; import de.markusfisch.android.shadereditor.hardware.CameraListener; import de.markusfisch.android.shadereditor.hardware.GravityListener; import de.markusfisch.android.shadereditor.hardware.GyroscopeListener; import de.markusfisch.android.shadereditor.hardware.MagneticFieldListener; import de.markusfisch.android.shadereditor.hardware.LightListener; import de.markusfisch.android.shadereditor.hardware.LinearAccelerationListener; import de.markusfisch.android.shadereditor.hardware.PressureListener; import de.markusfisch.android.shadereditor.hardware.ProximityListener; import de.markusfisch.android.shadereditor.hardware.RotationVectorListener; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.hardware.Camera; import android.hardware.SensorManager; import android.opengl.GLES11Ext; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.os.BatteryManager; import android.os.Build; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.view.MotionEvent; import android.view.Surface; import android.view.WindowManager; import java.io.ByteArrayOutputStream; import java.lang.IllegalArgumentException; import java.lang.InterruptedException; import java.nio.ByteBuffer; import java.nio.IntBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11ExtensionPack; import java.util.ArrayList; import java.util.Calendar; import java.util.regex.Pattern; import java.util.regex.Matcher; public class ShaderRenderer implements GLSurfaceView.Renderer { public interface OnRendererListener { void onInfoLog(String error); void onFramesPerSecond(int fps); } public static final String UNIFORM_BACKBUFFER = "backbuffer"; public static final String UNIFORM_BATTERY = "battery"; public static final String UNIFORM_CAMERA_ADDENT = "cameraAddent"; public static final String UNIFORM_CAMERA_BACK = "cameraBack"; public static final String UNIFORM_CAMERA_FRONT = "cameraFront"; public static final String UNIFORM_CAMERA_ORIENTATION = "cameraOrientation"; public static final String UNIFORM_DATE = "date"; public static final String UNIFORM_FRAME_NUMBER = "frame"; public static final String UNIFORM_FTIME = "ftime"; public static final String UNIFORM_GRAVITY = "gravity"; public static final String UNIFORM_GYROSCOPE = "gyroscope"; public static final String UNIFORM_LIGHT = "light"; public static final String UNIFORM_LINEAR = "linear"; public static final String UNIFORM_MAGNETIC = "magnetic"; public static final String UNIFORM_MOUSE = "mouse"; public static final String UNIFORM_OFFSET = "offset"; public static final String UNIFORM_ORIENTATION = "orientation"; public static final String UNIFORM_INCLINATION = "inclination"; public static final String UNIFORM_INCLINATION_MATRIX = "inclinationMatrix"; public static final String UNIFORM_POINTERS = "pointers"; public static final String UNIFORM_POINTER_COUNT = "pointerCount"; public static final String UNIFORM_POSITION = "position"; public static final String UNIFORM_PRESSURE = "pressure"; public static final String UNIFORM_PROXIMITY = "proximity"; public static final String UNIFORM_RESOLUTION = "resolution"; public static final String UNIFORM_ROTATION_MATRIX = "rotationMatrix"; public static final String UNIFORM_ROTATION_VECTOR = "rotationVector"; public static final String UNIFORM_SECOND = "second"; public static final String UNIFORM_START_RANDOM = "startRandom"; public static final String UNIFORM_SUB_SECOND = "subsecond"; public static final String UNIFORM_TIME = "time"; public static final String UNIFORM_TOUCH = "touch"; private static final int[] TEXTURE_UNITS = { GLES20.GL_TEXTURE0, GLES20.GL_TEXTURE1, GLES20.GL_TEXTURE2, GLES20.GL_TEXTURE3, GLES20.GL_TEXTURE4, GLES20.GL_TEXTURE5, GLES20.GL_TEXTURE6, GLES20.GL_TEXTURE7, GLES20.GL_TEXTURE8, GLES20.GL_TEXTURE9, GLES20.GL_TEXTURE10, GLES20.GL_TEXTURE11, GLES20.GL_TEXTURE12, GLES20.GL_TEXTURE13, GLES20.GL_TEXTURE14, GLES20.GL_TEXTURE15, GLES20.GL_TEXTURE16, GLES20.GL_TEXTURE17, GLES20.GL_TEXTURE18, GLES20.GL_TEXTURE19, GLES20.GL_TEXTURE20, GLES20.GL_TEXTURE21, GLES20.GL_TEXTURE22, GLES20.GL_TEXTURE23, GLES20.GL_TEXTURE24, GLES20.GL_TEXTURE25, GLES20.GL_TEXTURE26, GLES20.GL_TEXTURE27, GLES20.GL_TEXTURE28, GLES20.GL_TEXTURE29, GLES20.GL_TEXTURE30, GLES20.GL_TEXTURE31}; private static final int[] CUBE_MAP_TARGETS = { // all sides of a cube are stored in a single // rectangular source image for compactness: // /| -Z | | -X | -Z | // |/ -Y / | -Y | | -X | -Z | // > | +Y | -Y | // / +Y /| | +Y | | +Z | +X | // | +Z |/ | +Z | +X | // so, from left to right, top to bottom: GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL11ExtensionPack.GL_TEXTURE_CUBE_MAP_POSITIVE_X}; private static final float NS_PER_SECOND = 1000000000f; private static final long FPS_UPDATE_FREQUENCY_NS = 200000000L; private static final long BATTERY_UPDATE_INTERVAL = 10000000000L; private static final long DATE_UPDATE_INTERVAL = 1000000000L; private static final String SAMPLER_2D = "2D"; private static final String SAMPLER_CUBE = "Cube"; private static final String SAMPLER_EXTERNAL_OES = "ExternalOES"; private static final Pattern PATTERN_SAMPLER = Pattern.compile( String.format( "uniform[ \t]+sampler(" + SAMPLER_2D + "|" + SAMPLER_CUBE + "|" + SAMPLER_EXTERNAL_OES + ")+[ \t]+(%s);[ \t]*(.*)", AbstractSamplerPropertiesFragment.TEXTURE_NAME_PATTERN)); private static final Pattern PATTERN_FTIME = Pattern.compile( "^#define[ \\t]+FTIME_PERIOD[ \\t]+([0-9\\.]+)[ \\t]*$", Pattern.MULTILINE); private static final String OES_EXTERNAL = "#extension GL_OES_EGL_image_external : require\n"; private static final String VERTEX_SHADER = "attribute vec2 position;" + "void main() {" + "gl_Position = vec4(position, 0., 1.);" + "}"; private static final String VERTEX_SHADER_300 = "#version 300 es\n" + "in vec2 position;" + "void main() {" + "gl_Position = vec4(position, 0., 1.);" + "}"; private static final String FRAGMENT_SHADER = "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" + "precision highp float;\n" + "#else\n" + "precision mediump float;\n" + "#endif\n" + "uniform vec2 resolution;" + "uniform sampler2D frame;" + "void main(void) {" + "gl_FragColor = texture2D(frame," + "gl_FragCoord.xy / resolution.xy).rgba;" + "}"; private final TextureBinder textureBinder = new TextureBinder(); private final ArrayList<String> textureNames = new ArrayList<>(); private final ArrayList<TextureParameters> textureParameters = new ArrayList<>(); private final BackBufferParameters backBufferTextureParams = new BackBufferParameters(); private final int[] fb = new int[]{0, 0}; private final int[] tx = new int[]{0, 0}; private final int[] textureLocs = new int[32]; private final int[] textureTargets = new int[32]; private final int[] textureIds = new int[32]; private final float[] surfaceResolution = new float[]{0, 0}; private final float[] resolution = new float[]{0, 0}; private final float[] touch = new float[]{0, 0}; private final float[] mouse = new float[]{0, 0}; private final float[] pointers = new float[30]; private final float[] offset = new float[]{0, 0}; private final float[] dateTime = new float[]{0, 0, 0, 0}; private final float[] rotationMatrix = new float[9]; private final float[] inclinationMatrix = new float[9]; private final float[] orientation = new float[]{0, 0, 0}; private final Context context; private final ByteBuffer vertexBuffer; private AccelerometerListener accelerometerListener; private CameraListener cameraListener; private GravityListener gravityListener; private GyroscopeListener gyroscopeListener; private MagneticFieldListener magneticFieldListener; private LightListener lightListener; private LinearAccelerationListener linearAccelerationListener; private PressureListener pressureListener; private ProximityListener proximityListener; private RotationVectorListener rotationVectorListener; private OnRendererListener onRendererListener; private String fragmentShader; private int version = 2; private int deviceRotation; private int surfaceProgram = 0; private int surfacePositionLoc; private int surfaceResolutionLoc; private int surfaceFrameLoc; private int program = 0; private int positionLoc; private int timeLoc; private int secondLoc; private int subSecondLoc; private int frameNumLoc; private int fTimeLoc; private int resolutionLoc; private int touchLoc; private int mouseLoc; private int pointerCountLoc; private int pointersLoc; private int gravityLoc; private int linearLoc; private int gyroscopeLoc; private int magneticLoc; private int rotationMatrixLoc; private int rotationVectorLoc; private int orientationLoc; private int inclinationMatrixLoc; private int inclinationLoc; private int lightLoc; private int pressureLoc; private int proximityLoc; private int offsetLoc; private int batteryLoc; private int dateTimeLoc; private int startRandomLoc; private int backBufferLoc; private int cameraOrientationLoc; private int cameraAddentLoc; private int numberOfTextures; private int pointerCount; private int frontTarget; private int backTarget = 1; private int frameNum; private long startTime; private long lastRender; private long lastBatteryUpdate; private long lastDateUpdate; private float batteryLevel; private float quality = 1f; private float startRandom; private float fTimeMax; private float[] gravityValues; private float[] linearValues; private volatile byte[] thumbnail = new byte[1]; private volatile long nextFpsUpdate = 0; private volatile float sum; private volatile float samples; private volatile int lastFps; public ShaderRenderer(Context context) { this.context = context; vertexBuffer = ByteBuffer.allocateDirect(8); vertexBuffer.put(new byte[]{ -1, 1, -1, -1, 1, 1, 1, -1}).position(0); } public void setVersion(int version) { this.version = version; } public void setFragmentShader(String source, float quality) { setQuality(quality); setFragmentShader(source); } private void setFragmentShader(String source) { fTimeMax = parseFTime(source); resetFps(); fragmentShader = indexTextureNames(source); } public void setQuality(float quality) { this.quality = quality; } public void setOnRendererListener(OnRendererListener listener) { onRendererListener = listener; } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { GLES20.glDisable(GLES20.GL_CULL_FACE); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glClearColor(0f, 0f, 0f, 1f); if (surfaceProgram != 0) { // Don't glDeleteProgram(surfaceProgram) because // GLSurfaceView::onPause() destroys the GL context // what also deletes all programs. // With glDeleteProgram(): // <core_glDeleteProgram:594>: GL_INVALID_VALUE surfaceProgram = 0; } if (program != 0) { // Don't glDeleteProgram(program); // same as above program = 0; deleteTargets(); } if (fragmentShader != null && fragmentShader.length() > 0) { resetFps(); createTextures(); loadPrograms(); indexLocations(); enableAttribArrays(); registerListeners(); } } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { startTime = lastRender = System.nanoTime(); startRandom = (float) Math.random(); frameNum = 0; surfaceResolution[0] = width; surfaceResolution[1] = height; deviceRotation = getDeviceRotation(context); float w = Math.round(width * quality); float h = Math.round(height * quality); if (w != resolution[0] || h != resolution[1]) { deleteTargets(); } resolution[0] = w; resolution[1] = h; resetFps(); openCameraListener(); } @Override public void onDrawFrame(GL10 gl) { if (surfaceProgram == 0 || program == 0) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); return; } GLES20.glUseProgram(program); GLES20.glVertexAttribPointer(positionLoc, 2, GLES20.GL_BYTE, false, 0, vertexBuffer); final long now = System.nanoTime(); float delta = (now - startTime) / NS_PER_SECOND; if (timeLoc > -1) { GLES20.glUniform1f(timeLoc, delta); } if (secondLoc > -1) { GLES20.glUniform1i(secondLoc, (int) delta); } if (subSecondLoc > -1) { GLES20.glUniform1f(subSecondLoc, delta - (int) delta); } if (frameNumLoc > -1) { GLES20.glUniform1i(frameNumLoc, frameNum); } if (fTimeLoc > -1) { GLES20.glUniform1f(fTimeLoc, ((delta % fTimeMax) / fTimeMax * 2f - 1f)); } if (resolutionLoc > -1) { GLES20.glUniform2fv(resolutionLoc, 1, resolution, 0); } if (touchLoc > -1) { GLES20.glUniform2fv(touchLoc, 1, touch, 0); } if (mouseLoc > -1) { GLES20.glUniform2fv(mouseLoc, 1, mouse, 0); } if (pointerCountLoc > -1) { GLES20.glUniform1i(pointerCountLoc, pointerCount); } if (pointersLoc > -1) { GLES20.glUniform3fv(pointersLoc, pointerCount, pointers, 0); } if (gravityLoc > -1 && gravityValues != null) { GLES20.glUniform3fv(gravityLoc, 1, gravityValues, 0); } if (linearLoc > -1 && linearValues != null) { GLES20.glUniform3fv(linearLoc, 1, linearValues, 0); } if (gyroscopeLoc > -1 && gyroscopeListener != null) { GLES20.glUniform3fv(gyroscopeLoc, 1, gyroscopeListener.rotation, 0); } if (magneticLoc > -1 && magneticFieldListener != null) { GLES20.glUniform3fv(magneticLoc, 1, magneticFieldListener.values, 0); } if ((rotationMatrixLoc > -1 || orientationLoc > -1 || inclinationMatrixLoc > -1 || inclinationLoc > -1) && gravityValues != null) { setRotationMatrix(); } if (lightLoc > -1 && lightListener != null) { GLES20.glUniform1f(lightLoc, lightListener.getAmbient()); } if (pressureLoc > -1 && pressureListener != null) { GLES20.glUniform1f(pressureLoc, pressureListener.getPressure()); } if (proximityLoc > -1 && proximityListener != null) { GLES20.glUniform1f(proximityLoc, proximityListener.getCentimeters()); } if (rotationVectorLoc > -1 && rotationVectorListener != null) { GLES20.glUniform3fv(rotationVectorLoc, 1, rotationVectorListener.values, 0); } if (offsetLoc > -1) { GLES20.glUniform2fv(offsetLoc, 1, offset, 0); } if (batteryLoc > -1) { if (now - lastBatteryUpdate > BATTERY_UPDATE_INTERVAL) { // profiled getBatteryLevel() on slow/old devices // and it can take up to 6ms, so better do that // not for every frame but only once in a while batteryLevel = getBatteryLevel(); lastBatteryUpdate = now; } GLES20.glUniform1f(batteryLoc, batteryLevel); } if (dateTimeLoc > -1) { if (now - lastDateUpdate > DATE_UPDATE_INTERVAL) { Calendar calendar = Calendar.getInstance(); dateTime[0] = calendar.get(Calendar.YEAR); dateTime[1] = calendar.get(Calendar.MONTH); dateTime[2] = calendar.get(Calendar.DAY_OF_MONTH); dateTime[3] = calendar.get(Calendar.HOUR_OF_DAY) * 3600f + calendar.get(Calendar.MINUTE) * 60f + calendar.get(Calendar.SECOND); lastDateUpdate = now; } GLES20.glUniform4fv(dateTimeLoc, 1, dateTime, 0); } if (startRandomLoc > -1) { GLES20.glUniform1f(startRandomLoc, startRandom); } if (fb[0] == 0) { createTargets((int) resolution[0], (int) resolution[1]); } // first draw custom shader in framebuffer GLES20.glViewport(0, 0, (int) resolution[0], (int) resolution[1]); textureBinder.reset(); if (backBufferLoc > -1) { textureBinder.bind(backBufferLoc, GLES20.GL_TEXTURE_2D, tx[backTarget]); } if (cameraListener != null) { if (cameraOrientationLoc > -1) { GLES20.glUniformMatrix2fv(cameraOrientationLoc, 1, false, cameraListener.getOrientationMatrix()); } if (cameraAddentLoc > -1) { GLES20.glUniform2fv(cameraAddentLoc, 1, cameraListener.addent, 0); } cameraListener.update(); } for (int i = 0; i < numberOfTextures; ++i) { textureBinder.bind( textureLocs[i], textureTargets[i], textureIds[i]); } GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fb[frontTarget]); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); // then draw framebuffer on screen GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); GLES20.glViewport(0, 0, (int) surfaceResolution[0], (int) surfaceResolution[1]); GLES20.glUseProgram(surfaceProgram); GLES20.glVertexAttribPointer(surfacePositionLoc, 2, GLES20.GL_BYTE, false, 0, vertexBuffer); GLES20.glUniform2fv(surfaceResolutionLoc, 1, surfaceResolution, 0); GLES20.glUniform1i(surfaceFrameLoc, 0); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tx[frontTarget]); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); // swap buffers so the next image will be rendered // over the current backbuffer and the current image // will be the backbuffer for the next image int t = frontTarget; frontTarget = backTarget; backTarget = t; if (thumbnail == null) { thumbnail = saveThumbnail(); } if (onRendererListener != null) { updateFps(now); } ++frameNum; } public void unregisterListeners() { if (accelerometerListener != null) { accelerometerListener.unregister(); gravityValues = linearValues = null; } if (gravityListener != null) { gravityListener.unregister(); gravityValues = null; } if (linearAccelerationListener != null) { linearAccelerationListener.unregister(); linearValues = null; } if (gyroscopeListener != null) { gyroscopeListener.unregister(); } if (magneticFieldListener != null) { magneticFieldListener.unregister(); } if (lightListener != null) { lightListener.unregister(); } if (pressureListener != null) { pressureListener.unregister(); } if (proximityListener != null) { proximityListener.unregister(); } if (rotationVectorListener != null) { rotationVectorListener.unregister(); } unregisterCameraListener(); } public void touchAt(MotionEvent e) { float x = e.getX() * quality; float y = e.getY() * quality; touch[0] = x; touch[1] = resolution[1] - y; mouse[0] = x / resolution[0]; mouse[1] = 1 - y / resolution[1]; switch (e.getActionMasked()) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: pointerCount = 0; return; } pointerCount = Math.min( e.getPointerCount(), pointers.length / 3); for (int i = 0, offset = 0; i < pointerCount; ++i) { pointers[offset++] = e.getX(i) * quality; pointers[offset++] = resolution[1] - e.getY(i) * quality; pointers[offset++] = e.getTouchMajor(i); } } public void setOffset(float x, float y) { offset[0] = x; offset[1] = y; } public byte[] getThumbnail() { // settings thumbnail to null triggers // the capture on the OpenGL thread in // onDrawFrame() thumbnail = null; try { for (int trys = 10; trys-- > 0 && program > 0 && thumbnail == null; ) { Thread.sleep(100); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // don't clone() because the data doesn't need to be // protected from modification what means copying would // only mean using more memory than necessary return thumbnail; } private void resetFps() { sum = samples = 0; lastFps = 0; nextFpsUpdate = 0; } private void loadPrograms() { String vertexShader = fragmentShader.contains("#version 3") && version == 3 ? VERTEX_SHADER_300 : VERTEX_SHADER; if (((surfaceProgram = Program.loadProgram( VERTEX_SHADER, FRAGMENT_SHADER)) == 0 || (program = Program.loadProgram( vertexShader, fragmentShader)) == 0) && onRendererListener != null) { onRendererListener.onInfoLog(Program.getInfoLog()); } } private void indexLocations() { surfacePositionLoc = GLES20.glGetAttribLocation( surfaceProgram, "position"); surfaceResolutionLoc = GLES20.glGetUniformLocation( surfaceProgram, "resolution"); surfaceFrameLoc = GLES20.glGetUniformLocation( surfaceProgram, "frame"); positionLoc = GLES20.glGetAttribLocation( program, UNIFORM_POSITION); timeLoc = GLES20.glGetUniformLocation( program, UNIFORM_TIME); secondLoc = GLES20.glGetUniformLocation( program, UNIFORM_SECOND); subSecondLoc = GLES20.glGetUniformLocation( program, UNIFORM_SUB_SECOND); frameNumLoc = GLES20.glGetUniformLocation( program, UNIFORM_FRAME_NUMBER); fTimeLoc = GLES20.glGetUniformLocation( program, UNIFORM_FTIME); resolutionLoc = GLES20.glGetUniformLocation( program, UNIFORM_RESOLUTION); touchLoc = GLES20.glGetUniformLocation( program, UNIFORM_TOUCH); mouseLoc = GLES20.glGetUniformLocation( program, UNIFORM_MOUSE); pointerCountLoc = GLES20.glGetUniformLocation( program, UNIFORM_POINTER_COUNT); pointersLoc = GLES20.glGetUniformLocation( program, UNIFORM_POINTERS); gravityLoc = GLES20.glGetUniformLocation( program, UNIFORM_GRAVITY); gyroscopeLoc = GLES20.glGetUniformLocation( program, UNIFORM_GYROSCOPE); linearLoc = GLES20.glGetUniformLocation( program, UNIFORM_LINEAR); magneticLoc = GLES20.glGetUniformLocation( program, UNIFORM_MAGNETIC); rotationMatrixLoc = GLES20.glGetUniformLocation( program, UNIFORM_ROTATION_MATRIX); rotationVectorLoc = GLES20.glGetUniformLocation( program, UNIFORM_ROTATION_VECTOR); orientationLoc = GLES20.glGetUniformLocation( program, UNIFORM_ORIENTATION); inclinationMatrixLoc = GLES20.glGetUniformLocation( program, UNIFORM_INCLINATION_MATRIX); inclinationLoc = GLES20.glGetUniformLocation( program, UNIFORM_INCLINATION); lightLoc = GLES20.glGetUniformLocation( program, UNIFORM_LIGHT); pressureLoc = GLES20.glGetUniformLocation( program, UNIFORM_PRESSURE); proximityLoc = GLES20.glGetUniformLocation( program, UNIFORM_PROXIMITY); offsetLoc = GLES20.glGetUniformLocation( program, UNIFORM_OFFSET); batteryLoc = GLES20.glGetUniformLocation( program, UNIFORM_BATTERY); dateTimeLoc = GLES20.glGetUniformLocation( program, UNIFORM_DATE); startRandomLoc = GLES20.glGetUniformLocation( program, UNIFORM_START_RANDOM); backBufferLoc = GLES20.glGetUniformLocation( program, UNIFORM_BACKBUFFER); cameraOrientationLoc = GLES20.glGetUniformLocation( program, UNIFORM_CAMERA_ORIENTATION); cameraAddentLoc = GLES20.glGetUniformLocation( program, UNIFORM_CAMERA_ADDENT); for (int i = numberOfTextures; i textureLocs[i] = GLES20.glGetUniformLocation( program, textureNames.get(i)); } } private void enableAttribArrays() { GLES20.glEnableVertexAttribArray(surfacePositionLoc); GLES20.glEnableVertexAttribArray(positionLoc); } private void registerListeners() { if (gravityLoc > -1 || rotationMatrixLoc > -1 || orientationLoc > -1 || inclinationMatrixLoc > -1 || inclinationLoc > -1) { if (gravityListener == null) { gravityListener = new GravityListener(context); } if (!gravityListener.register()) { gravityListener = null; AccelerometerListener l = getAccelerometerListener(); gravityValues = l != null ? l.gravity : null; } else { gravityValues = gravityListener.values; } } if (linearLoc > -1) { if (linearAccelerationListener == null) { linearAccelerationListener = new LinearAccelerationListener(context); } if (!linearAccelerationListener.register()) { linearAccelerationListener = null; AccelerometerListener l = getAccelerometerListener(); linearValues = l != null ? l.linear : null; } else { linearValues = linearAccelerationListener.values; } } if (gyroscopeLoc > -1) { if (gyroscopeListener == null) { gyroscopeListener = new GyroscopeListener(context); } if (!gyroscopeListener.register()) { gyroscopeListener = null; } } if (magneticLoc > -1 || rotationMatrixLoc > -1 || orientationLoc > -1 || inclinationMatrixLoc > -1 || inclinationLoc > -1) { if (magneticFieldListener == null) { magneticFieldListener = new MagneticFieldListener(context); } if (!magneticFieldListener.register()) { magneticFieldListener = null; } } if (lightLoc > -1) { if (lightListener == null) { lightListener = new LightListener(context); } if (!lightListener.register()) { lightListener = null; } } if (pressureLoc > -1) { if (pressureListener == null) { pressureListener = new PressureListener(context); } if (!pressureListener.register()) { pressureListener = null; } } if (proximityLoc > -1) { if (proximityListener == null) { proximityListener = new ProximityListener(context); } if (!proximityListener.register()) { proximityListener = null; } } if (rotationVectorLoc > -1 || (magneticFieldListener == null && (orientationLoc > -1 || rotationMatrixLoc > -1))) { if (rotationVectorListener == null) { rotationVectorListener = new RotationVectorListener(context); } if (!rotationVectorListener.register()) { rotationVectorListener = null; } } } private AccelerometerListener getAccelerometerListener() { if (accelerometerListener == null) { accelerometerListener = new AccelerometerListener(context); } if (!accelerometerListener.register()) { return null; } return accelerometerListener; } private byte[] saveThumbnail() { final int min = (int) Math.min( surfaceResolution[0], surfaceResolution[1]); final int pixels = min * min; final int[] rgba = new int[pixels]; final int[] bgra = new int[pixels]; final IntBuffer colorBuffer = IntBuffer.wrap(rgba); GLES20.glReadPixels( 0, 0, min, min, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, colorBuffer); for (int i = 0, e = pixels; i < pixels; ) { e -= min; for (int x = min, b = e; x-- > 0; ++i, ++b) { final int c = rgba[i]; bgra[b] = ((c >> 16) & 0xff) | ((c << 16) & 0xff0000) | (c & 0xff00ff00); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); Bitmap.createScaledBitmap( Bitmap.createBitmap( bgra, min, min, Bitmap.Config.ARGB_8888), 144, 144, true).compress( Bitmap.CompressFormat.PNG, 100, out); return out.toByteArray(); } catch (IllegalArgumentException e) { // will never happen because neither // width nor height <= 0 return null; } } private void setRotationMatrix() { boolean haveInclination = false; if (gravityListener != null && magneticFieldListener != null && SensorManager.getRotationMatrix( rotationMatrix, inclinationMatrix, gravityValues, magneticFieldListener.filtered)) { haveInclination = true; } else if (rotationVectorListener != null) { SensorManager.getRotationMatrixFromVector( rotationMatrix, rotationVectorListener.values); } else { return; } if (deviceRotation != 0) { int x = SensorManager.AXIS_Y; int y = SensorManager.AXIS_MINUS_X; switch (deviceRotation) { default: break; case 270: x = SensorManager.AXIS_MINUS_Y; y = SensorManager.AXIS_X; break; } SensorManager.remapCoordinateSystem( rotationMatrix, x, y, rotationMatrix); } if (rotationMatrixLoc > -1) { GLES20.glUniformMatrix3fv(rotationMatrixLoc, 1, true, rotationMatrix, 0); } if (orientationLoc > -1) { SensorManager.getOrientation(rotationMatrix, orientation); GLES20.glUniform3fv(orientationLoc, 1, orientation, 0); } if (inclinationMatrixLoc > -1 && haveInclination) { GLES20.glUniformMatrix3fv(inclinationMatrixLoc, 1, true, inclinationMatrix, 0); } if (inclinationLoc > -1 && haveInclination) { GLES20.glUniform1f(inclinationLoc, SensorManager.getInclination(inclinationMatrix)); } } private void updateFps(long now) { long delta = now - lastRender; // because sum and samples are volatile synchronized (this) { sum += Math.min(NS_PER_SECOND / delta, 60f); if (++samples > 0xffff) { sum = sum / samples; samples = 1; } } if (now > nextFpsUpdate) { int fps = Math.round(sum / samples); if (fps != lastFps) { onRendererListener.onFramesPerSecond(fps); lastFps = fps; } nextFpsUpdate = now + FPS_UPDATE_FREQUENCY_NS; } lastRender = now; } private void deleteTargets() { if (fb[0] == 0) { return; } GLES20.glDeleteFramebuffers(2, fb, 0); GLES20.glDeleteTextures(2, tx, 0); fb[0] = 0; } private void createTargets(int width, int height) { deleteTargets(); GLES20.glGenFramebuffers(2, fb, 0); GLES20.glGenTextures(2, tx, 0); createTarget(frontTarget, width, height, backBufferTextureParams); createTarget(backTarget, width, height, backBufferTextureParams); // unbind textures that were bound in createTarget() GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); } private void createTarget( int idx, int width, int height, BackBufferParameters tp) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tx[idx]); boolean useBitmap = tp.setPresetBitmap(width, height); if (!useBitmap) { GLES20.glTexImage2D( GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null); } tp.setParameters(GLES20.GL_TEXTURE_2D); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fb[idx]); GLES20.glFramebufferTexture2D( GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, tx[idx], 0); if (!useBitmap) { // clear texture because some drivers // don't initialize texture memory GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); } } private void deleteTextures() { if (textureIds[0] == 1 || numberOfTextures < 1) { return; } GLES20.glDeleteTextures(numberOfTextures, textureIds, 0); } private void createTextures() { deleteTextures(); GLES20.glGenTextures(numberOfTextures, textureIds, 0); for (int i = 0; i < numberOfTextures; ++i) { String name = textureNames.get(i); if (UNIFORM_CAMERA_BACK.equals(name) || UNIFORM_CAMERA_FRONT.equals(name)) { // handled in onSurfaceChanged() because we need // the dimensions of the surface to pick a preview // resolution continue; } Bitmap bitmap = ShaderEditorApp.db.getTextureBitmap(name); if (bitmap == null) { continue; } switch (textureTargets[i]) { default: continue; case GLES20.GL_TEXTURE_2D: createTexture(textureIds[i], bitmap, textureParameters.get(i)); break; case GLES20.GL_TEXTURE_CUBE_MAP: createCubeTexture(textureIds[i], bitmap, textureParameters.get(i)); break; } bitmap.recycle(); } } private void createTexture( int id, Bitmap bitmap, TextureParameters tp) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, id); tp.setParameters(GLES20.GL_TEXTURE_2D); TextureParameters.setBitmap(bitmap); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); } private void createCubeTexture( int id, Bitmap bitmap, TextureParameters tp) { GLES20.glBindTexture(GLES20.GL_TEXTURE_CUBE_MAP, id); tp.setParameters(GLES20.GL_TEXTURE_CUBE_MAP); int bitmapWidth = bitmap.getWidth(); int bitmapHeight = bitmap.getHeight(); int sideWidth = (int) Math.ceil(bitmapWidth / 2f); int sideHeight = Math.round(bitmapHeight / 3f); int sideLength = Math.min(sideWidth, sideHeight); int x = 0; int y = 0; for (int target : CUBE_MAP_TARGETS) { Bitmap side = Bitmap.createBitmap( bitmap, x, y, // cube textures need to be quadratic sideLength, sideLength, // don't flip cube textures null, true); GLUtils.texImage2D( target, 0, GLES20.GL_RGBA, side, GLES20.GL_UNSIGNED_BYTE, 0); side.recycle(); if ((x += sideWidth) >= bitmapWidth) { x = 0; y += sideHeight; } } GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_CUBE_MAP); } private void unregisterCameraListener() { if (cameraListener != null) { cameraListener.unregister(); cameraListener = null; } } private void openCameraListener() { unregisterCameraListener(); for (int i = 0; i < numberOfTextures; ++i) { String name = textureNames.get(i); if (UNIFORM_CAMERA_BACK.equals(name) || UNIFORM_CAMERA_FRONT.equals(name)) { openCameraListener(name, textureIds[i], textureParameters.get(i)); // only one camera can be opened at a time break; } } } private void openCameraListener( String name, int id, TextureParameters tp) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { return; } int cameraId = CameraListener.findCameraId( UNIFORM_CAMERA_BACK.equals(name) ? Camera.CameraInfo.CAMERA_FACING_BACK : Camera.CameraInfo.CAMERA_FACING_FRONT); if (cameraId < 0) { return; } if (cameraListener == null || cameraListener.cameraId != cameraId) { unregisterCameraListener(); requestCameraPermission(); setCameraTextureProperties(id, tp); cameraListener = new CameraListener( id, cameraId, (int) resolution[0], (int) resolution[1], deviceRotation); } cameraListener.register(); } private void requestCameraPermission() { String permission = android.Manifest.permission.CAMERA; if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { Activity activity; try { activity = (Activity) context; } catch (ClassCastException e) { return; } ActivityCompat.requestPermissions( activity, new String[]{permission}, 1); } } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) private static void setCameraTextureProperties( int id, TextureParameters tp) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { return; } GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, id); tp.setParameters(GLES11Ext.GL_TEXTURE_EXTERNAL_OES); } private static float parseFTime(String source) { if (source != null) { Matcher m = PATTERN_FTIME.matcher(source); if (m.find() && m.groupCount() > 0) { return Float.parseFloat(m.group(1)); } } return 3f; } private String indexTextureNames(String source) { if (source == null) { return null; } textureNames.clear(); textureParameters.clear(); numberOfTextures = 0; backBufferTextureParams.reset(); final int maxTextures = textureIds.length; for (Matcher m = PATTERN_SAMPLER.matcher(source); m.find() && numberOfTextures < maxTextures; ) { String type = m.group(1); String name = m.group(2); String params = m.group(3); if (type == null || name == null) { continue; } if (UNIFORM_BACKBUFFER.equals(name)) { backBufferTextureParams.parse(params); continue; } int target; switch (type) { case SAMPLER_2D: target = GLES20.GL_TEXTURE_2D; break; case SAMPLER_CUBE: target = GLES20.GL_TEXTURE_CUBE_MAP; break; case SAMPLER_EXTERNAL_OES: if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { // needs to be done here or lint won't recognize // we're checking SDK version target = GLES11Ext.GL_TEXTURE_EXTERNAL_OES; } else { // ignore that uniform on lower SDKs continue; } if (!source.contains(OES_EXTERNAL)) { source = addPreprocessorDirective(source, OES_EXTERNAL); } break; default: continue; } textureTargets[numberOfTextures++] = target; textureNames.add(name); textureParameters.add(new TextureParameters(params)); } return source; } private static String addPreprocessorDirective(String source, String directive) { // #version must always be the very first directive if (source.trim().startsWith("#version")) { int lf = source.indexOf("\n"); if (lf < 0) { // no line break? return source; } ++lf; return source.substring(0, lf) + directive + source.substring(lf); } return directive + source; } private float getBatteryLevel() { Intent batteryStatus = context.registerReceiver( null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); if (batteryStatus == null) { return 0; } int level = batteryStatus.getIntExtra( BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra( BatteryManager.EXTRA_SCALE, -1); return (float) level / scale; } private static int getDeviceRotation(Context context) { WindowManager wm = (WindowManager) context.getSystemService( Context.WINDOW_SERVICE); if (wm == null) { return 0; } switch (wm.getDefaultDisplay().getRotation()) { default: case Surface.ROTATION_0: return 0; case Surface.ROTATION_90: return 90; case Surface.ROTATION_180: return 180; case Surface.ROTATION_270: return 270; } } private static class TextureBinder { private int index; private void reset() { index = 0; } private void bind(int loc, int target, int textureId) { if (loc < 0 || index >= TEXTURE_UNITS.length) { return; } GLES20.glUniform1i(loc, index); GLES20.glActiveTexture(TEXTURE_UNITS[index]); GLES20.glBindTexture(target, textureId); ++index; } } }
package es.craftsmanship.toledo.katangapp.activities; import es.craftsmanship.toledo.katangapp.interactors.StopsInteractor; import es.craftsmanship.toledo.katangapp.models.QueryResult; import es.craftsmanship.toledo.katangapp.utils.AndroidBus; import es.craftsmanship.toledo.katangapp.utils.KatangaFont; import android.Manifest; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.location.Location; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.squareup.otto.Subscribe; public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, View.OnClickListener { private static final int DEFAULT_RADIO = 500; private static final LocationRequest GPS_REQUEST = LocationRequest.create() .setInterval(3000) .setFastestInterval(16) .setNumUpdates(3) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); private static final String TAG = "KATANGAPP"; private static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 200; private ImageView button; private GoogleApiClient googleApiClient; private Double longitude; private Double latitude; private ProgressBar progressBar; private SeekBar seekBar; private TextView txtRadioLabel; @Override public void onClick(View v) { CharSequence charSequence = txtRadioLabel.getText(); String radio = charSequence.toString(); if (radio.isEmpty()) { radio = String.valueOf(DEFAULT_RADIO); } toggleVisualComponents(false); StopsInteractor stopsInteractor = new StopsInteractor(radio, latitude, longitude); new Thread(stopsInteractor).start(); } @Subscribe public void stopsReceived(QueryResult queryResult) { Intent intent = new Intent(MainActivity.this, ShowStopsActivity.class); intent.putExtra("queryResult", queryResult); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplicationContext().startActivity(intent); toggleVisualComponents(true); } @Subscribe public void stopsReceived(Error error) { toggleVisualComponents(true); Log.e(TAG, "Error calling server ", error); View content = findViewById(android.R.id.content); Snackbar.make(content, "Error finding the nearest stop", Snackbar.LENGTH_LONG).show(); } @Override public void onConnected(Bundle bundle) { Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); if (lastLocation != null) { longitude = lastLocation.getLongitude(); latitude = lastLocation.getLatitude(); } LocationServices.FusedLocationApi.requestLocationUpdates( googleApiClient, GPS_REQUEST, this); } private void checkRuntimePermissions(String[] permissions, int requestCode) { boolean explanation = false; for (String permission : permissions) { if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user explanation = true; } else { // requestCode is an // app-defined int constant. The callback method gets the // result of the request. } } } if (!explanation) { ActivityCompat.requestPermissions(this, permissions, requestCode); } } @Override public void onLocationChanged(Location location) { if (location != null) { longitude = location.getLongitude(); latitude = location.getLatitude(); } } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } @Override public void onConnectionSuspended(int i) { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode != REQUEST_CODE_RECOVER_PLAY_SERVICES) { return; } if (resultCode == RESULT_OK) { if (!googleApiClient.isConnecting() && !googleApiClient.isConnected()) { googleApiClient.connect(); } } else if (resultCode == RESULT_CANCELED) { Toast.makeText( this, "Google Play Services must be installed.", Toast.LENGTH_SHORT).show(); finish(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initializeRuntimePermissions(); initializeGooglePlayServices(); initializeVariables(); initializeSeekTrack(); initializeButton(); } @Override protected void onResume() { super.onResume(); if (googleApiClient != null) { googleApiClient.connect(); } AndroidBus.getInstance().register(this); } @Override protected void onPause() { AndroidBus.getInstance().unregister(this); if (googleApiClient != null) { googleApiClient.disconnect(); } super.onPause(); } private void initializeSeekTrack() { seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { txtRadioLabel.setText(String.valueOf(progress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } private void initializeButton() { button.setOnClickListener(this); } private void initializeGooglePlayServices() { int checkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (checkGooglePlayServices != ConnectionResult.SUCCESS) { /* * google play services is missing or update is required * return code could be * SUCCESS, * SERVICE_MISSING, SERVICE_VERSION_UPDATE_REQUIRED, * SERVICE_DISABLED, SERVICE_INVALID. */ Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( checkGooglePlayServices, this, REQUEST_CODE_RECOVER_PLAY_SERVICES); errorDialog.show(); return; } googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } private void initializeRuntimePermissions() { int requestCode = PackageManager.PERMISSION_GRANTED; String[] permissions = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET }; checkRuntimePermissions(permissions, requestCode); } /** * A private method to help us initialize our variables */ private void initializeVariables() { seekBar = (SeekBar) findViewById(R.id.seekBar); txtRadioLabel = (TextView) findViewById(R.id.txtRadioLabel); button = (ImageView) findViewById(R.id.button); progressBar = (ProgressBar) findViewById(R.id.progressBar1); toggleVisualComponents(true); Typeface tf = KatangaFont.getFont(getAssets(), KatangaFont.QUICKSAND_REGULAR); TextView txtKatangaLabel = (TextView) findViewById(R.id.title_katanga); txtKatangaLabel.setTypeface(tf); txtRadioLabel.setTypeface(tf); } private void toggleVisualComponents(boolean buttonEnabled) { button.setEnabled(buttonEnabled); int visibility = View.VISIBLE; txtRadioLabel.setVisibility(visibility); if (buttonEnabled) { visibility = View.INVISIBLE; } progressBar.setVisibility(visibility); } }
package kg.apc.cmdtools; import java.text.DecimalFormatSymbols; import java.io.File; import java.io.IOException; import kg.apc.emulators.TestJMeterUtils; import org.apache.jmeter.util.JMeterUtils; import java.io.PrintStream; import java.util.ListIterator; import kg.apc.emulators.FilesTestTools; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author undera */ public class ReporterToolTest { private final String basedir; public ReporterToolTest() { String file = this.getClass().getResource("short.jtl").getPath(); basedir = file.substring(0, file.lastIndexOf("/")); } @BeforeClass public static void setUpClass() throws Exception { TestJMeterUtils.createJmeterEnv(); } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { JMeterUtils.setJMeterHome(basedir); } @After public void tearDown() { } /** * Test of showHelp method, of class CMDReporterTool. */ @Test public void testShowHelp() { System.out.println("showHelp"); PrintStream os = System.out; ReporterTool instance = new ReporterTool(); instance.showHelp(os); } /** * Test of processParams method, of class CMDReporterTool. */ @Test public void testProcessParams() { System.out.println("processParams"); ListIterator<String> args = PluginsCMD.argsArrayToListIterator("--help".split(" ")); ReporterTool instance = new ReporterTool(); try { instance.processParams(args); fail(); } catch (UnsupportedOperationException e) { } } @Test // issue 39 public void testProcessParams_aggreg() throws IOException { System.out.println("processParams aggregate"); File f = File.createTempFile("test", ".csv"); String str = "--generate-csv " + f.getAbsolutePath() + " " + "--input-jtl " + basedir + "/few.jtl " + "--aggregate-rows yes --plugin-type ResponseTimesOverTime"; String[] args = str.split(" +"); ReporterTool instance = new ReporterTool(); int expResult = 0; int result = instance.processParams(PluginsCMD.argsArrayToListIterator(args)); assertEquals(expResult, result); assertTrue(78 == f.length() || 81 == f.length()); // 78 at linux, 81 at windows because or \r\n } @Test // issue 47 public void testProcessParams_outliers() throws IOException { System.out.println("processParams outliers"); File f = File.createTempFile("test", ".png"); String str = "--width 1000 --height 300 " + "--prevent-outliers yes " + "--plugin-type ResponseTimesDistribution" + " --generate-png " + f.getAbsolutePath() + " " + "--input-jtl " + basedir + "/results_issue_47.jtl"; String[] args = str.split(" +"); ReporterTool instance = new ReporterTool(); int expResult = 0; int result = instance.processParams(PluginsCMD.argsArrayToListIterator(args)); assertEquals(expResult, result); System.out.println(f.length()); assertTrue(14000 <= f.length()); } @Test // issue 64 public void testProcessParams_issue64() throws IOException { System.out.println("processParams outliers"); File f = File.createTempFile("test", ".png"); String str = "--width 800 --height 600 " + "--plugin-type HitsPerSecond " + "--aggregate-rows yes " + "--generate-png " + f.getAbsolutePath() + " " + "--input-jtl " + basedir + "/results_issue_47.jtl"; String[] args = str.split(" +"); ReporterTool instance = new ReporterTool(); try { int result = instance.processParams(PluginsCMD.argsArrayToListIterator(args)); fail("HitsPerSec don't handle aggregates"); } catch (UnsupportedOperationException e) { } } @Test // issue 96 public void testProcessParams_issue96() throws IOException { System.out.println("processParams outliers"); File f = File.createTempFile("test", ".csv"); String str = "--plugin-type TimesVsThreads " + "--hide-low-counts 5 " + "--generate-csv " + f.getAbsolutePath() + " " + "--input-jtl " + basedir + "/issue96.jtl"; String[] args = str.split(" +"); ReporterTool instance = new ReporterTool(); int result = instance.processParams(PluginsCMD.argsArrayToListIterator(args)); FilesTestTools.compareFiles(f, new File(basedir + "/issue96.semicolon.txt")); /* if (new DecimalFormatSymbols().getDecimalSeparator() == '.') { } else { FilesTestTools.compareFiles(f, new File(basedir + "/issue96.comma.txt")); } * */ } }
import sun.java2d.pipe.SpanShapeRenderer; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; public class System_Function { public static String getCurrentProfile() { String url = "jdbc:mysql://localhost/growonline"; String login = credentials.bdd_login; String passwd = credentials.bdd_psswd; Connection cn=null; Statement stmt = null; String query = "SELECT Name FROM profile WHERE ID='0';"; try { Class.forName("com.mysql.jdbc.Driver"); cn= DriverManager.getConnection(url, login, passwd); stmt = cn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { return rs.getString("Name"); } } catch (SQLException e ) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally { if (stmt != null) { try {stmt.close();} catch (SQLException e) {e.printStackTrace();} } } return ""; } public static void getProfile() { String url = "jdbc:mysql://localhost/growonline"; String login = credentials.bdd_login; String passwd = credentials.bdd_psswd; Connection cn=null; Statement stmt = null; String query = "SELECT * FROM profiles WHERE Name='"+getCurrentProfile()+"'"; try { Class.forName("com.mysql.jdbc.Driver"); cn= DriverManager.getConnection(url, login, passwd); stmt = cn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { Profile.Name = rs.getString("Name"); Profile.Sunrise = rs.getTime("Sunrise"); Profile.Sunset = rs.getTime("Sunset"); Profile.Interval = rs.getTime("Interval"); Profile.Working_Time = rs.getTime("Working_Time"); Profile.Tank_Capacity = rs.getDouble("Tank_Capacity"); Profile.Pump_Flow = rs.getDouble("Pump_Flow"); Profile.Watering_Hour = rs.getTime("Watering_Hour"); Profile.Water_Amount = rs.getDouble("Water_Amount"); Profile.Temperature = rs.getDouble("Temperature"); Profile.Humidity = rs.getDouble("Humidity"); Profile.Water_Days[0]= rs.getInt("Monday") == 1; Profile.Water_Days[1]= rs.getInt("Tuesday") == 1; Profile.Water_Days[2]= rs.getInt("Wednesday") == 1; Profile.Water_Days[3]= rs.getInt("Thursday") == 1; Profile.Water_Days[4]= rs.getInt("Friday") == 1; Profile.Water_Days[5]= rs.getInt("Saturday") == 1; Profile.Water_Days[6]= rs.getInt("Sunday") == 1; } } catch (SQLException e ) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally { if (stmt != null) { try {stmt.close();} catch (SQLException e) {e.printStackTrace();} } } } public static boolean isDay() { Date now = new Date(); SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); try {now = format.parse(format.format(now));} catch (ParseException e) {e.printStackTrace();} if(Profile.Sunrise==Profile.Sunset){return false;} return now.after(Profile.Sunrise)&&now.before(Profile.Sunset); } public static boolean isWaterDay() { GregorianCalendar calendar =new GregorianCalendar(); calendar.setTime(new Date()); int today = calendar.get(calendar.DAY_OF_WEEK); if(today==GregorianCalendar.MONDAY&&Profile.Water_Days[0]){return true;} else if(today==GregorianCalendar.TUESDAY&&Profile.Water_Days[1]){return true;} else if(today==GregorianCalendar.WEDNESDAY&&Profile.Water_Days[2]){return true;} else if(today==GregorianCalendar.THURSDAY&&Profile.Water_Days[3]){return true;} else if(today==GregorianCalendar.FRIDAY&&Profile.Water_Days[4]){return true;} else if(today==GregorianCalendar.SATURDAY&&Profile.Water_Days[5]){return true;} else if(today==GregorianCalendar.SUNDAY&&Profile.Water_Days[6]){return true;} return false; } public static boolean isFanOn() { ArrayList<Date> ON = new ArrayList<Date>(); ArrayList<Date> OFF = new ArrayList<Date>(); SimpleDateFormat formater = new SimpleDateFormat("HH:mm"); String[] s = formater.format(Profile.Interval).split(":"); int Hour_I = Integer.parseInt(s[0]); int Min_I = Integer.parseInt(s[1]); s = formater.format(Profile.Working_Time).split(":"); int Hour_W = Integer.parseInt(s[0]); int Min_W = Integer.parseInt(s[1]); if( Hour_W==0&&Min_W==0 ){return false;} if( Hour_I==0&&Min_I==0 ){return true;} int current=0; while (current<1440) { try { Date on = formater.parse(current/60+":"+current%60); ON.add(on); } catch (ParseException e) {e.printStackTrace();} try { Date off = formater.parse( (((current+Min_W)/60)+Hour_W) + ":" + (current+Min_W)%60); if(current+Hour_W*60+Min_W>=1440){OFF.add(formater.parse("23:59"));} else{OFF.add( off );} } catch (ParseException e) {e.printStackTrace();} current+=Hour_I*60+Hour_W*60+Min_I+Min_W; } formater = new SimpleDateFormat("HH:mm:ss"); Date now = new Date(); try {now = formater.parse(formater.format(now));} catch (ParseException e) {e.printStackTrace();} for (int i=0; i<ON.size()-1;i++) { if( now.after(ON.get(i)) && now.before(OFF.get(i)) ) { return true; } } return false; } public static String getDATETIME() { Date now = new Date(); //SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat formater = new SimpleDateFormat("yyyy"); String annee=formater.format(now); formater = new SimpleDateFormat("MM"); String month=""+(Integer.parseInt(formater.format(now))-1); formater = new SimpleDateFormat("-dd HH:mm:ss"); return annee+"-"+month+formater.format(now); } public static String[] getTempHum() { try { String result = exec_result("./lol_dht22/loldht"); return new String[]{reg.s("(Temperature = )(.*?)(\\*C)", result)[0].replace("Temperature = ", "").replace("*C", "").replace(" ", ""),reg.s("(Humidity = )(.*?)(%)", result)[0].replace("Humidity = ", "").replace("%", "").replace(" ", "")}; } catch (ArrayIndexOutOfBoundsException e) {} return new String[]{"error","error"}; } private static boolean procDone(Process p) { try { int v = p.exitValue(); return true; } catch (IllegalThreadStateException e) {} return false; } public static String exec_result(String command) { try { String result = ""; Process p = null; try { p = Runtime.getRuntime().exec(command); } catch (IOException e) { e.printStackTrace(); } BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); int count = 0; while (!procDone(p)) { try { String s; while ((s = stdInput.readLine()) != null) { count++; result = result + s + "\n"; } } catch (IOException e) {} } try { stdInput.close(); } catch (IOException e) { e.printStackTrace(); } return result; } catch (ArrayIndexOutOfBoundsException e) {} return ""; } public static void exec(String command) { try { Runtime r = Runtime.getRuntime(); Process p = r.exec(command); p.waitFor(); } catch (Exception e) { Debug.println("erreur d'execution " + command + e.toString()); } } }
package cpw.mods.fml.client; import java.util.List; import java.util.Map.Entry; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiYesNo; import net.minecraft.util.StringTranslate; import com.google.common.collect.Lists; import com.google.common.collect.MapDifference; import com.google.common.collect.MapDifference.ValueDifference; import cpw.mods.fml.common.registry.ItemData; import cpw.mods.fml.common.versioning.ArtifactVersion; public class GuiIdMismatchScreen extends GuiYesNo { private List<String> missingIds = Lists.newArrayList(); private List<String> mismatchedIds = Lists.newArrayList(); private boolean allowContinue; public GuiIdMismatchScreen(MapDifference<Integer, ItemData> idDifferences, boolean allowContinue) { super(null,"ID mismatch", "Should I continue?", 1); field_73942_a = this; for (Entry<Integer, ItemData> entry : idDifferences.entriesOnlyOnLeft().entrySet()) { missingIds.add(String.format("ID %d from Mod %s is missing", entry.getValue().getItemId(), entry.getValue().getModId(), entry.getValue().getItemType())); } for (Entry<Integer, ValueDifference<ItemData>> entry : idDifferences.entriesDiffering().entrySet()) { ItemData world = entry.getValue().leftValue(); ItemData game = entry.getValue().rightValue(); mismatchedIds.add(String.format("ID %d is mismatched between world and game", world.getItemId())); } this.allowContinue = allowContinue; } @Override public void func_73878_a(boolean choice, int p_73878_2_) { FMLClientHandler.instance().callbackIdDifferenceResponse(choice); } @Override public void func_73863_a(int p_73863_1_, int p_73863_2_, float p_73863_3_) { this.func_73873_v_(); if (!allowContinue && field_73887_h.size() == 2) { field_73887_h.remove(0); } int offset = Math.max(85 - (missingIds.size() + mismatchedIds.size()) * 10, 30); this.func_73732_a(this.field_73886_k, "Forge Mod Loader has found ID mismatches", this.field_73880_f / 2, 10, 0xFFFFFF); this.func_73732_a(this.field_73886_k, "Complete details are in the log file", this.field_73880_f / 2, 20, 0xFFFFFF); for (String s: missingIds) { this.func_73732_a(this.field_73886_k, s, this.field_73880_f / 2, offset, 0xEEEEEE); offset += 10; if (offset > this.field_73881_g - 30) break; } for (String s: mismatchedIds) { this.func_73732_a(this.field_73886_k, s, this.field_73880_f / 2, offset, 0xEEEEEE); offset += 10; if (offset > this.field_73881_g - 30) break; } if (allowContinue) { this.func_73732_a(this.field_73886_k, "Do you wish to continue loading?", this.field_73880_f / 2, this.field_73881_g - 30, 0xFFFFFF); } else { this.func_73732_a(this.field_73886_k, "You cannot connect to this server", this.field_73880_f / 2, this.field_73881_g - 30, 0xFFFFFF); } // super.super. Grrr for (int var4 = 0; var4 < this.field_73887_h.size(); ++var4) { GuiButton var5 = (GuiButton)this.field_73887_h.get(var4); var5.field_73743_d = this.field_73881_g - 20; if (!allowContinue) { var5.field_73746_c = this.field_73880_f / 2 - 75; var5.field_73744_e = StringTranslate.func_74808_a().func_74805_b("gui.done"); } var5.func_73737_a(this.field_73882_e, p_73863_1_, p_73863_2_); } } }
/* (Geometry: point in a rectangle?) Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the rectangle centered at (0, 0) with width 10 and height 5. For example, (2, 2) is inside the rectangle and (6, 4) is outside the rectangle, as shown in Figure 3.7b. (Hint: A point is in the rectangle if its horizontal distance to (0, 0) is less than or equal to 10 / 2 and its vertical distance to (0, 0) is less than or equal to 5.0 / 2. Test your program to cover all cases.) Here are two sample runs. */ import java.util.Scanner; public class Exercise_03_23 { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter a point (x, y) System.out.print("Enter a point with two coordinates: "); double x = input.nextDouble(); double y = input.nextDouble(); // Check whether the point is within the rectangle // centered at (0, 0) with width 10 and height 5 boolean withinRectangle = (Math.pow(Math.pow(x, 2), 0.5) <= 10 / 2 ) || (Math.pow(Math.pow(y, 2), 0.5) <= 5.0 / 2); // Display results System.out.println("Point (" + x + ", " + y + ") is " + ((withinRectangle) ? "in " : "not in ") + "the rectangle"); } }
package de.codescape.bitvunit.util.io; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; /** * Utility class that is used to handle resources available on the classpath. * * @author Stefan Glase * @since 0.5 */ public class ClassPathResource { private final String path; private final ClassLoader classLoader; /** * Constructs a new ClassPathResource and checks that that given path to the resource or file is not * <code>null</code> or an empty String. * * @param path the path to the resource or file */ private ClassPathResource(String path) { if (path == null || path.trim().isEmpty()) { throw new IllegalArgumentException("Given path must not be null or empty."); } if (path.startsWith("/")) { this.path = path.substring(1); } else { this.path = path; } classLoader = getDefaultClassLoader(); } /** * Returns the default {@link ClassLoader} to resolve resources. First the thread context {@link ClassLoader} will * be accessed and returns but as a fallback the {@link ClassLoader} that loaded the {@link ClassPathResource} class * will be used. * * @return default{@link ClassLoader} to resolve resources */ private ClassLoader getDefaultClassLoader() { ClassLoader classLoader = null; try { classLoader = Thread.currentThread().getContextClassLoader(); } catch (Throwable ex) { /* okay, so we are falling back to the system class loader... */ } if (classLoader == null) { classLoader = ClassPathResource.class.getClassLoader(); } return classLoader; } /** * Returns a {@link String} that contains the content of the file. * * @param path path to the resource or file * @return {@link String} that contains the content of the file */ public static String asString(String path) { return new ClassPathResource(path).asString(); } /** * Returns a {@link String} that contains the content of the file. * * @return {@link String} that contains the content of the file */ private String asString() { try { return IOUtils.toString(asInputStream()); } catch (IOException e) { throw new RuntimeException("Could not read from file '" + path + "'.", e); } } /** * Returns an {@link InputStream} to read from the file. * * @param path path to the resource or file * @return {@link InputStream} to read from the file */ public static InputStream asInputStream(String path) { return new ClassPathResource(path).asInputStream(); } /** * Returns an {@link InputStream} to read from the file. * * @return {@link InputStream} to read from the file */ private InputStream asInputStream() { InputStream inputStream = classLoader.getResourceAsStream(path); if (inputStream == null) { throw new RuntimeException("File '" + path + "' was not found."); } return inputStream; } }
package org.openhab.io.net.actions; import org.openhab.io.net.http.HttpUtil; /** * This class provides static methods that can be used in automation rules * for sending HTTP requests * * @author Kai Kreuzer * @since 0.9.0 * */ public class HTTP { /** * Send out a GET-HTTP request. Errors will be logged, returned values just ignored. * * @param url the URL to be used for the GET request. */ static public void sendHttpGetRequest(String url) { HttpUtil.executeUrl("GET", url, 5000); } /** * Send out a PUT-HTTP request. Errors will be logged, returned values just ignored. * * @param url the URL to be used for the PUT request. */ static public void sendHttpPutRequest(String url) { HttpUtil.executeUrl("PUT", url, 1000); } /** * Send out a POST-HTTP request. Errors will be logged, returned values just ignored. * * @param url the URL to be used for the POST request. */ static public void sendHttpPostRequest(String url) { HttpUtil.executeUrl("POST", url, 1000); } /** * Send out a DELETE-HTTP request. Errors will be logged, returned values just ignored. * * @param url the URL to be used for the DELETE request. */ static public void sendHttpDeleteRequest(String url) { HttpUtil.executeUrl("DELETE", url, 1000); } }
package org.openforis.calc.chain.pre; import org.openforis.calc.engine.SqlTask; import org.openforis.calc.engine.Workspace; import org.openforis.calc.persistence.postgis.Psql; import org.springframework.beans.factory.annotation.Value; /** * Copies category tables into the output schema.  Fails if output schema already exists. * * @author G. Miceli */ public final class OutputSchemaGrantsTask extends SqlTask { @Value("${calc.jdbc.username}") private String systemUser; @Override protected void execute() throws Throwable { Workspace workspace = getContext().getWorkspace(); String outputSchema = Psql.quote(workspace.getOutputSchema()); psql().grantAllOnTables(outputSchema, systemUser).execute(); psql().grantAllOnSchema(outputSchema, systemUser).execute(); } }
package com.dianping.cat.message.internal; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel.MapMode; import java.util.List; import org.unidal.helper.Splitters; import com.dianping.cat.configuration.NetworkInterfaceManager; public class MessageIdFactory { private long m_timestamp = getTimestamp(); private volatile int m_index; private String m_domain; private String m_ipAddress; private MappedByteBuffer m_byteBuffer; private RandomAccessFile m_markFile; private static final long HOUR = 3600 * 1000L; public void close() { try { m_markFile.close(); } catch (Exception e) { // ignore it } } public String getNextId() { long timestamp = getTimestamp(); int index; synchronized (this) { if (timestamp != m_timestamp) { m_index = 0; m_timestamp = timestamp; } index = m_index++; saveMark(); } StringBuilder sb = new StringBuilder(m_domain.length() + 32); sb.append(m_domain); sb.append('-'); sb.append(m_ipAddress); sb.append('-'); sb.append(timestamp); sb.append('-'); sb.append(index); return sb.toString(); } protected long getTimestamp() { long timestamp = MilliSecondTimer.currentTimeMillis(); return timestamp / HOUR; // version 2 } public void initialize(String domain) throws IOException { m_domain = domain; if (m_ipAddress == null) { String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress(); List<String> items = Splitters.by(".").noEmptyItem().split(ip); byte[] bytes = new byte[4]; for (int i = 0; i < 4; i++) { bytes[i] = (byte) Integer.parseInt(items.get(i)); } StringBuilder sb = new StringBuilder(bytes.length / 2); for (byte b : bytes) { sb.append(Integer.toHexString((b >> 4) & 0x0F)); sb.append(Integer.toHexString(b & 0x0F)); } m_ipAddress = sb.toString(); } File mark = new File("/data/appdatas/cat/", "cat-" + domain + ".mark"); if (!mark.exists()) { boolean success = true; try { success = mark.createNewFile(); } catch (Exception e) { success = false; } if (!success) { mark = createTempFile(domain); } } else if (!mark.canWrite()) { mark = createTempFile(domain); } m_markFile = new RandomAccessFile(mark, "rw"); m_byteBuffer = m_markFile.getChannel().map(MapMode.READ_WRITE, 0, 20); if (m_byteBuffer.limit() > 0) { int index = m_byteBuffer.getInt(); long lastTimestamp = m_byteBuffer.getLong(); if (lastTimestamp == m_timestamp) { // for same hour m_index = index + 10000; } else { m_index = 0; } } saveMark(); } private File createTempFile(String domain) { String tmpDir = System.getProperty("java.io.tmpdir"); File mark = new File(tmpDir, "cat-" + domain + ".mark"); return mark; } protected void resetIndex() { m_index = 0; } private void saveMark() { try { m_byteBuffer.rewind(); m_byteBuffer.putInt(m_index); m_byteBuffer.putLong(m_timestamp); if (m_index % 100 == 0) { m_byteBuffer.force(); } } catch (Exception e) { // ignore it } } public void setDomain(String domain) { m_domain = domain; } public void setIpAddress(String ipAddress) { m_ipAddress = ipAddress; } }
package ch.obermuhlner.math.big; import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import java.math.MathContext; import java.util.Random; import java.util.function.BiFunction; import java.util.function.Function; import org.junit.Test; public class BigDecimalMathTest { private static final MathContext MC = MathContext.DECIMAL128; private static final MathContext MC_CHECK_DOUBLE = MathContext.DECIMAL32; @Test public void testInternals() { assertEquals(toCheck(2.0), toCheck(BigDecimal.valueOf(2))); assertEquals(toCheck(2.0), toCheck(BigDecimal.valueOf(2.0))); assertEquals(null, toCheck(Double.NaN)); assertEquals(null, toCheck(Double.NEGATIVE_INFINITY)); assertEquals(null, toCheck(Double.POSITIVE_INFINITY)); } @Test public void testIsIntValue() { assertEquals(true, BigDecimalMath.isIntValue(BigDecimal.valueOf(Integer.MIN_VALUE))); assertEquals(true, BigDecimalMath.isIntValue(BigDecimal.valueOf(Integer.MAX_VALUE))); assertEquals(true, BigDecimalMath.isIntValue(BigDecimal.valueOf(0))); assertEquals(true, BigDecimalMath.isIntValue(BigDecimal.valueOf(-55))); assertEquals(true, BigDecimalMath.isIntValue(BigDecimal.valueOf(33))); assertEquals(true, BigDecimalMath.isIntValue(BigDecimal.valueOf(-55.0))); assertEquals(true, BigDecimalMath.isIntValue(BigDecimal.valueOf(33.0))); assertEquals(false, BigDecimalMath.isIntValue(BigDecimal.valueOf(Integer.MIN_VALUE - 1L))); assertEquals(false, BigDecimalMath.isIntValue(BigDecimal.valueOf(Integer.MAX_VALUE + 1L))); assertEquals(false, BigDecimalMath.isIntValue(BigDecimal.valueOf(3.333))); assertEquals(false, BigDecimalMath.isIntValue(BigDecimal.valueOf(-5.555))); } @Test public void testFactorial() { assertEquals(new BigDecimal("1"), BigDecimalMath.factorial(0)); assertEquals(new BigDecimal("1"), BigDecimalMath.factorial(1)); assertEquals(new BigDecimal("2"), BigDecimalMath.factorial(2)); assertEquals(new BigDecimal("6"), BigDecimalMath.factorial(3)); assertEquals(new BigDecimal("24"), BigDecimalMath.factorial(4)); assertEquals(new BigDecimal("120"), BigDecimalMath.factorial(5)); assertEquals( new BigDecimal("9425947759838359420851623124482936749562312794702543768327889353416977599316221476503087861591808346911623490003549599583369706302603264000000000000000000000000"), BigDecimalMath.factorial(101)); } @Test(expected = ArithmeticException.class) public void testPowIntZeroPowerNegative() { BigDecimalMath.pow(BigDecimal.valueOf(0), -5, MC); } @Test public void testPowIntPositiveY() { // positive exponents for(int x : new int[] { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 }) { for(int y : new int[] { 0, 1, 2, 3, 4, 5 }) { assertEquals( x + "^" + y, BigDecimal.valueOf((int) Math.pow(x, y)), BigDecimalMath.pow(BigDecimal.valueOf(x), y, MC)); } } } @Test public void testPowIntHighAccuracy() { // Result from wolframalpha.com: 1.000000000000001 ^ 1234567 BigDecimal expected = new BigDecimal("1.0000000012345670007620772217746112884011264566574371750661936042203432730421791357400340579375261062151425984605455718643834831212687809215508627027381366482513893346638309647254328483125554030430209837119592796226273439855097892690164822394282109582106572606688508863981956571098445811521589634730079294115917257238821829137340388818182807197358582081813107978164190701238742379894183398009280170118101371420721038965387736053980576803168658232943601622524279972909569009054951992769572674935063940581972099846878996147233580891866876374475623810230198932136306920161303356757346458080393981632574418878114647836311205301451612892591304592483387202671500569971713254903439669992702668656944996771767101889159835990797016804271347502053715595561455746434955874842970156476866700704289785119355240166844949092583102028847019848438487206052262820785557574627974128427022802453099783875466674774383283633178630613523399806185908766812896743349684394795523513553454443796268439405430281375480024234032172402840564635266057234920659063946839453576870882295214918516855889289061559150620879201634277096704728220897344041618549870872138380388841708643468696894694958739051584506837702527545643699395947205334800543370866515060967536750156194684592206567524739086165295878406662557303580256110172236670067327095217480071365601062314705686844139397480994156197621687313833641789783258629317024951883457084359977886729599488232112988200551717307628303748345907910029990065217835915703110440740246602046742181454674636608252499671425052811702208797030657332754492225689850123854291480472732132658657813229027494239083970478001231283002517914471878332200542180147054941938310139493813524503325181756491235593304058711999763930240249546122995086505989026270701355781888675020326791938289147344430814703304780863155994800418441632244536"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.pow(new BigDecimal("1.000000000000001"), 1234567, mathContext), 10); } @Test public void testPowIntNegativeY() { // positive exponents for(int x : new int[] { -5, -4, -3, -2, -1, 1, 2, 3, 4, 5 }) { // no x=0 ! for(int y : new int[] { -5, -4, -3, -2, -1}) { assertEquals( x + "^" + y, BigDecimal.ONE.divide(BigDecimal.valueOf((int) Math.pow(x, -y)), MC), BigDecimalMath.pow(BigDecimal.valueOf(x), y, MC)); } } } @Test public void testPowIntSpecialCases() { // 0^0 = 1 assertEquals(BigDecimal.valueOf(1), BigDecimalMath.pow(BigDecimal.valueOf(0), 0, MC)); // 0^x = 0 for x > 0 assertEquals(BigDecimal.valueOf(0), BigDecimalMath.pow(BigDecimal.valueOf(0), +5, MC)); // x^0 = 1 for all x assertEquals(BigDecimal.valueOf(1), BigDecimalMath.pow(BigDecimal.valueOf(-5), 0, MC)); assertEquals(BigDecimal.valueOf(1), BigDecimalMath.pow(BigDecimal.valueOf(+5), 0, MC)); } @Test(expected = ArithmeticException.class) public void testPowInt0NegativeY() { // 0^x for x < 0 is undefined System.out.println(BigDecimalMath.pow(BigDecimal.valueOf(0), -5, MC)); } @Test public void testPowPositiveX() { for(double x : new double[] { 1, 1.5, 2, 2.5, 3, 4, 5 }) { for(double y : new double[] { -5, -4, -3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 4, 5 }) { assertEquals( x + "^" + y, toCheck(Math.pow(x, y)), toCheck(BigDecimalMath.pow(BigDecimal.valueOf(x), BigDecimal.valueOf(y), MC))); } } for(double x : new double[] { 0 }) { for(double y : new double[] { 0, 0.5, 1, 1.5, 2, 2.5, 3, 4, 5 }) { assertEquals( x + "^" + y, toCheck(Math.pow(x, y)), toCheck(BigDecimalMath.pow(BigDecimal.valueOf(x), BigDecimal.valueOf(y), MC))); } } } @Test public void testPowNegativeX() { for(double x : new double[] { -2, -1 }) { for(double y : new double[] { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 }) { assertEquals( x + "^" + y, toCheck(Math.pow(x, y)), toCheck(BigDecimalMath.pow(BigDecimal.valueOf(x), BigDecimal.valueOf(y), MC))); } } } @Test public void testPowSpecialCases() { // 0^0 = 1 assertEquals(BigDecimal.valueOf(1), BigDecimalMath.pow(BigDecimal.valueOf(0), BigDecimal.valueOf(0), MC)); // 0^x = 0 for x > 0 assertEquals(BigDecimal.valueOf(0), BigDecimalMath.pow(BigDecimal.valueOf(0), BigDecimal.valueOf(+5), MC)); // x^0 = 1 for all x assertEquals(BigDecimal.valueOf(1), BigDecimalMath.pow(BigDecimal.valueOf(-5), BigDecimal.valueOf(0), MC)); assertEquals(BigDecimal.valueOf(1), BigDecimalMath.pow(BigDecimal.valueOf(+5), BigDecimal.valueOf(0), MC)); } @Test(expected = ArithmeticException.class) public void testPow0NegativeY() { // 0^x for x < 0 is undefined System.out.println(BigDecimalMath.pow(BigDecimal.valueOf(0), BigDecimal.valueOf(-5), MC)); } @Test public void testPowHighAccuracy1() { // Result from wolframalpha.com: 0.12345 ^ 0.54321 BigDecimal expected = new BigDecimal("0.3209880595151945185125730942395290036641685516401211365668021036227236806558712414817507777010529315619538091221044550517779379562785777203521073317310721887789752732383195992338046561142233197839101366627988301068817528932856364705673996626318789438689474137773276533959617159796843289130492749319006030362443626367021658149242426847020379714749221060925227256780407031977051743109767225075035162749746755475404882675969237304723283707838724317900591364308593663647305926456586738661094577874745954912201392504732008960366344473904725152289010662196139662871362863747003357119301290791005303042638323919552042428899542474653695157843324029537490471818904797202183382709740019779991866183409872343305557416160635632389025962773383948534706993646814493361946320537133866646649868386696744314086907873844459873522561100570574729858449637845765912377361924716997579241434414109143219005616107946583880474580592369219885446517321145488945984700859989002667482906803702408431898991426975130215742273501237614632961770832706470833822137675136844301417148974010849402947454745491575337007331634736828408418815679059906104486027992986268232803807301917429934411578887225359031451001114134791114208050651494053415141140416237540583107162910153240598400275170478935634433997238593229553374738812677055332589568742194164880936765282391919077003882108791507606561409745897362292129423109172883116578263204383034775181118065757584408324046421493189442843977781400819942671602106042861790274528866034496106158048150133736995335643971391805690440083096190217018526827375909068556103532422317360304116327640562774302558829111893179295765516557567645385660500282213611503701490309520842280796017787286271212920387358249026225529459857528177686345102946488625734747525296711978764741913791309106485960272693462458335037929582834061232406160"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.pow(new BigDecimal("0.12345"), new BigDecimal("0.54321"), mathContext), 10, 200); // TODO optimize pow() } //@Test public void testPowHighAccuracy2() { // Result from wolframalpha.com: 1234.5 ^ 5.4321 BigDecimal expected = new BigDecimal("62128200273178468.6677398330313037781753494560130835832101960387223758707669665725754895879107246310011029364211118269934534848627597104718365299707675269883473866053798863560099145230081124493870576780612499275723252481988188990085485417903685910250385975275407201318962063571641788853056193956632922391172489400257505790978314596080576631215805090936935676836971091464254857748180262699112027530753684170510323511798980747639116410705861310591624568227525136728034348718513230067867653958961909807085463366698897670703033966902227226026963721428348393842605660315775615215897171041744502317760375398468093874441545987214768846585209830041286071364933140664316884545264314137705612948991849327809564207354415319908754752255701802039139765434084951567836148382259822205056903343078315714330953561297888049627241752521508353126178543435267324563502039726903979264593590549404498146175495384414213014048644769191478319546475736458067346291095970042183567796890291583916374248166579807593334209446774446615766870268699990517113368293867016985423417705611330741518898131591089047503977721006889839010831321890964560951517989774344229913647667605138595803854678957098670003929907267918591145790413480904188741307063239101475728087298405926679231349800701106750462465201862628618772432920720630962325975002703818993580555861946571650399329644600854846155487513507946368829475408071100475344884929346742632438630083062705384305478596166582416332328006339035640924818942503261178020860473649223332292597947133883640686283632593820956826840942563265332271497540069352040396588314197259366049553760360493773149812879272759032356567261509967695159889106382819692093987902453799750689562469611095996225341555322139606462193260609916132372239906927497183040765412767764999503366952191218000245749101208123555266177028678838265168229"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.pow(new BigDecimal("1234.5"), new BigDecimal("5.4321"), mathContext), 10, 200); // TODO optimize pow() } @Test public void testSqrt() { for(double value : new double[] { 0, 0.1, 2, 10, 33.3333 }) { assertEquals( "sqrt(" + value + ")", toCheck(Math.sqrt(value)), toCheck(BigDecimalMath.sqrt(BigDecimal.valueOf(value), MC))); } } @Test public void testSqrtHighAccuracy() { // Result from wolframalpha.com: sqrt(2) BigDecimal expected = new BigDecimal("1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372352885092648612494977154218334204285686060146824720771435854874155657069677653720226485447015858801620758474922657226002085584466521458398893944370926591800311388246468157082630100594858704003186480342194897278290641045072636881313739855256117322040245091227700226941127573627280495738108967504018369868368450725799364729060762996941380475654823728997180326802474420629269124859052181004459842150591120249441341728531478105803603371077309182869314710171111683916581726889419758716582152128229518488472089694633862891562882765952635140542267653239694617511291602408715510135150455381287560052631468017127402653969470240300517495318862925631385188163478001569369176881852378684052287837629389214300655869568685964595155501644724509836896036887323114389415576651040883914292338113206052433629485317049915771756228549741438999188021762430965206564211827316726257539594717255934637238632261482742622208671155839599926521176252698917540988159348640083457085181472231814204070426509056532333398436457865796796519267292399875366617215982578860263363617827495994219403777753681426217738799194551397231274066898329989895386728822856378697749662519966583525776198939322845344735694794962952168891485492538904755828834526096524096542889394538646625744927556381964410316979833061852019379384940057156333720548068540575867999670121372239"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.sqrt(new BigDecimal("2"), mathContext), 10); } @Test public void testRoot() { for(double value : new double[] { 0.1, 2, 10, 33.3333 }) { assertEquals( "root(2," + value + ")", toCheck(Math.sqrt(value)), toCheck(BigDecimalMath.root(BigDecimal.valueOf(2), BigDecimal.valueOf(value), MC))); assertEquals( "root(3," + value + ")", toCheck(Math.cbrt(value)), toCheck(BigDecimalMath.root(BigDecimal.valueOf(3), BigDecimal.valueOf(value), MC))); } } @Test public void testRootHighAccuracy1() { // Result from wolframalpha.com: root(1.23, 123) BigDecimal expected = new BigDecimal("50.016102539344819307741514415079435545110277821887074630242881493528776023690905378058352283823814945584087486290764920313665152884137840533937075179853255596515758851877960056849468879933122908090021571162427934915567330612627267701300492535817858361072169790783434196345863626810981153268939825893279523570322533446766188724600595265286542918045850353371520018451295635609248478721067200812355632099802713302132804777044107393832707173313768807959788098545050700242134577863569636367439867566923334792774940569273585734964008310245010584348384920574103306733020525390136397928777667088202296433541706175886006626333525007680397351405390927420825851036548474519239425298649420795296781692303253055152441850691276044546565109657012938963181532017974206315159305959543881191233733179735321461579808278383770345759408145745617032705494900390986476773247981270283533959979287340513398944113566999839889290733896874439682249327621463735375868408190435590094166575473967368412983975580104741004390308453023021214626015068027388545767003666342291064051883531202983476423138817666738346033272948508395214246047027012105246939488877506475824651688812245962816086719050192476878886543996441778751825677213412487177484703116405390741627076678284295993334231429145515176165808842776515287299275536932744066126348489439143701880784521312311735178716650919024092723485314329094064704170548551468318250179561508293077056611877488417962195965319219352314664764649802231780262169742484818333055713291103286608643184332535729978330383356321740509817475633105247757622805298711765784874873240679024286215940395303989612556865748135450980540945799394622053158729350598632915060818702520420240989908678141379300904169936776618861221839938283876222332124814830207073816864076428273177778788053613345444299361357958409716099682468768353446625063"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.root(BigDecimal.valueOf(1.23), BigDecimal.valueOf(123), mathContext), 10, 100); // TODO optimize root() } @Test public void testRootHighAccuracy2() { // Result from wolframalpha.com: root(7.5, 123) BigDecimal expected = new BigDecimal("1.8995643695815870676539369434054361726808105217886880103090875996194822396396255621113000403452538887419132729641364085738725440707944858433996644867599831080192362123855812595483776922496542428049642916664676504355648001147425299497362249152998433619265150901899608932149147324281944326398659053901429881376755786331063699786297852504541315337453993167176639520666006383001509553952974478682921524643975384790223822148525159295285828652242201443762216662072731709846657895992750535254286493842754491094463672629441270037173501058364079340866564365554529160216015597086145980711187711119750807640654996392084846441696711420521658760165363535215241687408369549643269709297427044177507157609035697648282875422321141920576120188389383509318979064825824777240151847818551071255436323480281154877997743553609520167536258202911691329853232693386770937694807506144279660147324316659333074620896627829029651910783066736606497262785345465872401993026696735802446138584306213230373571409591420951964537136053258998945471633936332983896917810023265095766395377592848121611444196796785031727740335105553348270077424620974061727975050161324060753928284759055040064976732991126510635738927993365006832681484889202649313814280125684525505938973967575274196130269615461251746873419445856759329916403947432038902141704646304799083820073914767560878449162496519826664715572693747490088659968040153989493366037393989012508491856761986732685422561958101646754270192269505879594808800416777471196270722586367363680538183391904535845392721112874375802640395545739073303112631715831096156004422381940090623765493332249827278090443678800852264922795299927727708248191560574252923342860845325222035245426918719153132138325983001330317244830727602810422542012322698940744820925849667642343510406965273569391887099540050259962759858771196756422007171"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.root(BigDecimal.valueOf(7.5), BigDecimal.valueOf(123), mathContext), 10, 50); // TODO optimize root() } @Test public void testLog() { for(double value : new double[] { 0.1, 2, 10, 33.3333 }) { assertEquals("log(" + value + ")", toCheck(Math.log(value)), toCheck(BigDecimalMath.log(BigDecimal.valueOf(value), MC))); } } @Test public void testLogRandom() { assertRandomCalculation( 100, "log", random -> random.nextFloat() * 100 + 0.00001, (x, mathContext) -> BigDecimalMath.log(x, mathContext)); } private void assertRandomCalculation(int count, String functionName, Function<Random, Double> xFunction, BiFunction<BigDecimal, MathContext, BigDecimal> calculation) { Random random = new Random(1); for (int i = 0; i < count; i++) { int precision = random.nextInt(100) + 1; BigDecimal x = BigDecimal.valueOf(xFunction.apply(random)); MathContext mathContext = new MathContext(precision); BigDecimal result = calculation.apply(x, mathContext); BigDecimal expected = calculation.apply(x, new MathContext(precision + 20)).round(mathContext); String description = functionName + "(" + x + ") precision=" + precision; assertEquals(description, expected.toString(), result.toString()); } } @Test public void testLogHighAccuracy1() { // Result from wolframalpha.com: ln(0.1) BigDecimal expected = new BigDecimal("-2.30258509299404568401799145468436420760110148862877297603332790096757260967735248023599720508959829834196778404228624863340952546508280675666628736909878168948290720832555468084379989482623319852839350530896537773262884616336622228769821988674654366747440424327436515504893431493939147961940440022210510171417480036880840126470806855677432162283552201148046637156591213734507478569476834636167921018064450706480002775026849167465505868569356734206705811364292245544057589257242082413146956890167589402567763113569192920333765871416602301057030896345720754403708474699401682692828084811842893148485249486448719278096762712757753970276686059524967166741834857044225071979650047149510504922147765676369386629769795221107182645497347726624257094293225827985025855097852653832076067263171643095059950878075237103331011978575473315414218084275438635917781170543098274823850456480190956102992918243182375253577097505395651876975103749708886921802051893395072385392051446341972652872869651108625714921988499787488737713456862091670584980782805975119385444500997813114691593466624107184669231010759843831919129223079250374729865092900988039194170265441681633572755570315159611356484654619089704281976336583698371632898217440736600916217785054177927636773114504178213766011101073104239783252189489881759792179866639431952393685591644711824675324563091252877833096360426298215304087456092776072664135478757661626292656829870495795491395491804920906943858079003276301794150311786686209240853794986126493347935487173745167580953708828106745244010589244497647968607512027572418187498939597164310551884819528833074669931781463493000032120032776565413047262188397059679445794346834321839530441484480370130575367426215367557981477045803141363779323629156012818533649846694226146520645994207291711937060244492"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.log(new BigDecimal("0.1"), mathContext), 10); // TODO optimize log() for value close to 0.0 } @Test public void testLogHighAccuracy2() { // Result from wolframalpha.com: ln(1.1) BigDecimal expected = new BigDecimal("0.0953101798043248600439521232807650922206053653086441991852398081630010142358842328390575029130364930727479418458517498888460436935129806386890150217023263755687346983551204157456607731117050481406611584967219092627683199972666804124629171163211396201386277872575289851216418802049468841988934550053918259553296705084248072320206243393647990631942365020716424972582488628309770740635849277971589257686851592941134955982468458204470563781108676951416362518738052421687452698243540081779470585025890580291528650263570516836272082869034439007178525831485094480503205465208833580782304569935437696233763597527612962802332419887793490159262767738202097437296124304231269978317763387834500850947983607954894765663306829441000443449252110585597386446423305000249520642003351749383035733163887183863658864095987980592896922224719866617664086469438599082172014984648661016553883267832731905893594398418365160836037053676940083743785539126726302367554039807719021730407981203469520199824994506211545156995496539456365581027383589659382402015390419603824664083368873307873019384357785045824504691072378535575392646883979065139246126662251603763318447377681731632334250380687464278805888614468777887659631017437620270326399552535490068490417697909725326896790239468286121676873104226385183016443903673794887669845552057786043820598162664741719835262749471347084606772426040314789592161567246837020619602671610506695926435445325463039957620861253293473952704732964930764736250291219054949541518603372096218858644670199237818738241646938837142992083372427353696766016209216197009652464144415416340684821107427035544058078681627922043963452271529803892396332155037590445683916173953295983049207965617834301297873495901595044766960173144576650851894013006899406665176310040752323677741807454239794575425116685728529323731335086049670268306"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.log(new BigDecimal("1.1"), mathContext), 10); } @Test public void testLogHighAccuracy3() { // Result from wolframalpha.com: ln(12345.6) BigDecimal expected = new BigDecimal("9.42105500327135525114521501453525399237436111276300326386323534432727151942992511520562558738175320737219392933678106934681377640298797158131139323906361961480381516008415766949640011144295651380957422777114172279167654006534622812747920122075143832000303491928864417567534602811492095685408856581074035803357797631847469251006466446952382984400769172787795491275890878474305023861509824367243299385769279771744041937866552134975148449991501344008449686333627176197439283560717007769286520651804657135365525410547797134491863813264296599988480767570621877413992243488449252058389112464675521921368744908030643106093708139694498213865760209374231089223703469389057990578641477811580679006647361045368883126313166757159295044784734054746026667561208850147352459931288221690064827656007945926558137817955314752299200021125335319543610643148781413031739368946686197126231424703883123190210238015791369611214420726133482521541649129324232190740641049135517129893844376556993789191631768552752257796461172834352906322971133196717292014063557464657868471260257837864581817895933554699436597231519928906186824100551929174973211768975723220457184410041128885431823059460270296159512608527194960997843854276107619358871611335110158160499192067423059751567986373407423489599586293284362977309927604782683386482396609096117347165767675657470578510018397575185923185572052807175571518796143517238193372303027925460053807069802388627060672427272087223286476333683468229892546440731981947511457788744089944064466689422654892614083398427300212135529866471079161390374604296893598724751037581346990096479637907462110313260901383748633868418336284029147686046156013978973990920093756659785588328734878986910751799701679853456356654554727303139653731884939067754728654663370026652097310980166441905496504187282659704649813546716585697691"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.log(new BigDecimal("12345.6"), mathContext), 10, 200); // TODO optimize log() } @Test public void testExp() { for(double value : new double[] { -5, -1, 0.1, 2, 10 }) { assertEquals("exp(" + value + ")", toCheck(Math.exp(value)), toCheck(BigDecimalMath.exp(BigDecimal.valueOf(value), MC))); } } @Test public void testExpHighAccuracy1() { // Result from wolframalpha.com: exp(0.1) BigDecimal expected = new BigDecimal("1.1051709180756476248117078264902466682245471947375187187928632894409679667476543029891433189707486536329171204854012445361537347145315787020068902997574505197515004866018321613310249357028047934586850494525645057122112661163770326284627042965573236001851138977093600284769443372730658853053002811154007820888910705403712481387499832879763074670691187054786420033729321209162792986139109713136202181843612999064371057442214441509033603625128922139492683515203569550353743656144372757405378395318324008280741587539066613515113982139135726893022699091000215648706791206777090283207508625041582515035160384730085864811589785637025471895631826720701700554046867490844416060621933317666818019314469778173494549497985045303406629427511807573756398858555866448811811806333247210364950515781422279735945226411105718464916466588898895425154437563356326922423993425668055030150187978568089290481077628854935380963680803086975643392286380110893491216896970405186147072881173903395370306903756052863966751655566156177044091023716763999613715961429909147602055822171056918247483370329310652377494326018131931115202583455695740577117305727325929270892586003078380276849851024733440526333630939768046873818746897979176031710638428538365444373036344477660068827517905394205724765809719068497652979331103372768988364106139063845834332444587680278142035133567220351279735997089196132184270510670193246409032174006524564495804123904224547124821906736781803247534842994079537510834190198353331683651574603364551464993636940684957076677363104098202444018343049556576017452467191522001230198866508508728780804296630956390659819928014152407848066718063601429519635764058390569704470217925967541099757148635387989599481795155282833193600584112822014656645896726556449347326910544815360769564296952628696236865028848565540573895707695598984577773238"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.exp(new BigDecimal("0.1"), mathContext), 10); } @Test public void testExpHighAccuracy2() { // Result from wolframalpha.com: exp(123.4) BigDecimal expected = new BigDecimal("390786063200889154948155379410925404241701821048363382.932350954191939407875540538095053725850542917235991826991631549658381619846119064767940229694652504799690942074237719293556052198585602941442651814977379463173507703540164446248233994372649675083170661574855926134163163649067886904058135980414181563116455815478263535970747684634869846370078756117785925810367190913580101129012440848783613501818345221727921636036313301394206941005430607708535856550269918711349535144151578877168501672228271098301349906118292542981905746359989070403424693487891904874342086983801039403550584241691952868285098443443717286891245248589074794703961309335661643261592184482383775612097087066220605742406426487994296854782150419816494210555905079335674950579368212272414401633950719948812364415716009625682245889528799300726848267101515893741151833582331196187096157250772884710690932741239776061706938673734755604112474396879294621933875319320351790004373826158307559047749814106033538586272336832756712454484917457975827690460377128324949811226379546825509424852035625713328557508831082726245169380827972015037825516930075858966627188583168270036404466677106038985975116257215788600328710224325128935656214272530307376436037654248341541925033083450953659434992320670198187236379508778799056681080864264023524043718014105080505710276107680142887912693096434707224622405921182458722451547247803222237498053677146957211048297712875730899381841541047254172958887430559055751735318481711132216206915942752379320012433097749980476094039036829992786175018479140791048841069099146681433638254527364565199203683980587269493176948487694117499339581660653106481583097500412636413209554147009042448657752082659511080673300924304690964484273924800648584285968546527296722686071417123776801220060226116144242129928933422759721847194902947144831258"); assertPrecisionCalculation( expected, mathContext -> BigDecimalMath.exp(new BigDecimal("123.4"), mathContext), 60); } @Test public void testSin() { for(double value : new double[] { -5, -1, -0.3, 0, 0.1, 2, 10 }) { assertEquals("sin(" + value + ")", toCheck(Math.sin(value)), toCheck(BigDecimalMath.sin(BigDecimal.valueOf(value), MC))); } } @Test public void testCos() { for(double value : new double[] { -5, -1, -0.3, 0, 0.1, 2, 10 }) { assertEquals("cos(" + value + ")", toCheck(Math.cos(value)), toCheck(BigDecimalMath.cos(BigDecimal.valueOf(value), MC))); } } private void assertPrecisionCalculation(BigDecimal expected, Function<MathContext, BigDecimal> precisionCalculation, int startPrecision) { assertPrecisionCalculation(expected, precisionCalculation, startPrecision, expected.precision()); } private void assertPrecisionCalculation(BigDecimal expected, Function<MathContext, BigDecimal> precisionCalculation, int startPrecision, int endPrecision) { int precision = startPrecision; while (precision <= endPrecision) { MathContext mathContext = new MathContext(precision); assertEquals( "precision=" + precision, expected.round(mathContext).toString(), precisionCalculation.apply(mathContext).toString()); precision *= 2; } } private static BigDecimal toCheck(double value) { long longValue = (long) value; if (value == (double)longValue) { return toCheck(BigDecimal.valueOf(longValue)); } if (Double.isFinite(value)) { return toCheck(BigDecimal.valueOf(value)); } return null; } private static BigDecimal toCheck(BigDecimal value) { return value.setScale(MC_CHECK_DOUBLE.getPrecision(), MC_CHECK_DOUBLE.getRoundingMode()); } }
package org.gbif.checklistbank.cli.show; import org.gbif.api.model.checklistbank.NameUsage; import org.gbif.checklistbank.neo.NeoProperties; import org.gbif.checklistbank.neo.UsageDao; import org.gbif.checklistbank.nub.model.NubUsage; import org.gbif.cli.BaseCommand; import org.gbif.cli.Command; import java.io.FileWriter; import java.io.Writer; import java.util.Collection; import org.kohsuke.MetaInfServices; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; /** * Command that issues new normalize or import messages for manual admin purposes. */ @MetaInfServices(Command.class) public class ShowCommand extends BaseCommand { private final ShowConfiguration cfg = new ShowConfiguration(); public ShowCommand() { super("show"); } @Override protected Object getConfigurationObject() { return cfg; } @Override protected void doRun() { try { UsageDao dao = UsageDao.persistentDao(cfg.neo, cfg.key, true, null, false); Node root = null; try (Transaction tx = dao.beginTx()) { if (cfg.rootId != null || cfg.rootName != null) { if (cfg.rootId != null) { System.out.println("Show root node " + cfg.rootId); root = dao.getNeo().getNodeById(cfg.rootId); } else { System.out.println("Show root node " + cfg.rootName); Collection<Node> rootNodes = dao.findByName(cfg.rootName); if (rootNodes.isEmpty()) { System.out.println("No root found"); return; } else if (rootNodes.size() > 1) { System.out.println("Multiple root nodes found. Please select one by its id:"); for (Node n : rootNodes) { System.out.println(n.getId() + ": " + n.getProperty(NeoProperties.SCIENTIFIC_NAME, "???")); } return; } root = rootNodes.iterator().next(); } NubUsage nub = dao.readNub(root); System.out.println("NUB: " + (nub == null ? "null" : nub.toStringComplete())); NameUsage u = dao.readUsage(root, true); System.out.println("USAGE: " + u); } // show tree dao.logStats(); try (Writer writer = new FileWriter(cfg.file)) { dao.printTree(writer, cfg.format, cfg.fullNames, cfg.lowestRank, root); } } finally { dao.close(); } } catch (Exception e) { throw new RuntimeException(e); } } }
package VASSAL.tools.image.tilecache; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.concurrent.ExecutorService; import VASSAL.tools.lang.Callback; /** * Slices an image into tiles. * * @since 3.2.0 * @author Joel Uckelman */ public interface TileSlicer { /** * Slices an image into tiles. * * @param src the source image * @param iname the basename for the tiles * @param tpath the path for the tiles * @param tw the tile width * @param th the tile height * @param exec the executor in which to run tasks * @param progress a callback for indicating progress */ public void slice( BufferedImage src, String iname, String tpath, int tw, int th, ExecutorService exec, Callback<Void> progress ) throws IOException; }
package com.github.andlyticsproject.console.v2; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.github.andlyticsproject.model.AppInfo; import com.github.andlyticsproject.model.AppStats; import com.github.andlyticsproject.model.Comment; public class JsonParser { private static final String TAG = JsonParser.class.getSimpleName(); private JsonParser() { } /** * Parses the supplied JSON string and adds the extracted ratings to the supplied * {@link AppStats} object * * @param json * @param stats * @throws JSONException */ static void parseRatings(String json, AppStats stats) throws JSONException { // Extract just the array with the values JSONArray values = new JSONObject(json).getJSONArray("result").getJSONArray(1) .getJSONArray(0); // Ratings are at index 2 - 6 stats.setRating(values.getInt(2), values.getInt(3), values.getInt(4), values.getInt(5), values.getInt(6)); } /** * Parses the supplied JSON string and adds the extracted statistics to the supplied * {@link AppStats} object * based on the supplied statsType * Not used at the moment * * @param json * @param stats * @param statsType * @throws JSONException */ static void parseStatistics(String json, AppStats stats, int statsType) throws JSONException { // Extract the top level values array JSONArray values = new JSONObject(json).getJSONArray("result").getJSONArray(1); /* * null * Nested array [null, [null, Array containing historical data]] * null * null * null * Nested arrays containing summary and historical data broken down by dimension e.g. * Android version * null * null * App name */ // For now we just care about todays value, later we may delve into the historical and // dimensioned data JSONArray historicalData = values.getJSONArray(1).getJSONArray(1); JSONArray latestData = historicalData.getJSONArray(historicalData.length() - 1); /* * null * Date * [null, value] */ int latestValue = latestData.getJSONArray(2).getInt(1); switch (statsType) { case DevConsoleV2Protocol.STATS_TYPE_TOTAL_USER_INSTALLS: stats.setTotalDownloads(latestValue); break; case DevConsoleV2Protocol.STATS_TYPE_ACTIVE_DEVICE_INSTALLS: stats.setActiveInstalls(latestValue); break; default: break; } } /** * Parses the supplied JSON string and builds a list of apps from it * * @param json * @param accountName * @return List of apps * @throws JSONException */ static List<AppInfo> parseAppInfos(String json, String accountName) throws JSONException { Date now = new Date(); List<AppInfo> apps = new ArrayList<AppInfo>(); // Extract the base array containing apps JSONArray jsonApps = new JSONObject(json).getJSONArray("result").getJSONArray(1); int numberOfApps = jsonApps.length(); for (int i = 0; i < numberOfApps; i++) { AppInfo app = new AppInfo(); app.setAccount(accountName); app.setLastUpdate(now); /* * Per app: * null * [ APP_INFO_ARRAY * * null * * packageName * * Nested array with details * * null * * Nested array with version details * * Nested array with price details * * Last update Date * * Number [1=published, 5 = draft?] * ] * null * [ APP_STATS_ARRAY * * null, * * Active installs * * Total ratings * * Average rating * * Errors * * Total installs * ] */ JSONArray jsonApp = jsonApps.getJSONArray(i); JSONArray jsonAppInfo = jsonApp.getJSONArray(1); String packageName = jsonAppInfo.getString(1); // Look for "tmp.7238057230750432756094760456.235728507238057230542" if (packageName == null || (packageName.startsWith("tmp.") && Character.isDigit(packageName.charAt(4)))) { continue; // Draft app } // Check number code and last updated date // Published: 1 // Unpublished: 2 // Draft: 5 // Draft w/ in-app items?: 6 // TODO figure out the rest and add don't just skip, filter, etc. Cf. #223 int publishState = jsonAppInfo.getInt(7); Log.d(TAG, String.format("%s: publishState=%d", packageName, publishState)); if (publishState != 1) { // Not a published app, skipping continue; } app.setPublishState(publishState); app.setPackageName(packageName); /* * Per app details: * null * Country code * App Name * Description * Unknown * Last what's new */ JSONArray appDetails = jsonAppInfo.getJSONArray(2).getJSONArray(1).getJSONArray(0); app.setName(appDetails.getString(2)); /* * Per app version details: * null * null * packageName * versionNumber * versionName * null * Array with app icon [null,null,null,icon] */ JSONArray appVersions = jsonAppInfo.getJSONArray(4); JSONArray lastAppVersionDetails = appVersions.getJSONArray(appVersions.length() - 1) .getJSONArray(2); app.setVersionName(lastAppVersionDetails.getString(4)); app.setIconUrl(lastAppVersionDetails.getJSONArray(6).getString(3)); // App stats /* * null, * Active installs * Total ratings * Average rating * Errors * Total installs */ JSONArray jsonAppStats = jsonApp.getJSONArray(3); AppStats stats = new AppStats(); stats.setRequestDate(now); stats.setActiveInstalls(jsonAppStats.getInt(1)); stats.setTotalDownloads(jsonAppStats.getInt(5)); stats.setNumberOfErrors(jsonAppStats.optInt(4)); app.setLatestStats(stats); apps.add(app); } return apps; } /** * Parses the supplied JSON string and returns the number of comments. * * @param json * @return * @throws JSONException */ static int parseCommentsCount(String json) throws JSONException { // Just extract the number of comments /* * null * Array containing arrays of comments * numberOfComments */ return new JSONObject(json).getJSONArray("result").getInt(2); } /** * Parses the supplied JSON string and returns a list of comments. * * @param json * @return * @throws JSONException */ static List<Comment> parseComments(String json) throws JSONException { List<Comment> comments = new ArrayList<Comment>(); /* * null * Array containing arrays of comments * numberOfComments */ JSONArray jsonComments = new JSONObject(json).getJSONArray("result").getJSONArray(1); int count = jsonComments.length(); for (int i = 0; i < count; i++) { Comment comment = new Comment(); JSONArray jsonComment = jsonComments.getJSONArray(i); /* * null * "gaia:17919762185957048423:1:vm:11887109942373535891", -- ID? * "REVIEWERS_NAME", * "1343652956570", -- DATE? * RATING, * null * "COMMENT", * null, * "VERSION_NAME", * [ null, * "DEVICE_CODE_NAME", * "DEVICE_MANFACTURER", * "DEVICE_MODEL" * ], * "LOCALE", * null, * 0 */ // Example with developer reply /* * [ * null, * "gaia:12824185113034449316:1:vm:18363775304595766012", * "Mickal", * "1350333837326", * 1, * "", * "Nul\tNul!! N'arrive pas a scanner le moindre code barre!", * 73, * "3.2.5", * [ * null, * "X10i", * "SEMC", * "Xperia X10" * ], * "fr_FR", * [ * null, * "Prixing fonctionne pourtant bien sur Xperia X10. Essayez de prendre un minimum de recul, au moins 20 30cm, vitez les ombres et les reflets. N'hsitez pas nous crire sur contact@prixing.fr pour une assistance personnalise." * , * null, * "1350393460968" * ], * 1 * ] */ String user = jsonComment.getString(2); if (user != null && !"null".equals(user)) { comment.setUser(user); } comment.setDate(parseDate(jsonComment.getLong(3))); comment.setRating(jsonComment.getInt(4)); String version = jsonComment.getString(8); if (version != null && !version.equals("null")) { comment.setAppVersion(version); } comment.setText(jsonComment.getString(6)); JSONArray jsonDevice = jsonComment.optJSONArray(9); if (jsonDevice != null) { String device = jsonDevice.optString(3); JSONArray extraInfo = jsonDevice.optJSONArray(2); if (extraInfo != null) { device += " " + extraInfo.optString(0); } comment.setDevice(device.trim()); } JSONArray jsonReply = jsonComment.optJSONArray(11); if (jsonReply != null) { Comment reply = new Comment(true); reply.setText(jsonReply.getString(1)); reply.setReplyDate(parseDate(jsonReply.getLong(3))); reply.setDate(comment.getDate()); comment.setReply(reply); } comments.add(comment); } return comments; } /** * Parses the given date * * @param unixDateCode * @return */ private static Date parseDate(long unixDateCode) { return new Date(unixDateCode); } }
package com.github.takuji31.appbase.widget; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.AbsListView; import android.widget.Adapter; import android.widget.ListAdapter; import android.widget.ListView; public class PagingListView extends ListView implements AbsListView.OnScrollListener { private static final int POST_DELAY_TIME = 50; public static interface OnPagingListener { public void onScrollStart(int page); public void onScrollFinish(int page); public void onNextListLoad(int page); } private int mPage; private int mScrollDuration = 400; private boolean mFlinged; private OnPagingListener mListener; private OnGlobalLayoutListener mLayoutListener = new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (mViewHeight == 0) { postDelayed(new Runnable() { @Override public void run() { mViewHeight = getHeight(); invalidateViews(); } }, POST_DELAY_TIME); } } }; int mViewHeight; public PagingListView(Context context) { super(context); init(); } public PagingListView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PagingListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void setOnPagingListener(OnPagingListener listener) { mListener = listener; } public void setPage(int page) { mPage = page; } public int getPage() { return mPage; } public void scrollNextPage() { View firstVisibleView = getChildAt(0); mPage += 1; smoothScrollBy(mViewHeight - Math.abs(firstVisibleView.getTop()) - 1, mScrollDuration); } public void scrollPrevPage() { View firstVisibleView = getChildAt(0); mPage -= 1; smoothScrollBy(firstVisibleView.getTop(), mScrollDuration); } private void init() { setOnScrollListener(this); ViewTreeObserver observer = getViewTreeObserver(); observer.addOnGlobalLayoutListener(mLayoutListener); } @SuppressLint("NewApi") @SuppressWarnings("deprecation") public void addOnGlobalLayoutListener(OnGlobalLayoutListener listener) { ViewTreeObserver observer = getViewTreeObserver(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { observer.removeOnGlobalLayoutListener(mLayoutListener); } else { observer.removeGlobalOnLayoutListener(mLayoutListener); } observer.addOnGlobalLayoutListener(listener); observer.addOnGlobalLayoutListener(mLayoutListener); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { switch (scrollState) { case OnScrollListener.SCROLL_STATE_IDLE: if (mFlinged) { mFlinged = false; if (mListener != null) { mListener.onScrollFinish(mPage); } } else { postDelayed(new Runnable() { public void run() { int savedPosition = getFirstVisiblePosition(); View firstVisibleView = getChildAt(0); if (firstVisibleView.getHeight() / 2.0 < Math.abs(firstVisibleView .getTop())) { mPage = savedPosition; smoothScrollBy( mViewHeight - Math.abs(firstVisibleView .getTop() - 1), mScrollDuration); } else { mPage = savedPosition; smoothScrollBy(firstVisibleView.getTop(), mScrollDuration); } if (mListener != null) { mListener.onScrollFinish(mPage); } } }, POST_DELAY_TIME); } break; case OnScrollListener.SCROLL_STATE_FLING: mFlinged = true; postDelayed(new Runnable() { public void run() { int savedPosition = getFirstVisiblePosition(); View firstVisibleView = getChildAt(0); Adapter adapter = getAdapter(); int totalPage = adapter != null ? adapter.getCount() : 0; if (savedPosition < mPage) { if (mPage + 1 == totalPage) { int firstVisibleItem = mPage - getFirstVisiblePosition(); View lastView = getChildAt(firstVisibleItem); if (lastView != null && lastView.getTop() > 0) { scrollPrevPage(); } } else { scrollPrevPage(); } } else if (0 < savedPosition || (0 == savedPosition && 0 > firstVisibleView.getTop())) { if (mPage != totalPage - 1) { scrollNextPage(); } } if (mListener != null) { mListener.onScrollStart(mPage); } } }, POST_DELAY_TIME); break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mListener != null) { mListener.onNextListLoad(mPage); } } }
package com.haxademic.core.draw.mapping; import com.haxademic.core.data.ConvertUtil; import com.haxademic.core.debug.DebugUtil; import com.haxademic.core.file.FileUtil; import processing.core.PApplet; import processing.core.PConstants; import processing.core.PGraphics; import processing.core.PImage; import processing.event.KeyEvent; public class PGraphicsKeystone extends BaseSavedQuadUI { protected PGraphics pg; protected float subDivideSteps; public PGraphicsKeystone( PApplet p, PGraphics pg, float subDivideSteps, String filePath ) { super(p.width, p.height, filePath); this.pg = pg; this.subDivideSteps = subDivideSteps; } public PGraphicsKeystone( PApplet p, PGraphics pg, float subDivideSteps, String filePath, String filePathFineOffsets ) { this(p, pg, subDivideSteps, filePath); initFineControl(filePathFineOffsets); } public PGraphics pg() { return pg; } public void fillSolidColor( PGraphics canvas, int fill ) { // default single mapped quad canvas.noStroke(); canvas.fill(fill); canvas.beginShape(PConstants.QUAD); canvas.vertex(topLeft.x, topLeft.y, 0); canvas.vertex(topRight.x, topRight.y, 0); canvas.vertex(bottomRight.x, bottomRight.y, 0); canvas.vertex(bottomLeft.x, bottomLeft.y, 0); canvas.endShape(); } public void setOffsetsX(float[] offsetsX) { this.offsetsX = offsetsX; if(this.offsetsX.length != subDivideSteps + 1) DebugUtil.printErr("PGraphicsKeystone.offsetsX[] must have one more element than subDivideSteps"); } public void setOffsetsY(float[] offsetsY) { this.offsetsY = offsetsY; if(this.offsetsX.length != subDivideSteps + 1) DebugUtil.printErr("PGraphicsKeystone.offsetsY[] must have one more element than subDivideSteps"); } public void update( PGraphics canvas ) { update(canvas, true, pg); } public void update( PGraphics canvas, boolean subdivide ) { update(canvas, subdivide, pg); } public void update( PGraphics canvas, boolean subdivide, PImage texture ) { update(canvas, subdivide, texture, 0, 0, texture.width, texture.height); } public void update( PGraphics canvas, boolean subdivide, PImage texture, float mapX, float mapY, float mapW, float mapH) { // draw to screen with pinned corner coords canvas.textureMode(PConstants.IMAGE); canvas.noStroke(); if(selectedRowIndex != -1 || selectedColIndex != -1) canvas.stroke(255, 0, 0); canvas.fill(255); canvas.beginShape(PConstants.QUAD); canvas.texture(texture); if( subdivide == true ) { // subdivide quad for better resolution float stepsX = subDivideSteps; float stepsY = subDivideSteps; for( float x=0; x < stepsX; x += 1f ) { // calculate spread of mesh grid and uv coordinates float xPercent = x/stepsX; float xPercentNext = (x+1f)/stepsX; if( xPercentNext > 1 ) xPercentNext = 1; float uPercent = xPercent; float uPercentNext = xPercentNext; // add x offsets if array exists and values aren't zero if(offsetsX != null) { int fineIndex = (int) x; if(offsetsX[fineIndex] != 0) xPercent += offsetsX[fineIndex]; if(offsetsX[fineIndex + 1] != 0) xPercentNext += offsetsX[fineIndex + 1]; } for( float y=0; y < stepsY; y += 1f ) { // calculate spread of mesh grid and uv coordinates float yPercent = y/stepsY; float yPercentNext = (y+1f)/stepsY; if( yPercentNext > 1 ) yPercentNext = 1; float vPercent = yPercent; float vPercentNext = yPercentNext; // add y offsets if array exists and values aren't zero if(offsetsY != null) { int fineIndexY = (int) y; if(offsetsY[fineIndexY] != 0) yPercent += offsetsY[fineIndexY]; if(offsetsY[fineIndexY + 1] != 0) yPercentNext += offsetsY[fineIndexY + 1]; } // calc grid positions based on interpolating columns between corners float colTopX = interp(topLeft.x, topRight.x, xPercent); float colTopY = interp(topLeft.y, topRight.y, xPercent); float colBotX = interp(bottomLeft.x, bottomRight.x, xPercent); float colBotY = interp(bottomLeft.y, bottomRight.y, xPercent); float nextColTopX = interp(topLeft.x, topRight.x, xPercentNext); float nextColTopY = interp(topLeft.y, topRight.y, xPercentNext); float nextColBotX = interp(bottomLeft.x, bottomRight.x, xPercentNext); float nextColBotY = interp(bottomLeft.y, bottomRight.y, xPercentNext); // calc quad coords float quadTopLeftX = interp(colTopX, colBotX, yPercent); float quadTopLeftY = interp(colTopY, colBotY, yPercent); float quadTopRightX = interp(nextColTopX, nextColBotX, yPercent); float quadTopRightY = interp(nextColTopY, nextColBotY, yPercent); float quadBotRightX = interp(nextColTopX, nextColBotX, yPercentNext); float quadBotRightY = interp(nextColTopY, nextColBotY, yPercentNext); float quadBotLeftX = interp(colTopX, colBotX, yPercentNext); float quadBotLeftY = interp(colTopY, colBotY, yPercentNext); // draw subdivided quads canvas.vertex(quadTopLeftX, quadTopLeftY, 0, mapX + mapW * uPercent, mapY + mapH * vPercent); canvas.vertex(quadTopRightX, quadTopRightY, 0, mapX + mapW * uPercentNext, mapY + mapH * vPercent); canvas.vertex(quadBotRightX, quadBotRightY, 0, mapX + mapW * uPercentNext, mapY + mapH * vPercentNext); canvas.vertex(quadBotLeftX, quadBotLeftY, 0, mapX + mapW * uPercent, mapY + mapH * vPercentNext); } } // draw fine control debug lines if(offsetsX != null && selectedColIndex != -1) { float xPercent = selectedColIndex/stepsX; if(offsetsX[selectedColIndex] != 0) xPercent += offsetsX[selectedColIndex]; float colTopX = interp(topLeft.x, topRight.x, xPercent); float colTopY = interp(topLeft.y, topRight.y, xPercent); float colBotX = interp(bottomLeft.x, bottomRight.x, xPercent); float colBotY = interp(bottomLeft.y, bottomRight.y, xPercent); canvas.stroke(0, 255, 0); canvas.vertex(colTopX, colTopY, 0, 0, 0); canvas.vertex(colTopX, colTopY, 0, 0, 0); canvas.vertex(colBotX, colBotY, 0, 0, 0); canvas.vertex(colBotX, colBotY, 0, 0, 0); } if(offsetsY != null && selectedRowIndex != -1) { float yPercent = selectedRowIndex/stepsY; if(offsetsY[selectedRowIndex] != 0) yPercent += offsetsY[selectedRowIndex]; float rowTopX = interp(topLeft.x, bottomLeft.x, yPercent); float rowTopY = interp(topLeft.y, bottomLeft.y, yPercent); float rowBotX = interp(topRight.x, bottomRight.x, yPercent); float rowBotY = interp(topRight.y, bottomRight.y, yPercent); canvas.stroke(0, 255, 0); canvas.vertex(rowTopX, rowTopY, 0, 0, 0); canvas.vertex(rowTopX, rowTopY, 0, 0, 0); canvas.vertex(rowBotX, rowBotY, 0, 0, 0); canvas.vertex(rowBotX, rowBotY, 0, 0, 0); } // else canvas.noStroke(); } else { // default single mapped quad canvas.vertex(topLeft.x, topLeft.y, 0, mapX, mapY); canvas.vertex(topRight.x, topRight.y, 0, mapX + mapW, mapY); canvas.vertex(bottomRight.x, bottomRight.y, 0, mapX + mapW, mapY + mapH); canvas.vertex(bottomLeft.x, bottomLeft.y, 0, mapX, mapY + mapH); } canvas.endShape(); // draw UI after mapping drawDebug(canvas, false); } protected float interp( float lower, float upper, float n ) { return ( ( upper - lower ) * n ) + lower; } public void drawTestPattern() { pg.beginDraw(); pg.noStroke(); float spacingX = (float) pg.width / (float) subDivideSteps; float spacingY = (float) pg.height / (float) subDivideSteps; for( int x=0; x < subDivideSteps; x++) { for( int y=0; y < subDivideSteps; y++) { if( ( x % 2 == 0 && y % 2 == 1 ) || ( y % 2 == 0 && x % 2 == 1 ) ) { pg.fill(0, 160); } else { pg.fill(255, 160); } pg.rect(x * spacingX, y * spacingY, spacingX, spacingY); } } pg.endDraw(); } // FINE CONTROLS // fine subdivision controls protected float[] offsetsX = null; protected float[] offsetsY = null; protected int selectedRowIndex = -1; protected int selectedColIndex = -1; protected float offsetPushAmp = 0.0005f; protected String configFile; protected void initFineControl(String filePathFineOffsets) { configFile = filePathFineOffsets; buildMappingOffsets(); loadConfig(); } // init protected void buildMappingOffsets() { // build offsets arrays offsetsX = new float[(int) subDivideSteps + 1]; for (int i = 0; i < offsetsX.length; i++) offsetsX[i] = 0; setOffsetsX(offsetsX); offsetsY = new float[(int) subDivideSteps + 1]; for (int i = 0; i < offsetsY.length; i++) offsetsY[i] = 0; setOffsetsY(offsetsY); } // public public void setActive(boolean debug) { super.setActive(debug); if(!active) { selectedRowIndex = -1; selectedColIndex = -1; } } // config file protected void loadConfig() { if(FileUtil.fileExists(configFile)) { String[] textLines = FileUtil.readTextFromFile(configFile); String[] numbersStrArrayX = textLines[0].split(","); for (int i = 0; i < numbersStrArrayX.length; i++) { float offset = ConvertUtil.stringToFloat(numbersStrArrayX[i]); if(i < offsetsX.length) offsetsX[i] = offset; } String[] numbersStrArrayY = textLines[1].split(","); for (int i = 0; i < numbersStrArrayY.length; i++) { float offset = ConvertUtil.stringToFloat(numbersStrArrayY[i]); if(i < offsetsY.length) offsetsY[i] = offset; } } } protected void saveConfig() { String floatsStr = ""; for (int i = 0; i < offsetsX.length; i++) { if(i > 0) floatsStr += ","; floatsStr += offsetsX[i]; } floatsStr += FileUtil.NEWLINE; for (int i = 0; i < offsetsY.length; i++) { if(i > 0) floatsStr += ","; floatsStr += offsetsY[i]; } FileUtil.writeTextToFile(configFile, floatsStr); } // key commands public void keyEvent(KeyEvent e) { super.keyEvent(e); if(active == false) return; if(e.getAction() == KeyEvent.PRESS) { // fine controls if(e.getKey() == 'Z') { selectedColIndex if(selectedColIndex < -1) selectedColIndex = offsetsX.length - 1; } if(e.getKey() == 'X') { selectedColIndex++; if(selectedColIndex >= offsetsX.length) selectedColIndex = -1; } if(e.getKey() == 'C') { selectedRowIndex if(selectedRowIndex < -1) selectedRowIndex = offsetsY.length - 1; } if(e.getKey() == 'V') { selectedRowIndex++; if(selectedRowIndex >= offsetsY.length) selectedRowIndex = -1; } if(e.getKey() == 'O') fineControlAdjust(offsetsX, selectedColIndex, -1f); if(e.getKey() == 'P') fineControlAdjust(offsetsX, selectedColIndex, 1f); if(e.getKey() == '{') fineControlAdjust(offsetsY, selectedRowIndex, -1f); if(e.getKey() == '}') fineControlAdjust(offsetsY, selectedRowIndex, 1f); if(e.getKey() == 'E') saveConfig(); } } // navigate through rows/cols protected void fineControlAdjust(float[] offsets, int index, float amount) { amount *= offsetPushAmp; if(index != -1) { offsets[index] += amount; } } }
package com.haxademic.sketch.three_d.volume; import java.io.PrintWriter; import java.util.ArrayList; import processing.core.PImage; import processing.core.PVector; import toxi.geom.Vec3D; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.draw.shapes.MarchingCubes; import com.haxademic.core.hardware.kinect.KinectSize; @SuppressWarnings("serial") public class CubeMarchTest extends PAppletHax { MarchingCubes mc; Vec3D rotationAxis; Boolean bUseFill; // kinect float a = 0; float deg = 8; // Start at 15 degrees PImage depthImg; int minDepth = 40; int maxDepth = 1860; // set initial record to false boolean record = false; int counter = 0; // print custom file boolean printFile = false; ArrayList points; PrintWriter output; protected void overridePropsFile() { _appConfig.setProperty( "rendering", "false" ); _appConfig.setProperty( "kinect_active", "true" ); _appConfig.setProperty( "width", "1024" ); _appConfig.setProperty( "height", "768" ); } public void setup() { super.setup(); Vec3D aabbMin = new Vec3D(-width*2, -height*2, -1500); Vec3D aabbMax = new Vec3D(width*2, height*2, 1500); Vec3D numPoints = new Vec3D(50,50,50); float isoLevel = 2; mc = new MarchingCubes(this, aabbMin, aabbMax, numPoints, isoLevel); rotationAxis = new Vec3D(); bUseFill = false; points = new ArrayList(); } public void drawApp() { p.background(0); int skip = 20; float pixelDepth = 0; //translate(width/750,height/750,-50); mc.reset(); // original for loop // println("entering loop"); int nBalls = 0; for ( int x = 0; x < KinectSize.WIDTH; x += skip ) { for ( int y = 0; y < KinectSize.HEIGHT; y += skip ) { pixelDepth = p.kinectWrapper.getMillimetersDepthForKinectPixel( x, y ); if( pixelDepth != 0 && pixelDepth > minDepth && pixelDepth < maxDepth ) { PVector v = new PVector(x,y,pixelDepth); Vec3D metaBallPos = new Vec3D(v.x, v.y, -v.z); mc.addMetaBall(metaBallPos, 30, 3); nBalls++; } } } // println("done with loop, " + nBalls + " balls"); // end original for loop mc.createMesh(); if(bUseFill){ fill(0,255,0); noStroke(); } else { noFill(); stroke(127); } pushMatrix(); // translate(width/2, height/2, -500); rotateX(rotationAxis.x); rotateY(rotationAxis.y); mc.renderMesh(); popMatrix(); } public void keyPressed(){ if(key == CODED){ if(keyCode == LEFT) rotationAxis.y += 0.05; if(keyCode == RIGHT) rotationAxis.y -= 0.05; if(keyCode == UP) rotationAxis.x -= 0.05; if(keyCode == DOWN) rotationAxis.x += 0.05; } else { if(key == ' '){ bUseFill = !bUseFill; } if(key == 'r' || key == 'R'){ mc.reset(); rotationAxis.set(0,0,0); } } } }
package com.jcwhatever.nucleus.collections; import com.jcwhatever.nucleus.collections.ElementCounter.ElementCount; import com.jcwhatever.nucleus.utils.PreCon; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Counts the number of times an item is added but only holds a single reference to the item. * * <p>Depending on the removal policy, when the items count reaches 0 the item is or isn't removed.</p> * * @param <E> The element type. */ public class ElementCounter<E> implements Iterable<ElementCount<E>> { private Map<E, ElementCount<E>> _countMap; private RemovalPolicy _policy; // cache to quickly increment a value without having to look it up in the type count map. private transient E _current; private transient ElementCount<E> _currentCounter; /** * Used to specify if the counter should remove * an item when its count reaches 0 or continue counting * into negative numbers. */ public enum RemovalPolicy { /** * Remove item if its count reaches 0. */ REMOVE, /** * Allow item count to go below 0. The item is not removed. */ KEEP_COUNTING, /** * Item count never goes below 0. The item is not removed. */ BOTTOM_OUT } /** * Constructor. * * @param removalPolicy Specify how items are handled when their count reaches 0. */ public ElementCounter(RemovalPolicy removalPolicy) { this(removalPolicy, 10); } /** * Constructor. * * @param removalPolicy Specify how items are handled when their count reaches 0. * @param capacity The initial capacity of the internal collection. */ public ElementCounter(RemovalPolicy removalPolicy, int capacity) { PreCon.notNull(removalPolicy); _policy = removalPolicy; _countMap = new HashMap<>(capacity); } /** * Constructor. * * @param removalPolicy Specify how items are handled when their count reaches 0. * @param iterable The initial elements to count. */ public ElementCounter(RemovalPolicy removalPolicy, Iterable<? extends E> iterable) { PreCon.notNull(removalPolicy); PreCon.notNull(iterable); _policy = removalPolicy; _countMap = new HashMap<>(10); for (E element : iterable) { add(element); } } /** * Constructor. * * @param removalPolicy Specify how items are handled when their count reaches 0. * @param collection The initial collection of elements to count. */ public ElementCounter(RemovalPolicy removalPolicy, Collection<? extends E> collection) { PreCon.notNull(removalPolicy); PreCon.notNull(collection); _policy = removalPolicy; _countMap = new HashMap<>(collection.size()); for (E element : collection) { add(element); } } /** * Get the number of elements that are counted. */ public int size() { return _countMap.keySet().size(); } /** * Determine if an element is in the counter. * * @param element The element to check. */ public boolean contains(Object element) { PreCon.notNull(element); //noinspection SuspiciousMethodCalls return _countMap.keySet().contains(element); } /** * Increment elements in the counter. * * @param iterable The elements to increment. */ public void addAll(Iterable<? extends E> iterable) { addAll(iterable, 1); } /** * Increment elements in the counter. * * @param iterable The elements to increment. * @param amount The amount to add to each element. */ public void addAll(Iterable<? extends E> iterable, int amount) { PreCon.notNull(iterable); for (E element : iterable) modifyCount(element, amount); } /** * Increment an element in the counter. * * @param element The element to increment. * * @return The new count for the element. */ public int add(E element) { return modifyCount(element, 1); } /** * Increment an element in the counter. * * @param element The element to increment. * @param amount The amount to increment. * * @return The new count for the element. */ public int add(E element, int amount) { PreCon.notNull(element); return modifyCount(element, amount); } /** * Add from the specified {@code ElementCounter}'s counts * to the current {@code ElementCounter}. * * @param counter The counter. * * @return Self for chaining. */ public ElementCounter<E> add(ElementCounter<E> counter) { PreCon.notNull(counter); for (ElementCount<E> element : counter) { modifyCount(element.getElement(), element.getCount()); } return this; } /** * Decrement elements in the counter. * * @param iterable The iterable collection of elements to subtract. */ public void subtractAll(Iterable<? extends E> iterable) { subtractAll(iterable, -1); } /** * Decrement elements in the counter. * * @param iterable The iterable collection of elements to subtract. * @param amount The amount to subtract from each element. */ public void subtractAll(Iterable<? extends E> iterable, int amount) { PreCon.notNull(iterable); for (E element : iterable) { if (element == null) continue; modifyCount(element, -amount); } } /** * Decrement an elements count. * * @param element The element to subtract. * * @return The new count for the element. */ public int subtract(E element) { PreCon.notNull(element); return modifyCount(element, -1); } /** * Decrement an elements count. * * @param element The element to subtract. * @param amount The amount to subtract. * * @return The new count for the element. */ public int subtract(E element, int amount) { PreCon.notNull(element); return modifyCount(element, -amount); } /** * Subtract from the current {@code ElementCounter} all the items * counted by the specified {@code ElementCounter}. * * @param counter The counter. * * @return Self for chaining. */ public ElementCounter<E> subtract(ElementCounter<E> counter) { PreCon.notNull(counter); for (ElementCount<E> element : counter) { modifyCount(element.getElement(), -element.getCount()); } return this; } /** * Get the current counter value for the specified item. * * @param element The item to get the count value for */ public int count(Object element) { PreCon.notNull(element); if (_current != null && _current.equals(element)) { return _currentCounter.count; } //noinspection SuspiciousMethodCalls ElementCount counter = _countMap.get(element); if (counter == null) { return 0; } return counter.count; } /** * Get a new hash set containing the items that were counted. */ public Set<E> getElements() { return new HashSet<E>(_countMap.keySet()); } /** * Clear all items and counts. */ public void reset() { _countMap.clear(); _current = null; _currentCounter = null; } /** * Get an iterator to iterate over the items in the counter. * * <p>The iterator returned is from a copied list and does not affect * the collection.</p> * * <p>Each item appears only once in the iteration regardless of its count.</p> */ @Override public Iterator<ElementCount<E>> iterator() { return _countMap.values().iterator(); } /** * Modify the count of an element */ private int modifyCount(E element, int amount) { PreCon.notNull(element); ElementCount<E> counter; counter = _current != null && _current.equals(element) ? _currentCounter : _countMap.get(element); // Check if item is in counter if (counter == null) { if (_policy == RemovalPolicy.REMOVE) { return 0; } else { counter = new ElementCount<>(_policy, element, amount); _countMap.put(element, counter); } } // modify count else { counter.increment(amount); } // check if the item needs to be removed if (_policy == RemovalPolicy.REMOVE && counter.count <= 0) { _current = null; _currentCounter = null; _countMap.remove(element); return 0; } // place value in cache _current = element; _currentCounter = counter; return counter.count; } /** * Contains count information for a single element. * * @param <E> The element type. */ public static class ElementCount<E> { final RemovalPolicy policy; final E element; int count; ElementCount(RemovalPolicy policy, E element, int count) { this.policy = policy; this.element = element; this.count = policy == RemovalPolicy.BOTTOM_OUT ? Math.max(0, count) : count; } /** * Get the elements count. */ public int getCount() { return count; } /** * Get the element. */ public E getElement() { return element; } void increment(int amount) { if (policy == RemovalPolicy.BOTTOM_OUT) count = Math.max(0, count + amount); else count += amount; } } }
package com.jcwhatever.pvs.scripting; import com.jcwhatever.nucleus.managed.sounds.Sounds; import com.jcwhatever.nucleus.mixins.IDisposable; import com.jcwhatever.nucleus.utils.PreCon; import com.jcwhatever.nucleus.utils.player.PlayerUtils; import com.jcwhatever.pvs.api.arena.IArena; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import java.util.Collection; /** * Script Api to handle sending sound effects to players in the arena. */ public class ArenaSoundsApiObject implements IDisposable { private static final Location LOCATION = new Location(null, 0, 0, 0); private final IArena _arena; private boolean _isDisposed; public ArenaSoundsApiObject(IArena arena) { _arena = arena; } /** * Play a sound effect at the location. * * <p>Plays to all players within range who are in some way part of the arena.</p> * * @param locationObj The location of the object. * @param soundName The name of the sound to play. */ public void playEffect(Object locationObj, String soundName) { PreCon.notNull(locationObj); PreCon.notNullOrEmpty(soundName); playEffect(locationObj, soundName, _arena.getGame().getPlayers().asPlayers(), _arena.getLobby().getPlayers().asPlayers(), _arena.getSpectators().getPlayers().asPlayers()); } /** * Play a sound effect at the location of the specified location. * * <p>Plays to all players within range who are in game or are spectators.</p> * * @param locationObj The location of the object. * @param soundName The name of the sound to play. */ public void playGameEffect(Object locationObj, String soundName) { PreCon.notNull(locationObj); PreCon.notNullOrEmpty(soundName); playEffect(locationObj, soundName, _arena.getGame().getPlayers().asPlayers(), _arena.getSpectators().getPlayers().asPlayers()); } /** * Play a sound effect at the location of the specified location. * * <p>Plays to all players within range who are in the lobby or are spectators.</p> * * @param locationObj The location of the object. * @param soundName The name of the sound to play. */ public void playLobbyEffect(Object locationObj, String soundName) { PreCon.notNull(locationObj); PreCon.notNullOrEmpty(soundName); playEffect(locationObj, soundName, _arena.getGame().getPlayers().asPlayers(), _arena.getSpectators().getPlayers().asPlayers()); } /** * Play a sound effect at the location of the specified location. * * <p>Plays to all players within range who are spectators.</p> * * @param locationObj The location of the object. * @param soundName The name of the sound to play. */ public void playSpectatorEffect(Object locationObj, String soundName) { PreCon.notNull(locationObj); PreCon.notNullOrEmpty(soundName); playEffect(locationObj, soundName, _arena.getGame().getPlayers().asPlayers()); } @SafeVarargs private final void playEffect(Object locationObj, String soundName, Collection<Player>... playerCollections) { Location location = null; if (locationObj instanceof Location) { location = (Location)locationObj; } else { Player player = PlayerUtils.getPlayer(locationObj); if (player != null) { location = player.getLocation(LOCATION); } else if (locationObj instanceof Entity) { location = ((Entity) locationObj).getLocation(LOCATION); } } if (location == null) { throw new IllegalArgumentException("Invalid location object."); } for (Collection<Player> players : playerCollections) { if (players.isEmpty()) continue; Sounds.playEffect(soundName, players, location); } } @Override public boolean isDisposed() { return _isDisposed; } @Override public void dispose() { _isDisposed = true; } }
package com.monstarlab.servicedroid.model; import java.util.HashMap; import android.app.backup.BackupManager; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import com.monstarlab.servicedroid.R; import com.monstarlab.servicedroid.model.Models.BibleStudies; import com.monstarlab.servicedroid.model.Models.Calls; import com.monstarlab.servicedroid.model.Models.Literature; import com.monstarlab.servicedroid.model.Models.Placements; import com.monstarlab.servicedroid.model.Models.ReturnVisits; import com.monstarlab.servicedroid.model.Models.TimeEntries; import com.monstarlab.servicedroid.service.BackupService; public class ServiceProvider extends ContentProvider { private static final String TAG = "ServiceProvider"; private static final String DATABASE_NAME = "servicedroid"; private static final int DATABASE_VERSION = 5; private static final String TIME_ENTRIES_TABLE = "time_entries"; private static final String CALLS_TABLE = "calls"; private static final String BIBLE_STUDIES_TABLE = "bible_studies"; private static final String RETURN_VISITS_TABLE = "return_visits"; private static final String LITERATURE_TABLE = "literature"; private static final String PLACEMENTS_TABLE = "placements"; private static HashMap<String, String> sTimeProjectionMap; private static HashMap<String, String> sCallProjectionMap; private static HashMap<String, String> sRVProjectionMap; private static HashMap<String, String> sBibleStudyProjectionMap; private static HashMap<String, String> sLiteratureProjectionMap; private static HashMap<String, String> sPlacementProjectionMap; private static boolean sUseManager; private static final int TIME_ENTRIES = 1; private static final int TIME_ENTRY_ID = 2; private static final int CALLS = 3; private static final int CALLS_ID = 4; private static final int RETURN_VISITS = 5; private static final int RETURN_VISITS_ID = 6; private static final int PLACEMENTS = 7; private static final int PLACEMENTS_ID = 8; private static final int LITERATURE = 9; private static final int LITERATURE_ID = 10; private static final int PLACED_MAGAZINES = 11; private static final int PLACED_BROCHURES = 12; private static final int PLACED_BOOKS = 13; private static final int PLACEMENTS_DETAILS = 14; private static final int PLACEMENTS_DETAILS_ID = 15; private static final int BIBLE_STUDIES = 16; private static final int BIBLE_STUDIES_ID = 17; private static final UriMatcher sUriMatcher; static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(Models.AUTHORITY, "time_entries", TIME_ENTRIES); sUriMatcher.addURI(Models.AUTHORITY, "time_entries/#", TIME_ENTRY_ID); sUriMatcher.addURI(Models.AUTHORITY, "calls", CALLS); sUriMatcher.addURI(Models.AUTHORITY, "calls/#", CALLS_ID); sUriMatcher.addURI(Models.AUTHORITY, "returnvisits", RETURN_VISITS); sUriMatcher.addURI(Models.AUTHORITY, "returnvisits/#", RETURN_VISITS_ID); sUriMatcher.addURI(Models.AUTHORITY, "placements", PLACEMENTS); sUriMatcher.addURI(Models.AUTHORITY, "placements/#", PLACEMENTS_ID); sUriMatcher.addURI(Models.AUTHORITY, "literature", LITERATURE); sUriMatcher.addURI(Models.AUTHORITY, "literature/#", LITERATURE_ID); sUriMatcher.addURI(Models.AUTHORITY, "placements/magazines", PLACED_MAGAZINES); sUriMatcher.addURI(Models.AUTHORITY, "placements/brochures", PLACED_BROCHURES); sUriMatcher.addURI(Models.AUTHORITY, "placements/books", PLACED_BOOKS); sUriMatcher.addURI(Models.AUTHORITY, "placements/details", PLACEMENTS_DETAILS); sUriMatcher.addURI(Models.AUTHORITY, "placements/details/#", PLACEMENTS_DETAILS_ID); sUriMatcher.addURI(Models.AUTHORITY, "biblestudies", BIBLE_STUDIES); sUriMatcher.addURI(Models.AUTHORITY, "biblestudies/#", BIBLE_STUDIES_ID); sTimeProjectionMap = new HashMap<String, String>(); sTimeProjectionMap.put(TimeEntries._ID, TimeEntries._ID); sTimeProjectionMap.put(TimeEntries.LENGTH, TimeEntries.LENGTH); sTimeProjectionMap.put(TimeEntries.DATE, TimeEntries.DATE); sTimeProjectionMap.put(TimeEntries.NOTE, TimeEntries.NOTE); sCallProjectionMap = new HashMap<String, String>(); sCallProjectionMap.put(Calls._ID, CALLS_TABLE + "." + Calls._ID); sCallProjectionMap.put(Calls.NAME, CALLS_TABLE + "." + Calls.NAME); sCallProjectionMap.put(Calls.ADDRESS, CALLS_TABLE + "." + Calls.ADDRESS); sCallProjectionMap.put(Calls.NOTES, CALLS_TABLE + "." + Calls.NOTES); sCallProjectionMap.put(Calls.DATE, CALLS_TABLE + "." + Calls.DATE); sCallProjectionMap.put(Calls.TYPE, CALLS_TABLE + "." + Calls.TYPE); sCallProjectionMap.put(Calls.IS_STUDY, "((select count(bible_studies._id) from bible_studies where bible_studies.call_id = calls._id and bible_studies.date_end isnull) <> 0) as 'is_study'"); sCallProjectionMap.put(Calls.LAST_VISITED, "coalesce((select return_visits.date from return_visits where return_visits.call_id = calls._id order by return_visits.date desc limit 1),calls.date) as 'last_visited'"); sRVProjectionMap = new HashMap<String, String>(); sRVProjectionMap.put(ReturnVisits._ID, ReturnVisits._ID); sRVProjectionMap.put(ReturnVisits.DATE, ReturnVisits.DATE); sRVProjectionMap.put(ReturnVisits.CALL_ID, ReturnVisits.CALL_ID); sLiteratureProjectionMap = new HashMap<String, String>(); sLiteratureProjectionMap.put(Literature._ID, Literature._ID); sLiteratureProjectionMap.put(Literature.TYPE, Literature.TYPE); sLiteratureProjectionMap.put(Literature.TITLE, Literature.TITLE); sLiteratureProjectionMap.put(Literature.WEIGHT, Literature.WEIGHT); sLiteratureProjectionMap.put(Literature.PUBLICATION, LITERATURE_TABLE + "." + Literature.PUBLICATION); sPlacementProjectionMap = new HashMap<String, String>(); sPlacementProjectionMap.put(Placements._ID, PLACEMENTS_TABLE + "." + Placements._ID); sPlacementProjectionMap.put(Placements.DATE, PLACEMENTS_TABLE + "." + Placements.DATE); sPlacementProjectionMap.put(Placements.CALL_ID, PLACEMENTS_TABLE + "." + Placements.CALL_ID); sPlacementProjectionMap.put(Placements.LITERATURE_ID, PLACEMENTS_TABLE + "." + Placements.LITERATURE_ID); sPlacementProjectionMap.put(Literature.PUBLICATION, LITERATURE_TABLE + "." + Literature.PUBLICATION); sPlacementProjectionMap.put(Literature.TYPE, LITERATURE_TABLE + "." + Literature.TYPE); sPlacementProjectionMap.put(Literature.WEIGHT, LITERATURE_TABLE + "." + Literature.WEIGHT); sBibleStudyProjectionMap = new HashMap<String, String>(); sBibleStudyProjectionMap.put(BibleStudies._ID, BibleStudies._ID); sBibleStudyProjectionMap.put(BibleStudies.DATE_START, BibleStudies.DATE_START); sBibleStudyProjectionMap.put(BibleStudies.DATE_END, BibleStudies.DATE_END); sBibleStudyProjectionMap.put(BibleStudies.CALL_ID, BibleStudies.CALL_ID); try { WrapManager.checkAvailable(); sUseManager = true; } catch (Throwable t) { sUseManager = false; } } private static class DatabaseHelper extends SQLiteOpenHelper { protected Context mContext; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mContext = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + TIME_ENTRIES_TABLE + " (" + TimeEntries._ID + " integer primary key autoincrement," + TimeEntries.LENGTH + " integer," + TimeEntries.NOTE + " text," + TimeEntries.DATE + " date not null default current_timestamp);"); db.execSQL("create table " + CALLS_TABLE + " (" + Calls._ID + " integer primary key autoincrement," + Calls.NAME + " varchar(128)," + Calls.ADDRESS + " varchar(128)," + Calls.DATE + " date default current_timestamp," + Calls.NOTES + " text," + Calls.TYPE + " integer default 1 );"); db.execSQL("create table " + BIBLE_STUDIES_TABLE + " (" + BibleStudies._ID + " integer primary key autoincrement," + BibleStudies.DATE_START + " date default current_timestamp," + BibleStudies.DATE_END + " date," + BibleStudies.CALL_ID + " integer references calls(id) );"); db.execSQL("create table " + RETURN_VISITS_TABLE + " (" + ReturnVisits._ID + " integer primary key autoincrement," + ReturnVisits.DATE + " date default current_timestamp," + ReturnVisits.CALL_ID + " integer references calls(id) )"); db.execSQL("create table " + LITERATURE_TABLE + " (" + Literature._ID + " integer primary key autoincrement," + Literature.TYPE + " integer default 0," + Literature.WEIGHT + " integer default 1," + Literature.PUBLICATION + " varchar(256)," + Literature.TITLE + " varchar(256))"); db.execSQL("create table " + PLACEMENTS_TABLE + " (" + Placements._ID + " integer primary key autoincrement," + Placements.DATE + " date default current_timestamp," + Placements.CALL_ID + " integer references calls(id)," + Placements.LITERATURE_ID + " integer references literature(id))"); //some default books ContentValues values = new ContentValues(); values.put(Literature.TYPE, Literature.TYPE_BOOK); values.put(Literature.PUBLICATION, mContext.getString(R.string.bible)); db.insert(LITERATURE_TABLE, Literature.TITLE, values); values = new ContentValues(); values.put(Literature.TYPE, Literature.TYPE_BOOK); values.put(Literature.PUBLICATION, mContext.getString(R.string.bible_teach)); db.insert(LITERATURE_TABLE, Literature.TITLE, values); //some default brochures values = new ContentValues(); values.put(Literature.TYPE, Literature.TYPE_BROCHURE); values.put(Literature.PUBLICATION, mContext.getString(R.string.require_brochure)); db.insert(LITERATURE_TABLE, Literature.TITLE, values); values = new ContentValues(); values.put(Literature.TYPE, Literature.TYPE_BROCHURE); values.put(Literature.PUBLICATION, mContext.getString(R.string.comfort_brochure)); db.insert(LITERATURE_TABLE, Literature.TITLE, values); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "Upgrading database from version " + oldVersion); switch (oldVersion) { case 1: db.execSQL("alter table " + CALLS_TABLE + " add column " + Calls.TYPE + " integer default 1"); case 2: //remove dangling Bible Studies db.execSQL("delete from " + BIBLE_STUDIES_TABLE + " where " + BibleStudies.CALL_ID + " not in (select " + Calls._ID + " from " + CALLS_TABLE + ")"); case 3: db.execSQL("alter table " + TIME_ENTRIES_TABLE + " add column " + TimeEntries.NOTE + " text"); case 4: db.execSQL("alter table " + LITERATURE_TABLE + " add column " + Literature.WEIGHT + " integer default 1"); //these fall through on purpose break; default: Log.e(TAG, "Failed updating database to new version: no upgrade SQL exists."); break; } } } private DatabaseHelper mDbHelper; private WrapManager mWrappedManager; @Override public boolean onCreate() { mDbHelper = new DatabaseHelper(getContext()) { @Override public void onCreate(SQLiteDatabase db) { super.onCreate(db); restore(); } }; return true; } @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); int count; switch(sUriMatcher.match(uri)) { case TIME_ENTRIES: count = db.delete(TIME_ENTRIES_TABLE, where, whereArgs); break; case TIME_ENTRY_ID: String tId = uri.getPathSegments().get(1); count = db.delete(TIME_ENTRIES_TABLE, TimeEntries._ID + "=" + tId + (!TextUtils.isEmpty(where) ? " AND ( " + where + ")" : ""), whereArgs); break; case CALLS: count = db.delete(CALLS_TABLE, where, whereArgs); break; case CALLS_ID: String callId = uri.getPathSegments().get(1); count = db.delete(CALLS_TABLE, Calls._ID + "=" + callId + (!TextUtils.isEmpty(where) ? " AND ( " + where + ")" : ""), whereArgs); break; case RETURN_VISITS: count = db.delete(RETURN_VISITS_TABLE, where, whereArgs); break; case RETURN_VISITS_ID: String rvId = uri.getPathSegments().get(1); count = db.delete(RETURN_VISITS_TABLE, Calls._ID + "=" + rvId + (!TextUtils.isEmpty(where) ? " AND ( " + where + ")" : ""), whereArgs); break; case PLACEMENTS: count = db.delete(PLACEMENTS_TABLE, where, whereArgs); break; case PLACEMENTS_ID: String placementId = uri.getPathSegments().get(1); count = db.delete(PLACEMENTS_TABLE, Placements._ID + "=" + placementId + (!TextUtils.isEmpty(where) ? " AND ( " + where + ")" : ""), whereArgs); break; case LITERATURE: count = db.delete(LITERATURE_TABLE, where, whereArgs); break; case LITERATURE_ID: String litId = uri.getPathSegments().get(1); count = db.delete(LITERATURE_TABLE, Literature._ID + "=" + litId + (!TextUtils.isEmpty(where) ? " AND ( " + where + ")" : ""), whereArgs); break; case BIBLE_STUDIES: count = db.delete(BIBLE_STUDIES_TABLE, where, whereArgs); break; case BIBLE_STUDIES_ID: String bsId = uri.getPathSegments().get(1); count = db.delete(BIBLE_STUDIES_TABLE, BibleStudies._ID + "=" + bsId + (!TextUtils.isEmpty(where) ? " AND ( " + where + ")" : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); dataChanged(); return count; } @Override public String getType(Uri uri) { switch(sUriMatcher.match(uri)) { case TIME_ENTRIES: return TimeEntries.CONTENT_TYPE; case TIME_ENTRY_ID: return TimeEntries.CONTENT_ITEM_TYPE; case CALLS: return Calls.CONTENT_TYPE; case CALLS_ID: return Calls.CONTENT_ITEM_TYPE; case RETURN_VISITS: return ReturnVisits.CONTENT_TYPE; case RETURN_VISITS_ID: return ReturnVisits.CONTENT_ITEM_TYPE; case PLACEMENTS: return Placements.CONTENT_TYPE; case PLACEMENTS_ID: return Placements.CONTENT_ITEM_TYPE; case LITERATURE: return Literature.CONTENT_TYPE; case LITERATURE_ID: return Literature.CONTENT_ITEM_TYPE; case BIBLE_STUDIES: return BibleStudies.CONTENT_TYPE; case BIBLE_STUDIES_ID: return BibleStudies.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI " + uri); } } @Override public Uri insert(Uri uri, ContentValues initialValues) { //do some table specific setup String tableName; String nullColumn; Uri contentUri; switch(sUriMatcher.match(uri)) { case TIME_ENTRIES: tableName = TIME_ENTRIES_TABLE; nullColumn = TimeEntries.LENGTH; contentUri = TimeEntries.CONTENT_URI; break; case CALLS: tableName = CALLS_TABLE; nullColumn = Calls.NAME; contentUri = Calls.CONTENT_URI; break; case RETURN_VISITS: tableName = RETURN_VISITS_TABLE; nullColumn = ReturnVisits.DATE; contentUri = ReturnVisits.CONTENT_URI; break; case PLACEMENTS: tableName = PLACEMENTS_TABLE; nullColumn = Placements.LITERATURE_ID; contentUri = Placements.CONTENT_URI; break; case LITERATURE: tableName = LITERATURE_TABLE; nullColumn = Literature.TITLE; contentUri = Literature.CONTENT_URI; break; case BIBLE_STUDIES: tableName = BIBLE_STUDIES_TABLE; nullColumn = BibleStudies.DATE_END; contentUri = BibleStudies.CONTENT_URI; break; default: throw new IllegalArgumentException("Unknown URI + "+uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } //the inserting is the same across the board SQLiteDatabase db = mDbHelper.getWritableDatabase(); long rowId = db.insert(tableName, nullColumn, values); if(rowId > 0) { //insert worked Uri insertedUri = ContentUris.withAppendedId(contentUri, rowId); getContext().getContentResolver().notifyChange(insertedUri, null); dataChanged(); return insertedUri; } //insert failed throw new SQLException("Failed to insert row into " + uri); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); //setup for various tables String orderBy = null; String groupBy = null; if(!TextUtils.isEmpty(sortOrder)) { orderBy = sortOrder; } switch(sUriMatcher.match(uri)) { case TIME_ENTRY_ID: qb.appendWhere(TimeEntries._ID + "=" + uri.getPathSegments().get(1)); //falls through case TIME_ENTRIES: qb.setTables(TIME_ENTRIES_TABLE); qb.setProjectionMap(sTimeProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = TimeEntries.DEFAULT_SORT_ORDER; } break; case CALLS_ID: qb.appendWhere(Calls._ID + "=" + uri.getPathSegments().get(1)); //falls through case CALLS: qb.setTables(CALLS_TABLE); qb.setProjectionMap(sCallProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = Calls.DEFAULT_SORT_ORDER; } break; case RETURN_VISITS_ID: qb.appendWhere(ReturnVisits._ID + "=" + uri.getPathSegments().get(1)); //falls through case RETURN_VISITS: qb.setTables(RETURN_VISITS_TABLE); qb.setProjectionMap(sRVProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = ReturnVisits.DEFAULT_SORT_ORDER; } break; case PLACEMENTS_ID: qb.appendWhere(Placements._ID + "=" + uri.getPathSegments().get(1)); //falls through case PLACEMENTS: qb.setTables(PLACEMENTS_TABLE); qb.setProjectionMap(sPlacementProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = Placements.DEFAULT_SORT_ORDER; } break; case LITERATURE_ID: qb.appendWhere(Literature._ID + "=" + uri.getPathSegments().get(1)); //falls through case LITERATURE: qb.setTables(LITERATURE_TABLE); qb.setProjectionMap(sLiteratureProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = Literature.DEFAULT_SORT_ORDER; } break; case BIBLE_STUDIES_ID: qb.appendWhere(BibleStudies._ID + "=" + uri.getPathSegments().get(1)); //falls through case BIBLE_STUDIES: qb.setTables(BIBLE_STUDIES_TABLE); qb.setProjectionMap(sBibleStudyProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = BibleStudies.DEFAULT_SORT_ORDER; } groupBy = BibleStudies.CALL_ID; break; case PLACED_MAGAZINES: qb.setTables(PLACEMENTS_TABLE + " INNER JOIN " + LITERATURE_TABLE + " ON (" + PLACEMENTS_TABLE +"."+ Placements.LITERATURE_ID +" = "+LITERATURE_TABLE+"." + Literature._ID + " AND " + LITERATURE_TABLE + "." + Literature.TYPE + "=" + Literature.TYPE_MAGAZINE +")"); qb.setProjectionMap(sPlacementProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = PLACEMENTS_TABLE + "."+ Placements.DEFAULT_SORT_ORDER; } break; case PLACED_BROCHURES: qb.setTables(PLACEMENTS_TABLE + " INNER JOIN " + LITERATURE_TABLE + " ON (" + PLACEMENTS_TABLE +"."+ Placements.LITERATURE_ID +" = "+LITERATURE_TABLE+"." + Literature._ID + " AND " + LITERATURE_TABLE + "." + Literature.TYPE + "=" + Literature.TYPE_BROCHURE +")"); qb.setProjectionMap(sPlacementProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = PLACEMENTS_TABLE + "."+ Placements.DEFAULT_SORT_ORDER; } break; case PLACED_BOOKS: qb.setTables(PLACEMENTS_TABLE + " INNER JOIN " + LITERATURE_TABLE + " ON (" + PLACEMENTS_TABLE +"."+ Placements.LITERATURE_ID +" = "+LITERATURE_TABLE+"." + Literature._ID + " AND " + LITERATURE_TABLE + "." + Literature.TYPE + "=" + Literature.TYPE_BOOK +")"); qb.setProjectionMap(sPlacementProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = PLACEMENTS_TABLE + "."+ Placements.DEFAULT_SORT_ORDER; } break; case PLACEMENTS_DETAILS_ID: qb.appendWhere(PLACEMENTS_TABLE+"."+Placements._ID + "=" + uri.getPathSegments().get(2)); //falls through case PLACEMENTS_DETAILS: qb.setTables(PLACEMENTS_TABLE + " INNER JOIN " + LITERATURE_TABLE + " ON (" + PLACEMENTS_TABLE +"."+ Placements.LITERATURE_ID +" = "+LITERATURE_TABLE+"." + Literature._ID + ")"); qb.setProjectionMap(sPlacementProjectionMap); if(TextUtils.isEmpty(orderBy)) { orderBy = PLACEMENTS_TABLE + "."+ Placements.DEFAULT_SORT_ORDER; } break; default: throw new IllegalArgumentException("Unknown URI " + uri); } //standard query stuff SQLiteDatabase db = mDbHelper.getWritableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); int count; switch(sUriMatcher.match(uri)) { case TIME_ENTRIES: count = db.update(TIME_ENTRIES_TABLE, values, where, whereArgs); break; case TIME_ENTRY_ID: String tId = uri.getPathSegments().get(1); count = db.update(TIME_ENTRIES_TABLE, values, TimeEntries._ID + "=" + tId + (!TextUtils.isEmpty(where) ? " AND ( " + where + ")" : ""), whereArgs); break; case CALLS: count = db.update(CALLS_TABLE, values, where, whereArgs); break; case CALLS_ID: String callId = uri.getPathSegments().get(1); count = db.update(CALLS_TABLE, values, Calls._ID + "=" + callId + (!TextUtils.isEmpty(where) ? " AND ( " + where + " )" : ""), whereArgs); break; case RETURN_VISITS: count = db.update(RETURN_VISITS_TABLE, values, where, whereArgs); break; case RETURN_VISITS_ID: String rvId = uri.getPathSegments().get(1); count = db.update(RETURN_VISITS_TABLE, values, ReturnVisits._ID + "=" + rvId + (!TextUtils.isEmpty(where) ? " AND ( " + where + " )" : ""), whereArgs); break; case PLACEMENTS: count = db.update(PLACEMENTS_TABLE, values, where, whereArgs); break; case PLACEMENTS_ID: String placementId = uri.getPathSegments().get(1); count = db.update(PLACEMENTS_TABLE, values, Placements._ID + "=" + placementId + (!TextUtils.isEmpty(where) ? " AND ( " + where + " )" : ""), whereArgs); break; case LITERATURE: count = db.update(LITERATURE_TABLE, values, where, whereArgs); break; case LITERATURE_ID: String litId = uri.getPathSegments().get(1); count = db.update(LITERATURE_TABLE, values, Literature._ID + "=" + litId + (!TextUtils.isEmpty(where) ? " AND ( " + where + " )" : ""), whereArgs); break; case BIBLE_STUDIES: count = db.update(BIBLE_STUDIES_TABLE, values, where, whereArgs); break; case BIBLE_STUDIES_ID: String bsId = uri.getPathSegments().get(1); count = db.update(BIBLE_STUDIES_TABLE, values, BibleStudies._ID + "=" + bsId + (!TextUtils.isEmpty(where) ? " AND ( " + where + " )" : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); dataChanged(); return count; } protected void dataChanged() { //try to use BackupAgent, but backup to SD card also, for redundancy if(sUseManager) { //instantiate BackupManager and dataChanged if(mWrappedManager == null) { mWrappedManager = new WrapManager(getContext()); } mWrappedManager.dataChanged(); } //backup to SD card Context ctx = getContext(); Intent i = new Intent(BackupService.ACTION_BACKUP, null, ctx, BackupService.class); ctx.startService(i); } protected void restore() { Context ctx = getContext(); Intent i = new Intent(BackupService.ACTION_RESTORE, null, ctx, BackupService.class); ctx.startService(i); //BackupAgent will do its thing //but also check SD card for people upgrading to Android 2.2+ } }
package com.beetle.im; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.util.Log; import com.beetle.AsyncTCP; import com.beetle.TCPConnectCallback; import com.beetle.TCPReadCallback; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import static android.os.SystemClock.uptimeMillis; public class IMService { private final String HOST = "imnode2.gobelieve.io"; private final int PORT = 23000; public enum ConnectState { STATE_UNCONNECTED, STATE_CONNECTING, STATE_CONNECTED, STATE_CONNECTFAIL, } private final String TAG = "imservice"; private final int HEARTBEAT = 60*3; private AsyncTCP tcp; private boolean stopped = true; private boolean suspended = true; private boolean reachable = true; private boolean isBackground = false; private Timer connectTimer; private Timer heartbeatTimer; private int pingTimestamp; private int connectFailCount = 0; private int seq = 0; private ConnectState connectState = ConnectState.STATE_UNCONNECTED; private String hostIP; private int timestamp; private String host; private int port; private String token; private String deviceID; private long uid; private long appID; private long roomID; private boolean isSync; private long syncKey; private HashMap<Long, Long> groupSyncKeys = new HashMap<Long, Long>(); SyncKeyHandler syncKeyHandler; PeerMessageHandler peerMessageHandler; GroupMessageHandler groupMessageHandler; CustomerMessageHandler customerMessageHandler; ArrayList<IMServiceObserver> observers = new ArrayList<IMServiceObserver>(); ArrayList<GroupMessageObserver> groupObservers = new ArrayList<GroupMessageObserver>(); ArrayList<PeerMessageObserver> peerObservers = new ArrayList<PeerMessageObserver>(); ArrayList<SystemMessageObserver> systemMessageObservers = new ArrayList<SystemMessageObserver>(); ArrayList<CustomerMessageObserver> customerServiceMessageObservers = new ArrayList<CustomerMessageObserver>(); ArrayList<VOIPObserver> voipObservers = new ArrayList<VOIPObserver>(); ArrayList<RTMessageObserver> rtMessageObservers = new ArrayList<RTMessageObserver>(); ArrayList<RoomMessageObserver> roomMessageObservers = new ArrayList<RoomMessageObserver>(); HashMap<Integer, IMMessage> peerMessages = new HashMap<Integer, IMMessage>(); HashMap<Integer, IMMessage> groupMessages = new HashMap<Integer, IMMessage>(); HashMap<Integer, CustomerMessage> customerMessages = new HashMap<Integer, CustomerMessage>(); private byte[] data; private static IMService im = new IMService(); public static IMService getInstance() { return im; } public IMService() { connectTimer = new Timer() { @Override protected void fire() { IMService.this.connect(); } }; heartbeatTimer = new Timer() { @Override protected void fire() { IMService.this.sendHeartbeat(); } }; this.host = HOST; this.port = PORT; this.isSync = true; } private boolean isOnNet(Context context) { if (null == context) { Log.e("", "context is null"); return false; } boolean isOnNet = false; ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (null != activeNetInfo) { isOnNet = activeNetInfo.isConnected(); Log.i(TAG, "active net info:" + activeNetInfo); } return isOnNet; } class NetworkReceiver extends BroadcastReceiver { @Override public void onReceive (Context context, Intent intent) { if (isOnNet(context)) { Log.i(TAG, "connectivity status:on"); IMService.this.reachable = true; if (!IMService.this.stopped && !IMService.this.isBackground) { //todo socketlocalipip //socket Log.i(TAG, "reconnect im service"); IMService.this.suspend(); IMService.this.resume(); } } else { Log.i(TAG, "connectivity status:off"); IMService.this.reachable = false; if (!IMService.this.stopped) { IMService.this.suspend(); } } } }; public void registerConnectivityChangeReceiver(Context context) { NetworkReceiver receiver = new NetworkReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); context.registerReceiver(receiver, filter); this.reachable = isOnNet(context); } public ConnectState getConnectState() { return connectState; } public void setIsSync(boolean isSync) { this.isSync = isSync; } public void setHost(String host) { this.host = host; } public void setToken(String token) { this.token = token; } public void setUID(long uid) { this.uid = uid; } //app public void setAppID(long appID) { this.appID = appID; } public void setDeviceID(String deviceID) { this.deviceID = deviceID; } public void setSyncKey(long syncKey) { this.syncKey = syncKey; } public void addSuperGroupSyncKey(long groupID, long syncKey) { this.groupSyncKeys.put(groupID, syncKey); } public void removeSuperGroupSyncKey(long groupID) { this.groupSyncKeys.remove(groupID); } public void clearSuperGroupSyncKeys() { this.groupSyncKeys.clear(); } public void setSyncKeyHandler(SyncKeyHandler handler) { this.syncKeyHandler = handler; } public void setPeerMessageHandler(PeerMessageHandler handler) { this.peerMessageHandler = handler; } public void setGroupMessageHandler(GroupMessageHandler handler) { this.groupMessageHandler = handler; } public void setCustomerMessageHandler(CustomerMessageHandler handler) { this.customerMessageHandler = handler; } public void addObserver(IMServiceObserver ob) { if (observers.contains(ob)) { return; } observers.add(ob); } public void removeObserver(IMServiceObserver ob) { observers.remove(ob); } public void addPeerObserver(PeerMessageObserver ob) { if (peerObservers.contains(ob)) { return; } peerObservers.add(ob); } public void removePeerObserver(PeerMessageObserver ob) { peerObservers.remove(ob); } public void addGroupObserver(GroupMessageObserver ob) { if (groupObservers.contains(ob)) { return; } groupObservers.add(ob); } public void removeGroupObserver(GroupMessageObserver ob) { groupObservers.remove(ob); } public void addSystemObserver(SystemMessageObserver ob) { if (systemMessageObservers.contains(ob)) { return; } systemMessageObservers.add(ob); } public void removeSystemObserver(SystemMessageObserver ob) { systemMessageObservers.remove(ob); } public void addCustomerServiceObserver(CustomerMessageObserver ob) { if (customerServiceMessageObservers.contains(ob)) { return; } customerServiceMessageObservers.add(ob); } public void removeCustomerServiceObserver(CustomerMessageObserver ob) { customerServiceMessageObservers.remove(ob); } public void addRTObserver(RTMessageObserver ob) { if (rtMessageObservers.contains(ob)) { return; } rtMessageObservers.add(ob); } public void removeRTObserver(RTMessageObserver ob){ rtMessageObservers.remove(ob); } public void addRoomObserver(RoomMessageObserver ob) { if (roomMessageObservers.contains(ob)) { return; } roomMessageObservers.add(ob); } public void removeRoomObserver(RoomMessageObserver ob) { roomMessageObservers.remove(ob); } public void pushVOIPObserver(VOIPObserver ob) { if (voipObservers.contains(ob)) { return; } voipObservers.add(ob); } public void popVOIPObserver(VOIPObserver ob) { voipObservers.remove(ob); } public void enterBackground() { Log.i(TAG, "im service enter background"); this.isBackground = true; if (!this.stopped) { suspend(); } } public void enterForeground() { Log.i(TAG, "im service enter foreground"); this.isBackground = false; if (!this.stopped) { resume(); } } public void start() { if (this.token.length() == 0) { throw new RuntimeException("NO TOKEN PROVIDED"); } if (!this.stopped) { Log.i(TAG, "already started"); return; } Log.i(TAG, "start im service"); this.stopped = false; this.resume(); //start if (this.isBackground) { Log.w(TAG, "start im service when app is background"); } } public void stop() { if (this.stopped) { Log.i(TAG, "already stopped"); return; } Log.i(TAG, "stop im service"); stopped = true; suspend(); } private void suspend() { if (this.suspended) { Log.i(TAG, "suspended"); return; } this.close(); heartbeatTimer.suspend(); connectTimer.suspend(); this.suspended = true; Log.i(TAG, "suspend im service"); } private void resume() { if (!this.suspended) { return; } Log.i(TAG, "resume im service"); this.suspended = false; connectTimer.setTimer(uptimeMillis()); connectTimer.resume(); heartbeatTimer.setTimer(uptimeMillis(), HEARTBEAT*1000); heartbeatTimer.resume(); } public boolean isPeerMessageSending(long peer, int msgLocalID) { for(Map.Entry<Integer, IMMessage> entry : peerMessages.entrySet()) { IMMessage m = entry.getValue(); if (m.receiver == peer && m.msgLocalID == msgLocalID) { return true; } } return false; } public boolean isGroupMessageSending(long groupID, int msgLocalID) { for(Map.Entry<Integer, IMMessage> entry : groupMessages.entrySet()) { IMMessage m = entry.getValue(); if (m.receiver == groupID && m.msgLocalID == msgLocalID) { return true; } } return false; } public boolean isCustomerMessageSending(long storeID, int msgLocalID) { for(Map.Entry<Integer, CustomerMessage> entry : customerMessages.entrySet()) { CustomerMessage m = entry.getValue(); if (m.storeID == storeID && m.msgLocalID == msgLocalID) { return true; } } return false; } public boolean isCustomerSupportMessageSending(long customerID, long customerAppID, int msgLocalID) { for(Map.Entry<Integer, CustomerMessage> entry : customerMessages.entrySet()) { CustomerMessage m = entry.getValue(); if (m.customerID == customerID && m.customerAppID == customerAppID && m.msgLocalID == msgLocalID) { return true; } } return false; } public boolean sendPeerMessage(IMMessage im) { Message msg = new Message(); msg.cmd = Command.MSG_IM; msg.body = im; if (!sendMessage(msg)) { return false; } peerMessages.put(new Integer(msg.seq), im); return true; } public boolean sendGroupMessage(IMMessage im) { Message msg = new Message(); msg.cmd = Command.MSG_GROUP_IM; msg.body = im; if (!sendMessage(msg)) { return false; } groupMessages.put(new Integer(msg.seq), im); return true; } public boolean sendCustomerMessage(CustomerMessage im) { Message msg = new Message(); msg.cmd = Command.MSG_CUSTOMER; msg.body = im; if (!sendMessage(msg)) { return false; } customerMessages.put(new Integer(msg.seq), im); return true; } public boolean sendCustomerSupportMessage(CustomerMessage im) { Message msg = new Message(); msg.cmd = Command.MSG_CUSTOMER_SUPPORT; msg.body = im; if (!sendMessage(msg)) { return false; } customerMessages.put(new Integer(msg.seq), im); return true; } public boolean sendRTMessage(RTMessage rt) { Message msg = new Message(); msg.cmd = Command.MSG_RT; msg.body = rt; if (!sendMessage(msg)) { return false; } return true; } public boolean sendVOIPControl(VOIPControl ctl) { Message msg = new Message(); msg.cmd = Command.MSG_VOIP_CONTROL; msg.body = ctl; return sendMessage(msg); } public boolean sendRoomMessage(RoomMessage rm) { Message msg = new Message(); msg.cmd = Command.MSG_ROOM_IM; msg.body = rm; return sendMessage(msg); } private void sendEnterRoom(long roomID) { Message msg = new Message(); msg.cmd = Command.MSG_ENTER_ROOM; msg.body = new Long(roomID); sendMessage(msg); } private void sendLeaveRoom(long roomID) { Message msg = new Message(); msg.cmd = Command.MSG_LEAVE_ROOM; msg.body = new Long(roomID); sendMessage(msg); } public void enterRoom(long roomID) { if (roomID == 0) { return; } this.roomID = roomID; sendEnterRoom(roomID); } public void leaveRoom(long roomID) { if (this.roomID != roomID || roomID == 0) { return; } sendLeaveRoom(roomID); this.roomID = 0; } private void close() { Iterator iter = peerMessages.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Integer, IMMessage> entry = (Map.Entry<Integer, IMMessage>)iter.next(); IMMessage im = entry.getValue(); if (peerMessageHandler != null) { peerMessageHandler.handleMessageFailure(im.msgLocalID, im.receiver); } publishPeerMessageFailure(im.msgLocalID, im.receiver); } peerMessages.clear(); iter = groupMessages.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Integer, IMMessage> entry = (Map.Entry<Integer, IMMessage>)iter.next(); IMMessage im = entry.getValue(); if (groupMessageHandler != null) { groupMessageHandler.handleMessageFailure(im.msgLocalID, im.receiver); } publishGroupMessageFailure(im.msgLocalID, im.receiver); } groupMessages.clear(); iter = customerMessages.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Integer, CustomerMessage> entry = (Map.Entry<Integer, CustomerMessage>)iter.next(); CustomerMessage im = entry.getValue(); if (customerMessageHandler != null) { customerMessageHandler.handleMessageFailure(im); } publishCustomerServiceMessageFailure(im); } customerMessages.clear(); if (this.tcp != null) { Log.i(TAG, "close tcp"); this.tcp.close(); this.tcp = null; } } public static int now() { Date date = new Date(); long t = date.getTime(); return (int)(t/1000); } private void refreshHost() { new AsyncTask<Void, Integer, String>() { @Override protected String doInBackground(Void... urls) { return lookupHost(IMService.this.host); } private String lookupHost(String host) { try { InetAddress[] inetAddresses = InetAddress.getAllByName(host); for (int i = 0; i < inetAddresses.length; i++) { InetAddress inetAddress = inetAddresses[i]; Log.i(TAG, "host name:" + inetAddress.getHostName() + " " + inetAddress.getHostAddress()); if (inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } return ""; } catch (UnknownHostException exception) { exception.printStackTrace(); return ""; } } @Override protected void onPostExecute(String result) { if (result.length() > 0) { IMService.this.hostIP = result; IMService.this.timestamp = now(); } } }.execute(); } private void startConnectTimer() { if (this.stopped || this.suspended || this.isBackground) { return; } long t; if (this.connectFailCount > 60) { t = uptimeMillis() + 60*1000; } else { t = uptimeMillis() + this.connectFailCount*1000; } connectTimer.setTimer(t); Log.d(TAG, "start connect timer:" + this.connectFailCount); } private void onConnected() { Log.i(TAG, "tcp connected"); this.connectFailCount = 0; this.connectState = ConnectState.STATE_CONNECTED; this.publishConnectState(); this.sendAuth(); if (this.roomID > 0) { this.sendEnterRoom(IMService.this.roomID); } if (this.isSync) { this.sendSync(IMService.this.syncKey); for (Map.Entry<Long, Long> e : this.groupSyncKeys.entrySet()) { this.sendGroupSync(e.getKey(), e.getValue()); } } this.tcp.startRead(); } private void connect() { if (this.tcp != null) { return; } if (this.stopped) { Log.e(TAG, "opps...."); return; } if (hostIP == null || hostIP.length() == 0) { refreshHost(); IMService.this.connectFailCount++; Log.i(TAG, "host ip is't resolved"); long t; if (this.connectFailCount > 60) { t = uptimeMillis() + 60*1000; } else { t = uptimeMillis() + this.connectFailCount*1000; } connectTimer.setTimer(t); return; } if (now() - timestamp > 5*60) { refreshHost(); } this.pingTimestamp = 0; this.connectState = ConnectState.STATE_CONNECTING; IMService.this.publishConnectState(); this.tcp = new AsyncTCP(); Log.i(TAG, "new tcp..."); this.tcp.setConnectCallback(new TCPConnectCallback() { @Override public void onConnect(Object tcp, int status) { if (status != 0) { Log.i(TAG, "connect err:" + status); IMService.this.connectFailCount++; IMService.this.connectState = ConnectState.STATE_CONNECTFAIL; IMService.this.publishConnectState(); IMService.this.close(); IMService.this.startConnectTimer(); } else { IMService.this.onConnected(); } } }); this.tcp.setReadCallback(new TCPReadCallback() { @Override public void onRead(Object tcp, byte[] data) { if (data.length == 0) { Log.i(TAG, "tcp read eof"); IMService.this.connectState = ConnectState.STATE_UNCONNECTED; IMService.this.publishConnectState(); IMService.this.handleClose(); } else { IMService.this.pingTimestamp = 0; boolean b = IMService.this.handleData(data); if (!b) { IMService.this.connectState = ConnectState.STATE_UNCONNECTED; IMService.this.publishConnectState(); IMService.this.handleClose(); } } } }); boolean r = this.tcp.connect(this.hostIP, this.port); Log.i(TAG, "tcp connect:" + r); if (!r) { this.tcp = null; IMService.this.connectFailCount++; IMService.this.connectState = ConnectState.STATE_CONNECTFAIL; publishConnectState(); startConnectTimer(); } } private void handleAuthStatus(Message msg) { Integer status = (Integer)msg.body; Log.d(TAG, "auth status:" + status); if (status != 0) { //accesstoken,2s this.connectFailCount = 2; this.connectState = ConnectState.STATE_UNCONNECTED; this.publishConnectState(); this.close(); this.startConnectTimer(); } } private void handleIMMessage(Message msg) { IMMessage im = (IMMessage)msg.body; Log.d(TAG, "im message sender:" + im.sender + " receiver:" + im.receiver + " content:" + im.content); if (im.sender == this.uid) { if (peerMessageHandler != null && !peerMessageHandler.handleMessage(im, im.receiver)) { Log.i(TAG, "handle im message fail"); return; } } else { if (peerMessageHandler != null && !peerMessageHandler.handleMessage(im, im.sender)) { Log.i(TAG, "handle im message fail"); return; } } publishPeerMessage(im); Message ack = new Message(); ack.cmd = Command.MSG_ACK; ack.body = new Integer(msg.seq); sendMessage(ack); if (im.sender == this.uid) { if (peerMessageHandler != null && !peerMessageHandler.handleMessageACK(im.msgLocalID, im.receiver)) { Log.w(TAG, "handle message ack fail"); return; } publishPeerMessageACK(im.msgLocalID, im.receiver); } } private void handleGroupIMMessage(Message msg) { IMMessage im = (IMMessage)msg.body; Log.d(TAG, "group im message sender:" + im.sender + " receiver:" + im.receiver + " content:" + im.content); if (groupMessageHandler != null && !groupMessageHandler.handleMessage(im)) { Log.i(TAG, "handle im message fail"); return; } publishGroupMessage(im); Message ack = new Message(); ack.cmd = Command.MSG_ACK; ack.body = new Integer(msg.seq); sendMessage(ack); if (im.sender == this.uid) { if (groupMessageHandler != null && !groupMessageHandler.handleMessageACK(im.msgLocalID, im.receiver)) { Log.i(TAG, "handle group message ack fail"); return; } publishGroupMessageACK(im.msgLocalID, im.receiver); } } private void handleGroupNotification(Message msg) { String notification = (String)msg.body; Log.d(TAG, "group notification:" + notification); if (groupMessageHandler != null && !groupMessageHandler.handleGroupNotification(notification)) { Log.i(TAG, "handle group notification fail"); return; } publishGroupNotification(notification); Message ack = new Message(); ack.cmd = Command.MSG_ACK; ack.body = new Integer(msg.seq); sendMessage(ack); } private void handleClose() { close(); startConnectTimer(); } private void handleACK(Message msg) { Integer seq = (Integer)msg.body; IMMessage im = peerMessages.get(seq); if (im != null) { if (peerMessageHandler != null && !peerMessageHandler.handleMessageACK(im.msgLocalID, im.receiver)) { Log.w(TAG, "handle message ack fail"); return; } peerMessages.remove(seq); publishPeerMessageACK(im.msgLocalID, im.receiver); return; } im = groupMessages.get(seq); if (im != null) { if (groupMessageHandler != null && !groupMessageHandler.handleMessageACK(im.msgLocalID, im.receiver)) { Log.i(TAG, "handle group message ack fail"); return; } groupMessages.remove(seq); publishGroupMessageACK(im.msgLocalID, im.receiver); } CustomerMessage cm = customerMessages.get(seq); if (cm != null) { if (customerMessageHandler != null && !customerMessageHandler.handleMessageACK(cm)) { Log.i(TAG, "handle customer service message ack fail"); return; } customerMessages.remove(seq); publishCustomerServiceMessageACK(cm); } } private void handleInputting(Message msg) { MessageInputing inputting = (MessageInputing)msg.body; for (int i = 0; i < peerObservers.size(); i++ ) { PeerMessageObserver ob = peerObservers.get(i); ob.onPeerInputting(inputting.sender); } } private void handleSystemMessage(Message msg) { String sys = (String)msg.body; for (int i = 0; i < systemMessageObservers.size(); i++ ) { SystemMessageObserver ob = systemMessageObservers.get(i); ob.onSystemMessage(sys); } Message ack = new Message(); ack.cmd = Command.MSG_ACK; ack.body = new Integer(msg.seq); sendMessage(ack); } private void handleCustomerMessage(Message msg) { CustomerMessage cs = (CustomerMessage)msg.body; if (customerMessageHandler != null && !customerMessageHandler.handleMessage(cs)) { Log.i(TAG, "handle customer service message fail"); return; } publishCustomerMessage(cs); Message ack = new Message(); ack.cmd = Command.MSG_ACK; ack.body = new Integer(msg.seq); sendMessage(ack); if ((this.appID == 0 || this.appID == cs.customerAppID) && this.uid == cs.customerID) { if (customerMessageHandler != null && !customerMessageHandler.handleMessageACK(cs)) { Log.w(TAG, "handle customer service message ack fail"); return; } publishCustomerServiceMessageACK(cs); } } private void handleCustomerSupportMessage(Message msg) { CustomerMessage cs = (CustomerMessage)msg.body; if (customerMessageHandler != null && !customerMessageHandler.handleCustomerSupportMessage(cs)) { Log.i(TAG, "handle customer service message fail"); return; } publishCustomerSupportMessage(cs); Message ack = new Message(); ack.cmd = Command.MSG_ACK; ack.body = new Integer(msg.seq); sendMessage(ack); if (this.appID > 0 && this.appID != cs.customerAppID && this.uid == cs.sellerID) { if (customerMessageHandler != null && !customerMessageHandler.handleMessageACK(cs)) { Log.w(TAG, "handle customer service message ack fail"); return; } publishCustomerServiceMessageACK(cs); } } private void handleRTMessage(Message msg) { RTMessage rt = (RTMessage)msg.body; for (int i = 0; i < rtMessageObservers.size(); i++ ) { RTMessageObserver ob = rtMessageObservers.get(i); ob.onRTMessage(rt); } } private void handleVOIPControl(Message msg) { VOIPControl ctl = (VOIPControl)msg.body; int count = voipObservers.size(); if (count == 0) { return; } VOIPObserver ob = voipObservers.get(count-1); ob.onVOIPControl(ctl); } private void handleRoomMessage(Message msg) { RoomMessage rm = (RoomMessage)msg.body; for (int i= 0; i < roomMessageObservers.size(); i++) { RoomMessageObserver ob = roomMessageObservers.get(i); ob.onRoomMessage(rm); } } private void handleSyncNotify(Message msg) { Log.i(TAG, "sync notify:" + msg.body); Long newSyncKey = (Long)msg.body; if (newSyncKey > this.syncKey) { sendSync(this.syncKey); } } private void handleSyncBegin(Message msg) { Log.i(TAG, "sync begin...:" + msg.body); } private void handleSyncEnd(Message msg) { Log.i(TAG, "sync end...:" + msg.body); Long newSyncKey = (Long)msg.body; if (newSyncKey > this.syncKey) { this.syncKey = newSyncKey; if (this.syncKeyHandler != null) { this.syncKeyHandler.saveSyncKey(this.syncKey); } } } private void handleSyncGroupNotify(Message msg) { GroupSyncKey key = (GroupSyncKey)msg.body; Log.i(TAG, "group sync notify:" + key.groupID + " " + key.syncKey); Long origin = new Long(0); if (this.groupSyncKeys.containsKey(key.groupID)) { origin = this.groupSyncKeys.get(key.groupID); } if (key.syncKey > origin) { this.sendGroupSync(key.groupID, origin); } } private void handleSyncGroupBegin(Message msg) { GroupSyncKey key = (GroupSyncKey)msg.body; Log.i(TAG, "sync group begin...:" + key.groupID + " " + key.syncKey); } private void handleSyncGroupEnd(Message msg) { GroupSyncKey key = (GroupSyncKey)msg.body; Log.i(TAG, "sync group end...:" + key.groupID + " " + key.syncKey); Long origin = new Long(0); if (this.groupSyncKeys.containsKey(key.groupID)) { origin = this.groupSyncKeys.get(key.groupID); } if (key.syncKey > origin) { this.groupSyncKeys.put(key.groupID, key.syncKey); if (this.syncKeyHandler != null) { this.syncKeyHandler.saveGroupSyncKey(key.groupID, key.syncKey); } } } private void handlePong(Message msg) { this.pingTimestamp = 0; } private void handleMessage(Message msg) { Log.i(TAG, "message cmd:" + msg.cmd); if (msg.cmd == Command.MSG_AUTH_STATUS) { handleAuthStatus(msg); } else if (msg.cmd == Command.MSG_IM) { handleIMMessage(msg); } else if (msg.cmd == Command.MSG_ACK) { handleACK(msg); } else if (msg.cmd == Command.MSG_INPUTTING) { handleInputting(msg); } else if (msg.cmd == Command.MSG_PONG) { handlePong(msg); } else if (msg.cmd == Command.MSG_GROUP_IM) { handleGroupIMMessage(msg); } else if (msg.cmd == Command.MSG_GROUP_NOTIFICATION) { handleGroupNotification(msg); } else if (msg.cmd == Command.MSG_SYSTEM) { handleSystemMessage(msg); } else if (msg.cmd == Command.MSG_RT) { handleRTMessage(msg); } else if (msg.cmd == Command.MSG_VOIP_CONTROL) { handleVOIPControl(msg); } else if (msg.cmd == Command.MSG_CUSTOMER) { handleCustomerMessage(msg); } else if (msg.cmd == Command.MSG_CUSTOMER_SUPPORT) { handleCustomerSupportMessage(msg); } else if (msg.cmd == Command.MSG_ROOM_IM) { handleRoomMessage(msg); } else if (msg.cmd == Command.MSG_SYNC_NOTIFY) { handleSyncNotify(msg); } else if (msg.cmd == Command.MSG_SYNC_BEGIN) { handleSyncBegin(msg); } else if (msg.cmd == Command.MSG_SYNC_END) { handleSyncEnd(msg); } else if (msg.cmd == Command.MSG_SYNC_GROUP_NOTIFY) { handleSyncGroupNotify(msg); } else if (msg.cmd == Command.MSG_SYNC_GROUP_BEGIN) { handleSyncGroupBegin(msg); } else if (msg.cmd == Command.MSG_SYNC_GROUP_END) { handleSyncGroupEnd(msg); } else { Log.i(TAG, "unknown message cmd:"+msg.cmd); } } private void appendData(byte[] data) { if (this.data != null) { int l = this.data.length + data.length; byte[] buf = new byte[l]; System.arraycopy(this.data, 0, buf, 0, this.data.length); System.arraycopy(data, 0, buf, this.data.length, data.length); this.data = buf; } else { this.data = data; } } private boolean handleData(byte[] data) { appendData(data); int pos = 0; while (true) { if (this.data.length < pos + 4) { break; } int len = BytePacket.readInt32(this.data, pos); if (this.data.length < pos + 4 + Message.HEAD_SIZE + len) { break; } Message msg = new Message(); byte[] buf = new byte[Message.HEAD_SIZE + len]; System.arraycopy(this.data, pos+4, buf, 0, Message.HEAD_SIZE+len); if (!msg.unpack(buf)) { Log.i(TAG, "unpack message error"); return false; } handleMessage(msg); pos += 4 + Message.HEAD_SIZE + len; } byte[] left = new byte[this.data.length - pos]; System.arraycopy(this.data, pos, left, 0, left.length); this.data = left; return true; } private void sendAuth() { final int PLATFORM_ANDROID = 2; Message msg = new Message(); msg.cmd = Command.MSG_AUTH_TOKEN; AuthenticationToken auth = new AuthenticationToken(); auth.platformID = PLATFORM_ANDROID; auth.token = this.token; auth.deviceID = this.deviceID; msg.body = auth; sendMessage(msg); } private void sendSync(long syncKey) { Message msg = new Message(); msg.cmd = Command.MSG_SYNC; msg.body = new Long(syncKey); sendMessage(msg); } private void sendGroupSync(long groupID, long syncKey) { Message msg = new Message(); msg.cmd = Command.MSG_SYNC_GROUP; GroupSyncKey key = new GroupSyncKey(); key.groupID = groupID; key.syncKey = syncKey; msg.body = key; sendMessage(msg); } private void sendHeartbeat() { Log.i(TAG, "send ping"); Message msg = new Message(); msg.cmd = Command.MSG_PING; boolean r = sendMessage(msg); if (r && this.pingTimestamp == 0) { this.pingTimestamp = now(); Timer t = new Timer() { @Override protected void fire() { int now = now(); //3spong if (pingTimestamp > 0 && now - pingTimestamp >= 3) { Log.i(TAG, "ping timeout"); handleClose(); return; } } }; t.setTimer(uptimeMillis()+1000*3+100); t.resume(); } } private boolean sendMessage(Message msg) { if (this.tcp == null || connectState != ConnectState.STATE_CONNECTED) return false; this.seq++; msg.seq = this.seq; byte[] p = msg.pack(); if (p.length >= 32*1024) { Log.e(TAG, "message length overflow"); return false; } int l = p.length - Message.HEAD_SIZE; byte[] buf = new byte[p.length + 4]; BytePacket.writeInt32(l, buf, 0); System.arraycopy(p, 0, buf, 4, p.length); this.tcp.writeData(buf); return true; } private void publishGroupNotification(String notification) { for (int i = 0; i < groupObservers.size(); i++ ) { GroupMessageObserver ob = groupObservers.get(i); ob.onGroupNotification(notification); } } private void publishGroupMessage(IMMessage msg) { for (int i = 0; i < groupObservers.size(); i++ ) { GroupMessageObserver ob = groupObservers.get(i); ob.onGroupMessage(msg); } } private void publishGroupMessageACK(int msgLocalID, long gid) { for (int i = 0; i < groupObservers.size(); i++ ) { GroupMessageObserver ob = groupObservers.get(i); ob.onGroupMessageACK(msgLocalID, gid); } } private void publishGroupMessageFailure(int msgLocalID, long gid) { for (int i = 0; i < groupObservers.size(); i++ ) { GroupMessageObserver ob = groupObservers.get(i); ob.onGroupMessageFailure(msgLocalID, gid); } } private void publishPeerMessage(IMMessage msg) { for (int i = 0; i < peerObservers.size(); i++ ) { PeerMessageObserver ob = peerObservers.get(i); ob.onPeerMessage(msg); } } private void publishPeerMessageACK(int msgLocalID, long uid) { for (int i = 0; i < peerObservers.size(); i++ ) { PeerMessageObserver ob = peerObservers.get(i); ob.onPeerMessageACK(msgLocalID, uid); } } private void publishPeerMessageFailure(int msgLocalID, long uid) { for (int i = 0; i < peerObservers.size(); i++ ) { PeerMessageObserver ob = peerObservers.get(i); ob.onPeerMessageFailure(msgLocalID, uid); } } private void publishConnectState() { for (int i = 0; i < observers.size(); i++ ) { IMServiceObserver ob = observers.get(i); ob.onConnectState(connectState); } } private void publishCustomerMessage(CustomerMessage cs) { for (int i = 0; i < customerServiceMessageObservers.size(); i++) { CustomerMessageObserver ob = customerServiceMessageObservers.get(i); ob.onCustomerMessage(cs); } } private void publishCustomerSupportMessage(CustomerMessage cs) { for (int i = 0; i < customerServiceMessageObservers.size(); i++) { CustomerMessageObserver ob = customerServiceMessageObservers.get(i); ob.onCustomerSupportMessage(cs); } } private void publishCustomerServiceMessageACK(CustomerMessage msg) { for (int i = 0; i < customerServiceMessageObservers.size(); i++) { CustomerMessageObserver ob = customerServiceMessageObservers.get(i); ob.onCustomerMessageACK(msg); } } private void publishCustomerServiceMessageFailure(CustomerMessage msg) { for (int i = 0; i < customerServiceMessageObservers.size(); i++) { CustomerMessageObserver ob = customerServiceMessageObservers.get(i); ob.onCustomerMessageFailure(msg); } } }
package com.yidejia.app.mall.datamanage; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.yidejia.app.mall.model.Addresses; import com.yidejia.app.mall.net.address.DeleteUserAddress; import com.yidejia.app.mall.net.address.GetUserAddressList; import com.yidejia.app.mall.net.address.SaveUserAddress; import com.yidejia.app.mall.util.UnicodeToString; public class AddressDataManage { private ArrayList<Addresses> addressesArray; private Context context; private String TAG = "AddressDataManage"; // private int defaultUserId = 68298; // private int fromIndex = 0; // private int acount = 10; private UnicodeToString unicode; public AddressDataManage(Context context){ this.context = context; unicode = new UnicodeToString(); addressesArray = new ArrayList<Addresses>(); } public int addAddress(int userId, String name, String province, String city, String area, String address, String phone, boolean defaultAddress){ int addressId = -1; boolean isSuccess = false; TaskSave taskSave = new TaskSave(userId, name, province, city, area, address, phone, defaultAddress); try { isSuccess = taskSave.execute().get(); } catch (InterruptedException e) { // TODO Auto-generated catch block Log.e(TAG, "addAddress() InterruptedException"); e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block Log.e(TAG, "addAddress() ExecutionException"); e.printStackTrace(); } if(!isSuccess){ Toast.makeText(context, "", Toast.LENGTH_SHORT).show(); } else { return recipient_id; } return addressId; } public boolean updateAddress(int userId, String name, String province, String city, String area, String address, String phone, boolean defaultAddress, int recipientId){ boolean isSuccess = false; this.recipient_id = recipientId; TaskSave taskSave = new TaskSave(userId, name, province, city, area, address, phone, defaultAddress); try { isSuccess = taskSave.execute().get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e(TAG, "updateAddress() InterruptedException"); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e(TAG, "updateAddress() ExecutionException"); } if(!isSuccess){ Toast.makeText(context, "", Toast.LENGTH_SHORT).show(); } return isSuccess; } public boolean deleteAddress(int userId, int addressId){ boolean isSuccess = false; // String resultJson = deleteAddressJson(userId, addressId); TaskDelete taskDelete = new TaskDelete(userId, addressId); try { isSuccess = taskDelete.execute().get(); } catch (InterruptedException e) { // TODO Auto-generated catch block Log.e(TAG, "TaskDelete() InterruptedException"); e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block Log.e(TAG, "TaskDelete() ExecutionException"); e.printStackTrace(); } if(!isSuccess){ Toast.makeText(context, "", Toast.LENGTH_SHORT).show(); } // isSuccess = !isSuccess; return isSuccess; } public ArrayList<Addresses> getAddressesArray(int userId, int fromIndex, int acount){ TaskGetList taskGetList = new TaskGetList("customer_id="+userId, String.valueOf(fromIndex), String.valueOf(acount), "", "", "%2A"); boolean state = false ; try { state = taskGetList.execute().get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e(TAG, "TaskGetList() InterruptedException"); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e(TAG, "TaskGetList() ExecutionException"); } if(!state){ Toast.makeText(context, "", Toast.LENGTH_SHORT).show(); } return addressesArray; } // private String result = ""; private ArrayList<Addresses> analysisGetListJson(String httpResultString){ JSONObject httpResultObject; try { httpResultObject = new JSONObject(httpResultString); int code = httpResultObject.getInt("code"); Log.i(TAG, "code"+code); if(code == 1){ String responseString = httpResultObject.getString("response"); JSONArray responseArray = new JSONArray(responseString); int length = responseArray.length(); JSONObject addressItem ; for (int i = 0; i < length; i++) { Addresses addresses = new Addresses(); addressItem = responseArray.getJSONObject(i); String recipient_id = addressItem.getString("recipient_id"); addresses.setAddressId(recipient_id); String name = addressItem.getString("customer_name"); addresses.setName(unicode.revert(name)); String handset = addressItem.getString("handset"); addresses.setHandset(handset); String phone = addressItem.getString("telephone"); addresses.setPhone(phone); String province = addressItem.getString("province"); addresses.setProvince(unicode.revert(province)); String city = addressItem.getString("city"); addresses.setCity(unicode.revert(city)); String area = addressItem.getString("district"); addresses.setArea(unicode.revert(area)); String maddress = addressItem.getString("address"); addresses.setAddress(unicode.revert(maddress)); String isDefault = addressItem.getString("is_default"); boolean isDef = isDefault.equals("y") ? true : false; addresses.setDefaultAddress(isDef); addressesArray.add(addresses); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return addressesArray; } private class TaskGetList extends AsyncTask<Void, Void, Boolean>{ String where; String offset; String limit; String group; String order; String fields; public TaskGetList(String where, String offset, String limit, String group, String order, String fields){ this.where = where; this.offset = offset; this.limit = limit; this.group = group; this.order = order; this.fields = fields; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); bar.setProgressStyle(ProgressDialog.STYLE_SPINNER); bar.setMessage("ڲѯ"); bar.show(); } @Override protected Boolean doInBackground(Void... params) { // TODO Auto-generated method stub GetUserAddressList getList = new GetUserAddressList(context); try { String httpResultString = getList.getAddressListJsonString(where, offset, limit, group, order, fields); analysisGetListJson(httpResultString); return true; } catch (IOException e) { // TODO Auto-generated catch block Log.e(TAG, "task getlist ioex"); e.printStackTrace(); return false; } catch (Exception e) { // TODO: handle exception Log.e(TAG, "task getlist other ex"); e.printStackTrace(); return false; } } @Override protected void onPostExecute(Boolean result) { // TODO Auto-generated method stub super.onPostExecute(result); bar.dismiss(); // if(result) } private ProgressDialog bar = new ProgressDialog(context); } private class TaskDelete extends AsyncTask<Void, Void, Boolean>{ int userId; int addressId; public TaskDelete(int userId, int addressId){ this.userId = userId; this.addressId = addressId; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); bar.setProgressStyle(ProgressDialog.STYLE_SPINNER); bar.setMessage("ڲѯ"); bar.show(); } @Override protected Boolean doInBackground(Void... params) { // TODO Auto-generated method stub DeleteUserAddress deleteAddress = new DeleteUserAddress(context); try { String httpResultString = deleteAddress.deleteAddress(String.valueOf(userId), String.valueOf(addressId)); return analysicDeleteJson(httpResultString); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e(TAG, "task delete ioex"); return false; } catch (Exception e) { // TODO: handle exception Log.e(TAG, "task delete other ex"); return false; } } @Override protected void onPostExecute(Boolean result) { // TODO Auto-generated method stub super.onPostExecute(result); bar.dismiss(); // if(result) } private ProgressDialog bar = new ProgressDialog(context); } private class TaskSave extends AsyncTask<Void, Void, Boolean>{ private int userId; private String name; private String province; private String city; private String area; private String address; private String phone; private boolean defaultAddress; public TaskSave(int userId, String name, String province, String city, String area, String address, String phone, boolean defaultAddress){ this.userId = userId; this.name = name; this.province = province; this.city = city; this.area = area; this.address = address; this.phone = phone; this.defaultAddress = defaultAddress; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); bar.setProgressStyle(ProgressDialog.STYLE_SPINNER); bar.setMessage("ڲѯ"); bar.show(); if(defaultAddress); } @Override protected Boolean doInBackground(Void... params) { // TODO Auto-generated method stub SaveUserAddress saveUserAddress = new SaveUserAddress(context); try { String httpResultString = saveUserAddress.saveAddress(String.valueOf(userId), name, phone, province, city, area, address, String.valueOf(recipient_id)); return analysicSaveJson(httpResultString); } catch (IOException e) { // TODO Auto-generated catch block Log.e(TAG, "task save ioex"); e.printStackTrace(); return false; } catch (Exception e) { // TODO: handle exception Log.e(TAG, "task save other ex"); e.printStackTrace(); return false; } } @Override protected void onPostExecute(Boolean result) { // TODO Auto-generated method stub super.onPostExecute(result); bar.dismiss(); // if(result) } private ProgressDialog bar = new ProgressDialog(context); } private boolean analysicDeleteJson(String resultJson) { if ("".equals(resultJson)) return false; JSONObject httpResultObject; try { httpResultObject = new JSONObject(resultJson); int code = httpResultObject.getInt("code"); if (code == 1) return true; else return false; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e(TAG, "delete address analysis json jsonexception error"); return false; } catch (Exception e) { // TODO: handle exception Log.e(TAG, "delete address analysis json exception error"); return false; } } private int recipient_id = 0; private boolean analysicSaveJson(String resultJson) { if ("".equals(resultJson)) return false; JSONObject httpResultObject; try { httpResultObject = new JSONObject(resultJson); int code = httpResultObject.getInt("code"); if (code == 1){ String response = httpResultObject.getString("response"); JSONObject responseJsonObject = new JSONObject(response); String temp = responseJsonObject.getString("@p_recipient_id"); recipient_id = Integer.parseInt(temp); return true; } else return false; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e(TAG, "save address analysis json jsonexception error"); return false; } catch (Exception e) { // TODO: handle exception Log.e(TAG, "save address analysis json exception error"); return false; } } }