answer
stringlengths
17
10.2M
package picoded.struct; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; public class DeferredMapEntry_test { private DeferredMapEntry<String, String> deferredMapEntry; private String key = "key1"; private Map<String, String> map = null; @Before public void setUp() { map = new HashMap<String, String>(); map.put(key, "value_one"); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); } @After public void tearDown() { } @Test public void getKeyTest() { assertEquals("key1", deferredMapEntry.getKey()); } @Test public void getValueTest() { assertEquals("value_one", deferredMapEntry.getValue()); } @Test public void setValueTest() { deferredMapEntry.setValue("value_new"); assertEquals("value_new", deferredMapEntry.getValue()); } @Test public void equalsTest() { assertTrue(deferredMapEntry.equals(deferredMapEntry)); assertFalse(deferredMapEntry.equals((key = null))); assertFalse(deferredMapEntry.equals((key = ""))); DeferredMapEntry<String, String> temp = new DeferredMapEntry<String, String>(map, key); assertFalse(deferredMapEntry.equals(temp)); temp = new DeferredMapEntry<String, String>(null, key); map = new HashMap<String, String>(); map.put(null, null); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); temp = new DeferredMapEntry<String, String>(map, key); assertTrue(deferredMapEntry.equals(temp)); map = new HashMap<String, String>(); map.put(key, "value_one"); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); map = new HashMap<String, String>(); map.put(null, null); temp = new DeferredMapEntry<String, String>(map, key); assertFalse(deferredMapEntry.equals(temp)); map = new HashMap<String, String>(); map.put(null, null); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); map = new HashMap<String, String>(); map.put(key, "value_one"); temp = new DeferredMapEntry<String, String>(map, key); assertFalse(deferredMapEntry.equals(temp)); map = new HashMap<String, String>(); map.put(key, "value_one"); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); temp = new DeferredMapEntry<String, String>(map, key); assertTrue(deferredMapEntry.equals(temp)); map = new HashMap<String, String>(); map.put("", ""); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); temp = new DeferredMapEntry<String, String>(map, key); assertTrue(deferredMapEntry.equals(temp)); map = new HashMap<String, String>(); map.put(key, "value_one"); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); map = new HashMap<String, String>(); map.put("", ""); temp = new DeferredMapEntry<String, String>(map, key); assertFalse(deferredMapEntry.equals(temp)); map = new HashMap<String, String>(); map.put("", ""); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); map = new HashMap<String, String>(); map.put(key, "value_one"); temp = new DeferredMapEntry<String, String>(map, key); assertFalse(deferredMapEntry.equals(temp)); map = new HashMap<String, String>(); map.put(key, null); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); map = new HashMap<String, String>(); map.put(null, "value_one"); temp = new DeferredMapEntry<String, String>(map, key); assertTrue(deferredMapEntry.equals(temp)); map = new HashMap<String, String>(); map.put(null, "value_one"); deferredMapEntry = new DeferredMapEntry<String, String>(map, key); map = new HashMap<String, String>(); map.put(key, null); temp = new DeferredMapEntry<String, String>(map, key); assertTrue(deferredMapEntry.equals(temp)); } @Test public void equalsWithNullTest() { assertFalse(deferredMapEntry.equals(null)); } @Test public void equalsWithDifferentClassObjectTest() { assertFalse(deferredMapEntry.equals(map)); } @Test public void equalsWithDifferentObjectTest() { DeferredMapEntry<String, String> temp = new DeferredMapEntry<String, String>(map, key); assertTrue(deferredMapEntry.equals(temp)); } @Test public void hashCodeTest() { deferredMapEntry.hashCode(); } }
/* * $Id: TestJarValidator.java,v 1.12 2008-03-22 21:53:37 edwardsb1 Exp $ */ package org.lockss.util; import java.io.*; import java.util.*; import java.net.*; import java.security.KeyStore; import junit.framework.*; import org.lockss.test.*; import org.lockss.plugin.*; import org.lockss.plugin.base.*; import org.lockss.daemon.*; /** * Test class for <code>org.lockss.util.JarValidator</code>. */ public class TestJarValidator extends LockssTestCase { public static Class testedClasses[] = { org.lockss.util.JarValidator.class }; private static final String password = "f00bar"; private String goodJar = "org/lockss/test/good-plugin.jar"; private String badJar = "org/lockss/test/bad-plugin.jar"; private String unsignedJar = "org/lockss/test/unsigned-plugin.jar"; private String tamperedJar = "org/lockss/test/tampered-plugin.jar"; private String noManifestJar = "org/lockss/test/nomanifest-plugin.jar"; private String Expired1Jar = "org/lockss/test/Expired1.jar"; private String Expired2Jar = "org/lockss/test/Expired2.jar"; private String Future1Jar = "org/lockss/test/Future1.jar"; private String Future2Jar = "org/lockss/test/Future2.jar"; private String Good1Jar = "org/lockss/test/Good1.jar"; private String Good2Jar = "org/lockss/test/Good2.jar"; private String Modified1Jar = "org/lockss/test/Modified1.jar"; private String Modified2Jar = "org/lockss/test/Modified2.jar"; private String Unrecognized1Jar = "org/lockss/test/Unrecognized1.jar"; private String Unrecognized2Jar = "org/lockss/test/Unrecognized2.jar"; private String Unsigned1Jar = "org/lockss/test/Unsigned1.jar"; private String Unsigned2Jar = "org/lockss/test/Unsigned2.jar"; private String dirNonExisting = "/aftae/gthua/hjtno/gueao/"; private String fileExisting = "org/lockss/util/FileExisting"; private String pubKeystoreName = "org/lockss/test/public.keystore"; private KeyStore m_pubKeystore; private KeyStore getKeystoreResource(String name, String pass) throws Exception { KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(ClassLoader.getSystemClassLoader(). getResourceAsStream(name), pass.toCharArray()); return ks; } public void setUp() throws Exception { m_pubKeystore = getKeystoreResource(pubKeystoreName, password); } public void testNoPluginDir() throws Exception { MockCachedUrl goodCu = new MockCachedUrl("http://foo.com/good.jar", goodJar, true); JarValidator validator = new JarValidator(m_pubKeystore, null); try { validator.getBlessedJar(goodCu); fail("Should have thrown JarValidationException."); } catch (JarValidator.JarValidationException ignore) { //expected } } public void testNullKeystore() throws Exception { MockCachedUrl goodCu = new MockCachedUrl("http://foo.com/good.jar", goodJar, true); // Create a validator with a null keystore -- should fail validation. JarValidator validator = new JarValidator(null, getTempDir()); File f = null; try { f = validator.getBlessedJar(goodCu); fail("Should have thrown JarValidationException."); } catch (JarValidator.JarValidationException ignore) { //expected } assertNull("File should not exist.", f); } public void testGoodJar() throws Exception { MockCachedUrl goodCu = new MockCachedUrl("http://foo.com/good.jar", goodJar, true); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; f = validator.getBlessedJar(goodCu); assertNotNull(f); assertTrue(f.exists()); } public void testBadJar() throws Exception { MockCachedUrl badCu = new MockCachedUrl("http://foo.com/bad.jar", badJar, true); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(badCu); fail("Should have thrown JarValidationException"); } catch (JarValidator.JarValidationException ignore) { //expected } assertNull(f); } /** * Ensure that a tampered jar will not load. */ public void testTamperedJar() throws Exception { MockCachedUrl tamperedCu = new MockCachedUrl("http://foo.com/tampered.jar", tamperedJar, true); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(tamperedCu); } catch (JarValidator.JarValidationException ignore) { //expected } assertNull(f); } /** * Ensure that a jar with no manifest will not load. */ public void testNoManifestJar() throws Exception { MockCachedUrl noManifestCu = new MockCachedUrl("http://foo.com/nomanifest.jar", noManifestJar, true); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(noManifestCu); } catch (JarValidator.JarValidationException ignore) { //expected } assertNull(f); } public void testUnsignedJar() throws Exception { // Don't sign the test jar. MockCachedUrl unsignedCu = new MockCachedUrl("http://foo.com/unsigned.jar", unsignedJar, true); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(unsignedCu); fail("Should have thrown JarValidationException"); } catch (JarValidator.JarValidationException ignore) { //expected } assertNull(f); } // The below tests were written based on "JAR File Tests" by Brent E. Edwards. // Does the validator accept JAR files of one .java file with a good, known signature? public void testGood1() throws Exception { MockCachedUrl mcuGood1 = new MockCachedUrl("http://foo.com/Good1.jar", Good1Jar, true); examineInputStream(mcuGood1); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = validator.getBlessedJar(mcuGood1); assertNotNull(f); assertTrue(f.exists()); } // Does the validator accept JAR files of one .java file whose signature is expired? public void testExpired1() throws Exception { MockCachedUrl mcuExpired1 = new MockCachedUrl("http://foo.com/Expired1.jar", Expired1Jar, true); examineInputStream(mcuExpired1); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuExpired1); fail("testExpired1: getting an expired jar should have caused an exception."); } catch (JarValidator.JarValidationException ignore) { // Expected; ignore. } assertNull(f); } // Does the validator accept JAR files of one .java file whose signature is not yet available? public void testFuture1() throws Exception { MockCachedUrl mcuFuture1 = new MockCachedUrl("http://foo.com/Future1.jar", Future1Jar, true); examineInputStream(mcuFuture1); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuFuture1); fail("testFuture1: getting a future jar should have caused an exception."); } catch (JarValidator.JarValidationException ignore) { // Expected; ignore. } assertNull(f); } // Does the validator accept JAR files of one .java file without a signature? public void testUnsigned1() throws Exception { MockCachedUrl mcuUnsigned1 = new MockCachedUrl("http://foo.com/Unsigned1.jar", Unsigned1Jar, true); examineInputStream(mcuUnsigned1); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuUnsigned1); fail("testUnsigned1: getting an unsigned jar should have caused an exception."); } catch (JarValidator.JarValidationException ignore) { // Expected; ignore. } assertNull(f); } // Does the validator accept JAR files of one .java file whose signature does not match the file? public void testModified1() throws Exception { MockCachedUrl mcuModified1 = new MockCachedUrl("http://foo.com/Modified1.jar", Modified1Jar, true); examineInputStream(mcuModified1); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuModified1); fail("testModified1: getting a modified jar should have caused an exception."); } catch (Exception ignore) { // Expected; ignore. } assertNull(f); } // Does the validator accept JAR files of one .java file with a good signature from a source that it does not recognize? public void testUnrecognized1() throws Exception { MockCachedUrl mcuUnrecognized1 = new MockCachedUrl("http://foo.com/Unrecognized1.jar", Unrecognized1Jar, true); examineInputStream(mcuUnrecognized1); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuUnrecognized1); fail("testModified1: getting a modified jar should have caused an exception."); } catch (JarValidator.JarValidationException ignore) { // Expected; ignore. } assertNull(f); } // Does the validator accept JAR files with two .java files with a good, known signature? public void testGood2() throws Exception { MockCachedUrl mcuGood2 = new MockCachedUrl("http://foo.com/Good2.jar", Good2Jar, true); examineInputStream(mcuGood2); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = validator.getBlessedJar(mcuGood2); assertNotNull(f); assertTrue(f.exists()); } // Does the validator accept JAR files with two .java file whose signature is expired? public void testExpired2() throws Exception { MockCachedUrl mcuExpired2 = new MockCachedUrl("http://foo.com/Expired2.jar", Expired2Jar, true); examineInputStream(mcuExpired2); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuExpired2); fail("testExpired2: getting an expired jar should have caused an exception."); } catch (JarValidator.JarValidationException ignore) { // Expected; ignore. } assertNull(f); } // Does the validator accept JAR files with two .java files whose signature is not yet available? public void testFuture2() throws Exception { MockCachedUrl mcuFuture2 = new MockCachedUrl("http://foo.com/Future2.jar", Future2Jar, true); examineInputStream(mcuFuture2); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuFuture2); fail("testFuture2: getting a future jar should have caused an exception."); } catch (JarValidator.JarValidationException ignore) { // Expected; ignore. } assertNull(f); } // Does the validator accept JAR files with two .java files without a signature? public void testUnsigned2() throws Exception { MockCachedUrl mcuUnsigned2 = new MockCachedUrl("http://foo.com/Unsigned2.jar", Unsigned2Jar, true); examineInputStream(mcuUnsigned2); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuUnsigned2); fail("testUnsigned2: getting an unsigned jar should have caused an exception."); } catch (JarValidator.JarValidationException ignore) { // Expected; ignore. } assertNull(f); } // Does the validator accept JAR files with two .java files whose signature does not match the file? public void testModified2() throws Exception { MockCachedUrl mcuModified2 = new MockCachedUrl("http://foo.com/Modified2.jar", Modified2Jar, true); examineInputStream(mcuModified2); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuModified2); fail("testModified2: getting a modified jar should have caused an exception."); } catch (Exception ignore) { // Expected; ignore. } assertNull(f); } // Does the validator accept JAR files with two .java files with a good signature from a source that it does not recognize? public void testUnrecognized2() throws Exception { MockCachedUrl mcuUnrecognized2 = new MockCachedUrl("http://foo.com/Unrecognized2.jar", Unrecognized2Jar, true); examineInputStream(mcuUnrecognized2); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { f = validator.getBlessedJar(mcuUnrecognized2); fail("testModified2: getting a modified jar should have caused an exception."); } catch (JarValidator.JarValidationException ignore) { // Expected; ignore. } assertNull(f); } // ** Tests of JarValidator: // What happens if the keystore has not been loaded? // public void testUnloadedKeyStore() throws Exception { // KeyStore ks = KeyStore.getInstance("JKS", "SUN"); // // Note: NO call to ks.load. // try { // MockCachedUrl mcuGood2 = // JarValidator validator = new JarValidator(ks, getTempDir()); // validator.getBlessedJar(mcuGood2); // fail("testUnloadedKeyStore: We should have caused an exception when we got the blessed jar."); // } catch (Exception e) { // // The expected behavior. // What happens if pluginDir is null? public void testNullPlugInDir() throws Exception { try { MockCachedUrl mcuGood2 = new MockCachedUrl("http://foo.com/Good2.jar", Good2Jar, true); JarValidator validator = new JarValidator(m_pubKeystore, null); validator.getBlessedJar(mcuGood2); fail("testNullPlugInDir: We should have caused an exception when we got the blessed jar."); } catch (Exception e) { // The expected behavior. } } // What happens if pluginDir doesn't exist? public void testNonExistingPlugInDir() throws Exception { try { MockCachedUrl mcuGood2 = new MockCachedUrl("http://foo.com/Good2.jar", Good2Jar, true); JarValidator validator = new JarValidator(m_pubKeystore, new File(dirNonExisting)); validator.getBlessedJar(mcuGood2); fail("testNullPlugInDir: We should have caused an exception when we got the blessed jar."); } catch (Exception e) { // The expected behavior. } } // What happens if pluginDir points to a file, not a directory? public void testPlugInDirToFile() throws Exception { try { MockCachedUrl mcuGood2 = new MockCachedUrl("http://foo.com/Good2.jar", Good2Jar, true); JarValidator validator = new JarValidator(m_pubKeystore, new File(fileExisting)); validator.getBlessedJar(mcuGood2); fail("testPlugInDirToFile: We should have caused an exception when we got the blessed jar."); } catch (Exception e) { // The expected behavior. } } // What happens if pluginDir can't be written to? public void testPlugInDirUnwritable() throws Exception { File fileUnwritable; fileUnwritable = getTempDir(); if (fileUnwritable.canWrite()) { fileUnwritable.setReadOnly(); } try { MockCachedUrl mcuGood2 = new MockCachedUrl("http://foo.com/Good2.jar", Good2Jar, true); JarValidator validator = new JarValidator(m_pubKeystore, fileUnwritable); validator.getBlessedJar(mcuGood2); fail("testPlugInDirUnwritable: We should have caused an exception when we got the blessed jar."); } catch (Exception e) { // The expected behavior. } fileUnwritable.delete(); } // ** Tests of getBlessedJob // What happens if cu is null? public void testNullCU() throws Exception { MockCachedUrl mcuNull = null; JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); try { validator.getBlessedJar(mcuNull); fail("testNullCU: Using a null CachedUrl should have caused an exception."); } catch (Exception e) { // The expected behavior. } } // What happens if cu doesn't contain a JAR? public void testCUNotJar() throws Exception { MockCachedUrl mcuNull = new MockCachedUrl("http://foo.com/FileExisting", fileExisting, true); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); try { validator.getBlessedJar(mcuNull); fail("testCUNotJar: Using a CachedUrl that's not a jar should have caused an exception."); } catch (Exception e) { // The expected behavior. } } // Verify that turning off the expired flag allows us to read expired jars. public void testAllowExpired() throws Exception { MockCachedUrl mcuExpired2 = new MockCachedUrl("http://foo.com/Expired2.jar", Expired2Jar, true); examineInputStream(mcuExpired2); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; validator.allowExpired(true); f = validator.getBlessedJar(mcuExpired2); assertNotNull(f); assertTrue(f.exists()); } // Verify that turning on the expired flag disallows us to read expired jars. public void testDisallowExpired() throws Exception { MockCachedUrl mcuExpired2 = new MockCachedUrl("http://foo.com/Expired2.jar", Expired2Jar, true); examineInputStream(mcuExpired2); JarValidator validator = new JarValidator(m_pubKeystore, getTempDir()); File f = null; try { validator.allowExpired(false); f = validator.getBlessedJar(mcuExpired2); fail("testExpired2: getting an expired jar should have caused an exception."); } catch (JarValidator.JarValidationException ignore) { // Expected; ignore. } assertNull(f); } // If you have lots of time, reproduce every .jar test twice, // once with validator.allowExpired(false), and once with // validator.allowExpired(true), just to make sure that you // get the same answers. /** * @param mcuTest -- the mock cached url that we want to verify exists. * @throws IOException */ private void examineInputStream(MockCachedUrl mcuTest) throws IOException { InputStream isUnsigned1; isUnsigned1 = mcuTest.getUnfilteredInputStream(); assertNotNull(isUnsigned1); assertTrue(isUnsigned1.available() > 0); } }
package keygamep3; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Klas Spel, implementeert ActionListener * @author Ruben, Koray, Ruben */ public class Spel implements ActionListener{ private final int FRAME_BREEDTE = 300; private final int FRAME_HOOGTE = 100; private JFrame frame; private JButton openLevel; /** * Constructor Spel */ public Spel(){ frame = new JFrame(); frame.setTitle("KeyGame"); frame.setSize(FRAME_BREEDTE, FRAME_HOOGTE); openLevel = new JButton("Open level"); openLevel.setBackground(Color.BLACK); openLevel.addActionListener(this); frame.add(openLevel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } /** * Implementatie van de abstracte methode van ActionListener * @param event */ @Override public void actionPerformed(ActionEvent event) { if(event.getSource() == openLevel){// StartKnop FileDialog fd = new FileDialog(frame, "Test", FileDialog.LOAD); fd.setDirectory("levels/"); fd.setVisible(true); startLevel(fd.getDirectory() + fd.getFile()); } frame.revalidate(); frame.repaint(); } /** * Deze methode start de gevraagde level * @param pad */ public void startLevel(String pad) { Level l = new Level(pad); } }
package tonelitosnuevo; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import javax.swing.DefaultComboBoxModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import java.util.ArrayList; /** * * @author rick */ public class Tonelitos extends javax.swing.JFrame { /** * Creates new form Tonelitos */ public Tonelitos() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jd_relations = new javax.swing.JDialog(); jc_inicial = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jButton4 = new javax.swing.JButton(); jc_final = new javax.swing.JComboBox(); jd_eraseRelations = new javax.swing.JDialog(); jc_vertice = new javax.swing.JComboBox(); jButton6 = new javax.swing.JButton(); Tabla = new javax.swing.JDialog(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); Dijkstra = new javax.swing.JDialog(); jc_inicialDijkstra = new javax.swing.JComboBox(); jc_finalDijkstra = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jButton5 = new javax.swing.JButton(); jButton12 = new javax.swing.JButton(); Floyd = new javax.swing.JDialog(); jc_inicialFloyd = new javax.swing.JComboBox(); jc_finalFloyd = new javax.swing.JComboBox(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jButton10 = new javax.swing.JButton(); jButton13 = new javax.swing.JButton(); jb_addImage = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jp_lblparent = new javax.swing.JPanel(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jLayeredPane1 = new javax.swing.JLayeredPane(); jp_graphics = new javax.swing.JPanel(); jl_image = new javax.swing.JLabel(); jButton7 = new javax.swing.JButton(); jButton11 = new javax.swing.JButton(); jButton14 = new javax.swing.JButton(); jLabel1.setText("Vértice Inicial"); jLabel2.setText("Vértice Final"); jButton4.setText("Agregar Relacion"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); javax.swing.GroupLayout jd_relationsLayout = new javax.swing.GroupLayout(jd_relations.getContentPane()); jd_relations.getContentPane().setLayout(jd_relationsLayout); jd_relationsLayout.setHorizontalGroup( jd_relationsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jd_relationsLayout.createSequentialGroup() .addGap(54, 54, 54) .addGroup(jd_relationsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jc_inicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 99, Short.MAX_VALUE) .addGroup(jd_relationsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jc_final, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(85, 85, 85)) .addGroup(jd_relationsLayout.createSequentialGroup() .addGap(114, 114, 114) .addComponent(jButton4) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jd_relationsLayout.setVerticalGroup( jd_relationsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jd_relationsLayout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(jd_relationsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jd_relationsLayout.createSequentialGroup() .addComponent(jLabel2) .addGap(62, 62, 62)) .addGroup(jd_relationsLayout.createSequentialGroup() .addComponent(jLabel1) .addGap(39, 39, 39) .addGroup(jd_relationsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jc_inicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jc_final, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(60, 60, 60) .addComponent(jButton4) .addContainerGap(107, Short.MAX_VALUE)) ); jButton6.setText("Eliminar Vértice con sus relaciones"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); javax.swing.GroupLayout jd_eraseRelationsLayout = new javax.swing.GroupLayout(jd_eraseRelations.getContentPane()); jd_eraseRelations.getContentPane().setLayout(jd_eraseRelationsLayout); jd_eraseRelationsLayout.setHorizontalGroup( jd_eraseRelationsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jd_eraseRelationsLayout.createSequentialGroup() .addGap(175, 175, 175) .addComponent(jc_vertice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jd_eraseRelationsLayout.createSequentialGroup() .addContainerGap(78, Short.MAX_VALUE) .addComponent(jButton6) .addGap(69, 69, 69)) ); jd_eraseRelationsLayout.setVerticalGroup( jd_eraseRelationsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jd_eraseRelationsLayout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jc_vertice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38) .addComponent(jButton6) .addContainerGap(44, Short.MAX_VALUE)) ); jButton8.setText("Dijkstra"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jButton9.setText("Floyd"); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); javax.swing.GroupLayout TablaLayout = new javax.swing.GroupLayout(Tabla.getContentPane()); Tabla.getContentPane().setLayout(TablaLayout); TablaLayout.setHorizontalGroup( TablaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(TablaLayout.createSequentialGroup() .addGap(85, 85, 85) .addComponent(jButton8) .addGap(80, 80, 80) .addComponent(jButton9) .addContainerGap(105, Short.MAX_VALUE)) ); TablaLayout.setVerticalGroup( TablaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(TablaLayout.createSequentialGroup() .addGap(81, 81, 81) .addGroup(TablaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton8) .addComponent(jButton9)) .addContainerGap(102, Short.MAX_VALUE)) ); jc_inicialDijkstra.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jc_inicialDijkstraActionPerformed(evt); } }); jLabel3.setText("Nodo Inicial"); jLabel4.setText("Nodo Final"); jButton5.setText("Buscar Con Dijkstra"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButton12.setText("Generar Reporte"); jButton12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton12ActionPerformed(evt); } }); javax.swing.GroupLayout DijkstraLayout = new javax.swing.GroupLayout(Dijkstra.getContentPane()); Dijkstra.getContentPane().setLayout(DijkstraLayout); DijkstraLayout.setHorizontalGroup( DijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(DijkstraLayout.createSequentialGroup() .addGap(70, 70, 70) .addGroup(DijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jc_inicialDijkstra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 114, Short.MAX_VALUE) .addGroup(DijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jc_finalDijkstra, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(92, 92, 92)) .addGroup(DijkstraLayout.createSequentialGroup() .addGap(120, 120, 120) .addGroup(DijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton12) .addComponent(jButton5)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); DijkstraLayout.setVerticalGroup( DijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(DijkstraLayout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(DijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel4)) .addGap(31, 31, 31) .addGroup(DijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jc_inicialDijkstra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jc_finalDijkstra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(76, 76, 76) .addComponent(jButton5) .addGap(18, 18, 18) .addComponent(jButton12) .addContainerGap(53, Short.MAX_VALUE)) ); jLabel5.setText("Nodo Inicial"); jLabel6.setText("Nodo Final"); jButton10.setText("Buscar Con Floyd"); jButton10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton10ActionPerformed(evt); } }); jButton13.setText("Generar Reporte"); jButton13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton13ActionPerformed(evt); } }); javax.swing.GroupLayout FloydLayout = new javax.swing.GroupLayout(Floyd.getContentPane()); Floyd.getContentPane().setLayout(FloydLayout); FloydLayout.setHorizontalGroup( FloydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(FloydLayout.createSequentialGroup() .addGap(70, 70, 70) .addGroup(FloydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5) .addComponent(jc_inicialFloyd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 114, Short.MAX_VALUE) .addGroup(FloydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jc_finalFloyd, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(92, 92, 92)) .addGroup(FloydLayout.createSequentialGroup() .addGap(120, 120, 120) .addGroup(FloydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton13) .addComponent(jButton10)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); FloydLayout.setVerticalGroup( FloydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(FloydLayout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(FloydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel6)) .addGap(31, 31, 31) .addGroup(FloydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jc_inicialFloyd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jc_finalFloyd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(76, 76, 76) .addComponent(jButton10) .addGap(27, 27, 27) .addComponent(jButton13) .addContainerGap(44, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jb_addImage.setText("Add Image"); jb_addImage.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jb_addImageActionPerformed(evt); } }); jButton1.setText("Exportar Grafo"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jp_lblparent.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jp_lblparentMouseClicked(evt); } }); jp_lblparent.setLayout(null); jButton2.setText("Add Relation"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("AddVertex"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jp_graphics.setOpaque(false); jp_graphics.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jp_graphicsMouseClicked(evt); } }); javax.swing.GroupLayout jp_graphicsLayout = new javax.swing.GroupLayout(jp_graphics); jp_graphics.setLayout(jp_graphicsLayout); jp_graphicsLayout.setHorizontalGroup( jp_graphicsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 830, Short.MAX_VALUE) ); jp_graphicsLayout.setVerticalGroup( jp_graphicsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 579, Short.MAX_VALUE) ); javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1); jLayeredPane1.setLayout(jLayeredPane1Layout); jLayeredPane1Layout.setHorizontalGroup( jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 865, Short.MAX_VALUE) .addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jLayeredPane1Layout.createSequentialGroup() .addContainerGap(17, Short.MAX_VALUE) .addComponent(jp_graphics, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(18, Short.MAX_VALUE))) .addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane1Layout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(jl_image, javax.swing.GroupLayout.PREFERRED_SIZE, 830, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(18, Short.MAX_VALUE))) ); jLayeredPane1Layout.setVerticalGroup( jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 632, Short.MAX_VALUE) .addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane1Layout.createSequentialGroup() .addContainerGap() .addComponent(jp_graphics, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(41, Short.MAX_VALUE))) .addGroup(jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jLayeredPane1Layout.createSequentialGroup() .addContainerGap() .addComponent(jl_image, javax.swing.GroupLayout.PREFERRED_SIZE, 579, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); jLayeredPane1.setLayer(jp_graphics, javax.swing.JLayeredPane.DEFAULT_LAYER); jLayeredPane1.setLayer(jl_image, javax.swing.JLayeredPane.DEFAULT_LAYER); jButton7.setText("Borrar relacion/ Vértice"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jButton11.setText("Buscar el Camino mas corto de un Nodo a otro"); jButton11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton11ActionPerformed(evt); } }); jButton14.setText("Importar Grafo"); jButton14.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton14ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jp_lblparent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton11) .addGroup(layout.createSequentialGroup() .addComponent(jButton7) .addGap(18, 18, 18) .addComponent(jButton2) .addGap(18, 18, 18) .addComponent(jb_addImage) .addGap(18, 18, 18) .addComponent(jButton3) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(18, 18, 18) .addComponent(jButton14))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jp_lblparent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 631, Short.MAX_VALUE)) .addComponent(jLayeredPane1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jb_addImage) .addComponent(jButton1) .addComponent(jButton3) .addComponent(jButton7) .addComponent(jButton2) .addComponent(jButton14)) .addGap(18, 18, 18) .addComponent(jButton11) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jb_addImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_addImageActionPerformed JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Imagenes", "jpg", "png", "bmp", "mpg", "ico"); chooser.setFileFilter(filter); int Okoption; Okoption = chooser.showOpenDialog(this); if (Okoption == JFileChooser.APPROVE_OPTION) { imagen = chooser.getSelectedFile(); icon = new ImageIcon(imagen.getAbsolutePath()); int imgHeight = jl_image.getHeight(); int imgWidth = jl_image.getWidth(); img = icon.getImage(); newImg = img.getScaledInstance(imgWidth, imgHeight, java.awt.Image.SCALE_SMOOTH); icon = new ImageIcon(newImg); jl_image.setIcon(icon); } }//GEN-LAST:event_jb_addImageActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed boolean isEmpty = false; for (int i = 0; i < grafo.getNodos().size(); i++) { if (grafo.getNodos().get(i).getAristas().isEmpty()){ isEmpty = true; break; } } JFileChooser chooser = new JFileChooser(); int seleccion = chooser.showSaveDialog(this); if (seleccion == JFileChooser.APPROVE_OPTION){ File file=null; File temp; FileWriter fw=null; BufferedWriter writer = null; try { temp = chooser.getSelectedFile(); file = new File(temp.getAbsolutePath()+".grph"); fw = new FileWriter (file); writer = new BufferedWriter (fw); if (fw == null || writer == null ){ System.err.println("es 0.0000000000000000000000000000000001% probable que esta linea salga, revisar exportacion de grafo"); }else{ for (int i = 0; i < grafo.getNodos().size(); i++) { writer.write(grafo.getNodos().get(i).getID()+","); writer.write(grafo.getNodos().get(i).getNombre()+","); writer.write(grafo.getNodos().get(i).getCoordenada().getX()+","); if (grafo.getNodos().get(i).getAristas().isEmpty()){ writer.write(grafo.getNodos().get(i).getCoordenada().getY()+","); }else{ writer.write(grafo.getNodos().get(i).getCoordenada().getY()+",;"); for (int j = 0; j < grafo.getNodos().get(i).getAristas().size(); j++) { writer.write(grafo.getNodos().get(i).getAristas().get(j).getNodoInicial().getID()+"/"); writer.write(grafo.getNodos().get(i).getAristas().get(j).getNodoFinal().getID()+"/"); writer.write(Long.toString(grafo.getNodos().get(i).getAristas().get(j).getDistancia())+"/;"); } } writer.write("\r"); } writer.flush(); JOptionPane.showMessageDialog(this, "Archivo creado con exito"); } } catch (Exception e) { } finally{ try { writer.close(); fw.close(); } catch (Exception e) { } } } }//GEN-LAST:event_jButton1ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed JOptionPane.showMessageDialog(this, "Porfavor haga click en el mapa donde iria el nuevo vértice", "New Vertex", JOptionPane.INFORMATION_MESSAGE); addVertex = true; }//GEN-LAST:event_jButton3ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed DefaultComboBoxModel model = new DefaultComboBoxModel(); DefaultComboBoxModel model2 = new DefaultComboBoxModel(); for (int i = 0; i < grafo.getNodos().size(); i++) { model.addElement(grafo.getNodos().get(i).getNombre()); model2.addElement(grafo.getNodos().get(i).getNombre()); } this.jc_final.setModel(model); this.jc_inicial.setModel(model2); openDialog(this.jd_relations); }//GEN-LAST:event_jButton2ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed int indexInicial = jc_inicial.getSelectedIndex(); int indexFinal = jc_final.getSelectedIndex(); int distance; if (indexFinal == indexInicial) { JOptionPane.showMessageDialog(this, "No puede seleccionar el mismo vértice", "Error", JOptionPane.ERROR_MESSAGE); } else { distance = Integer.parseInt(JOptionPane.showInputDialog(this, "Ingrese la distancia entre los vértices")); grafo.getNodos().get(indexInicial).getAristas().add(new Arista(distance, grafo.getNodos().get(indexInicial), grafo.getNodos().get(indexFinal))); refresh(); } }//GEN-LAST:event_jButton4ActionPerformed private void jp_lblparentMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jp_lblparentMouseClicked Graphics draw = this.jp_graphics.getGraphics(); int x = evt.getX(); int y = evt.getY(); if (addVertex && this.jl_image.getIcon() != null) { grafo.getNodos().add(new Node()); grafo.getNodos().get(grafo.getNodos().size() - 1).setCoordenada(new Coordenada(x - 10, y - 10)); grafo.getNodos().get(grafo.getNodos().size() - 1).setID(grafo.getNodos().size() - 1); //draw.drawOval(x-10, y-10, 25, 25); //draw.fillOval(x-10, y-10, 25, 25); refresh(); addVertex = false; } else if (addVertex && this.jl_image.getIcon() == null) { JOptionPane.showMessageDialog(this, "Porfavor ingrese un mapa primero", "Error", JOptionPane.ERROR_MESSAGE); addVertex = false; } }//GEN-LAST:event_jp_lblparentMouseClicked private void jp_graphicsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jp_graphicsMouseClicked int x = evt.getX(); int y = evt.getY(); grafo.getNodos().add(new Node()); grafo.getNodos().get(grafo.getNodos().size() - 1).setCoordenada(new Coordenada(x - 10, y - 10)); grafo.getNodos().get(grafo.getNodos().size() - 1).setID(grafo.getNodos().size()-1); grafo.getNodos().get(grafo.getNodos().size()-1).setNombre(Abecedario[iteradorabc]); iteradorabc++; this.nodosMauricio = grafo.getNodos(); refresh(); addVertex = false; }//GEN-LAST:event_jp_graphicsMouseClicked private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed DefaultComboBoxModel model3 = new DefaultComboBoxModel(); for (int i = 0; i < grafo.getNodos().size(); i++) { model3.addElement(grafo.getNodos().get(i).getNombre()); } this.jc_vertice.setModel(model3); openDialog(this.jd_eraseRelations); refresh(); }//GEN-LAST:event_jButton7ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed int index = jc_vertice.getSelectedIndex(); grafo.removeVertex(index); this.setSize(this.getWidth()+1, this.getHeight()+1); this.setSize(this.getWidth()-1, this.getHeight()-1); refresh(); DefaultComboBoxModel model3 = new DefaultComboBoxModel(); for (int i = 0; i < grafo.getNodos().size(); i++) { model3.addElement(grafo.getNodos().get(i).getNombre()); } this.jc_vertice.setModel(model3); JOptionPane.showMessageDialog(this,"Vértice eliminado con exito, por favor cerrar esta ventana para mostrar los cambios","",JOptionPane.INFORMATION_MESSAGE); nodosMauricio = grafo.getNodos(); refresh(); }//GEN-LAST:event_jButton6ActionPerformed private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed DefaultComboBoxModel model = new DefaultComboBoxModel(); DefaultComboBoxModel model2 = new DefaultComboBoxModel(); for (int i = 0; i < grafo.getNodos().size(); i++) { model.addElement(grafo.getNodos().get(i).getNombre()); model2.addElement(grafo.getNodos().get(i).getNombre()); } this.jc_finalDijkstra.setModel(model); this.jc_inicialDijkstra.setModel(model2); openDialog(this.Dijkstra); }//GEN-LAST:event_jButton8ActionPerformed private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed DefaultComboBoxModel model = new DefaultComboBoxModel(); DefaultComboBoxModel model2 = new DefaultComboBoxModel(); for (int i = 0; i < grafo.getNodos().size(); i++) { model.addElement(grafo.getNodos().get(i).getNombre()); model2.addElement(grafo.getNodos().get(i).getNombre()); } this.jc_finalFloyd.setModel(model); this.jc_inicialFloyd.setModel(model2); openDialog(this.Floyd); }//GEN-LAST:event_jButton9ActionPerformed private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed openDialog(this.Tabla); }//GEN-LAST:event_jButton11ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed ArrayList<Arista> aristasDijkstra = new ArrayList(); int indexInicial = jc_inicialDijkstra.getSelectedIndex(); int indexFinal = jc_finalDijkstra.getSelectedIndex(); aristasDijkstra = grafo.summonDijkstra(indexInicial,indexFinal); for (int i = 0; i < aristasDijkstra.size(); i++) { System.out.println(aristasDijkstra.get(i).toString()); } hasDijkstra = true; }//GEN-LAST:event_jButton5ActionPerformed private void jc_inicialDijkstraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jc_inicialDijkstraActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jc_inicialDijkstraActionPerformed private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed }//GEN-LAST:event_jButton12ActionPerformed private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed }//GEN-LAST:event_jButton13ActionPerformed private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed /* int indexInicial = this.jc_inicialFloyd.getSelectedIndex(); int indexFinal = this.jc_finalFloyd.getSelectedIndex(); tempFloyd = grafo.FLoyd(grafo.getNodos().get(indexInicial), grafo.getNodos().get(indexFinal)); for (int i = 0; i < tempFloyd.size(); i++) { System.out.println(tempFloyd.get(i).getValue()+ ""); } */ }//GEN-LAST:event_jButton10ActionPerformed private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed //FileNameExtensionFilter filter = new FileNameExtensionFilter ("Archivo de grafo","grph"); JFileChooser chooser = new JFileChooser(); //chooser.setFileFilter(filter); int seleccion = chooser.showOpenDialog(this); if (seleccion == JFileChooser.APPROVE_OPTION){ grafo = new Grafo(); this.setSize(this.getWidth()+1, this.getHeight()+1); this.setSize(this.getWidth()-1, this.getHeight()-1); String stringGeneral; String generalTemp; String []nodos; String generalAristas; String []aristas; String []datosArista; int ID; String Nombre; int X; int Y; int indexhasAristas=-1; boolean hasAristas = false; File file = chooser.getSelectedFile(); FileReader fr = null; BufferedReader reader = null; try { fr = new FileReader(file); reader = new BufferedReader(fr); while ((generalTemp = reader.readLine())!=null){ stringGeneral = generalTemp; System.out.println(stringGeneral); //confirma que tiene aristas desde un principio for (int i = 0; i < stringGeneral.length(); i++) { if (stringGeneral.charAt(i) == ';'){ hasAristas = true; indexhasAristas = i+1; break; } } nodos = stringGeneral.split(","); if (hasAristas){ generalAristas = ""; for (int i = indexhasAristas; i < stringGeneral.length(); i++) { generalAristas+=stringGeneral.charAt(i); } aristas = generalAristas.split(";"); /////////////aqui se pone bueno ID = Integer.parseInt(nodos[0]); Nombre = nodos[1]; X = Integer.parseInt(nodos[2]); Y = Integer.parseInt(nodos[3]); grafo.getNodos().add(new Node(ID,Nombre,new Coordenada (X,Y))); for (String arista : aristas) { datosArista = arista.split("/"); grafo.getNodos().get(grafo.getNodos().size()-1).getAristas().add(new Arista (Long.parseLong(datosArista[2]), Integer.parseInt(datosArista[0]), Integer.parseInt(datosArista[1]))); } }else{ nodos = stringGeneral.split(","); ID = Integer.parseInt(nodos[0]); Nombre = nodos[1]; X = Integer.parseInt(nodos[2]); Y = Integer.parseInt(nodos[3]); grafo.getNodos().add(new Node(ID,Nombre,new Coordenada (X,Y))); } } for (int i = 0; i < grafo.getNodos().size(); i++) { for (int j = 0; j < grafo.getNodos().get(i).getAristas().size(); j++) { grafo.getNodos().get(i).getAristas().get(j).setNodoInicial(grafo.getNodos().get(grafo.getNodos().get(i).getAristas().get(j).getInicial())); grafo.getNodos().get(i).getAristas().get(j).setNodoFinal(grafo.getNodos().get(grafo.getNodos().get(i).getAristas().get(j).getFinall())); } } iteradorabc = grafo.getNodos().size(); } catch (Exception e) { }finally{ try { reader.close(); fr.close(); } catch (Exception e) { } } ////////////////// RECORDAR HACER QUE LAS ARISTAS SEAN VALIDAS!!!!!!!!!!!!!!!!!!!!!!!!!! ///////////////// TAMBIEN SETEAR EL contadorabc JOptionPane.showMessageDialog(this, "Grafo agregado con exito"); refresh(); nodosMauricio = grafo.getNodos(); System.out.println(grafo.getNodos().size()); } }//GEN-LAST:event_jButton14ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Tonelitos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Tonelitos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Tonelitos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Tonelitos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Tonelitos().setVisible(true); } }); } public void refresh() { //jp_graphics.updateUI(); //g.clearRect(0, 0, jp_graphics.getWidth(), jp_graphics.getHeight()); //jp_graphics.removeAll(); Font font = new Font ("Dialog",Font.BOLD,14); Graphics g = this.jp_graphics.getGraphics(); g.setFont(font); for (int i = 0; i < grafo.getNodos().size(); i++) { g.setColor(Color.RED); g.drawOval(grafo.getNodos().get(i).getCoordenada().getX(), grafo.getNodos().get(i).getCoordenada().getY(), 30, 30); g.fillOval(grafo.getNodos().get(i).getCoordenada().getX(), grafo.getNodos().get(i).getCoordenada().getY(), 30, 30); System.out.println("X" + (i + 1) + ": " + grafo.getNodos().get(i).getCoordenada().getX()); System.out.println("Y" + (i + 1) + ": " + grafo.getNodos().get(i).getCoordenada().getY() + "\n"); } int x1, x2, y1, y2; for (int i = 0; i < grafo.getNodos().size(); i++) { for (int j = 0; j < grafo.getNodos().get(i).getAristas().size(); j++) { try { x1 = grafo.getNodos().get(i).getAristas().get(j).getNodoInicial().getID(); y1 = grafo.getNodos().get(i).getAristas().get(j).getNodoInicial().getID(); x2 = grafo.getNodos().get(i).getAristas().get(j).getNodoFinal().getID(); y2 = grafo.getNodos().get(i).getAristas().get(j).getNodoFinal().getID(); g.setColor(Color.RED); g.drawLine(grafo.getNodos().get(x1).getCoordenada().getX() + 15, grafo.getNodos().get(y1).getCoordenada().getY()+15, grafo.getNodos().get(x2).getCoordenada().getX()+15, grafo.getNodos().get(y2).getCoordenada().getY()+15); g.setColor(Color.BLUE); g.drawString(Long.toString(grafo.getNodos().get(i).getAristas().get(j).getDistancia()), ((grafo.getNodos().get(x1).getCoordenada().getX()+15)+(grafo.getNodos().get(x2).getCoordenada().getX()+15))/2, ((grafo.getNodos().get(y1).getCoordenada().getY()+15)+(grafo.getNodos().get(y2).getCoordenada().getY()+15))/2); g.setColor(Color.RED); } catch (Exception e) { } } } for (int i = 0; i < grafo.getNodos().size(); i++) { g.setColor(Color.BLACK); g.drawString(grafo.getNodos().get(i).getNombre(),grafo.getNodos().get(i).getCoordenada().getX()+10 , grafo.getNodos().get(i).getCoordenada().getY()+18); } } public void openDialog(JDialog Dialog) { Dialog.setLocationRelativeTo(this); Dialog.setModal(true); Dialog.pack(); Dialog.setVisible(true); } public boolean isCompletelyRelated(){ return false; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JDialog Dijkstra; private javax.swing.JDialog Floyd; private javax.swing.JDialog Tabla; private javax.swing.JButton jButton1; private javax.swing.JButton jButton10; private javax.swing.JButton jButton11; private javax.swing.JButton jButton12; private javax.swing.JButton jButton13; private javax.swing.JButton jButton14; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLayeredPane jLayeredPane1; private javax.swing.JButton jb_addImage; private javax.swing.JComboBox jc_final; private javax.swing.JComboBox jc_finalDijkstra; private javax.swing.JComboBox jc_finalFloyd; private javax.swing.JComboBox jc_inicial; private javax.swing.JComboBox jc_inicialDijkstra; private javax.swing.JComboBox jc_inicialFloyd; private javax.swing.JComboBox jc_vertice; private javax.swing.JDialog jd_eraseRelations; private javax.swing.JDialog jd_relations; private javax.swing.JLabel jl_image; private javax.swing.JPanel jp_graphics; private javax.swing.JPanel jp_lblparent; // End of variables declaration//GEN-END:variables private Color red = Color.RED; private Grafo grafo = new Grafo(); private int contadorNodos = 0; private ImageIcon icon = null; private boolean addVertex = false; private File imagen; private Image img, newImg; private ArrayList<Integer> tempDijkstra = new ArrayList(); private ArrayList<Integer> tempFloyd = new ArrayList(); private boolean hasDijkstra=false; private boolean hasFloyd=false; private String Abecedario[] ={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R", "S","T","U","V","W","X","Y","Z","A1","B1","C1","D1","E1","F1","G1","H1","I1","J1","K1","L1","M1","N1","O1","P1","Q1","R1", "S1","T1","U1","V1","W1","X1","Y1","Z1","A2","B2","C2","D2","E2","F2","G2","H2","I2","J2","K2","L2","M2","N2","O2","P2","Q2","R2", "S2","T2","U2","V2","W2","X2","Y2","Z2"}; private int iteradorabc = 0; boolean dimsensionar = false; private ArrayList<Node> nodosMauricio = new ArrayList(); }
package ru.taximaxim.treeviewer; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import ru.taximaxim.treeviewer.dialog.ColumnConfigDialog; import ru.taximaxim.treeviewer.filter.MyTreeViewerFilter; import ru.taximaxim.treeviewer.listeners.DataUpdateListener; import ru.taximaxim.treeviewer.listeners.FilterListener; import ru.taximaxim.treeviewer.models.IColumn; import ru.taximaxim.treeviewer.models.MyTreeViewerDataSource; import ru.taximaxim.treeviewer.tree.MyTreeViewerTable; import ru.taximaxim.treeviewer.utils.ImageUtils; import ru.taximaxim.treeviewer.utils.Images; import java.util.List; import java.util.ResourceBundle; public class MyTreeViewer extends Composite{ private ToolBar toolBar; private ResourceBundle resourceBundle; private GridLayout mainLayout; private MyTreeViewerTable tree; private MyTreeViewerDataSource dataSource; private MyTreeViewerFilter viewerFilter; private DataUpdateListener dataUpdateListener; public MyTreeViewer(Composite parent, int style, Object userData, MyTreeViewerDataSource dataSource) { super(parent, style); //this.resourceBundle = bundle; mainLayout = new GridLayout(); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); setLayout(mainLayout); setLayoutData(data); createContent(); this.dataSource = dataSource; tree.setDataSource(dataSource); getTree().setInput(userData); } public MyTreeViewerTable getTree() { return tree; } private void createContent() { createToolItems(); viewerFilter = new MyTreeViewerFilter(this, SWT.TOP); viewerFilter.hide(); tree = new MyTreeViewerTable(MyTreeViewer.this, SWT.FILL | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.MULTI); dataUpdateListener = new DataUpdateListener() { @Override public void needUpdateData() { tree.refresh(); System.out.println("UPDATED!"); } }; } private void createToolItems() { toolBar = new ToolBar(this, SWT.HORIZONTAL); ToolItem updateToolItem = new ToolItem(toolBar, SWT.PUSH); updateToolItem.setImage(ImageUtils.getImage(Images.UPDATE)); //updateToolItem.setToolTipText(Images.UPDATE.getDescription(resourceBundle)); updateToolItem.addListener(SWT.Selection, event -> updateTreeViewerData()); ToolItem filterToolItem = new ToolItem(toolBar, SWT.PUSH); filterToolItem.setImage(ImageUtils.getImage(Images.FILTER)); filterToolItem.addListener(SWT.Selection, event -> openFilter()); //filterToolItem.setToolTipText(Images.TABLE.getDescription(resourceBundle)); ToolItem configColumnToolItem = new ToolItem(toolBar, SWT.PUSH); configColumnToolItem.setImage(ImageUtils.getImage(Images.TABLE)); //configColumnToolItem.setToolTipText(Images.TABLE.getDescription(resourceBundle)); configColumnToolItem.addListener(SWT.Selection, event -> openConfigColumnDialog()); } private void openFilter() { if (viewerFilter.isVisible()) { viewerFilter.hide(); }else viewerFilter.show(); } private void updateTreeViewerData() { if (dataUpdateListener != null) { dataUpdateListener.needUpdateData(); } } private void openConfigColumnDialog() { ColumnConfigDialog dialog = new ColumnConfigDialog(resourceBundle, tree, this.getShell()); dialog.open(); } public void setFilters(List<? extends IColumn> filters, FilterListener filterableListeners) { viewerFilter.setFilterList(filters, filterableListeners, dataUpdateListener); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import java.awt.*; import java.util.Collections; import java.util.Enumeration; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JTree tree = new JTree(); JTextArea textArea = new JTextArea(); TreeModel model = tree.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); JButton depthFirst = new JButton("<html>depthFirst<br>postorder"); depthFirst.addActionListener(ev -> { textArea.setText(""); // Java 9: Collections.list(root.depthFirstEnumeration()) Collections.list((Enumeration<?>) root.depthFirstEnumeration()) .forEach(n -> textArea.append(String.format("%s%n", n))); // // Java 9: Enumeration<TreeNode> e = root.depthFirstEnumeration(); // Enumeration<?> e = root.depthFirstEnumeration(); // while (e.hasMoreElements()) { // DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement(); // textArea.append(node.toString() + "\n"); }); // JButton postorder = new JButton("postorder"); // postorder.addActionListener(ev -> { // textArea.setText(""); // // Java 9: Collections.list(root.postorderEnumeration()) // Collections.list((Enumeration<?>) root.postorderEnumeration()) // .forEach(n -> textArea.append(Objects.toString(n) + "\n")); // // // Java 9: Enumeration<TreeNode> e = root.postorderEnumeration(); // // Enumeration<?> e = root.postorderEnumeration(); // // while (e.hasMoreElements()) { // // DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement(); // // textArea.append(node.toString() + "\n"); JButton breadthFirst = new JButton("breadthFirst"); breadthFirst.addActionListener(ev -> { textArea.setText(""); // Java 9: Collections.list(root.breadthFirstEnumeration()) Collections.list((Enumeration<?>) root.breadthFirstEnumeration()) .forEach(n -> textArea.append(String.format("%s%n", n))); // // Java 9: Enumeration<TreeNode> e = root.breadthFirstEnumeration(); // Enumeration<?> e = root.breadthFirstEnumeration(); // while (e.hasMoreElements()) { // DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement(); // textArea.append(node.toString() + "\n"); }); JButton preorder = new JButton("preorder"); preorder.addActionListener(ev -> { textArea.setText(""); // Java 9: Collections.list(root.preorderEnumeration()) Collections.list((Enumeration<?>) root.preorderEnumeration()) .forEach(n -> textArea.append(String.format("%s%n", n))); // // Java 9: Enumeration<TreeNode> e = root.preorderEnumeration(); // Enumeration<?> e = root.preorderEnumeration(); // while (e.hasMoreElements()) { // DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement(); // textArea.append(node.toString() + "\n"); }); JPanel p = new JPanel(new GridLayout(0, 1, 5, 5)); p.add(depthFirst); p.add(breadthFirst); p.add(preorder); JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); panel.add(p, BorderLayout.NORTH); JSplitPane sp = new JSplitPane(); sp.setLeftComponent(new JScrollPane(tree)); sp.setRightComponent(new JScrollPane(textArea)); add(sp); add(panel, BorderLayout.EAST); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
package client.shareserver; import java.util.ArrayList; import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** * * * * @param <T> The type of the resource that this manages. */ public class ResourcePoolExecutor<T> extends AbstractExecutorService { public interface ResourceUser<T> extends Runnable { /** Returns the resource this task will be using. */ T getResource(); } private final ConcurrentMap<T, ExecutorService> resourceMap = new ConcurrentHashMap<T, ExecutorService>(); public ResourcePoolExecutor(Iterable<T> resources) { for (T resource : resources) { resourceMap.put(resource, Executors.newFixedThreadPool(1)); } } public ResourcePoolExecutor(Iterable<T> resources, ThreadFactory factory) { for (T resource : resources) { resourceMap.put(resource, Executors.newFixedThreadPool(1, factory)); } } @Override public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); for (final ExecutorService ex : resourceMap.values()) { pool.submit(new Callable<Boolean>() { @Override public Boolean call() throws InterruptedException { return ex.awaitTermination(timeout, unit); } }); } pool.shutdown(); return pool.awaitTermination(timeout, unit); } @Override public boolean isShutdown() { for (ExecutorService ex : resourceMap.values()) { if (!ex.isShutdown()) return false; } return true; } @Override public boolean isTerminated() { for (ExecutorService ex : resourceMap.values()) { if (!ex.isTerminated()) return false; } return true; } @Override public void shutdown() { for (ExecutorService ex : resourceMap.values()) { ex.shutdown(); } } @Override public List<Runnable> shutdownNow() { List<Runnable> list = new ArrayList<Runnable>(); for (ExecutorService ex : resourceMap.values()) { list.addAll(ex.shutdownNow()); } return list; } @Override public void execute(Runnable command) { if (command instanceof ResourceUser<?>) { ResourceUser<?> user = (ResourceUser<?>) command; Object resource = user.getResource(); if (resourceMap.containsKey(resource)) { resourceMap.get(resource).execute(user); return; } } throw new RejectedExecutionException("Resource not found or undefined"); } }
package org.xbill.DNS; import java.util.*; import java.io.*; import org.xbill.DNS.utils.*; /** * A DNS Message. A message is the basic unit of communication between * the client and server of a DNS operation. A message consists of a Header * and 4 message sections. * @see Resolver * @see Header * @see Section * * @author Brian Wellington */ public class Message implements Cloneable { private Header header; private List [] sections; private int size; private byte [] wireFormat; private boolean frozen; boolean TSIGsigned, TSIGverified; /** Creates a new Message with the specified Message ID */ public Message(int id) { sections = new List[4]; for (int i=0; i<4; i++) sections[i] = new LinkedList(); header = new Header(id); wireFormat = null; frozen = false; } /** Creates a new Message with a random Message ID */ public Message() { this(Header.randomID()); } /** * Creates a new Message with a random Message ID suitable for sending as a * query. * @param r A record containing the question */ public static Message newQuery(Record r) { Message m = new Message(); m.header.setOpcode(Opcode.QUERY); m.header.setFlag(Flags.RD); m.addRecord(r, Section.QUESTION); return m; } /** * Creates a new Message to contain a dynamic update. A random Message ID * the zone are filled in. * @param zone The zone to be updated */ public static Message newUpdate(Name zone) { Message m = new Message(); m.header.setOpcode(Opcode.UPDATE); Record soa = Record.newRecord(zone, Type.SOA, DClass.IN); m.addRecord(soa, Section.QUESTION); return m; } Message(DataByteInputStream in) throws IOException { this(); header = new Header(in); for (int i = 0; i < 4; i++) { for (int j = 0; j < header.getCount(i); j++) { Record rec = Record.fromWire(in, i); sections[i].add(rec); } } size = in.getPos(); } /** Creates a new Message from its DNS wire format representation */ public Message(byte [] b) throws IOException { this(new DataByteInputStream(b)); } /** * Replaces the Header with a new one * @see Header */ public void setHeader(Header h) { header = h; } /** * Retrieves the Header * @see Header */ public Header getHeader() { return header; } /** * Adds a record to a section of the Message, and adjusts the header * @see Record * @see Section */ public void addRecord(Record r, int section) { sections[section].add(r); header.incCount(section); } /** * Removes a record from a section of the Message, and adjusts the header * @see Record * @see Section */ public boolean removeRecord(Record r, int section) { if (sections[section].remove(r)) { header.decCount(section); return true; } else return false; } /** * Removes all records from a section of the Message, and adjusts the header * @see Record * @see Section */ public void removeAllRecords(int section) { sections[section].clear(); header.setCount(section, (short)0); } /** * Determines if the given record is already present in the given section * @see Record * @see Section */ public boolean findRecord(Record r, int section) { return (sections[section].contains(r)); } /** * Determines if the given record is already present in any section * @see Record * @see Section */ public boolean findRecord(Record r) { return (sections[Section.ANSWER].contains(r) || sections[Section.AUTHORITY].contains(r) || sections[Section.ADDITIONAL].contains(r)); } /** * Determines if an RRset with the given name and type is already * present in the given section * @see RRset * @see Section */ public boolean findRRset(Name name, short type, int section) { for (int i = 0; i < sections[section].size(); i++) { Record r = (Record) sections[section].get(i); if (r.getType() == type && name.equals(r.getName())) return true; } return false; } /** * Determines if an RRset with the given name and type is already * present in any section * @see RRset * @see Section */ public boolean findRRset(Name name, short type) { return (findRRset(name, type, Section.ANSWER) || findRRset(name, type, Section.AUTHORITY) || findRRset(name, type, Section.ADDITIONAL)); } /** * Returns the first record in the QUESTION section * @see Record * @see Section */ public Record getQuestion() { try { return (Record) sections[Section.QUESTION].get(0); } catch (NoSuchElementException e) { return null; } } /** * Returns the TSIG record from the ADDITIONAL section, if one is present * @see TSIGRecord * @see TSIG * @see Section */ public TSIGRecord getTSIG() { int count = header.getCount(Section.ADDITIONAL); if (count == 0) return null; List l = sections[Section.ADDITIONAL]; Record rec = (Record) l.get(count - 1); if (rec.type != Type.TSIG) return null; return (TSIGRecord) rec; } /** * Was this message signed by a TSIG? * @see TSIG */ public boolean isSigned() { return TSIGsigned; } /** * If this message was signed by a TSIG, was the TSIG verified? * @see TSIG */ public boolean isVerified() { return TSIGverified; } /** * Returns the OPT record from the ADDITIONAL section, if one is present * @see OPTRecord * @see Section */ public OPTRecord getOPT() { Record [] additional = getSectionArray(Section.ADDITIONAL); for (int i = 0; i < additional.length; i++) if (additional[i] instanceof OPTRecord) return (OPTRecord) additional[i]; return null; } /** * Returns the message's rcode (error code). This incorporates the EDNS * extended rcode. */ public short getRcode() { short rcode = header.getRcode(); OPTRecord opt = getOPT(); if (opt != null) rcode += (short)(opt.getExtendedRcode() << 4); return rcode; } /** * Returns an Enumeration listing all records in the given section * @see Record * @see Section */ public Enumeration getSection(int section) { return Collections.enumeration(sections[section]); } /** * Returns an array containing all records in the given section * @see Record * @see Section */ public Record [] getSectionArray(int section) { List l = sections[section]; return (Record []) l.toArray(new Record[l.size()]); } void toWire(DataByteOutputStream out) throws IOException { header.toWire(out); Compression c = new Compression(); for (int i = 0; i < 4; i++) { for (int j = 0; j < sections[i].size(); j++) { Record rec = (Record)sections[i].get(j); rec.toWire(out, i, c); } } } /** * Returns an array containing the wire format representation of the Message. */ public byte [] toWire() throws IOException { if (frozen && wireFormat != null) return wireFormat; DataByteOutputStream out = new DataByteOutputStream(); toWire(out); size = out.getPos(); if (frozen) { wireFormat = out.toByteArray(); return wireFormat; } else return out.toByteArray(); } /** * Indicates that a message's contents will not be changed until a thaw * operation. * @see #thaw */ public void freeze() { frozen = true; } /** * Indicates that a message's contents can now change (are no longer frozen). * @see #freeze */ public void thaw() { frozen = false; wireFormat = null; } /** * Returns the size of the message. Only valid if the message has been * converted to or from wire format. */ public int numBytes() { return size; } /** * Converts the given section of the Message to a String * @see Section */ public String sectionToString(int i) { if (i > 3) return null; StringBuffer sb = new StringBuffer(); Record [] records = getSectionArray(i); for (int j = 0; i < records.length; j++) { Record rec = records[j]; if (i == Section.QUESTION) { sb.append(";;\t" + rec.name); sb.append(", type = " + Type.string(rec.type)); sb.append(", class = " + DClass.string(rec.dclass)); } else sb.append(rec); sb.append("\n"); } return sb.toString(); } /** * Converts the Message to a String */ public String toString() { StringBuffer sb = new StringBuffer(); OPTRecord opt = getOPT(); if (opt != null) sb.append(header.toStringWithRcode(getRcode()) + "\n"); else sb.append(header + "\n"); if (isSigned()) { sb.append(";; TSIG "); if (isVerified()) sb.append("ok"); else sb.append("invalid"); sb.append('\n'); } for (int i = 0; i < 4; i++) { if (header.getOpcode() != Opcode.UPDATE) sb.append(";; " + Section.longString(i) + ":\n"); else sb.append(";; " + Section.updString(i) + ":\n"); sb.append(sectionToString(i) + "\n"); } sb.append(";; done (" + numBytes() + " bytes)"); return sb.toString(); } /** * Creates a copy of this Message. This is done by the Resolver before adding * TSIG and OPT records, for example. * @see Resolver * @see TSIGRecord * @see OPTRecord */ public Object clone() { Message m = new Message(); for (int i = 0; i < sections.length; i++) m.sections[i] = new LinkedList(sections[i]); m.header = (Header) header.clone(); m.size = size; return m; } }
package jade.imtp.leap; import jade.core.ServiceManager; import jade.core.Node; import jade.core.IMTPException; import jade.core.Profile; import jade.core.ProfileException; import jade.core.Runtime; import jade.core.UnreachableException; import jade.mtp.TransportAddress; import jade.util.leap.Iterator; import jade.util.leap.ArrayList; import jade.util.leap.List; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.Logger; /** * This class provides the implementation of a command * dispatcher. The command dispatcher misses support for multiple remote * objects, multiple ICPs and command routing. * * <p>The command dispatcher is based on an implementation written by * Michael Watzke and Giovanni Caire (TILAB), 09/11/2000.</p> * * @author Tobias Schaefer * @version 1.0 */ class CommandDispatcher implements StubHelper, ICP.Listener { private static final String COMMAND_DISPATCHER_CLASS = "dispatcher-class"; private static final String MAIN_PROTO_CLASS = "main-proto-class"; /** * The default name for new instances of the class * <tt>CommandDispatcher</tt> that have not get an unique name by * their container yet. */ protected static final String DEFAULT_NAME = "Default"; /** * A singleton instance of the command dispatcher. */ protected static CommandDispatcher commandDispatcher; /** * The unique name of this command dispatcher used to avoid loops in * the forwarding mechanism. */ protected String name; /** * The transport address of the default router. Commands that cannot * be dispatched directly will be sent to this address. */ protected TransportAddress routerTA = null; /** * This hashtable maps the IDs of the objects remotized by this * command dispatcher to the skeletons for these objects. It is used * when a command is received from a remote JVM. */ protected Map skeletons = new HashMap(); /** * This hashtable maps the objects remotized by this command * dispatcher to their IDs. It is used when a stub of a remotized * object must be built to be sent to a remote JVM. */ protected Map ids = new HashMap(); /** * A counter that is used for determining IDs for remotized objects. * Everytime a new object is registered by the command dispatcher it * gets the value of this field as ID and the field is increased. */ protected int nextID; /** * The pool of ICP objects used by this command dispatcher to * actually send/receive data over the network. It is a table that * associates a <tt>String</tt> representing a protocol (e.g. "http") * to a list of ICPs supporting that protocol. */ protected Map icps = new HashMap(); /** * The transport addresses the ICPs managed by this command * dispatcher are listening for commands on. */ protected List addresses = new ArrayList(); /** * The URLs corresponding to the local transport addresses. */ protected List urls = new ArrayList(); /** The stub for the platform service manager. This stub will be shared by all nodes within this Java virtual Machine. */ private ServiceManagerStub theSvcMgrStub = null; /** * Tries to create a new command dispatcher and returns whether the * creation was successful. The implementation of the command * dispatcher is determined by the specified profile. The profile * must contain a parameter with the key <tt>"commandDispatcher"</tt> * and a value containing the fully qualified class name of the * desired command dispatcher. * * <p>When the profile contains no argument with key * <tt>"commandDispatcher"</tt> the class * {@link FullCommandDispatcher jade.imtp.leap.FullCommandDispatcher} * will be used per default.</p> * * @param p a profile determining the implementation of the command * dispatcher. * @return <tt>true</tt>, if a command dispatcher of the desired * class is created or already exists, otherwise * <tt>false</tt>. */ public static final boolean create(Profile p) { String implementation = null; // Set CommandDispatcher class name implementation = p.getParameter(COMMAND_DISPATCHER_CLASS, "jade.imtp.leap.CommandDispatcher"); if (commandDispatcher == null) { try { commandDispatcher = (CommandDispatcher) Class.forName(implementation).newInstance(); // DEBUG // System.out.println("Using command dispatcher '" + implementation + "'"); return true; } catch (Exception e) { Logger.println("Instantiation of class "+implementation+" failed ["+e+"]."); } return false; } else { return commandDispatcher.getClass().getName().equals(implementation); } } /** * Returns a reference to the singleton instance of the command * dispatcher. When no such instance exists, <tt>null</tt> is * returned. * * @return a reference to the singleton instance of the command * dispatcher or <tt>null</tt>, if no such instance exists. */ public static final CommandDispatcher getDispatcher() { return commandDispatcher; } /** * A sole constructor. To get a command dispatcher the constructor * should not be called directly but the static <tt>create</tt> and * <tt>getDispatcher</tt> methods should be used. Thereby the * existence of a singleton instance of the command dispatcher will * be guaranteed. */ public CommandDispatcher() { // Set a temporary name. Will be substituted as soon as the first // container attached to this CommandDispatcher will receive a // unique name from the main. name = DEFAULT_NAME; nextID = 1; } public synchronized ServiceManagerStub getServiceManagerStub(Profile p) throws IMTPException { if(theSvcMgrStub == null) { theSvcMgrStub = new ServiceManagerStub(); TransportAddress mainTA = initMainTA(p); theSvcMgrStub.bind(this); theSvcMgrStub.addTA(mainTA); } return theSvcMgrStub; } public ServiceManagerStub getServiceManagerStub(String addr) throws IMTPException { // Try to translate the address into a TransportAddress // using a protocol supported by this CommandDispatcher try { ServiceManagerStub stub = new ServiceManagerStub(); TransportAddress ta = stringToAddr(addr); stub.bind(this); stub.addTA(ta); return stub; } catch (DispatcherException de) { throw new IMTPException("Invalid address for a Service Manager", de); } } public void addAddressToStub(Stub target, String toAdd) { try { TransportAddress ta = stringToAddr(toAdd); target.addTA(ta); } catch(DispatcherException de) { de.printStackTrace(); } } public void removeAddressFromStub(Stub target, String toRemove) { try { TransportAddress ta = stringToAddr(toRemove); target.removeTA(ta); } catch(DispatcherException de) { de.printStackTrace(); } } public void clearStubAddresses(Stub target) { target.clearTAs(); } /** * Sets the transport address of the default router used for the * forwarding mechanism. * * @param url the URL of the default router. */ void setRouterAddress(String url) { if (url != null) { // The default router must be directly reachable --> // Its URL can be converted into a TransportAddress by // the ICP registered to this CommandDispatcher try { TransportAddress ta = stringToAddr(url); if (routerTA != null && !routerTA.equals(ta)) { Logger.println("WARNING : transport address of current router has been changed"); } routerTA = ta; } catch (Exception e) { // Just print a warning: default (i.e. main TA) will be used Logger.println("Can't initialize router address"); } } } /** * This method dispatches the specified command to the first address * (among those specified) to which dispatching succeeds. * * @param destTAs a list of transport addresses where the command * dispatcher should try to dispatch the command. * @param command the command that is to be dispatched. * @return a response command from the receiving container. * @throws DispatcherException if an error occurs during dispatching. * @throws UnreachableException if none of the destination addresses * is reachable. */ public Command dispatchCommand(List destTAs, Command command) throws DispatcherException, UnreachableException { // DEBUG //TransportAddress ta = (TransportAddress) destTAs.get(0); //System.out.println("Dispatching command of type " + command.getCode() + " to "+ta.getHost()+":"+ta.getPort()); Command response = null; if (isLocal(destTAs)) { Integer id = new Integer(command.getObjectID()); Skeleton skel = (Skeleton) skeletons.get(id); if (skel != null) { response = skel.processCommand(command); } } if (response == null) { try { response = dispatchSerializedCommand(destTAs, serializeCommand(command), name); } catch (LEAPSerializationException lse) { throw new DispatcherException("Error serializing command "+command+" ["+lse.getMessage()+"]"); } } // If the dispatched command was an ADD_NODE --> get the // name from the response and use it as the name of the CommandDispatcher if (command.getCode() == Command.ADD_NODE && name.equals(DEFAULT_NAME)) { name = (String) response.getParamAt(0); } return response; } private boolean isLocal(List destTAs) { try { TransportAddress ta1 = (TransportAddress) addresses.get(0); TransportAddress ta2 = (TransportAddress) destTAs.get(0); return (ta1.getHost().equals(ta2.getHost()) && ta1.getPort().equals(ta2.getPort()) && ta2.getFile() == null); } catch (Exception e) { return false; } } /** * Dispatches the specified serialized command to one of the * specified transport addresses (the first where dispatching * succeeds) directly or through the router. * * @param destTAs a list of transport addresses where the command * dispatcher should try to dispatch the command. * @param commandPayload the serialized command that is to be * dispatched. * @param origin a <tt>String</tt> object describing the origin of * the command to be dispatched. * @return a response command from the receiving container. * @throws DispatcherException if an error occurs during dispatching. * @throws UnreachableException if none of the destination addresses * is reachable. */ protected Command dispatchSerializedCommand(List destTAs, byte[] commandPayload, String origin) throws DispatcherException, UnreachableException { // Be sure that the destination addresses are correctly specified if (destTAs == null || destTAs.size() == 0) { throw new DispatcherException("no destination address specified."); } byte[] responsePayload = null; try { // Try to dispatch the command directly responsePayload = dispatchDirectly(destTAs, commandPayload); // Runtime.instance().gc(23); } catch (UnreachableException ue) { // Direct dispatching failed --> Try through the router // DEBUG // System.out.println("Dispatch command through router"); responsePayload = dispatchThroughRouter(destTAs, commandPayload, origin); // Runtime.instance().gc(24); } // Deserialize the response try { Command response = deserializeCommand(responsePayload); // Runtime.instance().gc(25); // Check whether some exceptions to be handled by the // CommandDispatcher occurred on the remote site checkRemoteExceptions(response); return response; } catch (LEAPSerializationException lse) { throw new DispatcherException("error deserializing response ["+lse.getMessage()+"]."); } } /** * Dispatches the specified serialized command to one of the * specified transport addresses (the first where dispatching * succeeds) directly. * * @param destTAs a list of transport addresses where the command * dispatcher should try to dispatch the command. * @param commandPayload the serialized command that is to be * dispatched. * @return a serialized response command from the receiving * container. * @throws UnreachableException if none of the destination addresses * is reachable. */ protected byte[] dispatchDirectly(List destTAs, byte[] commandPayload) throws UnreachableException { // Loop on destinaltion addresses (No need to check again // that the list of addresses is not-null and not-empty) for (int i = 0; i < destTAs.size(); i++) { try { return send((TransportAddress) destTAs.get(i), commandPayload); } catch (UnreachableException ue) { // Can't send command to this address --> try the next one // DEBUG //TransportAddress ta = (TransportAddress)destTAs.get(i); //System.out.println("Sending command to " + ta.getProto() + "://" + ta.getHost() + ":" + ta.getPort() + " failed [" + ue.getMessage() + "]"); //if (i < destTAs.size() - 1) // System.out.println("Try next address"); } } // Sending failed to all addresses. // No need for a meaningful message as this exception will // trigger dispatching through router throw new UnreachableException(""); } /** * Dispatches the specified serialized command to one of the * specified transport addresses (the first where dispatching * succeeds) through the router. * * @param destTAs a list of transport addresses where the command * dispatcher should try to dispatch the command. * @param commandPayload the serialized command that is to be * dispatched. * @param origin a <tt>String</tt> object describing the origin of * the command to be dispatched. * @return a serialized response command from the receiving * container. * @throws DispatcherException if an error occurs during dispatching. * @throws UnreachableException if none of the destination addresses * is reachable. */ protected byte[] dispatchThroughRouter(List destTAs, byte[] commandPayload, String origin) throws DispatcherException, UnreachableException { if (routerTA == null) { throw new UnreachableException("destination unreachable."); // Build a FORWARD command } Command forward = new Command(Command.FORWARD); forward.addParam(commandPayload); forward.addParam(destTAs); forward.addParam(origin); // Runtime.instance().gc(26); try { return send(routerTA, serializeCommand(forward)); } catch (LEAPSerializationException lse) { throw new DispatcherException("error serializing FORWARD command ["+lse.getMessage()+"]."); } } /** * Checks whether some exceptions to be handled by the command * dispatcher occurred on the remote site. If this is the case the * command dispatcher throws the corresponding exception locally. * * @param response the resonse comman from the receiving container. * @throws DispatcherException if an error occurs on the remote site * during dispatching. * @throws UnreachableException if the destination address is not * reachable. */ protected void checkRemoteExceptions(Command response) throws DispatcherException, UnreachableException { if (response.getCode() == Command.ERROR) { String exception = (String) response.getParamAt(0); // DispatcherException (some error occurred in the remote // CommandDispatcher) --> throw a DispatcherException. if (exception.equals("jade.imtp.leap.DispatcherException")) { throw new DispatcherException("DispatcherException in remote site."); } else // UnreachableException (the Command was sent to the router, // but the final destination was unreachable from there) // --> throw an UnreachableException if (exception.equals("jade.core.UnreachableException")) { throw new UnreachableException((String) response.getParamAt(1)); } } } /** * Serializes a <tt>Command</tt> object into a <tt>byte</tt> array. * * @param command the command to be serialized. * @return the serialized command. * @throws LEAPSerializationException if the command cannot be * serialized. */ protected byte[] serializeCommand(Command command) throws LEAPSerializationException { DeliverableDataOutputStream ddout = new DeliverableDataOutputStream(this); ddout.serializeCommand(command); return ddout.getSerializedByteArray(); } /** * Deserializes a <tt>Command</tt> object from a <tt>byte</tt> array. * * @param data the <tt>byte</tt> array containing serialized command. * @return the deserialized command. * @throws LEAPSerializationException if the command cannot be * deserialized. */ protected Command deserializeCommand(byte[] data) throws LEAPSerializationException { return new DeliverableDataInputStream(data, this).deserializeCommand(); } /** * Builds a command that carries an exception. * * @param exception the exception to be carried. * @return the command carrying the exception. */ protected Command buildExceptionResponse(Exception exception) { Command response = new Command(Command.ERROR); response.addParam(exception.getClass().getName()); response.addParam(exception.getMessage()); return response; } private TransportAddress initMainTA(Profile p) throws IMTPException { TransportAddress mainTA = null; try { String mainURL = p.getParameter(LEAPIMTPManager.MAIN_URL, null); System.out.println("Main URL is "+mainURL); // Try to translate the mainURL into a TransportAddress // using a protocol supported by this CommandDispatcher try { mainTA = stringToAddr(mainURL); } catch (DispatcherException de) { // Failure --> A suitable protocol class may be explicitly // indicated in the profile (otherwise rethrow the exception) String mainTPClass = p.getParameter(MAIN_PROTO_CLASS, null); if (mainTPClass != null) { TransportProtocol tp = (TransportProtocol) Class.forName(mainTPClass).newInstance(); mainTA = tp.stringToAddr(mainURL); } else { throw de; } } // If the router TA was not set --> use the mainTA as default if (routerTA == null) { routerTA = mainTA; } return mainTA; } catch (Exception e) { throw new IMTPException("Error getting Main Container address", e); } } /** * Adds (and activates) an ICP to this command dispatcher. * * @param peer the ICP to add. * @param args the arguments required by the ICP for the activation. * These arguments are ICP specific. */ public void addICP(ICP peer, String peerID, Profile p) { try { // Activate the peer. TransportAddress ta = peer.activate(this, peerID, p); // Add the listening address to the list of local addresses. TransportProtocol tp = peer.getProtocol(); String url = tp.addrToString(ta); addresses.add(ta); urls.add(url); // Put the peer in the table of local ICPs. String proto = tp.getName().toLowerCase(); List list = (List) icps.get(proto); if (list == null) { icps.put(proto, (list = new ArrayList())); } list.add(peer); } catch (ICPException icpe) { // Print a warning. System.out.println("Error adding ICP "+peer+"["+icpe.getMessage()+"]."); } } /** * Returns the ID of the specified remotized object. * * @param remoteObject the object whose ID should be returned. * @return the ID of the reomte object. * @throws RuntimeException if the specified object is not * remotized by this command dispatcher. */ public int getID(Object remoteObject) throws IMTPException { Integer id = (Integer) ids.get(remoteObject); if (id != null) { return id.intValue(); } throw new IMTPException("specified object is not remotized by this command dispatcher."); } /** * Returns the list of local addresses. * * @return the list of local addresses. */ public List getLocalTAs() { return addresses; } /** * Returns the list of URLs corresponding to the local addresses. * * @return the list of URLs corresponding to the local addresses. */ public List getLocalURLs() { return urls; } /** * Converts an URL into a transport address using the transport * protocol supported by the ICPs currently installed in the command * dispatcher. If there is no ICP installed to the command dispatcher * or their transport protocols are not able to convert the specified * URL a <tt>DispatcherException</tt> is thrown. * * @param url a <tt>String</tt> object specifying the URL to convert. * @return the converted URL. * @throws DispatcherException if there is no ICP installed to the * command dispatcher or the transport protocols of the ICPs * are not able to convert the specified URL. */ protected TransportAddress stringToAddr(String url) throws DispatcherException { Iterator peers = icps.values().iterator(); while (peers.hasNext()) { // Try to convert the url using the TransportProtocol // supported by this ICP. try { // There can be more than one peer supporting the same // protocol. Use the first one. return ((ICP) ((List) peers.next()).get(0)).getProtocol().stringToAddr(url); } catch (Throwable t) { // Do nothing and try the next one. } } // If we reach this point the url can't be converted. throw new DispatcherException("can't convert URL "+url+"."); } /** * Registers the specified skeleton to the command dispatcher. * * @param skeleton a skeleton to be managed by the command * dispatcher. * @param remoteObject the remote object related to the specified * skeleton. */ public void registerSkeleton(Skeleton skeleton, Object remotizedObject) { Integer id = null; if(remotizedObject instanceof ServiceManager) { synchronized(this) { id = new Integer(0); name = "Service-Manager"; // Since we're exporting a local Service Manager, we // make the SM stub point to the local SM, using our // local transport addresses theSvcMgrStub = new ServiceManagerStub(); theSvcMgrStub.bind(this); Iterator it = addresses.iterator(); while(it.hasNext()) { TransportAddress ta = (TransportAddress)it.next(); theSvcMgrStub.addTA(ta); } } } else { id = new Integer(nextID++); } skeletons.put(id, skeleton); ids.put(remotizedObject, id); } /** * Deregisters the specified remote object from the command dispatcher. * * @param remoteObject the remote object related to the specified * skeleton. */ public void deregisterSkeleton(Object remoteObject) { try { skeletons.remove(ids.remove(remoteObject)); } catch (NullPointerException npe) { } if (ids.isEmpty()) { //System.out.println("CommandDispatcher shutting down"); shutDown(); } } public Stub buildLocalStub(Object remotizedObject) throws IMTPException { Stub stub = null; if (remotizedObject instanceof Node) { stub = new NodeStub(getID(remotizedObject)); // Add the local addresses. Iterator it = addresses.iterator(); while (it.hasNext()) { stub.addTA((TransportAddress) it.next()); } } else { throw new IMTPException("can't create a stub for object "+remotizedObject+"."); } return stub; } /** * Selects a suitable peer and sends the specified serialized command * to the specified transport address. * * @param ta the transport addresses where the command should be * sent. * @param commandPayload the serialized command that is to be * sent. * @return a serialized response command from the receiving * container. * @throws UnreachableException if the destination address is not * reachable. */ protected byte[] send(TransportAddress ta, byte[] commandPayload) throws UnreachableException { // Get the ICPs suitable for the given TransportAddress. List list = (List) icps.get(ta.getProto().toLowerCase()); if (list == null) { throw new UnreachableException("no ICP suitable for protocol "+ta.getProto()+"."); } for (int i = 0; i < list.size(); i++) { try { return ((ICP) list.get(i)).deliverCommand(ta, commandPayload); } catch (ICPException icpe) { // DEBUG // Print a warning and try next address //System.out.println("Warning: can't deliver command to "+ta+". "+icpe.getMessage()); } } throw new UnreachableException("ICPException delivering command to address "+ta+"."); } /** * Shuts the command dispatcher down and deactivates the local ICPs. */ public void shutDown() { Iterator peersKeys = icps.keySet().iterator(); while (peersKeys.hasNext()) { List list = (List) icps.get(peersKeys.next()); for (int i = 0; i < list.size(); i++) { try { // This call interrupts the listening thread of this peer // and waits for its completion. ((ICP) list.get(i)).deactivate(); // DEBUG // System.out.println("ICP deactivated."); } catch (ICPException icpe) { // Do nothing as this means that this peer had never been // activated. } } list.clear(); } icps.clear(); } // ICP.Listener INTERFACE /** * Handles a received (still serialized) command object, i.e. * deserialize it and launch processing of the command. * * @param commandPayload the command to be deserialized and * processed. * @return a <tt>byte</tt> array containing the serialized response * command. * @throws LEAPSerializationException if the command cannot be * (de-)serialized. */ public byte[] handleCommand(byte[] commandPayload) throws LEAPSerializationException { try { // Deserialize the incoming command. Command command = deserializeCommand(commandPayload); Command response = null; // DEBUG //System.out.println("Received command of type " + command.getCode()); if (command.getCode() == Command.FORWARD) { // DEBUG // System.out.println("Routing command"); // If this is a FORWARD command then handle it directly. byte[] originalPayload = (byte[]) command.getParamAt(0); List destTAs = (List) command.getParamAt(1); String origin = (String) command.getParamAt(2); if (origin.equals(name)) { // The forwarding mechanism is looping. response = buildExceptionResponse(new UnreachableException("destination unreachable (and forward loop).")); } else { try { response = dispatchSerializedCommand(destTAs, originalPayload, origin); } catch (UnreachableException ue) { // rsp = buildExceptionResponse("jade.core.UnreachableException", ue.getMessage()); response = buildExceptionResponse(ue); } } } else { // If this is a normal Command, let the proper Skeleton // process it. Integer id = new Integer(command.getObjectID()); Skeleton s = (Skeleton) skeletons.get(id); if (s == null) { throw new DispatcherException("No skeleton for object-id "+id); } response = s.processCommand(command); } return serializeCommand(response); } catch (Exception e) { // FIXME. If this throws an exception this is not handled by // the CommandDispatcher. return serializeCommand(buildExceptionResponse(new DispatcherException(e.getMessage()))); } } }
package com.blarg.gdx.tilemap3d; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.g3d.ModelBatch; public class TileMapRenderer { public void render(ModelBatch modelBatch, Camera camera, TileMap tileMap) { TileChunk[] chunks = tileMap.chunks; for (int i = 0; i < chunks.length; ++i) { TileChunk chunk = chunks[i]; if (camera.frustum.boundsInFrustum(chunk.getMeshBounds())) modelBatch.render(chunk); } } }
package com.dmdirc.actions.metatypes; import com.dmdirc.actions.interfaces.ActionMetaType; import com.dmdirc.ui.interfaces.Window; /** * Defines link-related events. * * @author Chris */ public enum LinkEvents implements ActionMetaType { /** URL Link clicked. */ LINK_CLICKED(new String[]{"Window","URL"}, Window.class, String.class), /** Channel link clicked. */ CHANNEL_CLICKED(new String[]{"Window", "Channel"}, Window.class, String.class), /** Nickname link clicked. */ NICKNAME_CLICKED(new String[]{"Window", "Nickname"}, Window.class, String.class); /** The names of the arguments for this meta type. */ private String[] argNames; /** The classes of the arguments for this meta type. */ private Class[] argTypes; /** * Creates a new instance of this meta-type. * * @param argNames The names of the meta-type's arguments * @param argTypes The types of the meta-type's arguments */ LinkEvents(final String[] argNames, final Class... argTypes) { this.argNames = argNames; this.argTypes = argTypes; } /** {@inheritDoc} */ @Override public int getArity() { return argNames.length; } /** {@inheritDoc} */ @Override public Class[] getArgTypes() { return argTypes; } /** {@inheritDoc} */ @Override public String[] getArgNames() { return argNames; } /** {@inheritDoc} */ @Override public String getGroup() { return "Link Events"; } }
package com.fox.collections; import com.fox.io.log.ConsoleLogger; import com.fox.types.ClassExtension; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Iterator; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static com.fox.general.PredicateTests.isTrue; import static com.fox.io.log.ConsoleLogger.debugFormatted; import static com.fox.io.log.ConsoleLogger.exception; public class CollectionExtension { public static void classLoader() { try { Method[] myMethods = Class.forName("com.fox.collections.CollectionExtension").getDeclaredMethods(); for (Method myMethod : myMethods) { ConsoleLogger.writeLine(myMethod); } } catch (ClassNotFoundException e) { exception(e, "the classLoading is still experimental"); } } public static <T> boolean containsAll(Collection<T> a, Collection<T> b, boolean sequential) { if (sequential) { return containsAllSequential(a, b); } else { boolean contains = false; for (T t : b) { contains = a.contains(t); } return contains; } } public static <T> boolean containsAllSequential(Collection<T> larger, Collection<T> smaller) { Iterator<T> left = larger.iterator(); Iterator<T> right = smaller.iterator(); T left_Curr = left.next(), right_Curr = right.next(); // find the first match to start checking the sequence. while (left.hasNext() && left_Curr != right_Curr) left_Curr = left.next(); try { isTrue(left.hasNext()); // Assert we haven't gone the entirety of our first collection. for (; left.hasNext() && right.hasNext(); left_Curr = left.next(), right_Curr = right.next()) { if (left_Curr != right_Curr) return false; } return true; } catch (Exception e) { exception(e, "The first collection never found the start of the second collection"); return false; } } // TODO: Provide a better implementation than Collectors.toList(), which is "good enough" public static <E, T extends E> Collection<T> cast(Collection<E> collection) throws ClassCastException { return collection.stream().map(e -> (T) e).collect(Collectors.toList()); } public static <E, T extends E> Collection<T> transform(Iterable<E> iterable, Function<? super E, T> function) { return StreamSupport.stream(iterable.spliterator(), false).map(function).collect(Collectors.toList()); } public static <E, T extends E> Collection<T> transform(Collection<E> collection, Function<? super E, T> function) { return collection.stream().map(function).collect(Collectors.toList()); } public static <E> Collection<E> from(Iterable<E> iterable) { if (iterable instanceof Collection) return (Collection<E>) iterable; return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); } /** * Performs an O(n) - where 'n' is the element count of the passed collection - casting of the * elements into another type lens * Ex: * // This runs, given HistoricEvent matches the Event constructor * {@code * ArrayDequeue<Event> events = EventQueueFactory.foo(); * Queue<HistoricEvent> histories = CollectionExtension.castBetter(events); * } * <p> * In the future, I want this to be able to match constructors reflectively and be able to match * the type off of param <C> instead. * <p> * Future ex: * <p> * // shout out to Google's Guava library "collections" package * {@code * ImmutableList<Integer> integers = ImmutableList.of(1,2,3,4); * RegularImmutableList<Integer> regularInts = CollectionExtension.castBetter(integers); * // of better yet... * RegularImmutableList<Long> regularInts = CollectionExtension.castBetter(integers); * // because, if we can, we SHOULD * } * * @param collection Some generic collection * @param <E> type in passed collection * @param <T> some child * @param <C> Some collection of that child, where super/interface types perform more reliably * @return newInstance of the passed collection through the lens of param {@code <C>} */ public static <E, T extends E, C extends Collection<T>> C castBetter(Collection<? extends E> collection) { // Type preliminarySuperType = ClassExtension.getPreliminarySuperType(collection.getClass()); try { Class<Object> objectClass = ClassExtension.dotClass(collection.getClass()); debugFormatted("collection.class: %s", objectClass); Constructor<Object> constructor = objectClass.getConstructor(Collection.class); debugFormatted("Got ctor: %s", constructor); debugFormatted("Collection<E>.preliminarySuperType()", ClassExtension.getPreliminarySuperType(collection.getClass())); return (C) constructor.newInstance(collection); } catch (NoSuchMethodException e) { exception(e, "No method could be found"); } catch (InvocationTargetException e) { exception(e, "Invocation target was invalid... Probably"); } catch (InstantiationException e) { exception(e, "Instantiation exception... Whatever that is\n"); } catch (IllegalAccessException e) { exception(e, "Constructor was inaccessible"); } catch (NullPointerException e) { exception(e, "Null pointer on objectClass (see code for more)\n"); } catch (ClassNotFoundException e) { exception(e, "ClassNotFound from ClassExtension.dotClass(collection.getClass())"); } return null; } }
package com.frc2013.rmr662.eastereggs; import com.frc2013.rmr662.system.generic.Component; import com.frc2013.rmr662.system.generic.RobotMode; import com.frc2013.rmr662.wrappers.RMRJaguar; public class DanceMode extends RobotMode { /** * The drive component for DanceMode */ private static class DanceDrive extends Component { private static final int MOTOR_CHANNEL_LEFT = 1; private static final int MOTOR_CHANNEL_RIGHT = 2; private static final double MOTOR_SPEED = 0.5; private final RMRJaguar leftMotor; private final RMRJaguar rightMotor; public DanceDrive() { leftMotor = new RMRJaguar(MOTOR_CHANNEL_LEFT, 1.0); rightMotor = new RMRJaguar(MOTOR_CHANNEL_RIGHT, 1.0); } protected void onBegin() { leftMotor.set(-MOTOR_SPEED); rightMotor.set(MOTOR_SPEED); } protected void update() { } protected void onEnd() { leftMotor.set(0.0); rightMotor.set(0.0); leftMotor.free(); rightMotor.free(); } } // /** // * The manipulator component for DanceMode // */ // private static class DanceManipulator extends Component { // private final Jaguar motor = new Jaguar(Climber.MOTOR_PORT); // private final DigitalInput top = new DigitalInput(Climber.SENSOR0); // private final DigitalInput bottom = new DigitalInput(Climber.SENSOR1); // protected void onBegin() { // motor.set(.5 * Climber.MOTOR_DIRECTION_MULT); // protected void update() { // if (bottom.get() != INVERTED_BOTTOM) { // motor.set(.5 * Climber.MOTOR_DIRECTION_MULT); // } else if (top.get() != INVERTED_TOP) { // motor.set(-.5 * Climber.MOTOR_DIRECTION_MULT); // public void onEnd() { // motor.set(0); private final DanceDrive drive; public DanceMode() { super("DanceMode"); drive = new DanceDrive(); } protected void onBegin() { drive.start(); } protected void loop() { System.out.println("NYAN"); } protected void onEnd() { drive.end(); } }
package com.googlecode.objectify; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.persistence.Id; import javax.persistence.Transient; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.googlecode.objectify.annotation.Indexed; import com.googlecode.objectify.annotation.OldName; import com.googlecode.objectify.annotation.Parent; /** * Everything you need to know about mapping between Datastore Entity objects * and typed entity objects. * * @author Jeff Schnitzer <jeff@infohazard.org> */ public class EntityMetadata { /** We do not persist fields with any of these modifiers */ static final int BAD_MODIFIERS = Modifier.FINAL | Modifier.STATIC | Modifier.TRANSIENT; /** We need to be able to populate fields and methods with @OldName */ static interface Populator { /** Actually populate the thing (field or method) */ void populate(Object entity, Object value); /** Get the thing for hashing, string conversion, etc */ Object getThing(); /** Get the type of the thing */ Class<?> getType(); } /** Works with fields */ static class FieldPopulator implements Populator { Field field; public FieldPopulator(Field field) { this.field = field; } public Object getThing() { return this.field; } public Class<?> getType() { return this.field.getType(); } public void populate(Object entity, Object value) { try { this.field.set(entity, value); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } } } /** Works with methods */ static class MethodPopulator implements Populator { Method method; public MethodPopulator(Method method) { this.method = method; } public Object getThing() { return this.method; } public Class<?> getType() { return this.method.getParameterTypes()[0]; } public void populate(Object entity, Object value) { try { this.method.invoke(entity, value); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } } private Class<?> entityClass; public Class<?> getEntityClass() { return this.entityClass; } /** The kind that is associated with the class, ala ObjectifyFactory.getKind(Class<?>) */ private String kind; /** We treat the @Id key field specially - it will be either Long id or String name */ private Field idField; private Field nameField; /** If the entity has a @Parent field, treat it specially */ private Field parentField; /** The fields we persist, not including the @Id or @Parebnt fields */ private Set<Field> writeables = new HashSet<Field>(); /** The things that we read, keyed by name (including @OldName fields and methods). A superset of writeables. */ private Map<String, Populator> readables = new HashMap<String, Populator>(); public EntityMetadata(Class<?> clazz) { this.entityClass = clazz; this.kind = ObjectifyFactory.getKind(clazz); // Recursively walk up the inheritance chain looking for fields this.visit(clazz); // There must be some field marked with @Id if (this.idField == null && this.nameField == null) throw new IllegalStateException("There must be an @Id field (String, Long, or long) for " + this.entityClass.getName()); } /** * Recursive function adds any appropriate fields to our internal data * structures for persisting and retreiving later. */ private void visit(Class<?> clazz) { if (clazz == null || clazz == Object.class) return; // Check all the fields for (Field field: clazz.getDeclaredFields()) { if (field.isAnnotationPresent(Transient.class) || (field.getModifiers() & BAD_MODIFIERS) != 0) continue; field.setAccessible(true); if (field.isAnnotationPresent(Id.class)) { if (this.idField != null || this.nameField != null) throw new IllegalStateException("Multiple @Id fields in the class hierarchy of " + this.entityClass.getName()); if (field.getType() == Long.class || field.getType() == Long.TYPE) this.idField = field; else if (field.getType() == String.class) this.nameField = field; else throw new IllegalStateException("Only fields of type Long, long, or String are allowed as @Id. Invalid on field " + field + " in " + clazz.getName()); } else if (field.isAnnotationPresent(Parent.class)) { if (this.parentField != null) throw new IllegalStateException("Multiple @Parent fields in the class hierarchy of " + this.entityClass.getName()); if (field.getType() != Key.class) throw new IllegalStateException("Only fields of type Key are allowed as @Parent. Illegal parent '" + field + "' in " + clazz.getName()); this.parentField = field; } else { this.writeables.add(field); Populator pop = new FieldPopulator(field); this.putReadable(field.getName(), pop); OldName old = field.getAnnotation(OldName.class); if (old != null) this.putReadable(old.value(), pop); } } // Now look for methods with one param that are annotated with @OldName for (Method method: clazz.getDeclaredMethods()) { OldName oldName = method.getAnnotation(OldName.class); if (oldName != null) { if (method.getParameterTypes().length != 1) throw new IllegalStateException("@OldName methods must have a single parameter. Can't use " + method); method.setAccessible(true); this.putReadable(oldName.value(), new MethodPopulator(method)); } } } /** * Adds the key/value pair to this.readables, throwing an exception if there * is a duplicate key. */ private void putReadable(String name, Populator p) { if (this.readables.put(name, p) != null) throw new IllegalStateException( "Data property name '" + name + "' is duplicated in hierarchy of " + this.entityClass.getName() + ". Check for conflicting @OldNames."); } /** * Converts an entity to an object of the appropriate type for this metadata structure. * Does not check that the entity is appropriate; that should be done when choosing * which EntityMetadata to call. */ public Object toObject(Entity ent) { try { Object obj = this.entityClass.newInstance(); // This will set the id and parent fields as appropriate. this.setKey(obj, ent.getKey()); // Keep track of which fields and methods have been done so we don't repeat any; // this could happen if an Entity has data for both @OldName and the current name. Set<Object> done = new HashSet<Object>(); for (Map.Entry<String, Object> property: ent.getProperties().entrySet()) { Populator pop = this.readables.get(property.getKey()); if (pop != null) { // First make sure we haven't already done this one if (done.contains(pop.getThing())) throw new IllegalStateException("Tried to set '" + pop.getThing() + "' twice; check @OldName annotations"); else done.add(pop.getThing()); Object value = property.getValue(); value = this.convert(value, pop.getType()); pop.populate(obj, value); } } return obj; } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } /** * Converts the value into an object suitable for the type (hopefully). */ Object convert(Object value, Class<?> type) { if (value == null || type == value.getClass()) { return value; } else if (type == String.class) { return value.toString(); } else if (value instanceof Number) { Number number = (Number)value; if (type == Byte.class || type == Byte.TYPE) return number.byteValue(); else if (type == Short.class || type == Short.TYPE) return number.shortValue(); else if (type == Integer.class || type == Integer.TYPE) return number.intValue(); else if (type == Long.class || type == Long.TYPE) return number.longValue(); else if (type == Float.class || type == Float.TYPE) return number.floatValue(); else if (type == Double.class || type == Double.TYPE) return number.doubleValue(); } throw new IllegalArgumentException("Don't know how to convert " + value.getClass() + " to " + type); } /** * Converts an object to a datastore Entity with the appropriate Key type. */ public Entity toEntity(Object obj) { try { Entity ent = this.initEntity(obj); for (Field f: this.writeables) { Object value = f.get(obj); if (f.isAnnotationPresent(Indexed.class)) ent.setProperty(f.getName(), value); else ent.setUnindexedProperty(f.getName(), value); } return ent; } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } /** * <p>This hides all the messiness of trying to create an Entity from an object that:</p> * <ul> * <li>Might have a long id, might have a String name</li> * <li>If it's a Long id, might be null and require autogeneration</li> * <li>Might have a parent key</li> * </ul> * <p>Gross, isn't it?</p> */ Entity initEntity(Object obj) { try { Key parentKey = null; // First thing, get the parentKey (if appropriate) if (this.parentField != null) { parentKey = (Key)this.parentField.get(obj); if (parentKey == null) throw new IllegalStateException("Missing parent of " + obj); } if (this.idField != null) { Long id = (Long)this.idField.get(obj); // possibly null if (id != null) { if (this.parentField != null) return new Entity(KeyFactory.createKey(parentKey, this.kind, id)); else return new Entity(KeyFactory.createKey(this.kind, id)); } else // id is null, must autogenerate { if (this.parentField != null) return new Entity(this.kind, parentKey); else return new Entity(this.kind); } } else // this.nameField contains id { String name = (String)this.nameField.get(obj); if (name == null) throw new IllegalStateException("Tried to persist null String @Id for " + obj); if (this.parentField != null) { return new Entity(this.kind, name, parentKey); } else { return new Entity(this.kind, name); } } } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } } /** * Sets the relevant id and parent fields of the object to the values stored in the key. * Object must be of the entityClass type for this metadata. */ public void setKey(Object obj, Key key) { if (obj.getClass() != this.entityClass) throw new IllegalArgumentException("Trying to use metadata for " + this.entityClass.getName() + " to set key of " + obj.getClass().getName()); try { if (key.getName() != null) { if (this.nameField == null) throw new IllegalStateException("Loaded Entity has name but " + this.entityClass.getName() + " has no String @Id"); this.nameField.set(obj, key.getName()); } else { if (this.idField == null) throw new IllegalStateException("Loaded Entity has id but " + this.entityClass.getName() + " has no Long (or long) @Id"); this.idField.set(obj, key.getId()); } Key parentKey = key.getParent(); if (parentKey != null) { if (this.parentField == null) throw new IllegalStateException("Loaded Entity has parent but " + this.entityClass.getName() + " has no @Parent"); this.parentField.set(obj, parentKey); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public Key getKey(Object obj) { if (obj.getClass() != this.entityClass) throw new IllegalArgumentException("Trying to use metadata for " + this.entityClass.getName() + " to get key of " + obj.getClass().getName()); try { if (this.nameField != null) { String name = (String)this.nameField.get(obj); if (this.parentField != null) { Key parent = (Key)this.parentField.get(obj); return KeyFactory.createKey(parent, this.kind, name); } else // name yes parent no { return KeyFactory.createKey(this.kind, name); } } else // has id not name { Long id = (Long)this.idField.get(obj); if (id == null) throw new IllegalArgumentException("You cannot create a Key for an object with a null @Id. Object was " + obj); if (this.parentField != null) { Key parent = (Key)this.parentField.get(obj); return KeyFactory.createKey(parent, this.kind, id); } else // id yes parent no { return KeyFactory.createKey(this.kind, id); } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
package com.googlecode.yatspec.junit; import com.googlecode.totallylazy.Predicate; import com.googlecode.yatspec.state.Result; import com.googlecode.yatspec.state.Scenario; import com.googlecode.yatspec.state.TestResult; import com.googlecode.yatspec.state.givenwhenthen.TestState; import com.googlecode.yatspec.state.givenwhenthen.WithTestState; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.googlecode.totallylazy.Sequences.sequence; import static java.lang.System.getProperty; public class SpecRunner extends TableRunner { public static final String OUTPUT_DIR = "yatspec.output.dir"; private final Result testResult; private Map<String, Scenario> currentScenario = new HashMap<String, Scenario>(); public SpecRunner(Class<?> klass) throws org.junit.runners.model.InitializationError { super(klass); testResult = new TestResult(klass); } @Override protected List<FrameworkMethod> computeTestMethods() { return sequence(super.computeTestMethods()).filter(isNotEvaluateMethod()).toList(); } private static Predicate<FrameworkMethod> isNotEvaluateMethod() { return new Predicate<FrameworkMethod>() { public boolean matches(FrameworkMethod method) { return !method.getName().equals("evaluate"); } }; } private WithCustomResultListeners listeners = new DefaultResultListeners(); @Override protected Object createTest() throws Exception { Object instance = super.createTest(); if (instance instanceof WithCustomResultListeners) { listeners = (WithCustomResultListeners) instance; } else { listeners = new DefaultResultListeners(); } return instance; } @Override public void run(RunNotifier notifier) { final SpecListener listener = new SpecListener(); notifier.addListener(listener); super.run(notifier); notifier.removeListener(listener); try { for (SpecResultListener resultListener : listeners.getResultListeners()) { resultListener.complete(outputDirectory(), testResult); } } catch (Exception e) { System.out.println("Error while writing yatspec output"); e.printStackTrace(System.out); } } public static File outputDirectory() { return new File(getProperty(OUTPUT_DIR, getProperty("java.io.tmpdir"))); } @Override protected Statement methodInvoker(final FrameworkMethod method, final Object test) { final Statement statement = super.methodInvoker(method, test); return new Statement() { @Override public void evaluate() throws Throwable { final String fullyQualifiedTestMethod = test.getClass().getCanonicalName() + "." + method.getName(); final Scenario scenario = testResult.getScenario(method.getName()); currentScenario.put(fullyQualifiedTestMethod, scenario); if (test instanceof WithTestState) { TestState testState = ((WithTestState) test).testState(); currentScenario.get(fullyQualifiedTestMethod).setTestState(testState); } statement.evaluate(); } }; } private final class SpecListener extends RunListener { @Override public void testFailure(Failure failure) throws Exception { String fullyQualifiedTestMethod = failure.getDescription().getClassName() + "." + failure.getDescription().getMethodName(); if (currentScenario.get(fullyQualifiedTestMethod) != null) currentScenario.get(fullyQualifiedTestMethod).setException(failure.getException()); } } }
package com.limewoodMedia.nsapi.holders; public class Embassy { /** * Embassy status */ public enum EmbassyStatus { /** An established embassy */ ESTABLISHED(null), /** An embassy being created */ PENDING("pending"), /** An embassy invitation from another region */ INVITED("invited"), /** An embassy this region requested with another region */ REQUESTED("requested"), /** An requested embassy that was denied recently */ DENIED("denied"), /** An embassy that was recently closed */ CLOSING("closing"); public static EmbassyStatus parse(String description) { for(EmbassyStatus es : values()) { if(description == null) { return ESTABLISHED; } else if(description.equalsIgnoreCase(es.description)) { return es; } } return null; } private String description; private EmbassyStatus(String description) { this.description = description; } public String getDescription() { return description; } }; public String region; public EmbassyStatus status; public Embassy() {} public Embassy(String region, EmbassyStatus status) { this.region = region; this.status = status; } }
package com.mantono.webserver; import java.io.IOException; import java.lang.reflect.Method; import java.net.Socket; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.mantono.webserver.reflection.ClassParser; import com.mantono.webserver.reflection.MethodParser; import com.mantono.webserver.reflection.ResourceFinder; import com.mantono.webserver.rest.Resource; public class ConnectionHandler { private final BlockingQueue<Socket> socketQueue; private final ThreadPoolExecutor threadPool; private final Map<Resource, Method> resources; public ConnectionHandler(final int threads, final BlockingQueue<Socket> socketQueue) throws ClassNotFoundException, IOException { this.socketQueue = socketQueue; BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(100); this.threadPool = new ThreadPoolExecutor(threads/2+1, threads, 5000, TimeUnit.MILLISECONDS, queue); resources = findResources(); for(int i = 0; i < threads; i++) threadPool.execute(new RequestResponder(resources, socketQueue)); } public ConnectionHandler(final int threads, final int queueSize) throws ClassNotFoundException, IOException { this(threads, new ArrayBlockingQueue<Socket>(queueSize)); } private Map<Resource, Method> findResources() throws IOException, ClassNotFoundException { Map<Resource, Method> resourceMap = new HashMap<Resource, Method>(); ResourceFinder finder = new ResourceFinder(); final int found = finder.search(); if(found == 0) { System.err.print("No resources found in classpath System.err.println(System.getProperty("java.class.path")); System.exit(4); } List<Class<?>> classes = finder.getClasses(); for(Class<?> classX : classes) { final ClassParser cp = new ClassParser(classX); final List<Method> methods = cp.getResourceMethods(); final MethodParser methodParser = new MethodParser(methods); resourceMap.putAll(methodParser.getResources()); } return resourceMap; } public BlockingQueue<Socket> getConnectionQueue() { return socketQueue; } }
package com.vaadin.terminal.gwt.client.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Node; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ContextMenuEvent; import com.google.gwt.event.dom.client.ContextMenuHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.BrowserInfo; import com.vaadin.terminal.gwt.client.MouseEventDetails; import com.vaadin.terminal.gwt.client.Paintable; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.Util; import com.vaadin.terminal.gwt.client.ui.dd.DDUtil; import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler; import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback; import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager; import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent; import com.vaadin.terminal.gwt.client.ui.dd.VDropHandler; import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler; import com.vaadin.terminal.gwt.client.ui.dd.VTransferable; import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation; public class VTree extends FocusElementPanel implements Paintable, VHasDropHandler, FocusHandler, BlurHandler, KeyPressHandler, KeyDownHandler, SubPartAware, ActionOwner { public static final String CLASSNAME = "v-tree"; public static final String ITEM_CLICK_EVENT_ID = "itemClick"; public static final int MULTISELECT_MODE_DEFAULT = 0; public static final int MULTISELECT_MODE_SIMPLE = 1; private static final int CHARCODE_SPACE = 32; private final FlowPanel body = new FlowPanel(); private Set<String> selectedIds = new HashSet<String>(); private ApplicationConnection client; private String paintableId; private boolean selectable; private boolean isMultiselect; private String currentMouseOverKey; private TreeNode lastSelection; private TreeNode focusedNode; private int multiSelectMode = MULTISELECT_MODE_DEFAULT; private final HashMap<String, TreeNode> keyToNode = new HashMap<String, TreeNode>(); private final HashMap<String, String> actionMap = new HashMap<String, String>(); private boolean immediate; private boolean isNullSelectionAllowed = true; private boolean disabled = false; private boolean readonly; private boolean rendering; private VAbstractDropHandler dropHandler; private int dragMode; private boolean selectionHasChanged = false; private String[] bodyActionKeys; public VLazyExecutor iconLoaded = new VLazyExecutor(50, new ScheduledCommand() { public void execute() { Util.notifyParentOfSizeChange(VTree.this, true); } }); public VTree() { super(); setStyleName(CLASSNAME); add(body); addFocusHandler(this); addBlurHandler(this); /* * Listen to context menu events on the empty space in the tree */ sinkEvents(Event.ONCONTEXTMENU); addDomHandler(new ContextMenuHandler() { public void onContextMenu(ContextMenuEvent event) { handleBodyContextMenu(event); } }, ContextMenuEvent.getType()); /* * Firefox auto-repeat works correctly only if we use a key press * handler, other browsers handle it correctly when using a key down * handler */ if (BrowserInfo.get().isGecko() || BrowserInfo.get().isOpera()) { addKeyPressHandler(this); } else { addKeyDownHandler(this); } /* * We need to use the sinkEvents method to catch the keyUp events so we * can cache a single shift. KeyUpHandler cannot do this. At the same * time we catch the mouse down and up events so we can apply the text * selection patch in IE */ sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP | Event.ONKEYUP); /* * Re-set the tab index to make sure that the FocusElementPanel's * (super) focus element gets the tab index and not the element * containing the tree. */ setTabIndex(0); } /* * (non-Javadoc) * * @see * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt.user * .client.Event) */ @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); if (event.getTypeInt() == Event.ONMOUSEDOWN) { // Prevent default text selection in IE if (BrowserInfo.get().isIE()) { ((Element) event.getEventTarget().cast()).setPropertyJSO( "onselectstart", applyDisableTextSelectionIEHack()); } } else if (event.getTypeInt() == Event.ONMOUSEUP) { // Remove IE text selection hack if (BrowserInfo.get().isIE()) { ((Element) event.getEventTarget().cast()).setPropertyJSO( "onselectstart", null); } } else if (event.getTypeInt() == Event.ONKEYUP) { if (selectionHasChanged) { if (event.getKeyCode() == getNavigationDownKey() && !event.getShiftKey()) { sendSelectionToServer(); event.preventDefault(); } else if (event.getKeyCode() == getNavigationUpKey() && !event.getShiftKey()) { sendSelectionToServer(); event.preventDefault(); } else if (event.getKeyCode() == KeyCodes.KEY_SHIFT) { sendSelectionToServer(); event.preventDefault(); } else if (event.getKeyCode() == getNavigationSelectKey()) { sendSelectionToServer(); event.preventDefault(); } } } } private void updateActionMap(UIDL c) { final Iterator<?> it = c.getChildIterator(); while (it.hasNext()) { final UIDL action = (UIDL) it.next(); final String key = action.getStringAttribute("key"); final String caption = action.getStringAttribute("caption"); actionMap.put(key + "_c", caption); if (action.hasAttribute("icon")) { // TODO need some uri handling ?? actionMap.put(key + "_i", client.translateVaadinUri(action .getStringAttribute("icon"))); } else { actionMap.remove(key + "_i"); } } } public String getActionCaption(String actionKey) { return actionMap.get(actionKey + "_c"); } public String getActionIcon(String actionKey) { return actionMap.get(actionKey + "_i"); } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // Ensure correct implementation and let container manage caption if (client.updateComponent(this, uidl, true)) { return; } rendering = true; this.client = client; if (uidl.hasAttribute("partialUpdate")) { handleUpdate(uidl); rendering = false; return; } paintableId = uidl.getId(); immediate = uidl.hasAttribute("immediate"); disabled = uidl.getBooleanAttribute("disabled"); readonly = uidl.getBooleanAttribute("readonly"); dragMode = uidl.hasAttribute("dragMode") ? uidl .getIntAttribute("dragMode") : 0; isNullSelectionAllowed = uidl.getBooleanAttribute("nullselect"); if (uidl.hasAttribute("alb")) { bodyActionKeys = uidl.getStringArrayAttribute("alb"); } body.clear(); TreeNode childTree = null; for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) { final UIDL childUidl = (UIDL) i.next(); if ("actions".equals(childUidl.getTag())) { updateActionMap(childUidl); continue; } else if ("-ac".equals(childUidl.getTag())) { updateDropHandler(childUidl); continue; } childTree = new TreeNode(); if (childTree.ie6compatnode != null) { body.add(childTree); } childTree.updateFromUIDL(childUidl, client); if (childTree.ie6compatnode == null) { body.add(childTree); } childTree.addStyleDependentName("root"); childTree.childNodeContainer.addStyleDependentName("root"); } if (childTree != null) { childTree.addStyleDependentName("last"); childTree.childNodeContainer.addStyleDependentName("last"); } final String selectMode = uidl.getStringAttribute("selectmode"); selectable = !"none".equals(selectMode); isMultiselect = "multi".equals(selectMode); if (isMultiselect) { multiSelectMode = uidl.getIntAttribute("multiselectmode"); } selectedIds = uidl.getStringArrayVariableAsSet("selected"); if (lastSelection == null && focusedNode == null && !selectedIds.isEmpty()) { setFocusedNode(keyToNode.get(selectedIds.iterator().next())); focusedNode.setFocused(false); } rendering = false; } /** * Returns the first root node of the tree or null if there are no root * nodes. * * @return The first root {@link TreeNode} */ protected TreeNode getFirstRootNode() { if (body.getWidgetCount() == 0) { return null; } return (TreeNode) body.getWidget(0); } /** * Returns the last root node of the tree or null if there are no root * nodes. * * @return The last root {@link TreeNode} */ protected TreeNode getLastRootNode() { if (body.getWidgetCount() == 0) { return null; } return (TreeNode) body.getWidget(body.getWidgetCount() - 1); } /** * Returns a list of all root nodes in the Tree in the order they appear in * the tree. * * @return A list of all root {@link TreeNode}s. */ protected List<TreeNode> getRootNodes() { ArrayList<TreeNode> rootNodes = new ArrayList<TreeNode>(); for (int i = 0; i < body.getWidgetCount(); i++) { rootNodes.add((TreeNode) body.getWidget(i)); } return rootNodes; } private void updateTreeRelatedDragData(VDragEvent drag) { currentMouseOverKey = findCurrentMouseOverKey(drag.getElementOver()); drag.getDropDetails().put("itemIdOver", currentMouseOverKey); if (currentMouseOverKey != null) { TreeNode treeNode = keyToNode.get(currentMouseOverKey); VerticalDropLocation detail = treeNode.getDropDetail(drag .getCurrentGwtEvent()); Boolean overTreeNode = null; if (treeNode != null && !treeNode.isLeaf() && detail == VerticalDropLocation.MIDDLE) { overTreeNode = true; } drag.getDropDetails().put("itemIdOverIsNode", overTreeNode); drag.getDropDetails().put("detail", detail); } else { drag.getDropDetails().put("itemIdOverIsNode", null); drag.getDropDetails().put("detail", null); } } private String findCurrentMouseOverKey(Element elementOver) { TreeNode treeNode = Util.findWidget(elementOver, TreeNode.class); return treeNode == null ? null : treeNode.key; } private void updateDropHandler(UIDL childUidl) { if (dropHandler == null) { dropHandler = new VAbstractDropHandler() { @Override public void dragEnter(VDragEvent drag) { } @Override protected void dragAccepted(final VDragEvent drag) { } @Override public void dragOver(final VDragEvent currentDrag) { final Object oldIdOver = currentDrag.getDropDetails().get( "itemIdOver"); final VerticalDropLocation oldDetail = (VerticalDropLocation) currentDrag .getDropDetails().get("detail"); updateTreeRelatedDragData(currentDrag); final VerticalDropLocation detail = (VerticalDropLocation) currentDrag .getDropDetails().get("detail"); boolean nodeHasChanged = (currentMouseOverKey != null && currentMouseOverKey != oldIdOver) || (currentMouseOverKey == null && oldIdOver != null); boolean detailHasChanded = (detail != null && detail != oldDetail) || (detail == null && oldDetail != null); if (nodeHasChanged || detailHasChanded) { final String newKey = currentMouseOverKey; TreeNode treeNode = keyToNode.get(oldIdOver); if (treeNode != null) { // clear old styles treeNode.emphasis(null); } if (newKey != null) { validate(new VAcceptCallback() { public void accepted(VDragEvent event) { VerticalDropLocation curDetail = (VerticalDropLocation) event .getDropDetails().get("detail"); if (curDetail == detail && newKey .equals(currentMouseOverKey)) { keyToNode.get(newKey).emphasis(detail); } /* * Else drag is already on a different * node-detail pair, new criteria check is * going on */ } }, currentDrag); } } } @Override public void dragLeave(VDragEvent drag) { cleanUp(); } private void cleanUp() { if (currentMouseOverKey != null) { keyToNode.get(currentMouseOverKey).emphasis(null); currentMouseOverKey = null; } } @Override public boolean drop(VDragEvent drag) { cleanUp(); return super.drop(drag); } @Override public Paintable getPaintable() { return VTree.this; } public ApplicationConnection getApplicationConnection() { return client; } }; } dropHandler.updateAcceptRules(childUidl); } private void handleUpdate(UIDL uidl) { final TreeNode rootNode = keyToNode.get(uidl .getStringAttribute("rootKey")); if (rootNode != null) { if (!rootNode.getState()) { // expanding node happened server side rootNode.setState(true, false); } rootNode.renderChildNodes(uidl.getChildIterator()); } } public void setSelected(TreeNode treeNode, boolean selected) { if (selected) { if (!isMultiselect) { while (selectedIds.size() > 0) { final String id = selectedIds.iterator().next(); final TreeNode oldSelection = keyToNode.get(id); if (oldSelection != null) { // can be null if the node is not visible (parent // collapsed) oldSelection.setSelected(false); } selectedIds.remove(id); } } treeNode.setSelected(true); selectedIds.add(treeNode.key); } else { if (!isNullSelectionAllowed) { if (!isMultiselect || selectedIds.size() == 1) { return; } } selectedIds.remove(treeNode.key); treeNode.setSelected(false); } sendSelectionToServer(); } /** * Sends the selection to the server */ private void sendSelectionToServer() { client.updateVariable(paintableId, "selected", selectedIds .toArray(new String[selectedIds.size()]), immediate); selectionHasChanged = false; } /** * Is a node selected in the tree * * @param treeNode * The node to check * @return */ public boolean isSelected(TreeNode treeNode) { return selectedIds.contains(treeNode.key); } public class TreeNode extends SimplePanel implements ActionOwner { public static final String CLASSNAME = "v-tree-node"; public static final String CLASSNAME_FOCUSED = CLASSNAME + "-focused"; public String key; private String[] actionKeys = null; private boolean childrenLoaded; private Element nodeCaptionDiv; protected Element nodeCaptionSpan; private FlowPanel childNodeContainer; private boolean open; private Icon icon; private Element ie6compatnode; private Event mouseDownEvent; private int cachedHeight = -1; private boolean focused = false; /** * Track onload events as IE6 sends two */ private boolean onloadHandled = false; public TreeNode() { constructDom(); sinkEvents(Event.ONCLICK | Event.ONDBLCLICK | Event.MOUSEEVENTS | Event.TOUCHEVENTS | Event.ONCONTEXTMENU); } public VerticalDropLocation getDropDetail(NativeEvent currentGwtEvent) { if (cachedHeight < 0) { /* * Height is cached to avoid flickering (drop hints may change * the reported offsetheight -> would change the drop detail) */ cachedHeight = nodeCaptionDiv.getOffsetHeight(); } VerticalDropLocation verticalDropLocation = DDUtil .getVerticalDropLocation(nodeCaptionDiv, cachedHeight, currentGwtEvent, 0.15); return verticalDropLocation; } protected void emphasis(VerticalDropLocation detail) { String base = "v-tree-node-drag-"; UIObject.setStyleName(getElement(), base + "top", VerticalDropLocation.TOP == detail); UIObject.setStyleName(getElement(), base + "bottom", VerticalDropLocation.BOTTOM == detail); UIObject.setStyleName(getElement(), base + "center", VerticalDropLocation.MIDDLE == detail); base = "v-tree-node-caption-drag-"; UIObject.setStyleName(nodeCaptionDiv, base + "top", VerticalDropLocation.TOP == detail); UIObject.setStyleName(nodeCaptionDiv, base + "bottom", VerticalDropLocation.BOTTOM == detail); UIObject.setStyleName(nodeCaptionDiv, base + "center", VerticalDropLocation.MIDDLE == detail); // also add classname to "folder node" into which the drag is // targeted TreeNode folder = null; /* Possible parent of this TreeNode will be stored here */ TreeNode parentFolder = getParentNode(); // TODO fix my bugs if (isLeaf()) { folder = parentFolder; // note, parent folder may be null if this is root node => no // folder target exists } else { if (detail == VerticalDropLocation.TOP) { folder = parentFolder; } else { folder = this; } // ensure we remove the dragfolder classname from the previous // folder node setDragFolderStyleName(this, false); setDragFolderStyleName(parentFolder, false); } if (folder != null) { setDragFolderStyleName(folder, detail != null); } } private TreeNode getParentNode() { Widget parent2 = getParent().getParent(); if (parent2 instanceof TreeNode) { return (TreeNode) parent2; } return null; } private void setDragFolderStyleName(TreeNode folder, boolean add) { if (folder != null) { UIObject.setStyleName(folder.getElement(), "v-tree-node-dragfolder", add); UIObject.setStyleName(folder.nodeCaptionDiv, "v-tree-node-caption-dragfolder", add); } } /** * Handles mouse selection * * @param ctrl * Was the ctrl-key pressed * @param shift * Was the shift-key pressed * @return Returns true if event was handled, else false */ private boolean handleClickSelection(final boolean ctrl, final boolean shift) { // always when clicking an item, focus it setFocusedNode(this, false); if (!isIE6OrOpera()) { /* * Ensure that the tree's focus element also gains focus * (TreeNodes focus is faked using FocusElementPanel in browsers * other than IE6 and Opera). */ focus(); } ScheduledCommand command = new ScheduledCommand() { public void execute() { if (multiSelectMode == MULTISELECT_MODE_SIMPLE || !isMultiselect) { toggleSelection(); lastSelection = TreeNode.this; } else if (multiSelectMode == MULTISELECT_MODE_DEFAULT) { // Handle ctrl+click if (isMultiselect && ctrl && !shift) { toggleSelection(); lastSelection = TreeNode.this; // Handle shift+click } else if (isMultiselect && !ctrl && shift) { deselectAll(); selectNodeRange(lastSelection.key, key); sendSelectionToServer(); // Handle ctrl+shift click } else if (isMultiselect && ctrl && shift) { selectNodeRange(lastSelection.key, key); // Handle click } else { // TODO should happen only if this alone not yet // selected, // now sending excess server calls deselectAll(); toggleSelection(); lastSelection = TreeNode.this; } } } }; if (BrowserInfo.get().isWebkit() && !treeHasFocus) { /* * Safari may need to wait for focus. See FocusImplSafari. */ // VConsole.log("Deferring click handling to let webkit gain focus..."); Scheduler.get().scheduleDeferred(command); } else { command.execute(); } return true; } /* * (non-Javadoc) * * @see * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt * .user.client.Event) */ @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); final int type = DOM.eventGetType(event); final Element target = DOM.eventGetTarget(event); if (type == Event.ONLOAD && target == icon.getElement()) { if (onloadHandled) { return; } if (BrowserInfo.get().isIE6()) { fixWidth(); } iconLoaded.trigger(); onloadHandled = true; } if (disabled) { return; } final boolean inCaption = target == nodeCaptionSpan || (icon != null && target == icon.getElement()); if (inCaption && client .hasEventListeners(VTree.this, ITEM_CLICK_EVENT_ID) && (type == Event.ONDBLCLICK || type == Event.ONMOUSEUP)) { fireClick(event); } if (type == Event.ONCLICK) { if (getElement() == target || ie6compatnode == target) { // state change toggleState(); } else if (!readonly && inCaption) { if (selectable) { // caption click = selection change && possible click // event if (handleClickSelection(event.getCtrlKey() || event.getMetaKey(), event.getShiftKey())) { event.preventDefault(); } } else { // Not selectable, only focus the node. setFocusedNode(this); } } event.stopPropagation(); } else if (type == Event.ONCONTEXTMENU) { showContextMenu(event); } if (dragMode != 0 || dropHandler != null) { if (type == Event.ONMOUSEDOWN || type == Event.ONTOUCHSTART) { if (nodeCaptionDiv.isOrHasChild((Node) event .getEventTarget().cast())) { if (dragMode > 0 && (type == Event.ONTOUCHSTART || event .getButton() == NativeEvent.BUTTON_LEFT)) { mouseDownEvent = event; // save event for possible // dd operation if (type == Event.ONMOUSEDOWN) { event.preventDefault(); // prevent text // selection } else { /* * FIXME We prevent touch start event to be used * as a scroll start event. Note that we cannot * easily distinguish whether the user wants to * drag or scroll. The same issue is in table * that has scrollable area and has drag and * drop enable. Some kind of timer might be used * to resolve the issue. */ event.stopPropagation(); } } } } else if (type == Event.ONMOUSEMOVE || type == Event.ONMOUSEOUT || type == Event.ONTOUCHMOVE) { if (mouseDownEvent != null) { // start actual drag on slight move when mouse is down VTransferable t = new VTransferable(); t.setDragSource(VTree.this); t.setData("itemId", key); VDragEvent drag = VDragAndDropManager.get().startDrag( t, mouseDownEvent, true); drag.createDragImage(nodeCaptionDiv, true); event.stopPropagation(); mouseDownEvent = null; } } else if (type == Event.ONMOUSEUP) { mouseDownEvent = null; } if (type == Event.ONMOUSEOVER) { mouseDownEvent = null; currentMouseOverKey = key; event.stopPropagation(); } } else if (type == Event.ONMOUSEDOWN && event.getButton() == NativeEvent.BUTTON_LEFT) { event.preventDefault(); // text selection } } private void fireClick(final Event evt) { /* * Ensure we have focus in tree before sending variables. Otherwise * previously modified field may contain dirty variables. */ if (!treeHasFocus) { if (isIE6OrOpera()) { if (focusedNode == null) { getNodeByKey(key).setFocused(true); } else { focusedNode.setFocused(true); } } else { focus(); } } final MouseEventDetails details = new MouseEventDetails(evt); ScheduledCommand command = new ScheduledCommand() { public void execute() { // non-immediate iff an immediate select event is going to // happen boolean imm = !immediate || !selectable || (!isNullSelectionAllowed && isSelected() && selectedIds .size() == 1); client .updateVariable(paintableId, "clickedKey", key, false); client.updateVariable(paintableId, "clickEvent", details .toString(), imm); } }; if (treeHasFocus) { command.execute(); } else { /* * Webkits need a deferring due to FocusImplSafari uses timeout */ Scheduler.get().scheduleDeferred(command); } } private void toggleSelection() { if (selectable) { VTree.this.setSelected(this, !isSelected()); } } private void toggleState() { setState(!getState(), true); } protected void constructDom() { addStyleName(CLASSNAME); // workaround for a very weird IE6 issue #1245 if (BrowserInfo.get().isIE6()) { ie6compatnode = DOM.createDiv(); setStyleName(ie6compatnode, CLASSNAME + "-ie6compatnode"); DOM.setInnerText(ie6compatnode, " "); DOM.appendChild(getElement(), ie6compatnode); DOM.sinkEvents(ie6compatnode, Event.ONCLICK); } nodeCaptionDiv = DOM.createDiv(); DOM.setElementProperty(nodeCaptionDiv, "className", CLASSNAME + "-caption"); Element wrapper = DOM.createDiv(); nodeCaptionSpan = DOM.createSpan(); DOM.appendChild(getElement(), nodeCaptionDiv); DOM.appendChild(nodeCaptionDiv, wrapper); DOM.appendChild(wrapper, nodeCaptionSpan); if (isIE6OrOpera()) { /* * Focus the caption div of the node to get keyboard navigation * to work without scrolling up or down when focusing a node. */ nodeCaptionDiv.setTabIndex(-1); } childNodeContainer = new FlowPanel(); childNodeContainer.setStyleName(CLASSNAME + "-children"); setWidget(childNodeContainer); } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { setText(uidl.getStringAttribute("caption")); key = uidl.getStringAttribute("key"); keyToNode.put(key, this); if (uidl.hasAttribute("al")) { actionKeys = uidl.getStringArrayAttribute("al"); } if (uidl.getTag().equals("node")) { if (uidl.getChildCount() == 0) { childNodeContainer.setVisible(false); } else { renderChildNodes(uidl.getChildIterator()); childrenLoaded = true; } } else { addStyleName(CLASSNAME + "-leaf"); } if (uidl.hasAttribute("style")) { addStyleName(CLASSNAME + "-" + uidl.getStringAttribute("style")); Widget.setStyleName(nodeCaptionDiv, CLASSNAME + "-caption-" + uidl.getStringAttribute("style"), true); childNodeContainer.addStyleName(CLASSNAME + "-children-" + uidl.getStringAttribute("style")); } if (uidl.getBooleanAttribute("expanded") && !getState()) { setState(true, false); } if (uidl.getBooleanAttribute("selected")) { setSelected(true); // ensure that identifier is in selectedIds array (this may be a // partial update) selectedIds.add(key); } if (uidl.hasAttribute("icon")) { if (icon == null) { onloadHandled = false; icon = new Icon(client); DOM.insertBefore(DOM.getFirstChild(nodeCaptionDiv), icon .getElement(), nodeCaptionSpan); } icon.setUri(uidl.getStringAttribute("icon")); } else { if (icon != null) { DOM.removeChild(DOM.getFirstChild(nodeCaptionDiv), icon .getElement()); icon = null; } } if (BrowserInfo.get().isIE6() && isAttached()) { fixWidth(); } } public boolean isLeaf() { return getStyleName().contains("leaf"); } private void setState(boolean state, boolean notifyServer) { if (open == state) { return; } if (state) { if (!childrenLoaded && notifyServer) { client.updateVariable(paintableId, "requestChildTree", true, false); } if (notifyServer) { client.updateVariable(paintableId, "expand", new String[] { key }, true); } addStyleName(CLASSNAME + "-expanded"); childNodeContainer.setVisible(true); } else { removeStyleName(CLASSNAME + "-expanded"); childNodeContainer.setVisible(false); if (notifyServer) { client.updateVariable(paintableId, "collapse", new String[] { key }, true); } } open = state; if (!rendering) { Util.notifyParentOfSizeChange(VTree.this, false); } } private boolean getState() { return open; } private void setText(String text) { DOM.setInnerText(nodeCaptionSpan, text); } private void renderChildNodes(Iterator<?> i) { childNodeContainer.clear(); childNodeContainer.setVisible(true); while (i.hasNext()) { final UIDL childUidl = (UIDL) i.next(); // actions are in bit weird place, don't mix them with children, // but current node's actions if ("actions".equals(childUidl.getTag())) { updateActionMap(childUidl); continue; } final TreeNode childTree = new TreeNode(); if (ie6compatnode != null) { childNodeContainer.add(childTree); } childTree.updateFromUIDL(childUidl, client); if (ie6compatnode == null) { childNodeContainer.add(childTree); } if (!i.hasNext()) { childTree.addStyleDependentName(childTree.isLeaf() ? "leaf-last" : "last"); childTree.childNodeContainer.addStyleDependentName("last"); } } childrenLoaded = true; } public boolean isChildrenLoaded() { return childrenLoaded; } /** * Returns the children of the node * * @return A set of tree nodes */ public List<TreeNode> getChildren() { List<TreeNode> nodes = new LinkedList<TreeNode>(); if (!isLeaf() && isChildrenLoaded()) { Iterator<Widget> iter = childNodeContainer.iterator(); while (iter.hasNext()) { TreeNode node = (TreeNode) iter.next(); nodes.add(node); } } return nodes; } public Action[] getActions() { if (actionKeys == null) { return new Action[] {}; } final Action[] actions = new Action[actionKeys.length]; for (int i = 0; i < actions.length; i++) { final String actionKey = actionKeys[i]; final TreeAction a = new TreeAction(this, String.valueOf(key), actionKey); a.setCaption(getActionCaption(actionKey)); a.setIconUrl(getActionIcon(actionKey)); actions[i] = a; } return actions; } public ApplicationConnection getClient() { return client; } public String getPaintableId() { return paintableId; } /** * Adds/removes Vaadin specific style name. This method ought to be * called only from VTree. * * @param selected */ protected void setSelected(boolean selected) { // add style name to caption dom structure only, not to subtree setStyleName(nodeCaptionDiv, "v-tree-node-selected", selected); } protected boolean isSelected() { return VTree.this.isSelected(this); } /** * Travels up the hierarchy looking for this node * * @param child * The child which grandparent this is or is not * @return True if this is a grandparent of the child node */ public boolean isGrandParentOf(TreeNode child) { TreeNode currentNode = child; boolean isGrandParent = false; while (currentNode != null) { currentNode = currentNode.getParentNode(); if (currentNode == this) { isGrandParent = true; break; } } return isGrandParent; } public boolean isSibling(TreeNode node) { return node.getParentNode() == getParentNode(); } public void showContextMenu(Event event) { if (!readonly && !disabled) { if (actionKeys != null) { int left = event.getClientX(); int top = event.getClientY(); top += Window.getScrollTop(); left += Window.getScrollLeft(); client.getContextMenu().showAt(this, left, top); } event.stopPropagation(); event.preventDefault(); } } /* * We need to fix the width of TreeNodes so that the float in * ie6compatNode does not wrap (see ticket #1245) */ private void fixWidth() { nodeCaptionDiv.getStyle().setProperty("styleFloat", "left"); nodeCaptionDiv.getStyle().setProperty("display", "inline"); nodeCaptionDiv.getStyle().setProperty("marginLeft", "0"); final int captionWidth = ie6compatnode.getOffsetWidth() + nodeCaptionDiv.getOffsetWidth(); setWidth(captionWidth + "px"); } /* * (non-Javadoc) * * @see com.google.gwt.user.client.ui.Widget#onAttach() */ @Override public void onAttach() { super.onAttach(); if (ie6compatnode != null) { fixWidth(); } } /* * (non-Javadoc) * * @see com.google.gwt.user.client.ui.Widget#onDetach() */ @Override protected void onDetach() { super.onDetach(); client.getContextMenu().ensureHidden(this); } /* * (non-Javadoc) * * @see com.google.gwt.user.client.ui.UIObject#toString() */ @Override public String toString() { return nodeCaptionSpan.getInnerText(); } /** * Is the node focused? * * @param focused * True if focused, false if not */ public void setFocused(boolean focused) { if (!this.focused && focused) { nodeCaptionDiv.addClassName(CLASSNAME_FOCUSED); if (BrowserInfo.get().isIE6()) { ie6compatnode.addClassName(CLASSNAME_FOCUSED); } this.focused = focused; if (isIE6OrOpera()) { nodeCaptionDiv.focus(); } treeHasFocus = true; } else if (this.focused && !focused) { nodeCaptionDiv.removeClassName(CLASSNAME_FOCUSED); if (BrowserInfo.get().isIE6()) { ie6compatnode.removeClassName(CLASSNAME_FOCUSED); } this.focused = focused; treeHasFocus = false; } } /** * Scrolls the caption into view */ public void scrollIntoView() { nodeCaptionDiv.scrollIntoView(); } } public VDropHandler getDropHandler() { return dropHandler; } public TreeNode getNodeByKey(String key) { return keyToNode.get(key); } /** * Deselects all items in the tree */ public void deselectAll() { for (String key : selectedIds) { TreeNode node = keyToNode.get(key); if (node != null) { node.setSelected(false); } } selectedIds.clear(); selectionHasChanged = true; } /** * Selects a range of nodes * * @param startNodeKey * The start node key * @param endNodeKey * The end node key */ private void selectNodeRange(String startNodeKey, String endNodeKey) { TreeNode startNode = keyToNode.get(startNodeKey); TreeNode endNode = keyToNode.get(endNodeKey); // The nodes have the same parent if (startNode.getParent() == endNode.getParent()) { doSiblingSelection(startNode, endNode); // The start node is a grandparent of the end node } else if (startNode.isGrandParentOf(endNode)) { doRelationSelection(startNode, endNode); // The end node is a grandparent of the start node } else if (endNode.isGrandParentOf(startNode)) { doRelationSelection(endNode, startNode); } else { doNoRelationSelection(startNode, endNode); } } /** * Selects a node and deselect all other nodes * * @param node * The node to select */ private void selectNode(TreeNode node, boolean deselectPrevious) { if (deselectPrevious) { deselectAll(); } if (node != null) { node.setSelected(true); selectedIds.add(node.key); lastSelection = node; } selectionHasChanged = true; } /** * Deselects a node * * @param node * The node to deselect */ private void deselectNode(TreeNode node) { node.setSelected(false); selectedIds.remove(node.key); selectionHasChanged = true; } /** * Selects all the open children to a node * * @param node * The parent node */ private void selectAllChildren(TreeNode node, boolean includeRootNode) { if (includeRootNode) { node.setSelected(true); selectedIds.add(node.key); } for (TreeNode child : node.getChildren()) { if (!child.isLeaf() && child.getState()) { selectAllChildren(child, true); } else { child.setSelected(true); selectedIds.add(child.key); } } selectionHasChanged = true; } /** * Selects all children until a stop child is reached * * @param root * The root not to start from * @param stopNode * The node to finish with * @param includeRootNode * Should the root node be selected * @param includeStopNode * Should the stop node be selected * * @return Returns false if the stop child was found, else true if all * children was selected */ private boolean selectAllChildrenUntil(TreeNode root, TreeNode stopNode, boolean includeRootNode, boolean includeStopNode) { if (includeRootNode) { root.setSelected(true); selectedIds.add(root.key); } if (root.getState() && root != stopNode) { for (TreeNode child : root.getChildren()) { if (!child.isLeaf() && child.getState() && child != stopNode) { if (!selectAllChildrenUntil(child, stopNode, true, includeStopNode)) { return false; } } else if (child == stopNode) { if (includeStopNode) { child.setSelected(true); selectedIds.add(child.key); } return false; } else if (child.isLeaf()) { child.setSelected(true); selectedIds.add(child.key); } } } selectionHasChanged = true; return true; } /** * Select a range between two nodes which have no relation to each other * * @param startNode * The start node to start the selection from * @param endNode * The end node to end the selection to */ private void doNoRelationSelection(TreeNode startNode, TreeNode endNode) { TreeNode commonParent = getCommonGrandParent(startNode, endNode); TreeNode startBranch = null, endBranch = null; // Find the children of the common parent List<TreeNode> children; if (commonParent != null) { children = commonParent.getChildren(); } else { children = getRootNodes(); } // Find the start and end branches for (TreeNode node : children) { if (nodeIsInBranch(startNode, node)) { startBranch = node; } if (nodeIsInBranch(endNode, node)) { endBranch = node; } } // Swap nodes if necessary if (children.indexOf(startBranch) > children.indexOf(endBranch)) { TreeNode temp = startBranch; startBranch = endBranch; endBranch = temp; temp = startNode; startNode = endNode; endNode = temp; } // Select all children under the start node selectAllChildren(startNode, true); TreeNode startParent = startNode.getParentNode(); TreeNode currentNode = startNode; while (startParent != null && startParent != commonParent) { List<TreeNode> startChildren = startParent.getChildren(); for (int i = startChildren.indexOf(currentNode) + 1; i < startChildren .size(); i++) { selectAllChildren(startChildren.get(i), true); } currentNode = startParent; startParent = startParent.getParentNode(); } // Select nodes until the end node is reached for (int i = children.indexOf(startBranch) + 1; i <= children .indexOf(endBranch); i++) { selectAllChildrenUntil(children.get(i), endNode, true, true); } // Ensure end node was selected endNode.setSelected(true); selectedIds.add(endNode.key); selectionHasChanged = true; } /** * Examines the children of the branch node and returns true if a node is in * that branch * * @param node * The node to search for * @param branch * The branch to search in * @return True if found, false if not found */ private boolean nodeIsInBranch(TreeNode node, TreeNode branch) { if (node == branch) { return true; } for (TreeNode child : branch.getChildren()) { if (child == node) { return true; } if (!child.isLeaf() && child.getState()) { if (nodeIsInBranch(node, child)) { return true; } } } return false; } /** * Selects a range of items which are in direct relation with each other.<br/> * NOTE: The start node <b>MUST</b> be before the end node! * * @param startNode * * @param endNode */ private void doRelationSelection(TreeNode startNode, TreeNode endNode) { TreeNode currentNode = endNode; while (currentNode != startNode) { currentNode.setSelected(true); selectedIds.add(currentNode.key); // Traverse children above the selection List<TreeNode> subChildren = currentNode.getParentNode() .getChildren(); if (subChildren.size() > 1) { selectNodeRange(subChildren.iterator().next().key, currentNode.key); } else if (subChildren.size() == 1) { TreeNode n = subChildren.get(0); n.setSelected(true); selectedIds.add(n.key); } currentNode = currentNode.getParentNode(); } startNode.setSelected(true); selectedIds.add(startNode.key); selectionHasChanged = true; } /** * Selects a range of items which have the same parent. * * @param startNode * The start node * @param endNode * The end node */ private void doSiblingSelection(TreeNode startNode, TreeNode endNode) { TreeNode parent = startNode.getParentNode(); List<TreeNode> children; if (parent == null) { // Topmost parent children = getRootNodes(); } else { children = parent.getChildren(); } // Swap start and end point if needed if (children.indexOf(startNode) > children.indexOf(endNode)) { TreeNode temp = startNode; startNode = endNode; endNode = temp; } Iterator<TreeNode> childIter = children.iterator(); boolean startFound = false; while (childIter.hasNext()) { TreeNode node = childIter.next(); if (node == startNode) { startFound = true; } if (startFound && node != endNode && node.getState()) { selectAllChildren(node, true); } else if (startFound && node != endNode) { node.setSelected(true); selectedIds.add(node.key); } if (node == endNode) { node.setSelected(true); selectedIds.add(node.key); break; } } selectionHasChanged = true; } /** * Returns the first common parent of two nodes * * @param node1 * The first node * @param node2 * The second node * @return The common parent or null */ public TreeNode getCommonGrandParent(TreeNode node1, TreeNode node2) { // If either one does not have a grand parent then return null if (node1.getParentNode() == null || node2.getParentNode() == null) { return null; } // If the nodes are parents of each other then return null if (node1.isGrandParentOf(node2) || node2.isGrandParentOf(node1)) { return null; } // Get parents of node1 List<TreeNode> parents1 = new ArrayList<TreeNode>(); TreeNode parent1 = node1.getParentNode(); while (parent1 != null) { parents1.add(parent1); parent1 = parent1.getParentNode(); } // Get parents of node2 List<TreeNode> parents2 = new ArrayList<TreeNode>(); TreeNode parent2 = node2.getParentNode(); while (parent2 != null) { parents2.add(parent2); parent2 = parent2.getParentNode(); } // Search the parents for the first common parent for (int i = 0; i < parents1.size(); i++) { parent1 = parents1.get(i); for (int j = 0; j < parents2.size(); j++) { parent2 = parents2.get(j); if (parent1 == parent2) { return parent1; } } } return null; } /** * Sets the node currently in focus * * @param node * The node to focus or null to remove the focus completely * @param scrollIntoView * Scroll the node into view */ public void setFocusedNode(TreeNode node, boolean scrollIntoView) { // Unfocus previously focused node if (focusedNode != null) { focusedNode.setFocused(false); } if (node != null) { node.setFocused(true); } focusedNode = node; if (node != null && scrollIntoView) { /* * Delay scrolling the focused node into view if we are still * rendering. #5396 */ if (!rendering) { node.scrollIntoView(); } else { Scheduler.get().scheduleDeferred(new Command() { public void execute() { focusedNode.scrollIntoView(); } }); } } } /** * Focuses a node and scrolls it into view * * @param node * The node to focus */ public void setFocusedNode(TreeNode node) { setFocusedNode(node, true); } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event * .dom.client.FocusEvent) */ public void onFocus(FocusEvent event) { treeHasFocus = true; // If no node has focus, focus the first item in the tree if (focusedNode == null && lastSelection == null && selectable) { setFocusedNode(getFirstRootNode(), false); } else if (focusedNode != null && selectable) { setFocusedNode(focusedNode, false); } else if (lastSelection != null && selectable) { setFocusedNode(lastSelection, false); } } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event * .dom.client.BlurEvent) */ public void onBlur(BlurEvent event) { treeHasFocus = false; if (focusedNode != null) { focusedNode.setFocused(false); } } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google * .gwt.event.dom.client.KeyPressEvent) */ public void onKeyPress(KeyPressEvent event) { NativeEvent nativeEvent = event.getNativeEvent(); int keyCode = nativeEvent.getKeyCode(); if (keyCode == 0 && nativeEvent.getCharCode() == ' ') { // Provide a keyCode for space to be compatible with FireFox // keypress event keyCode = CHARCODE_SPACE; } if (handleKeyNavigation(keyCode, event.isControlKeyDown() || event.isMetaKeyDown(), event.isShiftKeyDown())) { event.preventDefault(); event.stopPropagation(); } } /* * (non-Javadoc) * * @see * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt * .event.dom.client.KeyDownEvent) */ public void onKeyDown(KeyDownEvent event) { if (handleKeyNavigation(event.getNativeEvent().getKeyCode(), event .isControlKeyDown() || event.isMetaKeyDown(), event.isShiftKeyDown())) { event.preventDefault(); event.stopPropagation(); } } /** * Handles the keyboard navigation * * @param keycode * The keycode of the pressed key * @param ctrl * Was ctrl pressed * @param shift * Was shift pressed * @return Returns true if the key was handled, else false */ protected boolean handleKeyNavigation(int keycode, boolean ctrl, boolean shift) { // Navigate down if (keycode == getNavigationDownKey()) { TreeNode node = null; // If node is open and has children then move in to the children if (!focusedNode.isLeaf() && focusedNode.getState() && focusedNode.getChildren().size() > 0) { node = focusedNode.getChildren().get(0); } // Else move down to the next sibling else { node = getNextSibling(focusedNode); if (node == null) { // Else jump to the parent and try to select the next // sibling there TreeNode current = focusedNode; while (node == null && current.getParentNode() != null) { node = getNextSibling(current.getParentNode()); current = current.getParentNode(); } } } if (node != null) { setFocusedNode(node); if (selectable) { if (!ctrl && !shift) { selectNode(node, true); } else if (shift && isMultiselect) { deselectAll(); selectNodeRange(lastSelection.key, node.key); } else if (shift) { selectNode(node, true); } } } return true; } // Navigate up if (keycode == getNavigationUpKey()) { TreeNode prev = getPreviousSibling(focusedNode); TreeNode node = null; if (prev != null) { node = getLastVisibleChildInTree(prev); } else if (focusedNode.getParentNode() != null) { node = focusedNode.getParentNode(); } if (node != null) { setFocusedNode(node); if (selectable) { if (!ctrl && !shift) { selectNode(node, true); } else if (shift && isMultiselect) { deselectAll(); selectNodeRange(lastSelection.key, node.key); } else if (shift) { selectNode(node, true); } } } return true; } // Navigate left (close branch) if (keycode == getNavigationLeftKey()) { if (!focusedNode.isLeaf() && focusedNode.getState()) { focusedNode.setState(false, true); } else if (focusedNode.getParentNode() != null && (focusedNode.isLeaf() || !focusedNode.getState())) { if (ctrl || !selectable) { setFocusedNode(focusedNode.getParentNode()); } else if (shift) { doRelationSelection(focusedNode.getParentNode(), focusedNode); setFocusedNode(focusedNode.getParentNode()); } else { focusAndSelectNode(focusedNode.getParentNode()); } } return true; } // Navigate right (open branch) if (keycode == getNavigationRightKey()) { if (!focusedNode.isLeaf() && !focusedNode.getState()) { focusedNode.setState(true, true); } else if (!focusedNode.isLeaf()) { if (ctrl || !selectable) { setFocusedNode(focusedNode.getChildren().get(0)); } else if (shift) { setSelected(focusedNode, true); setFocusedNode(focusedNode.getChildren().get(0)); setSelected(focusedNode, true); } else { focusAndSelectNode(focusedNode.getChildren().get(0)); } } return true; } // Selection if (keycode == getNavigationSelectKey()) { if (!focusedNode.isSelected()) { selectNode( focusedNode, (!isMultiselect || multiSelectMode == MULTISELECT_MODE_SIMPLE) && selectable); } else { deselectNode(focusedNode); } return true; } // Home selection if (keycode == getNavigationStartKey()) { TreeNode node = getFirstRootNode(); if (ctrl || !selectable) { setFocusedNode(node); } else if (shift) { deselectAll(); selectNodeRange(focusedNode.key, node.key); } else { selectNode(node, true); } sendSelectionToServer(); return true; } // End selection if (keycode == getNavigationEndKey()) { TreeNode lastNode = getLastRootNode(); TreeNode node = getLastVisibleChildInTree(lastNode); if (ctrl || !selectable) { setFocusedNode(node); } else if (shift) { deselectAll(); selectNodeRange(focusedNode.key, node.key); } else { selectNode(node, true); } sendSelectionToServer(); return true; } return false; } private void focusAndSelectNode(TreeNode node) { /* * Keyboard navigation doesn't work reliably if the tree is in * multiselect mode as well as isNullSelectionAllowed = false. It first * tries to deselect the old focused node, which fails since there must * be at least one selection. After this the newly focused node is * selected and we've ended up with two selected nodes even though we * only navigated with the arrow keys. * * Because of this, we first select the next node and later de-select * the old one. */ TreeNode oldFocusedNode = focusedNode; setFocusedNode(node); setSelected(focusedNode, true); setSelected(oldFocusedNode, false); } /** * Traverses the tree to the bottom most child * * @param root * The root of the tree * @return The bottom most child */ private TreeNode getLastVisibleChildInTree(TreeNode root) { if (root.isLeaf() || !root.getState() || root.getChildren().size() == 0) { return root; } List<TreeNode> children = root.getChildren(); return getLastVisibleChildInTree(children.get(children.size() - 1)); } /** * Gets the next sibling in the tree * * @param node * The node to get the sibling for * @return The sibling node or null if the node is the last sibling */ private TreeNode getNextSibling(TreeNode node) { TreeNode parent = node.getParentNode(); List<TreeNode> children; if (parent == null) { children = getRootNodes(); } else { children = parent.getChildren(); } int idx = children.indexOf(node); if (idx < children.size() - 1) { return children.get(idx + 1); } return null; } /** * Returns the previous sibling in the tree * * @param node * The node to get the sibling for * @return The sibling node or null if the node is the first sibling */ private TreeNode getPreviousSibling(TreeNode node) { TreeNode parent = node.getParentNode(); List<TreeNode> children; if (parent == null) { children = getRootNodes(); } else { children = parent.getChildren(); } int idx = children.indexOf(node); if (idx > 0) { return children.get(idx - 1); } return null; } /** * Add this to the element mouse down event by using element.setPropertyJSO * ("onselectstart",applyDisableTextSelectionIEHack()); Remove it then again * when the mouse is depressed in the mouse up event. * * @return Returns the JSO preventing text selection */ private native JavaScriptObject applyDisableTextSelectionIEHack() /*-{ return function(){ return false; }; }-*/; /** * Get the key that moves the selection head upwards. By default it is the * up arrow key but by overriding this you can change the key to whatever * you want. * * @return The keycode of the key */ protected int getNavigationUpKey() { return KeyCodes.KEY_UP; } /** * Get the key that moves the selection head downwards. By default it is the * down arrow key but by overriding this you can change the key to whatever * you want. * * @return The keycode of the key */ protected int getNavigationDownKey() { return KeyCodes.KEY_DOWN; } /** * Get the key that scrolls to the left in the table. By default it is the * left arrow key but by overriding this you can change the key to whatever * you want. * * @return The keycode of the key */ protected int getNavigationLeftKey() { return KeyCodes.KEY_LEFT; } /** * Get the key that scroll to the right on the table. By default it is the * right arrow key but by overriding this you can change the key to whatever * you want. * * @return The keycode of the key */ protected int getNavigationRightKey() { return KeyCodes.KEY_RIGHT; } /** * Get the key that selects an item in the table. By default it is the space * bar key but by overriding this you can change the key to whatever you * want. * * @return */ protected int getNavigationSelectKey() { return CHARCODE_SPACE; } /** * Get the key the moves the selection one page up in the table. By default * this is the Page Up key but by overriding this you can change the key to * whatever you want. * * @return */ protected int getNavigationPageUpKey() { return KeyCodes.KEY_PAGEUP; } /** * Get the key the moves the selection one page down in the table. By * default this is the Page Down key but by overriding this you can change * the key to whatever you want. * * @return */ protected int getNavigationPageDownKey() { return KeyCodes.KEY_PAGEDOWN; } /** * Get the key the moves the selection to the beginning of the table. By * default this is the Home key but by overriding this you can change the * key to whatever you want. * * @return */ protected int getNavigationStartKey() { return KeyCodes.KEY_HOME; } /** * Get the key the moves the selection to the end of the table. By default * this is the End key but by overriding this you can change the key to * whatever you want. * * @return */ protected int getNavigationEndKey() { return KeyCodes.KEY_END; } private final String SUBPART_NODE_PREFIX = "n"; private final String EXPAND_IDENTIFIER = "expand"; /* * In webkit, focus may have been requested for this component but not yet * gained. Use this to trac if tree has gained the focus on webkit. See * FocusImplSafari and #6373 */ private boolean treeHasFocus; /* * (non-Javadoc) * * @see * com.vaadin.terminal.gwt.client.ui.SubPartAware#getSubPartElement(java * .lang.String) */ public Element getSubPartElement(String subPart) { if (subPart.startsWith(SUBPART_NODE_PREFIX + "[")) { boolean expandCollapse = false; // Node String[] nodes = subPart.split("/"); TreeNode treeNode = null; try { for (String node : nodes) { if (node.startsWith(SUBPART_NODE_PREFIX)) { // skip SUBPART_NODE_PREFIX"[" node = node.substring(SUBPART_NODE_PREFIX.length() + 1); // skip "]" node = node.substring(0, node.length() - 1); int position = Integer.parseInt(node); if (treeNode == null) { treeNode = getRootNodes().get(position); } else { treeNode = treeNode.getChildren().get(position); } } else if (node.startsWith(EXPAND_IDENTIFIER)) { expandCollapse = true; } } if (expandCollapse) { if (treeNode.ie6compatnode != null) { return treeNode.ie6compatnode; } else { return treeNode.getElement(); } } else { return treeNode.nodeCaptionSpan; } } catch (Exception e) { // Invalid locator string or node could not be found return null; } } return null; } /* * (non-Javadoc) * * @see * com.vaadin.terminal.gwt.client.ui.SubPartAware#getSubPartName(com.google * .gwt.user.client.Element) */ public String getSubPartName(Element subElement) { // Supported identifiers: // n[index]/n[index]/n[index]{/expand} // Ends with "/expand" if the target is expand/collapse indicator, // otherwise ends with the node boolean isExpandCollapse = false; if (!getElement().isOrHasChild(subElement)) { return null; } TreeNode treeNode = Util.findWidget(subElement, TreeNode.class); if (treeNode == null) { // Did not click on a node, let somebody else take care of the // locator string return null; } if (subElement == treeNode.getElement() || subElement == treeNode.ie6compatnode) { // Targets expand/collapse arrow isExpandCollapse = true; } ArrayList<Integer> positions = new ArrayList<Integer>(); while (treeNode.getParentNode() != null) { positions.add(0, treeNode.getParentNode().getChildren().indexOf( treeNode)); treeNode = treeNode.getParentNode(); } positions.add(0, getRootNodes().indexOf(treeNode)); String locator = ""; for (Integer i : positions) { locator += SUBPART_NODE_PREFIX + "[" + i + "]/"; } locator = locator.substring(0, locator.length() - 1); if (isExpandCollapse) { locator += "/" + EXPAND_IDENTIFIER; } return locator; } public Action[] getActions() { if (bodyActionKeys == null) { return new Action[] {}; } final Action[] actions = new Action[bodyActionKeys.length]; for (int i = 0; i < actions.length; i++) { final String actionKey = bodyActionKeys[i]; final TreeAction a = new TreeAction(this, null, actionKey); a.setCaption(getActionCaption(actionKey)); a.setIconUrl(getActionIcon(actionKey)); actions[i] = a; } return actions; } public ApplicationConnection getClient() { return client; } public String getPaintableId() { return paintableId; } private void handleBodyContextMenu(ContextMenuEvent event) { if (!readonly && !disabled) { if (bodyActionKeys != null) { int left = event.getNativeEvent().getClientX(); int top = event.getNativeEvent().getClientY(); top += Window.getScrollTop(); left += Window.getScrollLeft(); client.getContextMenu().showAt(this, left, top); } event.stopPropagation(); event.preventDefault(); } } private boolean isIE6OrOpera() { return BrowserInfo.get().isIE6() || BrowserInfo.get().isOpera(); } }
package com.vaadin.terminal.gwt.client.ui; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.event.dom.client.DomEvent.Type; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.BrowserInfo; import com.vaadin.terminal.gwt.client.Container; import com.vaadin.terminal.gwt.client.Focusable; import com.vaadin.terminal.gwt.client.Paintable; import com.vaadin.terminal.gwt.client.RenderSpace; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.Util; import com.vaadin.terminal.gwt.client.VConsole; import com.vaadin.terminal.gwt.client.ui.ShortcutActionHandler.ShortcutActionHandlerOwner; public class VView extends SimplePanel implements Container, ResizeHandler, Window.ClosingHandler, ShortcutActionHandlerOwner, Focusable { private static final String CLASSNAME = "v-view"; public static final String NOTIFICATION_HTML_CONTENT_NOT_ALLOWED = "useplain"; private String theme; private Paintable layout; private final LinkedHashSet<VWindow> subWindows = new LinkedHashSet<VWindow>(); private String id; private ShortcutActionHandler actionHandler; /** stored width for IE resize optimization */ private int width; /** stored height for IE resize optimization */ private int height; private ApplicationConnection connection; /** * We are postponing resize process with IE. IE bugs with scrollbars in some * situations, that causes false onWindowResized calls. With Timer we will * give IE some time to decide if it really wants to keep current size * (scrollbars). */ private Timer resizeTimer; private int scrollTop; private int scrollLeft; private boolean rendering; private boolean scrollable; private boolean immediate; private boolean resizeLazy = false; public static final String RESIZE_LAZY = "rL"; /** * Reference to the parent frame/iframe. Null if there is no parent (i)frame * or if the application and parent frame are in different domains. */ private Element parentFrame; private ClickEventHandler clickEventHandler = new ClickEventHandler(this, VPanel.CLICK_EVENT_IDENTIFIER) { @Override protected <H extends EventHandler> HandlerRegistration registerHandler( H handler, Type<H> type) { return addDomHandler(handler, type); } }; private VLazyExecutor delayedResizeExecutor = new VLazyExecutor(200, new ScheduledCommand() { public void execute() { windowSizeMaybeChanged(Window.getClientWidth(), Window.getClientHeight()); } }); public VView() { super(); setStyleName(CLASSNAME); // Allow focusing the view by using the focus() method, the view // should not be in the document focus flow getElement().setTabIndex(-1); } /** * Called when the window might have been resized. * * @param newWidth * The new width of the window * @param newHeight * The new height of the window */ protected void windowSizeMaybeChanged(int newWidth, int newHeight) { boolean changed = false; if (width != newWidth) { width = newWidth; changed = true; VConsole.log("New window width: " + width); } if (height != newHeight) { height = newHeight; changed = true; VConsole.log("New window height: " + height); } if (changed) { VConsole.log("Running layout functions due to window resize"); connection.runDescendentsLayout(VView.this); Util.runWebkitOverflowAutoFix(getElement()); sendClientResized(); } } public String getTheme() { return theme; } /** * Used to reload host page on theme changes. */ private static native void reloadHostPage() /*-{ $wnd.location.reload(); }-*/; /** * Evaluate the given script in the browser document. * * @param script * Script to be executed. */ private static native void eval(String script) /*-{ try { if (script == null) return; $wnd.eval(script); } catch (e) { } }-*/; /** * Returns true if the body is NOT generated, i.e if someone else has made * the page that we're running in. Otherwise we're in charge of the whole * page. * * @return true if we're running embedded */ public boolean isEmbedded() { return !getElement().getOwnerDocument().getBody().getClassName() .contains(ApplicationConnection.GENERATED_BODY_CLASSNAME); } public void updateFromUIDL(final UIDL uidl, ApplicationConnection client) { rendering = true; id = uidl.getId(); boolean firstPaint = connection == null; connection = client; immediate = uidl.hasAttribute("immediate"); resizeLazy = uidl.hasAttribute(RESIZE_LAZY); String newTheme = uidl.getStringAttribute("theme"); if (theme != null && !newTheme.equals(theme)) { // Complete page refresh is needed due css can affect layout // calculations etc reloadHostPage(); } else { theme = newTheme; } if (uidl.hasAttribute("style")) { setStyleName(getStylePrimaryName() + " " + uidl.getStringAttribute("style")); } if (uidl.hasAttribute("name")) { client.setWindowName(uidl.getStringAttribute("name")); } clickEventHandler.handleEventHandlerRegistration(client); if (!isEmbedded()) { // only change window title if we're in charge of the whole page com.google.gwt.user.client.Window.setTitle(uidl .getStringAttribute("caption")); } // Process children int childIndex = 0; // Open URL:s boolean isClosed = false; // was this window closed? while (childIndex < uidl.getChildCount() && "open".equals(uidl.getChildUIDL(childIndex).getTag())) { final UIDL open = uidl.getChildUIDL(childIndex); final String url = client.translateVaadinUri(open .getStringAttribute("src")); final String target = open.getStringAttribute("name"); if (target == null) { // source will be opened to this browser window, but we may have // to finish rendering this window in case this is a download // (and window stays open). Scheduler.get().scheduleDeferred(new Command() { public void execute() { goTo(url); } }); } else if ("_self".equals(target)) { // This window is closing (for sure). Only other opens are // relevant in this change. See #3558, #2144 isClosed = true; goTo(url); } else { String options; if (open.hasAttribute("border")) { if (open.getStringAttribute("border").equals("minimal")) { options = "menubar=yes,location=no,status=no"; } else { options = "menubar=no,location=no,status=no"; } } else { options = "resizable=yes,menubar=yes,toolbar=yes,directories=yes,location=yes,scrollbars=yes,status=yes"; } if (open.hasAttribute("width")) { int w = open.getIntAttribute("width"); options += ",width=" + w; } if (open.hasAttribute("height")) { int h = open.getIntAttribute("height"); options += ",height=" + h; } Window.open(url, target, options); } childIndex++; } if (isClosed) { // don't render the content, something else will be opened to this // browser view rendering = false; return; } // Draw this application level window UIDL childUidl = uidl.getChildUIDL(childIndex); final Paintable lo = client.getPaintable(childUidl); if (layout != null) { if (layout != lo) { // remove old client.unregisterPaintable(layout); // add new setWidget((Widget) lo); layout = lo; } } else { setWidget((Widget) lo); layout = lo; } layout.updateFromUIDL(childUidl, client); if (!childUidl.getBooleanAttribute("cached")) { updateParentFrameSize(); } // Save currently open subwindows to track which will need to be closed final HashSet<VWindow> removedSubWindows = new HashSet<VWindow>( subWindows); // Handle other UIDL children while ((childUidl = uidl.getChildUIDL(++childIndex)) != null) { String tag = childUidl.getTag().intern(); if (tag == "actions") { if (actionHandler == null) { actionHandler = new ShortcutActionHandler(id, client); } actionHandler.updateActionMap(childUidl); } else if (tag == "execJS") { String script = childUidl.getStringAttribute("script"); eval(script); } else if (tag == "notifications") { for (final Iterator<?> it = childUidl.getChildIterator(); it .hasNext();) { final UIDL notification = (UIDL) it.next(); VNotification.showNotification(client, notification); } } else { // subwindows final Paintable w = client.getPaintable(childUidl); if (subWindows.contains(w)) { removedSubWindows.remove(w); } else { subWindows.add((VWindow) w); } w.updateFromUIDL(childUidl, client); } } // Close old windows which where not in UIDL anymore for (final Iterator<VWindow> rem = removedSubWindows.iterator(); rem .hasNext();) { final VWindow w = rem.next(); client.unregisterPaintable(w); subWindows.remove(w); w.hide(); } if (uidl.hasAttribute("focused")) { // set focused component when render phase is finished Scheduler.get().scheduleDeferred(new Command() { public void execute() { final Paintable toBeFocused = uidl.getPaintableAttribute( "focused", connection); /* * Two types of Widgets can be focused, either implementing * GWT HasFocus of a thinner Vaadin specific Focusable * interface. */ if (toBeFocused instanceof com.google.gwt.user.client.ui.Focusable) { final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) toBeFocused; toBeFocusedWidget.setFocus(true); } else if (toBeFocused instanceof Focusable) { ((Focusable) toBeFocused).focus(); } else { VConsole.log("Could not focus component"); } } }); } // Add window listeners on first paint, to prevent premature // variablechanges if (firstPaint) { Window.addWindowClosingHandler(this); Window.addResizeHandler(this); } onResize(); // finally set scroll position from UIDL if (uidl.hasVariable("scrollTop")) { scrollable = true; scrollTop = uidl.getIntVariable("scrollTop"); DOM.setElementPropertyInt(getElement(), "scrollTop", scrollTop); scrollLeft = uidl.getIntVariable("scrollLeft"); DOM.setElementPropertyInt(getElement(), "scrollLeft", scrollLeft); } else { scrollable = false; } // Safari workaround must be run after scrollTop is updated as it sets // scrollTop using a deferred command. if (BrowserInfo.get().isSafari()) { Util.runWebkitOverflowAutoFix(getElement()); } scrollIntoView(uidl); rendering = false; } /** * Tries to scroll paintable referenced from given UIDL snippet to be * visible. * * @param uidl */ void scrollIntoView(final UIDL uidl) { if (uidl.hasAttribute("scrollTo")) { Scheduler.get().scheduleDeferred(new Command() { public void execute() { final Paintable paintable = uidl.getPaintableAttribute( "scrollTo", connection); ((Widget) paintable).getElement().scrollIntoView(); } }); } } @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); int type = DOM.eventGetType(event); if (type == Event.ONKEYDOWN && actionHandler != null) { actionHandler.handleKeyboardEvent(event); return; } else if (scrollable && type == Event.ONSCROLL) { updateScrollPosition(); } } /** * Updates scroll position from DOM and saves variables to server. */ private void updateScrollPosition() { int oldTop = scrollTop; int oldLeft = scrollLeft; scrollTop = DOM.getElementPropertyInt(getElement(), "scrollTop"); scrollLeft = DOM.getElementPropertyInt(getElement(), "scrollLeft"); if (connection != null && !rendering) { if (oldTop != scrollTop) { connection.updateVariable(id, "scrollTop", scrollTop, false); } if (oldLeft != scrollLeft) { connection.updateVariable(id, "scrollLeft", scrollLeft, false); } } } /* * (non-Javadoc) * * @see * com.google.gwt.event.logical.shared.ResizeHandler#onResize(com.google * .gwt.event.logical.shared.ResizeEvent) */ public void onResize(ResizeEvent event) { onResize(); } /** * Called when a resize event is received. */ private void onResize() { /* * IE (pre IE9 at least) will give us some false resize events due to * problems with scrollbars. Firefox 3 might also produce some extra * events. We postpone both the re-layouting and the server side event * for a while to deal with these issues. * * We may also postpone these events to avoid slowness when resizing the * browser window. Constantly recalculating the layout causes the resize * operation to be really slow with complex layouts. */ boolean lazy = resizeLazy || (BrowserInfo.get().isIE() && BrowserInfo.get() .getIEVersion() <= 8) || BrowserInfo.get().isFF3(); if (lazy) { delayedResizeExecutor.trigger(); } else { windowSizeMaybeChanged(Window.getClientWidth(), Window.getClientHeight()); } } /** * Send new dimensions to the server. */ private void sendClientResized() { connection.updateVariable(id, "height", height, false); connection.updateVariable(id, "width", width, immediate); } public native static void goTo(String url) /*-{ $wnd.location = url; }-*/; public void onWindowClosing(Window.ClosingEvent event) { // Change focus on this window in order to ensure that all state is // collected from textfields // TODO this is a naive hack, that only works with text fields and may // cause some odd issues. Should be replaced with a decent solution, see // also related BeforeShortcutActionListener interface. Same interface // might be usable here. VTextField.flushChangesFromFocusedTextField(); // Send the closing state to server connection.updateVariable(id, "close", true, false); connection.sendPendingVariableChangesSync(); } private final RenderSpace myRenderSpace = new RenderSpace() { private int excessHeight = -1; private int excessWidth = -1; @Override public int getHeight() { return getElement().getOffsetHeight() - getExcessHeight(); } private int getExcessHeight() { if (excessHeight < 0) { detectExcessSize(); } return excessHeight; } private void detectExcessSize() { // TODO define that iview cannot be themed and decorations should // get to parent element, then get rid of this expensive and error // prone function final String overflow = getElement().getStyle().getProperty( "overflow"); getElement().getStyle().setProperty("overflow", "hidden"); if (BrowserInfo.get().isIE() && getElement().getPropertyInt("clientWidth") == 0) { // can't detect possibly themed border/padding width in some // situations (with some layout configurations), use empty div // to measure width properly DivElement div = Document.get().createDivElement(); div.setInnerHTML("&nbsp;"); div.getStyle().setProperty("overflow", "hidden"); div.getStyle().setProperty("height", "1px"); getElement().appendChild(div); excessWidth = getElement().getOffsetWidth() - div.getOffsetWidth(); getElement().removeChild(div); } else { excessWidth = getElement().getOffsetWidth() - getElement().getPropertyInt("clientWidth"); } excessHeight = getElement().getOffsetHeight() - getElement().getPropertyInt("clientHeight"); getElement().getStyle().setProperty("overflow", overflow); } @Override public int getWidth() { int w = getRealWidth(); if (w < 10 && BrowserInfo.get().isIE7()) { // Overcome an IE7 bug #3295 Util.shakeBodyElement(); w = getRealWidth(); } return w; } private int getRealWidth() { if (connection.getConfiguration().isStandalone()) { return getElement().getOffsetWidth() - getExcessWidth(); } // If not running standalone, there might be multiple Vaadin apps // that won't shrink with the browser window as the components have // calculated widths (#3125) // Find all Vaadin applications on the page ArrayList<String> vaadinApps = new ArrayList<String>(); loadAppIdListFromDOM(vaadinApps); // Store original styles here so they can be restored ArrayList<String> originalDisplays = new ArrayList<String>( vaadinApps.size()); String ownAppId = connection.getConfiguration().getRootPanelId(); // Set display: none for all Vaadin apps for (int i = 0; i < vaadinApps.size(); i++) { String appId = vaadinApps.get(i); Element targetElement; if (appId.equals(ownAppId)) { // Only hide the contents of current application targetElement = ((Widget) layout).getElement(); } else { // Hide everything for other applications targetElement = Document.get().getElementById(appId); } Style layoutStyle = targetElement.getStyle(); originalDisplays.add(i, layoutStyle.getDisplay()); layoutStyle.setDisplay(Display.NONE); } int w = getElement().getOffsetWidth() - getExcessWidth(); // Then restore the old display style before returning for (int i = 0; i < vaadinApps.size(); i++) { String appId = vaadinApps.get(i); Element targetElement; if (appId.equals(ownAppId)) { targetElement = ((Widget) layout).getElement(); } else { targetElement = Document.get().getElementById(appId); } Style layoutStyle = targetElement.getStyle(); String originalDisplay = originalDisplays.get(i); if (originalDisplay.length() == 0) { layoutStyle.clearDisplay(); } else { layoutStyle.setProperty("display", originalDisplay); } } return w; } private int getExcessWidth() { if (excessWidth < 0) { detectExcessSize(); } return excessWidth; } @Override public int getScrollbarSize() { return Util.getNativeScrollbarSize(); } }; private native static void loadAppIdListFromDOM(ArrayList<String> list) /*-{ var j; for(j in $wnd.vaadin.vaadinConfigurations) { list.@java.util.Collection::add(Ljava/lang/Object;)(j); } }-*/; public RenderSpace getAllocatedSpace(Widget child) { return myRenderSpace; } public boolean hasChildComponent(Widget component) { return (component != null && component == layout); } public void replaceChildComponent(Widget oldComponent, Widget newComponent) { // TODO This is untested as no layouts require this if (oldComponent != layout) { return; } setWidget(newComponent); layout = (Paintable) newComponent; } public boolean requestLayout(Set<Paintable> child) { /* * Can never propagate further and we do not want need to re-layout the * layout which has caused this request. */ updateParentFrameSize(); // layout size change may affect its available space (scrollbars) connection.handleComponentRelativeSize((Widget) layout); return true; } private void updateParentFrameSize() { if (parentFrame == null) { return; } int childHeight = Util.getRequiredHeight(getWidget().getElement()); int childWidth = Util.getRequiredWidth(getWidget().getElement()); parentFrame.getStyle().setPropertyPx("width", childWidth); parentFrame.getStyle().setPropertyPx("height", childHeight); } private static native Element getParentFrame() /*-{ try { var frameElement = $wnd.frameElement; if (frameElement == null) { return null; } if (frameElement.getAttribute("autoResize") == "true") { return frameElement; } } catch (e) { } return null; }-*/; public void updateCaption(Paintable component, UIDL uidl) { // NOP Subwindows never draw caption for their first child (layout) } /** * Return an iterator for current subwindows. This method is meant for * testing purposes only. * * @return */ public ArrayList<VWindow> getSubWindowList() { ArrayList<VWindow> windows = new ArrayList<VWindow>(subWindows.size()); for (VWindow widget : subWindows) { windows.add(widget); } return windows; } public void init(String rootPanelId, ApplicationConnection applicationConnection) { DOM.sinkEvents(getElement(), Event.ONKEYDOWN | Event.ONSCROLL); // iview is focused when created so element needs tabIndex // 1 due 0 is at the end of natural tabbing order DOM.setElementProperty(getElement(), "tabIndex", "1"); RootPanel root = RootPanel.get(rootPanelId); // Remove the v-app-loading or any splash screen added inside the div by // the user root.getElement().setInnerHTML(""); // For backwards compatibility with static index pages only. // No longer added by AbstractApplicationServlet/Portlet root.removeStyleName("v-app-loading"); root.add(this); if (applicationConnection.getConfiguration().isStandalone()) { // set focus to iview element by default to listen possible keyboard // shortcuts. For embedded applications this is unacceptable as we // don't want to steal focus from the main page nor we don't want // side-effects from focusing (scrollIntoView). getElement().focus(); } parentFrame = getParentFrame(); } public ShortcutActionHandler getShortcutActionHandler() { return actionHandler; } public void focus() { getElement().focus(); } }
package com.vectrace.MercurialEclipse.model; import com.vectrace.MercurialEclipse.HgRevision; /** * @author <a href="mailto:zsolt.koppany@intland.com">Zsolt Koppany</a> * @version $Id$ */ public class Tag implements Comparable<Tag> { private final static String TIP = HgRevision.TIP.getChangeset(); /** name of the tag, unique in the repository */ private final String name; private final int revision; private final String globalId; private final boolean local; public Tag(String name, int revision, String globalId, boolean local) { super(); this.name = name; this.revision = revision; this.globalId = globalId; this.local = local; } public String getName() { return name; } public int getRevision() { return revision; } public String getGlobalId() { return globalId; } public boolean isLocal() { return local; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Tag other = (Tag) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { return name + " [" + revision + ':' + globalId + ']'; } public int compareTo(Tag tag) { /* "tip" must be always the first in the collection */ if (tag == null || name == null || TIP.equals(name)) { return -1; } if (TIP.equals(tag.getName())) { return 1; } int cmp = tag.getRevision() - revision; if(cmp != 0){ // sort by revision first return cmp; } // sort by name cmp = name.compareToIgnoreCase(tag.getName()); if (cmp == 0) { // Check it case sensitive cmp = name.compareTo(tag.getName()); } return cmp; } }
package com.wrapp.android.webimage; import android.content.Context; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.widget.ImageView; import java.net.MalformedURLException; import java.net.URL; /** * ImageView successor class which can load images asynchronously from the web. This class * is safe to use in ListAdapters or views which may trigger many simultaneous requests. */ @SuppressWarnings({"UnusedDeclaration"}) public class WebImageView extends ImageView implements ImageRequest.Listener { Handler uiHandler; private Listener listener; // Save both a Drawable and int here. If the user wants to pass a resource ID, we can load // this lazily and save a bit of memory. private Drawable errorImage; private int errorImageResId; private Drawable placeholderImage; private int placeholderImageResId; private URL currentImageUrl; public interface Listener { public void onImageLoadStarted(); public void onImageLoadComplete(); public void onImageLoadError(); public void onImageLoadCancelled(); } public WebImageView(Context context) { super(context); initialize(); } public WebImageView(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } public WebImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(); } private void initialize() { uiHandler = new Handler(); } /** * Set a listener to be informed about events from this view. If this is not set, then no events are sent. * @param listener Listener */ public void setListener(Listener listener) { this.listener = listener; } /** * Load an image asynchronously from the web * @param imageUrlString Image URL to download image from. By default, this image will be cached to * disk (ie, SD card), but not in memory. */ public void setImageUrl(String imageUrlString) { try { setImageUrl(new URL(imageUrlString)); } catch(MalformedURLException e) { LogWrapper.logException(e); } } /** * Load an image asynchronously from the web * @param imageUrl Image URL to download image from. By default, this image will be cached to * disk (ie, SD card), but not in memory. */ public void setImageUrl(URL imageUrl) { //noinspection NullableProblems setImageUrl(imageUrl, false, null, 0, 0); } /** * Load an image asynchronously from the web * @param imageUrl Image URL to download image from * @param cacheInMemory True to keep the downloaded drawable in the memory cache. Set to true for faster * access, but be careful about using this flag, as it can consume a lot of memory. This is recommended * only for activities which re-use the same images frequently. * @param options Options to use when loading the image. See the documentation for {@link BitmapFactory.Options} * for more details. Can be null. * @param errorImageResId Resource ID to be displayed in case the image could not be loaded. If 0, no new image * will be displayed on error. * @param placeholderImageResId Resource ID to set for placeholder image while image is loading. */ public void setImageUrl(URL imageUrl, boolean cacheInMemory, BitmapFactory.Options options, int errorImageResId, int placeholderImageResId) { if(imageUrl.equals(currentImageUrl)) { return; } this.errorImageResId = errorImageResId; if(this.placeholderImageResId > 0) { setImageResource(this.placeholderImageResId); } else if(this.placeholderImage != null) { setImageDrawable(this.placeholderImage); } else if(placeholderImageResId > 0) { setImageResource(placeholderImageResId); } if(this.listener != null) { listener.onImageLoadStarted(); } currentImageUrl = imageUrl; ImageLoader.load(getContext(), imageUrl, this, cacheInMemory, options); } /** * This method is called when the drawable has been downloaded (or retreived from cache) and is * ready to be displayed. If you override this class, then you should not call this method via * super.onBitmapLoaded(). Instead, handle the drawable as necessary (ie, resizing or other * transformations), and then call postToGuiThread() to display the image from the correct thread. * * If you only need a callback to be notified about the drawable being loaded to update other * GUI elements and whatnot, then you should override onImageLoaded() instead. * * @param response Request response */ public void onBitmapLoaded(final RequestResponse response) { if(response.imageUrl.equals(currentImageUrl)) { postToGuiThread(new Runnable() { public void run() { setImageBitmap(response.bitmap); } }); if(listener != null) { listener.onImageLoadComplete(); } } else { if(listener != null) { listener.onImageLoadCancelled(); } } } /** * This method is called if the drawable could not be loaded for any reason. If you need a callback * to react to these events, you should override onImageError() instead. * @param message Error message (non-localized) */ public void onBitmapLoadError(String message) { LogWrapper.logMessage(message); postToGuiThread(new Runnable() { public void run() { // In case of error, lazily load the drawable here if(errorImageResId > 0) { errorImage = getResources().getDrawable(errorImageResId); } if(errorImage != null) { setImageDrawable(errorImage); } } }); if(listener != null) { listener.onImageLoadError(); } } /** * Called when the URL which the caller asked to load was cancelled. This can happen for a number * of reasons, including the activity being closed or scrolling rapidly in a ListView. For this * reason it is recommended not to do so much work in this method. */ public void onBitmapLoadCancelled() { if(listener != null) { listener.onImageLoadCancelled(); } } /** * Post a message to the GUI thread. This should be used for updating the component from * background tasks. * @param runnable Runnable task */ public final void postToGuiThread(Runnable runnable) { uiHandler.post(runnable); } public void setErrorImageResId(int errorImageResId) { this.errorImageResId = errorImageResId; } public void setErrorImage(Drawable errorImage) { this.errorImage = errorImage; } public void setPlaceholderImage(Drawable placeholderImage) { this.placeholderImage = placeholderImage; } public void setPlaceholderImageResId(int placeholderImageResId) { this.placeholderImageResId = placeholderImageResId; } }
package main; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.TextArea; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.PixelReader; import javafx.scene.image.WritableImage; import javafx.scene.paint.Color; import javafx.stage.FileChooser; import kelas.AlertInfo; import javax.imageio.ImageIO; import javax.imageio.plugins.bmp.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Random; public class UjiGambar { Image image = null; BufferedImage bufferedImageNoise = null; BufferedImage bufferedImage; Image imagePrev; String imgPath = ""; Alert alert; @FXML Button btnBrowseImage, btnSaveImage; @FXML ImageView imgviewOri, imgviewWrite; @FXML TextArea textareaInfoImgOri; @FXML public void handleimgviewOri(ActionEvent event) { String teks = ""; Graphics graphics; Color color; PixelReader pixelReader; FileChooser fc = new FileChooser(); fc.setTitle("Buka Berkas Gambar"); fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("BMP Image", "*.bmp")); File fio = fc.showOpenDialog(null); if (fio != null) { try { imgPath = fio.toURI().toURL().toString(); image = new Image(imgPath); imgviewOri.setImage(image); pixelReader = image.getPixelReader(); color = pixelReader.getColor(0,0); this.bufferedImage = SwingFXUtils.fromFXImage(image, null); graphics = bufferedImage.getGraphics(); int blue = graphics.getColor().getBlue(); teks += "Nama File: " + fio.getName() + "\n" + "Lebar: " + bufferedImage.getWidth() + "\n" + "Tinggi: " + bufferedImage.getHeight() + "\n"; teks += "\n===========================\n"; teks += "Info Piksel:"; teks += "\n===========================\n"; //teks += "Pixel 0,0: " + r + "," + g + "," + b + "\n"; teks += "Pixel Gambar: \n"; int tambahNoise = 10, tmpp; double x0, x1, x2, xn; // for (int x = 0; x < 35; x += 1) { // for (int y = 0, lines = 0; y < 35; y += 1) { // int argb = bufferedImage.getRGB(x,y); /*int r = (argb)&0xFF; int g = (argb>>8)&0xFF; int b = (argb>>16)&0xFF; int a = (argb>>24)&0xFF;*/ // int a = (argb>>24)&0x000000FF; // int r = (argb>>16)&0x000000FF; // int g = (argb>>8)&0x000000FF; // int b = (argb)&0x000000FF; // teks += "[" + x + "," + y +"]: " + r + "," + g + "," + b + " " + a + "\n"; // int argb2 = (a << 24) | (r << 16) | (g << 8) | b; // int argban = ((a << 24) | (255 << 16) | (255 << 8) | 255); // x1 = Math.random(); // } while (x1 == 0); // x2 = Math.random(); // x0 = Math.sqrt(-2 * Math.log(x1) * Math.cos(2 * Math.PI * x2)); // xn = 1 + Math.sqrt(0.1) * x; // tmpp = argban + (int)xn; // if (tmpp < 0) { // bufferedImage.setRGB(x, y, ((a << 24) | (0 << 16) | (0 << 8) | 0)); // else if (tmpp > 255) { // bufferedImage.setRGB(x, y, ((a << 24) | (255 << 16) | (255 << 8) | 255)); // else { // bufferedImage.setRGB(x, y, ((a << 24) | tmpp)); /*if (tambahNoise > 0) { bufferedImage.setRGB((y * 2) % 19, tambahNoise, argban); tambahNoise -= 1; }*/ /*int r2 = (argb2)&0xFF; int g2 = (argb2>>8)&0xFF; int b2 = (argb2>>16)&0xFF; int a2 = (argb2>>24)&0xFF;*/ // int a2 = (argb2>>24)&0x000000FF; // int r2 = (argb2>>16)&0x000000FF; // int g2 = (argb2>>8)&0x000000FF; // int b2 = (argb2)&0x000000FF; // teks += "[" + x + "," + y +"]: " + r2 + "," + g2 + "," + b2 + " " + a2 + "\n"; // if (lines == 5) { // lines = 0; // teks += "\n"; // } else { // lines += 1; // teks += "\n"; /*if (bufferedImageOut == null) { imgviewWrite.setImage(SwingFXUtils.toFXImage(bufferedImage, null)); bufferedImageOut = bufferedImage; } else { imgviewWrite.setImage(SwingFXUtils.toFXImage(bufferedImageOut, null)); }*/ //imgviewWrite.setImage(SwingFXUtils.toFXImage(bufferedImage, null)); textareaInfoImgOri.setText(teks); } catch (MalformedURLException mue) { alert = new Alert(Alert.AlertType.INFORMATION, "Gagal mengupload gambar ke aplikasi", ButtonType.OK); alert.setTitle("Informasi Aplikasi"); alert.setHeaderText("Terjadi Exception PATH File"); alert.show(); } catch (Exception exc) { alert = new Alert(Alert.AlertType.INFORMATION, "Terjadi kesalahan set Image", ButtonType.OK); alert.setTitle("Informasi Aplikasi"); alert.setHeaderText("Terjadi Exception PATH File"); alert.show(); } addGaussianNoise(); } } private void addGaussianNoise() { Double presentaseNoise = new Double(50); Random gaussianDistribution = new Random(); Double distribution = gaussianDistribution.nextGaussian(); int acakX = (this.bufferedImage.getWidth() * 30) / 100; int acakY = (this.bufferedImage.getHeight() * 30) / 100; java.util.List<Integer> dataNoise = new ArrayList<>(); try { /*for (int x = 0; x < this.bufferedImage.getWidth(); x += 1) { for (int y = 0; y < this.bufferedImage.getHeight(); y += 1) { } }*/ this.textareaInfoImgOri.appendText("\n\nNilai noise: \n"); int lines = 8; // for (int x = 0; x < this.bufferedImage.getWidth(); x += 1) { // for (int y = 0; y < this.bufferedImage.getHeight(); y += 1) { // int rgb = this.bufferedImage.getRGB(x, y); // int r = (rgb>>16)&0x000000FF; // int g = (rgb>>8)&0x000000FF; // int b = (rgb)&0x000000FF; // int gray = (r + g + b) / 3; // Double getNoise = presentaseNoise * distribution; // int withNoise = Math.round((255 + r + g + b) + getNoise.floatValue()); // r = (r + Math.round(getNoise) > 255) ? 255 : (r + Math.round(getNoise) < 0) ? 0 : (int)(r + Math.round(getNoise)); // g = (g + Math.round(getNoise) > 255) ? 255 : (g + Math.round(getNoise) < 0) ? 0 : (int)(g + Math.round(getNoise)); // b = (b + Math.round(getNoise) > 255) ? 255 : (b + Math.round(getNoise) < 0) ? 0 : (int)(b + Math.round(getNoise)); // //int withNoise = Math.round(gray + getNoise.floatValue()); // this.bufferedImage.setRGB( // ((255 << 24) | (r << 16) | (g << 8) | b) // /*this.bufferedImage.setRGB(x, // y, // withNoise // );*/ // dataNoise.add(withNoise); /*for (int i = 0; i < dataNoise.size(); i += 1) { this.textareaInfoImgOri.appendText("" + dataNoise.get(i) + " "); lines -= 1; if (lines == 1) { this.textareaInfoImgOri.appendText("\n"); lines = 8; } }*/ //imgviewWrite.setImage(SwingFXUtils.toFXImage(this.bufferedImage, null)); this.bufferedImageNoise = noiseSaltAndPepper(this.bufferedImage, 10); imgviewWrite.setImage(SwingFXUtils.toFXImage(this.bufferedImageNoise, null)); AlertInfo.showAlertInfoMessage( "Informasi Aplikasi", "Penambahan Gaussian Noise", "Penambahan noise berhasil dilakukan", ButtonType.OK ); } catch (Exception gaussianException) { alert = new Alert(Alert.AlertType.INFORMATION, "Terjadi kesalahan Penambahan gaussian noise", ButtonType.OK); alert.setTitle("Informasi Aplikasi"); alert.setHeaderText("Terjadi Exception PATH File"); alert.show(); } } @FXML public void handleBtnSaveImage(ActionEvent event) { //Image img = SwingFXUtils.toFXImage(bufferedImage, null); FileChooser fcs = new FileChooser(); fcs.setTitle("Buka Berkas Gambar"); fcs.getExtensionFilters().add(new FileChooser.ExtensionFilter("BMP Image", "*.bmp")); String teks = "\n\nInfo Ukuran BufferedImage sekarang: " + bufferedImage.getWidth() + "," + bufferedImage.getHeight(); teks += "\n"; textareaInfoImgOri.appendText(teks); File fis = fcs.showSaveDialog(null); if (fis != null) { String selected_desc = fcs.getSelectedExtensionFilter().getDescription(); String extension = "bmp"; boolean sukses = true; if (fis.getName().endsWith(".bmp")) extension = "bmp"; else if (fis.getName().endsWith(".jpg")) extension = "jpg"; else extension = "bmp"; try { boolean res = ImageIO.write(this.bufferedImage, extension, fis); AlertInfo.showAlertErrorMessage("Informasi Kesalahan", "Penyimpanan Gambar Berhasil", "Berhasil menyimpan gambar ke direktori", ButtonType.OK); } catch (Exception e) { AlertInfo.showAlertErrorMessage("Informasi Kesalahan", "Penyimpanan Gambar Gagal", "Gagal menyimpan gambar ke direktori", ButtonType.OK); } } } private BufferedImage noiseSaltAndPepper(BufferedImage imageOri, int noiseProbabilitas) { BufferedImage temp = imageOri; Random rnd = new Random(); int width = imageOri.getWidth(); int height = imageOri.getHeight(); int prob = (int) (width * height * noiseProbabilitas * 0.01); for (int i = 0; i < prob; i += 1) { int x1 = rnd.nextInt(imageOri.getWidth() - 1); int y1 = rnd.nextInt(imageOri.getHeight() - 1); int random = rnd.nextInt(20) + 1; if (random <= 10) { temp.setRGB(x1, y1, ((255 << 24) | (0 << 16) | (0 << 8) | 0)); } else { temp.setRGB(x1, y1, ((255 << 24) | (255 << 16) | (255 << 8) | 255)); } } this.textareaInfoImgOri.appendText("\nNilai prob: " + prob + "\n"); return temp; } }
import com.cloudant.client.api.ClientBuilder; import com.cloudant.client.api.CloudantClient; import com.cloudant.client.api.Database; import com.cloudant.http.Http; import com.cloudant.http.HttpConnection; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.net.URL; import java.util.*; public class Main { private static String fakeRevisionId = "9999-a"; private static Gson gson = new GsonBuilder().create(); public static void main(String[] args) { if (args.length != 4) { System.err.println("Error: Usage: DatabaseCompare url1 database1 url2 database2"); } try { compare(new URL(args[0]), args[1], new URL(args[2]), args[3]); } catch (Exception e) { System.err.println("Error: "+e); e.printStackTrace(); } } public static void compare(URL databaseUrl1, String databaseName1, URL databaseUrl2, String databaseName2) throws Exception { CloudantClient client1 = ClientBuilder.url(databaseUrl1).build(); CloudantClient client2 = ClientBuilder.url(databaseUrl2).build(); Database database1 = client1.database(databaseName1, false); Database database2 = client2.database(databaseName2, false); System.out.println("Getting all document ids"); List<String> allDocs1 = database1.getAllDocsRequestBuilder().build().getResponse().getDocIds(); List<String> allDocs2 = database2.getAllDocsRequestBuilder().build().getResponse().getDocIds(); Set<String> onlyInDb1 = new HashSet<>(allDocs1); onlyInDb1.removeAll(allDocs2); Set<String> onlyInDb2 = new HashSet<>(allDocs2); onlyInDb2.removeAll(allDocs1); System.out.println("Documents only in db 1:"+ onlyInDb1); System.out.println("Documents only in db 2:"+ onlyInDb2); Set<String> common = new HashSet<>(allDocs1); common.retainAll(allDocs2); List<List<String>> batches = partition(common, 500); Map<String, List<String>> missingRevsInDb2 = getMissingRevs(batches, client1, databaseName1, client2, databaseName2); Map<String, List<String>> missingRevsInDb1 = getMissingRevs(batches, client2, databaseName2, client1, databaseName1); System.out.println("Missing revs in db 1:"+missingRevsInDb1); System.out.println("Missing revs in db 2:"+missingRevsInDb2); } public static <T> List<List<T>> partition(Collection list, int size) { int i = 0; List<List<T>> output = new ArrayList<>(); List current = null; for (Object item : list) { if (i++ % size == 0) { current = new ArrayList(); output.add(current); } current.add(item); } return output; } public static Map<String, List<String>> getMissingRevs(List<List<String>> batches, CloudantClient client1, String databaseName1, CloudantClient client2, String databaseName2) throws Exception { Map<String, List<String>> missing = new HashMap<>(); Map<String, List<String>> revsDiffRequestDb1 = new HashMap<>(); Map<String, List<String>> revsDiffRequestDb2 = new HashMap<>(); for (List<String> docIds : batches) { System.out.print("."); // look in db1 - use a fake revision ID to fetch all leaf revisions for (String docId : docIds) { revsDiffRequestDb1.put(docId, Collections.singletonList(fakeRevisionId)); } String jsonRequestDb1 = gson.toJson(revsDiffRequestDb1); HttpConnection hc1 = Http.POST(new URL(client1.getBaseUri() + "/" + databaseName1 + "/_revs_diff"), "application/json"); hc1.setRequestBody(jsonRequestDb1); String response1 = client1.executeRequest(hc1).responseAsString(); Map<String, Object> responseMap1 = (Map<String, Object>) gson.fromJson(response1, Map.class); for (String docId : responseMap1.keySet()) { Map<String, List<String>> entry = (Map<String, List<String>>) responseMap1.get(docId); List<String> revIds = entry.get("possible_ancestors"); if (revIds != null) { revsDiffRequestDb2.put(docId, revIds); } } // look in db2 String jsonRequestDb2 = gson.toJson(revsDiffRequestDb2); HttpConnection hc2 = Http.POST(new URL(client2.getBaseUri() + "/" + databaseName2 + "/_revs_diff"), "application/json"); hc2.setRequestBody(jsonRequestDb2); String response2 = client2.executeRequest(hc2).responseAsString(); Map<String, Object> responseMap2 = (Map<String, Object>) gson.fromJson(response2, Map.class); for (String docId : responseMap2.keySet()) { Map<String, List<String>> entry = (Map<String, List<String>>) responseMap2.get(docId); List<String> revIds = entry.get("missing"); if (revIds != null) { missing.put(docId, revIds); } } } System.out.println(""); return missing; } }
import com.rocketchat.common.data.model.ErrorObject; import com.rocketchat.common.listener.SubscribeListener; import com.rocketchat.common.network.ReconnectionStrategy; import com.rocketchat.core.RocketChatAPI; import com.rocketchat.core.adapter.CoreAdapter; import com.rocketchat.core.model.SubscriptionObject; import com.rocketchat.core.model.TokenObject; import java.util.List; // TODO: 09/09/17 add autosubscription scheduler public class Main extends CoreAdapter { String username = "*****"; String password = "*****"; private static String serverurl = "wss://demo.rocket.chat"; RocketChatAPI api; public static void main(String[] args) { new Main().call(); } public void call() { api = new RocketChatAPI(serverurl); api.setReconnectionStrategy(new ReconnectionStrategy(4, 2000)); api.connect(this); } @Override public void onLogin(TokenObject token, ErrorObject error) { System.out.println("Logged in successfully"); api.getSubscriptions(this); } @Override public void onConnect(String sessionID) { System.out.println("Connected to server"); api.login(username, password, this); } @Override public void onGetSubscriptions(List<SubscriptionObject> subscriptions, ErrorObject error) { api.getChatRoomFactory().createChatRooms(subscriptions); RocketChatAPI.ChatRoom room = api.getChatRoomFactory().getChatRoomByName("general"); room.subscribeStarredMessages(20, new SubscribeListener() { public void onSubscribe(Boolean isSubscribed, String subId) { if (isSubscribed) { System.out.println("Subscribed to room successfully with subId " + subId); } } }); } @Override public void onConnectError(Exception websocketException) { System.out.println("Got connect error here"); } @Override public void onDisconnect(boolean closedByServer) { System.out.println("Disconnect detected here"); } } /** * RocketChat server dummy user : {"userName":"guest-3829","roomId":"1hrjr4sruo9q1","userId":"9kAri3uXquAnkMeb4","visitorToken":"-57c7cb8f9c53963712368351705f4d9b","authToken":"qTcmnjIrfQB55bTd9GYhuGOOU63WY0-_afbCe8hyX_r"} * <p> * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} * <p> * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} * <p> * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} * <p> * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} * <p> * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} * <p> * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} * <p> * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} * <p> * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} * <p> * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} */ /** * Localhost dummy user: {"userName":"guest-18","roomId":"u7xcgonkr7sh","userId":"rQ2EHbhjryZnqbZxC","visitorToken":"707d47ae407b3790465f61d28ee4c63d","authToken":"VYIvfsfIdBaOy8hdWLNmzsW0yVsKK4213edmoe52133"} */
import java.sql.*; import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import static spark.Spark.*; import pro.tmedia.CardController; import pro.tmedia.CardService; import pro.tmedia.JsonUtil; import spark.template.freemarker.FreeMarkerEngine; import spark.ModelAndView; import static spark.Spark.get; import com.heroku.sdk.jdbc.DatabaseUrl; public class Main { public static void main(String[] args) { port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); new CardController(new CardService()); /*get("/is-server-available-status", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Server is available!"); return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine());*/ get("/is-server-available-status", (req, res) -> "Server is available!", JsonUtil.json()); get("/depot", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)"); stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks"); ArrayList<String> output = new ArrayList<String>(); while (rs.next()) { output.add( "Read from DB: " + rs.getTimestamp("tick")); } attributes.put("results", output); return new ModelAndView(attributes, "depot.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); /* Using DB with recording of "mantras" */ get("/", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS mantra (wisdom varchar, tick timestamp)"); //stmt.executeUpdate("INSERT INTO ticks VALUES (now())"); ResultSet rs = stmt.executeQuery("SELECT wisdom FROM mantra"); ArrayList<String> output = new ArrayList<String>(); output.add("<button>Записать</button><button>Сохранить</button><div>...</div><br/>"); while (rs.next()) { //output.add( "Read from DB: " + rs.getTimestamp("tick")); //output.add( "Read from DB: " + rs.getString("wisdom")); output.add( "<div class=\"wisdom\" style=\"background: #CCCCCC;\">" + rs.getString("wisdom") + "</div>"); } attributes.put("results", output); return new ModelAndView(attributes, "db.ftl"); } catch (Exception e) { attributes.put("message", "There was an error: " + e); return new ModelAndView(attributes, "error.ftl"); } finally { if (connection != null) try{connection.close();} catch(SQLException e){} } }, new FreeMarkerEngine()); get("/mantra/create", (req, res) -> { Connection connection = null; Map<String, Object> attributes = new HashMap<>(); try { connection = DatabaseUrl.extract().getConnection(); Statement stmt = connection.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS mantra (wisdom varchar, tick timestamp)"); stmt.executeUpdate("INSERT INTO mantra VALUES (\"" + req.params("wisdom") + "\",now())"); }); get("/общественная-приемная", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Hello World!"); return new ModelAndView(attributes, "mp-public-reception.ftl"); }, new FreeMarkerEngine()); } }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; import java.nio.charset.Charset; public class Main extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //resp.getWriter().print("Hello from Java! Charset: " + Charset.defaultCharset()); //resp.sendRedirect("/html/index.html"); RequestDispatcher view = req.getRequestDispatcher("/html/index.html"); // don't add your web-app name to the path view.forward(req, resp); } }
package com.map; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.imageio.*; import javax.swing.*; class TileServer implements MapSource { //Number of pixels a tile takes up private static final int TILE_SIZE = 256; //Minimum index any tile can have on Z private static final int MIN_Z = 2; //Maximum index any tile can have on Z private static final int MAX_Z = 18; //Maximum index any tile can have on X private static final int MAX_X = (1 << MAX_Z) / TILE_SIZE; //Maximum index any tile can have on Y private static final int MAX_Y = (1 << MAX_Z) / TILE_SIZE; //Maximum number of tiles to keep in the cache at any given moment private static final int CACHE_SIZE = 256; //maximum number of concurrent tile load requests private static final int CC_REQUEST = 12; //How many tiles to remove from the cache whenever a sweep is done private static final int CLEAN_NUM = 16; //Ratio of lateral to vertical tile priority private static final int Z_PRIORITY = 6; //rings of offscreen tiles around the margins to try and load private static final int CUR_ZOOM_MARGIN = 2; //rings of offscreen tiles on the next zoom to try and load private static final int NEXT_ZOOM_MARGIN =-1; //maximum percentage to zoom a tile before shrinking the layer below instead private static final float ZOOM_CROSSOVER = 1.30f; //Dummy image to render when a tile that has not loaded is requested private static final Image dummyTile = new BufferedImage(TILE_SIZE,TILE_SIZE, BufferedImage.TYPE_INT_ARGB); private java.util.List<Component> repaintListeners = new LinkedList<Component>(); private Map<TileTag, Image> cache = new HashMap<TileTag, Image>(CACHE_SIZE+1, 1.0f); private final String rootURL; private TileTag centerTag; TileServer(String url){ this.rootURL = url; } public void clear(){ if(tileLoader != null) { tileLoader.interrupt(); } cache.clear(); } public void paint(Graphics2D gd, Point2D center, int scale, int width, int height){ Graphics2D g2d = (Graphics2D) gd.create(); int recs = scale/TILE_SIZE; int zoom = 31 - Integer.numberOfLeadingZeros(recs); int effs = (1 << zoom); float zfix = 1.0f + ((recs-effs)/(float)effs); if(zfix >= ZOOM_CROSSOVER){ zoom += 1; effs *= 2; zfix /= 2.0f; } float ewidth = (width /zfix); float eheight = (height/zfix); g2d.translate((width / 2.0f), (height/ 2.0f)); g2d.scale(zfix, zfix); g2d.translate(-(ewidth / 2.0f), -(eheight/ 2.0f)); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); /** * From here on, the graphics object is mapped so that if we draw * around the center of an ewidth by eheight screen normally, it will * fit in the orginal screen size zoomed correctly */ //normalized coordinates of the central lat/son float nlon = ((float)(center.getX()+90.0f)/180.0f); float nlat = ((float)(center.getY()+90.0f)/180.0f); //pixel positions of top left point from lat/lon float sLon = (effs * TILE_SIZE * nlon) - (ewidth /2.0f); float sLat = (effs * TILE_SIZE * nlat) - (eheight/2.0f); //row/col Base index in the top left corner int rowB = (int)(sLon/TILE_SIZE); int colB = (int)(sLat/TILE_SIZE); //X,Y shifts to keep the view in alignment int xalign = (int) -(sLon - rowB*TILE_SIZE); int yalign = (int) -(sLat - colB*TILE_SIZE); //width/height in tiles int wit = (((int)ewidth -xalign)/TILE_SIZE)+1; int hit = (((int)eheight-yalign)/TILE_SIZE)+1; for(int row = 0; row < wit; row++){ for(int col = 0; col < hit; col++){ Image img = pollImage(new TileTag(row+rowB, col+colB, zoom)); g2d.drawImage(img, xalign+row*TILE_SIZE, yalign + col*TILE_SIZE,null); } } g2d.dispose(); System.out.println(zoom); TileTag newCenterTag = new TileTag(rowB + wit/2, colB + hit/2, zoom); if(!newCenterTag.equals(centerTag)){ System.out.println("New center tag"); centerTag = newCenterTag; launchTileLoader(centerTag, wit, hit); } } Image pollImage(TileTag target){ Image tile = cache.get(target); if(tile != null) return tile; return dummyTile; } private Thread tileLoader = null; private void launchTileLoader(TileTag center, int width, int height){ if(tileLoader != null) { tileLoader.interrupt(); //tileLoader.join(); } tileLoader = new TileLoader(centerTag, width, height); tileLoader.start(); } /** * Remove the CLEAN_NUM furthest tiles from the cache to make space */ private void cleanTiles(){ TileTag[] loaded = cache.keySet().toArray(new TileTag[]{}); Arrays.sort(loaded, new TileDistCmp(centerTag, TileDistCmp.FURTHEST)); for(int i=0; i<CLEAN_NUM; i++){ cache.remove(loaded[i]); } } /** * Add given tile as image to the cache */ private synchronized void addTile(TileTag tag, Image tile){ if(cache.size() >= CACHE_SIZE){ cleanTiles(); } cache.put(tag, tile); } /** * Add listener to be repainted if the viewed map ever changes */ public void addRepaintListener(Component c){ repaintListeners.add(c); } /** * Remove listener to be repainted if the viewed map ever changes */ public void removeRepaintListener(Component c){ repaintListeners.remove(c); } /** * Notify listeners that the current map view may have changed */ private void contentChanged(){ for(Component c : repaintListeners){ c.repaint(); } } /** * Tile loader thread * This will load all the tiles around ref given width and height, as well * as all the tiles one level below that, in the order specified by the * TileDistCmp comparator */ private class TileLoader extends Thread { final TileTag ref; final int width; final int height; boolean stop = false; int numToLoad; AtomicInteger loadIndex = new AtomicInteger(0); AtomicInteger finishedHelpers = new AtomicInteger(0); java.util.List<TileTag> toLoad = new ArrayList<TileTag>(CACHE_SIZE); TileLoader(TileTag ref, int width, int height){ this.ref = ref; this.width = width; this.height = height; } public void run(){ try{ long st = System.nanoTime(); //enqueue all the tiles on this zoom level by view+margin int hw = ((width +1)/2) + CUR_ZOOM_MARGIN; int hh = ((height+1)/2) + CUR_ZOOM_MARGIN; for(int row=-hw; row<hw; row++){ for(int col=-hh; col<hh; col++){ enqueue(new TileTag(ref.x+row, ref.y+col, ref.z)); } } if(interrupted()) return; //enqueue all the tiles on the next zoom level by view+margin hw = ((width +1)/2) + NEXT_ZOOM_MARGIN; hh = ((height+1)/2) + NEXT_ZOOM_MARGIN; for(int row=-hw; row<hw; row++){ for(int col=-hh; col<hh; col++){ enqueueBeneath(new TileTag(ref.x+row, ref.y+col, ref.z)); } } if(interrupted()) return; //sort queue by distance from current view Collections.sort(toLoad, new TileDistCmp(ref, TileDistCmp.CLOSEST)); if(interrupted()) return; //Set up and wait for the loading threads numToLoad = Math.min(toLoad.size(), CACHE_SIZE); for(int i=0; i<CC_REQUEST; i++) (new Helper()).start(); while(finishedHelpers.get() != CC_REQUEST){ try{ Thread.sleep(50); } catch(Exception e){ stop = true; } } long et = System.nanoTime(); double ns = et-st; double mspt = (ns/numToLoad)/1000000.0d; if(!stop) System.out.println(numToLoad+" Tiles at "+mspt+" mspt"); } catch (Exception e) { } } //enqueue the 4 tiles on the next zoom level, beneath the argument void enqueueBeneath(TileTag tag){ enqueue(new TileTag(tag.x*2+0, tag.y*2+0, tag.z+1)); enqueue(new TileTag(tag.x*2+0, tag.y*2+1, tag.z+1)); enqueue(new TileTag(tag.x*2+1, tag.y*2+0, tag.z+1)); enqueue(new TileTag(tag.x*2+1, tag.y*2+1, tag.z+1)); } void enqueue(TileTag tag){ if(tag.valid() && !cache.containsKey(tag)) toLoad.add(tag); } private class Helper extends Thread { @Override public void run(){ while(true){ int index = loadIndex.getAndIncrement(); if(index >= numToLoad || TileLoader.this.stop){ finishedHelpers.incrementAndGet(); break; } TileTag next = toLoad.get(index); loadTile(next); } } } } /** * Method for fetching a given TileTag and putting it in the cache */ private void loadTile(TileTag target){ try { Image img = ImageIO.read(target.getURL(rootURL)); addTile(target, img); } catch (Exception e) { System.err.println("failed to load "+target); } finally { //don't repaint for prefetched tiles if(target.z == centerTag.z) contentChanged(); } } /** * Compares two TileTags based on which one is closer to the given tag * Z axis is weighten using Z_PRIORITY * This should allow components to select the tags most/least important * to the viewer based on their current viewport into the map */ static class TileDistCmp implements Comparator<TileTag>{ static final int FURTHEST = -1; static final int CLOSEST = 1; final TileTag ref; final int dir; TileDistCmp(TileTag reference, int direction){ ref = reference; dir = direction; } TileTag onRefZoom(TileTag n){ int zdiff = ref.z - n.z; if (zdiff == 0) { return n; } else if (zdiff > 0) { //n is more zoomed out than ref int fact = (1 << zdiff); int newX = n.x * fact; int newY = n.y * fact; return new TileTag(newX, newY, ref.z); } else { //zdiff < 0 //n is more zoomed in than ref int fact = (1 << -zdiff); int newX = n.x / fact; int newY = n.x / fact; return new TileTag(newX, newY, ref.z); } } int xyDiff(TileTag a, TileTag b){ TileTag newA = onRefZoom(a); TileTag newB = onRefZoom(b); int adiff = Math.abs(ref.x - newA.x) + Math.abs(ref.y - newA.y); int bdiff = Math.abs(ref.x - newB.x) + Math.abs(ref.y - newB.y); return adiff - bdiff; } public int compare(TileTag a, TileTag b){ int xydiff = xyDiff(a, b); int azdiff = Math.abs(ref.z - a.z); int bzdiff = Math.abs(ref.z - b.z); return dir * (xydiff + Z_PRIORITY * (azdiff - bzdiff)); } } /** * TileTag contains refereces to x,y,z coordinates, defining equals * and hash code appropriately, and generating url's for standard * web-mercator protocols */ static class TileTag{ final int x,y,z; TileTag(int x, int y, int z){ this.x = x; this.y = y; this.z = z; } @Override public int hashCode() { int result = x; result = result*(MAX_Y) + y; result = result*(MAX_Z) + z; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; TileTag other = (TileTag) obj; if (x != other.x || y != other.y || z != other.z) return false; return true; } //check if a tile is within the coordinate bounds boolean valid(){ return z >= MIN_Z && z <= MAX_Z && x >= 0 && x < (1 << z) && y >= 0 && y < (1 << z) ; } URL getURL(String rootURL) { StringBuilder sb = new StringBuilder(rootURL); sb.append("/"); sb.append(z); sb.append("/"); sb.append(x); sb.append("/"); sb.append(y); sb.append(".png"); URL res = null; try{ res = new URL(sb.toString()); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public String toString(){ StringBuilder sb = new StringBuilder("Tile @ "); sb.append("x: "); sb.append(x); sb.append(" y: "); sb.append(y); sb.append(" z: "); sb.append(z); return sb.toString(); } } /** * small set of tests for TileDistCmp and TileTag */ private void testTileDist(){ TileTag ref = new TileTag(4, 4, 3); Comparator<TileTag> cmp = new TileDistCmp(ref, TileDistCmp.CLOSEST); System.out.println("Hello from test Tile Dist Test"); System.out.println(cmp.compare(new TileTag(4,4,3), ref)); System.out.println(cmp.compare(new TileTag(0,4,3), ref)); System.out.println(cmp.compare(new TileTag(4,0,3), ref)); System.out.println(cmp.compare(new TileTag(2,2,2), ref)); System.out.println(cmp.compare(new TileTag(8,8,4), ref)); TileTag[] test = new TileTag[]{ new TileTag(5,4,3), new TileTag(4,3,3), new TileTag(5,8,7), new TileTag(4,5,3), new TileTag(3,4,3), new TileTag(5,8,2), new TileTag(4,4,3), new TileTag(5,5,3), new TileTag(5,8,3) }; Arrays.sort(test, cmp); for(TileTag t : test) System.out.println(t); } }
package maze; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.util.HashMap; import javax.swing.JPanel; import javax.swing.Timer; public class MazeView extends JPanel{ private final Cell[][] maze; private final HashMap<Cell, CellView> map; public MazeSettings settings; private CellView toUpdate; private Timer timer; public MazeView(Cell[][] maze, MazeSettings settings) { super(); this.maze = maze; this.settings = settings; map = new HashMap(); } public void init(Maker maker) { setLayout(new GridLayout(settings.getMazeHeight(), settings.getMazeWidth())); Dimension size = new Dimension(settings.getCellSize(), settings.getCellSize()); for (int i = 0 ; i < settings.getMazeHeight() ; i++) { for (int j = 0 ; j < settings.getMazeWidth() ; j++) { CellView view = new CellView(maze[j][i], settings); view.setPreferredSize(size); map.put(maze[j][i], view); add(view); } } toUpdate = map.get(maze[0][0]); timer = new Timer(settings.getFrameDelay(), (ActionEvent e) -> { update(maker.step()); }); } public Cell getStartCell() { return maze[0][0]; } public void start() { timer.start(); } public void solveMode(MazeSettings settings, Solver solver) { this.settings.setFrameDelay(settings.getFrameDelay()); this.settings.setShowUnseen(settings.showUnseen()); map.keySet().stream().forEach((cell) -> { cell.visited = false; }); map.values().stream().forEach((view) -> { view.setGenMode(false); }); maze[0][0].visited=true; repaint(); toUpdate = map.get(maze[0][0]); timer = new Timer(settings.getFrameDelay(), (ActionEvent e) -> { update(solver.step()); }); timer.start(); } private void update(Cell source) { toUpdate.repaint(); toUpdate = map.get(source); if (source == null) timer.stop(); else toUpdate.repaint(); } }
package com.ggj.game.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.ggj.game.GlobalGameJam; public class DesktopLauncher { public static float scale = 2; public static void main(String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.width = (int)(512f * scale); config.height = (int)(192f * scale); new LwjglApplication(new GlobalGameJam(), config); } }
package org.elasticsearch.xpack.ml; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.NamedDiff; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.IndexScopedSettings; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.SettingsFilter; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.env.Environment; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.script.ScriptService; import org.elasticsearch.threadpool.ExecutorBuilder; import org.elasticsearch.threadpool.FixedExecutorBuilder; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.watcher.ResourceWatcherService; import org.elasticsearch.xpack.ml.action.CloseJobAction; import org.elasticsearch.xpack.ml.action.DeleteDatafeedAction; import org.elasticsearch.xpack.ml.action.DeleteFilterAction; import org.elasticsearch.xpack.ml.action.DeleteJobAction; import org.elasticsearch.xpack.ml.action.DeleteModelSnapshotAction; import org.elasticsearch.xpack.ml.action.FlushJobAction; import org.elasticsearch.xpack.ml.action.GetBucketsAction; import org.elasticsearch.xpack.ml.action.GetCategoriesAction; import org.elasticsearch.xpack.ml.action.GetDatafeedsAction; import org.elasticsearch.xpack.ml.action.GetDatafeedsStatsAction; import org.elasticsearch.xpack.ml.action.GetFiltersAction; import org.elasticsearch.xpack.ml.action.GetInfluencersAction; import org.elasticsearch.xpack.ml.action.GetJobsAction; import org.elasticsearch.xpack.ml.action.GetJobsStatsAction; import org.elasticsearch.xpack.ml.action.GetModelSnapshotsAction; import org.elasticsearch.xpack.ml.action.GetRecordsAction; import org.elasticsearch.xpack.ml.action.InternalOpenJobAction; import org.elasticsearch.xpack.ml.action.InternalStartDatafeedAction; import org.elasticsearch.xpack.ml.action.OpenJobAction; import org.elasticsearch.xpack.ml.action.PostDataAction; import org.elasticsearch.xpack.ml.action.PutDatafeedAction; import org.elasticsearch.xpack.ml.action.PutFilterAction; import org.elasticsearch.xpack.ml.action.PutJobAction; import org.elasticsearch.xpack.ml.action.RevertModelSnapshotAction; import org.elasticsearch.xpack.ml.action.StartDatafeedAction; import org.elasticsearch.xpack.ml.action.StopDatafeedAction; import org.elasticsearch.xpack.ml.action.UpdateDatafeedStatusAction; import org.elasticsearch.xpack.ml.action.UpdateJobStatusAction; import org.elasticsearch.xpack.ml.action.UpdateModelSnapshotAction; import org.elasticsearch.xpack.ml.action.ValidateDetectorAction; import org.elasticsearch.xpack.ml.datafeed.DatafeedJobRunner; import org.elasticsearch.xpack.ml.job.JobManager; import org.elasticsearch.xpack.ml.job.metadata.MlInitializationService; import org.elasticsearch.xpack.ml.job.metadata.MlMetadata; import org.elasticsearch.xpack.ml.job.persistence.JobDataCountsPersister; import org.elasticsearch.xpack.ml.job.persistence.JobProvider; import org.elasticsearch.xpack.ml.job.persistence.JobRenormalizedResultsPersister; import org.elasticsearch.xpack.ml.job.persistence.JobResultsPersister; import org.elasticsearch.xpack.ml.job.process.DataCountsReporter; import org.elasticsearch.xpack.ml.job.process.NativeController; import org.elasticsearch.xpack.ml.job.process.ProcessCtrl; import org.elasticsearch.xpack.ml.job.process.autodetect.AutodetectProcessFactory; import org.elasticsearch.xpack.ml.job.process.autodetect.AutodetectProcessManager; import org.elasticsearch.xpack.ml.job.process.autodetect.BlackHoleAutodetectProcess; import org.elasticsearch.xpack.ml.job.process.autodetect.NativeAutodetectProcessFactory; import org.elasticsearch.xpack.ml.job.process.autodetect.output.AutodetectResultsParser; import org.elasticsearch.xpack.ml.job.process.normalizer.MultiplyingNormalizerProcess; import org.elasticsearch.xpack.ml.job.process.normalizer.NativeNormalizerProcessFactory; import org.elasticsearch.xpack.ml.job.process.normalizer.NormalizerFactory; import org.elasticsearch.xpack.ml.job.process.normalizer.NormalizerProcessFactory; import org.elasticsearch.xpack.ml.job.usage.UsageReporter; import org.elasticsearch.xpack.ml.rest.datafeeds.RestDeleteDatafeedAction; import org.elasticsearch.xpack.ml.rest.datafeeds.RestGetDatafeedStatsAction; import org.elasticsearch.xpack.ml.rest.datafeeds.RestGetDatafeedsAction; import org.elasticsearch.xpack.ml.rest.datafeeds.RestPutDatafeedAction; import org.elasticsearch.xpack.ml.rest.datafeeds.RestStartDatafeedAction; import org.elasticsearch.xpack.ml.rest.datafeeds.RestStopDatafeedAction; import org.elasticsearch.xpack.ml.rest.filter.RestDeleteFilterAction; import org.elasticsearch.xpack.ml.rest.filter.RestGetFiltersAction; import org.elasticsearch.xpack.ml.rest.filter.RestPutFilterAction; import org.elasticsearch.xpack.ml.rest.job.RestCloseJobAction; import org.elasticsearch.xpack.ml.rest.job.RestDeleteJobAction; import org.elasticsearch.xpack.ml.rest.job.RestFlushJobAction; import org.elasticsearch.xpack.ml.rest.job.RestGetJobStatsAction; import org.elasticsearch.xpack.ml.rest.job.RestGetJobsAction; import org.elasticsearch.xpack.ml.rest.job.RestOpenJobAction; import org.elasticsearch.xpack.ml.rest.job.RestPostDataAction; import org.elasticsearch.xpack.ml.rest.job.RestPutJobAction; import org.elasticsearch.xpack.ml.rest.modelsnapshots.RestDeleteModelSnapshotAction; import org.elasticsearch.xpack.ml.rest.modelsnapshots.RestGetModelSnapshotsAction; import org.elasticsearch.xpack.ml.rest.modelsnapshots.RestRevertModelSnapshotAction; import org.elasticsearch.xpack.ml.rest.modelsnapshots.RestUpdateModelSnapshotAction; import org.elasticsearch.xpack.ml.rest.results.RestGetBucketsAction; import org.elasticsearch.xpack.ml.rest.results.RestGetCategoriesAction; import org.elasticsearch.xpack.ml.rest.results.RestGetInfluencersAction; import org.elasticsearch.xpack.ml.rest.results.RestGetRecordsAction; import org.elasticsearch.xpack.ml.rest.validate.RestValidateDetectorAction; import org.elasticsearch.xpack.ml.utils.NamedPipeHelper; import java.io.IOException; import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.Supplier; import static java.util.Collections.emptyList; public class MlPlugin extends Plugin implements ActionPlugin { public static final String NAME = "ml"; public static final String BASE_PATH = "/_xpack/ml/"; public static final String THREAD_POOL_NAME = NAME; public static final String DATAFEED_RUNNER_THREAD_POOL_NAME = NAME + "_datafeed_runner"; public static final String AUTODETECT_PROCESS_THREAD_POOL_NAME = NAME + "_autodetect_process"; // NORELEASE - temporary solution public static final Setting<Boolean> USE_NATIVE_PROCESS_OPTION = Setting.boolSetting("useNativeProcess", true, Property.NodeScope, Property.Deprecated); /** Setting for enabling or disabling machine learning. Defaults to true. */ public static final Setting<Boolean> ML_ENABLED = Setting.boolSetting("xpack.ml.enabled", true, Setting.Property.NodeScope); private final Settings settings; private final Environment env; private boolean enabled; public MlPlugin(Settings settings) { this(settings, new Environment(settings)); } public MlPlugin(Settings settings, Environment env) { this.enabled = ML_ENABLED.get(settings); this.settings = settings; this.env = env; } @Override public List<Setting<?>> getSettings() { return Collections.unmodifiableList( Arrays.asList(USE_NATIVE_PROCESS_OPTION, ML_ENABLED, ProcessCtrl.DONT_PERSIST_MODEL_STATE_SETTING, ProcessCtrl.MAX_ANOMALY_RECORDS_SETTING, DataCountsReporter.ACCEPTABLE_PERCENTAGE_DATE_PARSE_ERRORS_SETTING, DataCountsReporter.ACCEPTABLE_PERCENTAGE_OUT_OF_ORDER_ERRORS_SETTING, UsageReporter.UPDATE_INTERVAL_SETTING, AutodetectProcessManager.MAX_RUNNING_JOBS_PER_NODE)); } @Override public List<NamedWriteableRegistry.Entry> getNamedWriteables() { return Arrays.asList( new NamedWriteableRegistry.Entry(MetaData.Custom.class, "ml", MlMetadata::new), new NamedWriteableRegistry.Entry(NamedDiff.class, "ml", MlMetadata.MlMetadataDiff::new) ); } @Override public List<NamedXContentRegistry.Entry> getNamedXContent() { NamedXContentRegistry.Entry entry = new NamedXContentRegistry.Entry( MetaData.Custom.class, new ParseField("ml"), parser -> MlMetadata.ML_METADATA_PARSER.parse(parser, null).build() ); return Collections.singletonList(entry); } @Override public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool, ResourceWatcherService resourceWatcherService, ScriptService scriptService, NamedXContentRegistry xContentRegistry) { if (false == enabled) { return emptyList(); } JobResultsPersister jobResultsPersister = new JobResultsPersister(settings, client); JobProvider jobProvider = new JobProvider(client, 0); JobRenormalizedResultsPersister jobRenormalizedResultsPersister = new JobRenormalizedResultsPersister(settings, client); JobDataCountsPersister jobDataCountsPersister = new JobDataCountsPersister(settings, client); JobManager jobManager = new JobManager(settings, jobProvider, jobResultsPersister, clusterService); AutodetectProcessFactory autodetectProcessFactory; NormalizerProcessFactory normalizerProcessFactory; if (USE_NATIVE_PROCESS_OPTION.get(settings)) { try { NativeController nativeController = new NativeController(env, new NamedPipeHelper()); nativeController.tailLogsInThread(); autodetectProcessFactory = new NativeAutodetectProcessFactory(jobProvider, env, settings, nativeController); normalizerProcessFactory = new NativeNormalizerProcessFactory(env, settings, nativeController); } catch (IOException e) { throw new ElasticsearchException("Failed to create native process factories", e); } } else { autodetectProcessFactory = (jobDetails, modelSnapshot, quantiles, filters, ignoreDowntime, executorService) -> new BlackHoleAutodetectProcess(); // factor of 1.0 makes renormalization a no-op normalizerProcessFactory = (jobId, quantilesState, bucketSpan, perPartitionNormalization, executorService) -> new MultiplyingNormalizerProcess(settings, 1.0); } NormalizerFactory normalizerFactory = new NormalizerFactory(normalizerProcessFactory, threadPool.executor(MlPlugin.THREAD_POOL_NAME)); AutodetectResultsParser autodetectResultsParser = new AutodetectResultsParser(settings); AutodetectProcessManager dataProcessor = new AutodetectProcessManager(settings, client, threadPool, jobManager, jobProvider, jobResultsPersister, jobRenormalizedResultsPersister, jobDataCountsPersister, autodetectResultsParser, autodetectProcessFactory, normalizerFactory); DatafeedJobRunner datafeedJobRunner = new DatafeedJobRunner(threadPool, client, clusterService, jobProvider, System::currentTimeMillis); return Arrays.asList( jobProvider, jobManager, dataProcessor, new MlInitializationService(settings, threadPool, clusterService, jobProvider), jobDataCountsPersister, datafeedJobRunner ); } @Override public List<RestHandler> getRestHandlers(Settings settings, RestController restController, ClusterSettings clusterSettings, IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver, Supplier<DiscoveryNodes> nodesInCluster) { if (false == enabled) { return emptyList(); } return Arrays.asList( new RestGetJobsAction(settings, restController), new RestGetJobStatsAction(settings, restController), new RestPutJobAction(settings, restController), new RestDeleteJobAction(settings, restController), new RestOpenJobAction(settings, restController), new RestGetFiltersAction(settings, restController), new RestPutFilterAction(settings, restController), new RestDeleteFilterAction(settings, restController), new RestGetInfluencersAction(settings, restController), new RestGetRecordsAction(settings, restController), new RestGetBucketsAction(settings, restController), new RestPostDataAction(settings, restController), new RestCloseJobAction(settings, restController), new RestFlushJobAction(settings, restController), new RestValidateDetectorAction(settings, restController), new RestGetCategoriesAction(settings, restController), new RestGetModelSnapshotsAction(settings, restController), new RestRevertModelSnapshotAction(settings, restController), new RestUpdateModelSnapshotAction(settings, restController), new RestGetDatafeedsAction(settings, restController), new RestGetDatafeedStatsAction(settings, restController), new RestPutDatafeedAction(settings, restController), new RestDeleteDatafeedAction(settings, restController), new RestStartDatafeedAction(settings, restController), new RestStopDatafeedAction(settings, restController), new RestDeleteModelSnapshotAction(settings, restController) ); } @Override public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() { if (false == enabled) { return emptyList(); } return Arrays.asList( new ActionHandler<>(GetJobsAction.INSTANCE, GetJobsAction.TransportAction.class), new ActionHandler<>(GetJobsStatsAction.INSTANCE, GetJobsStatsAction.TransportAction.class), new ActionHandler<>(PutJobAction.INSTANCE, PutJobAction.TransportAction.class), new ActionHandler<>(DeleteJobAction.INSTANCE, DeleteJobAction.TransportAction.class), new ActionHandler<>(OpenJobAction.INSTANCE, OpenJobAction.TransportAction.class), new ActionHandler<>(InternalOpenJobAction.INSTANCE, InternalOpenJobAction.TransportAction.class), new ActionHandler<>(UpdateJobStatusAction.INSTANCE, UpdateJobStatusAction.TransportAction.class), new ActionHandler<>(UpdateDatafeedStatusAction.INSTANCE, UpdateDatafeedStatusAction.TransportAction.class), new ActionHandler<>(GetFiltersAction.INSTANCE, GetFiltersAction.TransportAction.class), new ActionHandler<>(PutFilterAction.INSTANCE, PutFilterAction.TransportAction.class), new ActionHandler<>(DeleteFilterAction.INSTANCE, DeleteFilterAction.TransportAction.class), new ActionHandler<>(GetBucketsAction.INSTANCE, GetBucketsAction.TransportAction.class), new ActionHandler<>(GetInfluencersAction.INSTANCE, GetInfluencersAction.TransportAction.class), new ActionHandler<>(GetRecordsAction.INSTANCE, GetRecordsAction.TransportAction.class), new ActionHandler<>(PostDataAction.INSTANCE, PostDataAction.TransportAction.class), new ActionHandler<>(CloseJobAction.INSTANCE, CloseJobAction.TransportAction.class), new ActionHandler<>(FlushJobAction.INSTANCE, FlushJobAction.TransportAction.class), new ActionHandler<>(ValidateDetectorAction.INSTANCE, ValidateDetectorAction.TransportAction.class), new ActionHandler<>(GetCategoriesAction.INSTANCE, GetCategoriesAction.TransportAction.class), new ActionHandler<>(GetModelSnapshotsAction.INSTANCE, GetModelSnapshotsAction.TransportAction.class), new ActionHandler<>(RevertModelSnapshotAction.INSTANCE, RevertModelSnapshotAction.TransportAction.class), new ActionHandler<>(UpdateModelSnapshotAction.INSTANCE, UpdateModelSnapshotAction.TransportAction.class), new ActionHandler<>(GetDatafeedsAction.INSTANCE, GetDatafeedsAction.TransportAction.class), new ActionHandler<>(GetDatafeedsStatsAction.INSTANCE, GetDatafeedsStatsAction.TransportAction.class), new ActionHandler<>(PutDatafeedAction.INSTANCE, PutDatafeedAction.TransportAction.class), new ActionHandler<>(DeleteDatafeedAction.INSTANCE, DeleteDatafeedAction.TransportAction.class), new ActionHandler<>(StartDatafeedAction.INSTANCE, StartDatafeedAction.TransportAction.class), new ActionHandler<>(InternalStartDatafeedAction.INSTANCE, InternalStartDatafeedAction.TransportAction.class), new ActionHandler<>(StopDatafeedAction.INSTANCE, StopDatafeedAction.TransportAction.class), new ActionHandler<>(DeleteModelSnapshotAction.INSTANCE, DeleteModelSnapshotAction.TransportAction.class) ); } public static Path resolveConfigFile(Environment env, String name) { return env.configFile().resolve(NAME).resolve(name); } @Override public List<ExecutorBuilder<?>> getExecutorBuilders(Settings settings) { if (false == enabled) { return emptyList(); } int maxNumberOfJobs = AutodetectProcessManager.MAX_RUNNING_JOBS_PER_NODE.get(settings); FixedExecutorBuilder ml = new FixedExecutorBuilder(settings, THREAD_POOL_NAME, maxNumberOfJobs * 2, 1000, "xpack.ml.thread_pool"); // fail quick to run autodetect process / datafeed, so no queues // 4 threads: for c++ logging, result processing, state processing and restore state FixedExecutorBuilder autoDetect = new FixedExecutorBuilder(settings, AUTODETECT_PROCESS_THREAD_POOL_NAME, maxNumberOfJobs * 4, 4, "xpack.ml.autodetect_process_thread_pool"); // TODO: if datafeed and non datafeed jobs are considered more equal and the datafeed and // autodetect process are created at the same time then these two different TPs can merge. FixedExecutorBuilder datafeed = new FixedExecutorBuilder(settings, DATAFEED_RUNNER_THREAD_POOL_NAME, maxNumberOfJobs, 1, "xpack.ml.datafeed_thread_pool"); return Arrays.asList(ml, autoDetect, datafeed); } }
package org.projog.core.function.io; import static org.projog.core.term.ListUtils.toJavaUtilList; import static org.projog.core.term.TermUtils.toLong; import java.util.List; import org.projog.core.function.AbstractSingletonPredicate; import org.projog.core.term.ListUtils; import org.projog.core.term.Term; import org.projog.core.term.TermFormatter; import org.projog.core.term.TermUtils; /* TEST %QUERY writef('%s%n %t%r', [[h,e,l,l,o], 44, world, !, 3]) %OUTPUT hello, world!!! %ANSWER/ %QUERY writef('.%7l.\n.%7l.\n.%7l.\n.%7l.\n.%7l.', [a, abc, abcd, abcdefg, abcdefgh]) %OUTPUT % .a . % .abc . % .abcd . % .abcdefg. % .abcdefgh. %OUTPUT %ANSWER/ %QUERY writef('.%7r.\n.%7r.\n.%7r.\n.%7r.\n.%7r.', [a, abc, abcd, abcdefg, abcdefgh]) %OUTPUT % . a. % . abc. % . abcd. % .abcdefg. % .abcdefgh. %OUTPUT %ANSWER/ %QUERY writef('.%7c.\n.%7c.\n.%7c.\n.%7c.\n.%7c.', [a, abc, abcd, abcdefg, abcdefgh]) %OUTPUT % . a . % . abc . % . abcd . % .abcdefg. % .abcdefgh. %OUTPUT %ANSWER/ %QUERY writef('%w %d', [1+1, 1+1]) %OUTPUT 1 + 1 +(1, 1) %ANSWER/ %QUERY writef('\%\%%q\\\\\r\n\u0048',[abc]) %OUTPUT % %%abc\\ % H %OUTPUT %ANSWER/ */ /** * <code>writef(X,Y)</code> - writes formatted text to the output stream. * <p> * The first argument is an atom representing the text to be output. The text can contain special character sequences which specify formatting and substitution rules. * </p> * <p> * Supported special character sequences are: * <table> * <tr><th>Sequence</th><th>Action</th></tr> * <tr><td>\n</td><td>Output a 'new line' character (ASCII code 10).</td></tr> * <tr><td>\l</td><td>Same as <code>\n</code>.</td></tr> * <tr><td>\r</td><td>Output a 'carriage return' character (ASCII code 13).</td></tr> * <tr><td>\t</td><td>Output a tab character (ASCII code 9).</td></tr> * <tr><td>\\</td><td>Output the <code>\</code> character.</td></tr> * <tr><td>\%</td><td>Output the <code>%</code> character.</td></tr> * <tr><td>\\u<i>NNNN</i></td><td>Output the unicode character represented by the hex digits <i>NNNN</i>.</td></tr> * * <tr><td>%t</td><td>Output the next term - in same format as <code>write/1</code>.</td></tr> * <tr><td>%w</td><td>Same as <code>\t</code>.</td></tr> * <tr><td>%q</td><td>Same as <code>\t</code>.</td></tr> * <tr><td>%p</td><td>Same as <code>\t</code>.</td></tr> * <tr><td>%d</td><td>Output the next term - in same format as <code>write_canonical/1</code>.</td></tr> * <tr><td>%f</td><td>Ignored (only included to support compatibility with other Prologs).</td></tr> * <tr><td>%s</td><td>Output the elements contained in the list represented by the next term.</td></tr> * <tr><td>%n</td><td>Output the character code of the next term.</td></tr> * <tr><td>%r</td><td>Write the next term <i>N</i> times, where <i>N</i> is the value of the second term.</td></tr> * <tr><td>%<i>N</i>c</td><td>Write the next term centered in <i>N</i> columns.</td></tr> * <tr><td>%<i>N</i>l</td><td>Write the next term left-aligned in <i>N</i> columns.</td></tr> * <tr><td>%<i>N</i>r</td><td>Write the next term right-aligned in <i>N</i> columns.</td></tr> * </table> * </p> */ public final class Writef extends AbstractSingletonPredicate { @Override public boolean evaluate(Term atom, Term list) { final String text = TermUtils.getAtomName(atom); final List<Term> args = toJavaUtilList(list); if (args == null) { return false; } final StringBuilder sb = format(text, args); print(sb); return true; } private StringBuilder format(final String text, final List<Term> args) { final Formatter f = new Formatter(text, args, termFormatter()); while (f.hasMore()) { final int c = f.pop(); if (c == '%') { parsePercentEscapeSequence(f); } else if (c == '\\') { parseSlashEscapeSequence(f); } else { f.writeChar(c); } } return f.output; } private TermFormatter termFormatter() { return new TermFormatter(getKnowledgeBase().getOperands()); } private void parsePercentEscapeSequence(final Formatter f) { final int next = f.pop(); if (next == 'f') { // flush - not supported, so ignore return; } final Term arg = f.nextArg(); final String output; switch (next) { case 't': case 'w': case 'q': case 'p': output = f.format(arg); break; case 'n': long charCode = toLong(getKnowledgeBase(), arg); output = Character.toString((char) charCode); break; case 'r': long timesToRepeat = toLong(getKnowledgeBase(), f.nextArg()); output = repeat(f.format(arg), timesToRepeat); break; case 's': output = concat(f, arg); break; case 'd': // Write the term, ignoring operators. output = arg.toString(); break; default: f.rewind(); output = align(f, arg); } f.writeString(output); } private String repeat(final String text, long timesToRepeat) { StringBuilder sb = new StringBuilder(); for (long i = 0; i < timesToRepeat; i++) { sb.append(text); } return sb.toString(); } private String concat(final Formatter f, final Term t) { List<Term> l = ListUtils.toJavaUtilList(t); if (l == null) { throw new IllegalArgumentException("Expected list but got: " + t); } StringBuilder sb = new StringBuilder(); for (Term e : l) { sb.append(f.format(e)); } return sb.toString(); } private String align(final Formatter f, final Term t) { String s = f.format(t); int actualWidth = s.length(); int requiredWidth = parseNumber(f); int diff = Math.max(0, requiredWidth - actualWidth); int alignmentChar = f.pop(); switch (alignmentChar) { case 'l': return s + getWhitespace(diff); case 'r': return getWhitespace(diff) + s; case 'c': String prefix = getWhitespace(diff / 2); String suffix = diff % 2 == 0 ? prefix : prefix + " "; return prefix + s + suffix; default: throw new IllegalArgumentException("? " + alignmentChar); } } private String getWhitespace(int diff) { String s = ""; for (int i = 0; i < diff; i++) { s += " "; } return s; } private int parseNumber(Formatter f) { int next = 0; while (isNumber(f.peek())) { next = (next * 10) + (f.pop() - '0'); } return next; } private void parseSlashEscapeSequence(final Formatter f) { final int next = f.pop(); final int output; switch (next) { case 'l': case 'n': output = '\n'; break; case 'r': output = '\r'; break; case 't': output = '\t'; break; case '\\': output = '\\'; break; case '%': output = '%'; break; case 'u': output = parseUnicode(f); break; default: throw new IllegalArgumentException("? " + next); } f.writeChar(output); } private int parseUnicode(final Formatter f) { final StringBuilder sb = new StringBuilder(); sb.append((char) f.pop()); sb.append((char) f.pop()); sb.append((char) f.pop()); sb.append((char) f.pop()); return Integer.parseInt(sb.toString(), 16); } private boolean isNumber(int c) { return c >= '0' && c <= '9'; } private void print(final StringBuilder sb) { getKnowledgeBase().getFileHandles().getCurrentOutputStream().print(sb); } private static class Formatter { final StringBuilder output = new StringBuilder(); final char[] chars; final List<Term> args; final TermFormatter termFormatter; int charIdx; int argIdx; Formatter(String text, List<Term> args, TermFormatter termFormatter) { this.chars = text.toCharArray(); this.args = args; this.termFormatter = termFormatter; } public void rewind() { charIdx } Term nextArg() { return args.get(argIdx++); } String format(Term t) { return termFormatter.toString(t); } int peek() { if (hasMore()) { return chars[charIdx]; } else { return -1; } } int pop() { int c = peek(); charIdx++; return c; } boolean hasMore() { return charIdx < chars.length; } void writeChar(int c) { output.append((char) c); } void writeString(String s) { output.append(s); } } }
package org.flymine.gbrowse; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.io.File; import java.io.PrintWriter; import java.io.FileWriter; import java.io.PrintStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.tools.ant.Task; import org.apache.tools.ant.BuildException; import org.biojava.bio.program.gff.SimpleGFFRecord; import org.biojava.bio.symbol.IllegalSymbolException; import org.intermine.objectstore.query.*; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.TypeUtil; import org.intermine.util.DynamicUtil; import org.intermine.objectstore.proxy.ProxyCollection; import org.flymine.postprocess.PostProcessUtil; import org.flymine.model.genomic.*; import org.apache.log4j.Logger; /** * A Task for creating GFF and FASTA files for use by GBrowse. Only those features that are * located on a Chromosome are written. * @author Kim Rutherford */ public class WriteGFFTask extends Task { protected static final Logger LOG = Logger.getLogger(WriteGFFTask.class); private String alias; private File destinationDirectory; /** * Set the ObjectStore alias to read from * @param alias name of the ObjectStore */ public void setAlias(String alias) { this.alias = alias; } /** * Set the name of the directory where the GFF and FASTA files should be created. * @param destinationDirectory the directory for creating new files in. */ public void setDest(File destinationDirectory) { this.destinationDirectory = destinationDirectory; } /** * @see Task#execute */ public void execute() throws BuildException { if (destinationDirectory == null) { throw new BuildException("dest attribute is not set"); } if (alias == null) { throw new BuildException("alias attribute is not set"); } ObjectStore os = null; try { os = ObjectStoreFactory.getObjectStore(alias); writeGFF(os, destinationDirectory); } catch (Exception e) { e.printStackTrace(System.out); throw new BuildException(e); } } void writeGFF(ObjectStore os, File destinationDirectory) throws ObjectStoreException, IOException, IllegalSymbolException { Results results = PostProcessUtil.findLocations(os, Chromosome.class, BioEntity.class, false); results.setBatchSize(2000); Iterator resIter = results.iterator(); PrintWriter gffWriter = null; // a Map of object classes to counts Map objectCounts = null; // Map from Transcript to Location (on Chromosome) Map seenTranscripts = new HashMap(); // Map from exon to Location (on Chromosome) Map seenTranscriptParts = new HashMap(); // the last Chromosome seen Integer currentChrId = null; Chromosome currentChr = null; Map synonymMap = null; while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Integer resultChrId = (Integer) rr.get(0); BioEntity feature = (BioEntity) rr.get(1); Location loc = (Location) rr.get(2); if (currentChrId == null || !currentChrId.equals(resultChrId)) { synonymMap = makeSynonymMap(os, resultChrId); if (currentChrId != null) { writeTranscriptsAndExons(gffWriter, currentChr, seenTranscripts, seenTranscriptParts, synonymMap); seenTranscripts = new HashMap(); seenTranscriptParts = new HashMap(); } currentChr = (Chromosome) os.getObjectById(resultChrId); if (!currentChr.getIdentifier().endsWith("_random") && !currentChr.getIdentifier().equals("M")) { writeChromosomeFasta(destinationDirectory, currentChr); File gffFile = chromosomeGFFFile(destinationDirectory, currentChr); if (gffWriter != null) { gffWriter.close(); } gffWriter = new PrintWriter(new FileWriter(gffFile)); writeFeature(gffWriter, currentChr, currentChr, null, chromosomeFileNamePrefix(currentChr), new Integer(0), "chromosome", "Chromosome", null, synonymMap, currentChr.getId()); objectCounts = new HashMap(); currentChrId = resultChrId; } } // process Transcripts but not tRNAs if (feature instanceof Transcript && !(feature instanceof NcRNA)) { seenTranscripts.put(feature, loc); } if (feature instanceof Exon) { seenTranscriptParts.put(feature, loc); } if (!currentChr.getIdentifier().endsWith("_random") && !currentChr.getIdentifier().equals("M")) { String identifier = feature.getIdentifier(); String featureType = getFeatureName(feature); if (identifier == null) { identifier = featureType + "_" + objectCounts.get(feature.getClass()); } writeFeature(gffWriter, currentChr, feature, loc, identifier, null, featureType.toLowerCase(), featureType, null, synonymMap, feature.getId()); } incrementCount(objectCounts, feature); } if (!currentChr.getIdentifier().endsWith("_random") && !currentChr.getIdentifier().equals("M")) { writeTranscriptsAndExons(gffWriter, currentChr, seenTranscripts, seenTranscriptParts, synonymMap); } gffWriter.close(); } private String getFeatureName(BioEntity feature) { Class bioEntityClass = feature.getClass(); Set classes = DynamicUtil.decomposeClass(bioEntityClass); StringBuffer nameBuffer = new StringBuffer(); Iterator iter = classes.iterator(); while (iter.hasNext()) { Class thisClass = (Class) iter.next(); if (nameBuffer.length() > 0) { nameBuffer.append("_"); } else { nameBuffer.append(TypeUtil.unqualifiedName(thisClass.getName())); } } return nameBuffer.toString(); } private void writeTranscriptsAndExons(PrintWriter gffWriter, Chromosome chr, Map seenTranscripts, Map seenTranscriptParts, Map synonymMap) throws IOException { Iterator transcriptIter = seenTranscripts.keySet().iterator(); while (transcriptIter.hasNext()) { Transcript transcript = (Transcript) transcriptIter.next(); Gene gene = transcript.getGene(); if (gene == null) { continue; } Location transcriptLocation = (Location) seenTranscripts.get(transcript); String transcriptFeatureType = null; if (gene instanceof Pseudogene) { transcriptFeatureType = "pseudogene_mRNA"; } else { transcriptFeatureType = "gene_mRNA"; } Map geneNameAttributeMap = new HashMap(); ArrayList geneNameList = new ArrayList(); geneNameList.add(gene.getIdentifier()); geneNameAttributeMap.put("Gene", geneNameList); writeFeature(gffWriter, chr, transcript, transcriptLocation, transcript.getIdentifier(), null, transcriptFeatureType, "mRNA", geneNameAttributeMap, synonymMap, transcript.getId()); Collection exons = transcript.getExons(); ProxyCollection exonsResults = (ProxyCollection) exons; // exon collections are small enough that optimisation just slows things down exonsResults.setNoOptimise(); exonsResults.setNoExplain(); String exonFeatureType = null; if (gene instanceof Pseudogene) { exonFeatureType = "pseudogene_CDS"; } else { exonFeatureType = "gene_CDS"; } Iterator exonIter = exons.iterator(); while (exonIter.hasNext()) { Exon exon = (Exon) exonIter.next(); Location exonLocation = (Location) seenTranscriptParts.get(exon); writeFeature(gffWriter, chr, exon, exonLocation, transcript.getIdentifier(), null, exonFeatureType, "mRNA", null, synonymMap, transcript.getId()); } } } private void incrementCount(Map objectCounts, Object object) { if (objectCounts.containsKey(object.getClass())) { int oldCount = ((Integer) objectCounts.get(object.getClass())).intValue(); objectCounts.put(object.getClass(), new Integer(oldCount + 1)); } else { objectCounts.put(object.getClass(), new Integer(1)); } } private static final String FLYMINE_STRING = "flymine"; /** * @param bioEntity the obejct to write * @param location the location of the object on the chromosome * @param index the index of this object (first object written is 0, then 1, ...) * @param featureType the type (third output column) to be used when writing - null means create * the featureType automatically from the java class name on the object to write * @param idType the type tag to use when storing the ID in the attributes Map - null means use * the featureType * @param flyMineId */ private void writeFeature(PrintWriter gffWriter, Chromosome chr, BioEntity bioEntity, Location location, String identifier, Integer index, String featureType, String idType, Map extraAttributes, Map synonymMap, Integer flyMineId) throws IOException { if (index == null) { index = new Integer(0); } StringBuffer lineBuffer = new StringBuffer(); lineBuffer.append(chromosomeFileNamePrefix(chr)).append("\t"); lineBuffer.append(FLYMINE_STRING).append("\t"); lineBuffer.append(featureType).append("\t"); if (location == null && bioEntity == chr) { // special case for Chromosome location lineBuffer.append(1).append("\t").append(chr.getLength()).append("\t"); } else { lineBuffer.append(location.getStart()).append("\t"); lineBuffer.append(location.getEnd()).append("\t"); } lineBuffer.append(0).append("\t"); int strand; if (location == null) { lineBuffer.append("."); } else { if (location.getStrand().intValue() == 1) { lineBuffer.append("+"); } else { if (location.getStrand().intValue() == -1) { lineBuffer.append("-"); } else { lineBuffer.append("."); } } } lineBuffer.append("\t"); if (location == null) { lineBuffer.append("."); } else { if (location.getPhase() == null) { lineBuffer.append("."); } else { lineBuffer.append(location.getPhase()); } } lineBuffer.append("\t"); Map attributes = new LinkedHashMap(); List identifiers = new ArrayList(); identifiers.add(identifier); attributes.put(idType, identifiers); ArrayList flyMineIDs = new ArrayList(); flyMineIDs.add("FlyMineInternalID_" + flyMineId); attributes.put("FlyMineInternalID", flyMineIDs.clone()); List allIds = (List) flyMineIDs.clone(); List synonymValues = (List) synonymMap.get(bioEntity.getId()); if (synonymValues == null) { LOG.warn("cannot find any synonyms for: " + bioEntity.getId() + " identifier: " + bioEntity.getIdentifier()); } else { Iterator synonymIter = synonymValues.iterator(); while (synonymIter.hasNext()) { String thisSynonymValue = (String) synonymIter.next(); if (!allIds.contains(thisSynonymValue)) { allIds.add(thisSynonymValue); } } } attributes.put("Alias", allIds); if (extraAttributes != null) { Iterator extraAttributesIter = extraAttributes.keySet().iterator(); while (extraAttributesIter.hasNext()) { String key = (String) extraAttributesIter.next(); attributes.put(key, extraAttributes.get(key)); } } if (bioEntity instanceof ChromosomeBand) { ArrayList indexList = new ArrayList(); indexList.add(index.toString()); attributes.put("Index", indexList); } if (bioEntity instanceof PCRProduct) { ArrayList promoterFlagList = new ArrayList(); promoterFlagList.add(((PCRProduct) bioEntity).getPromoter().toString()); attributes.put("promoter", promoterFlagList); } lineBuffer.append(stringifyAttributes(attributes)); gffWriter.println(lineBuffer.toString()); } /** * Taken from BioJava's SimpleGFFRecord.java */ static String stringifyAttributes(Map attMap) { StringBuffer sBuff = new StringBuffer(); Iterator ki = attMap.keySet().iterator(); while (ki.hasNext()) { String key = (String) ki.next(); List values = (List) attMap.get(key); if (values.size() == 0) { sBuff.append(key); sBuff.append(";"); } else { for (Iterator vi = values.iterator(); vi.hasNext();) { sBuff.append(key); String value = (String) vi.next(); sBuff.append(" \"" + value + "\""); if (ki.hasNext() || vi.hasNext()) { sBuff.append(";"); } if (vi.hasNext()) { sBuff.append(" "); } } } if (ki.hasNext()) { sBuff.append(" "); } } return sBuff.toString(); } /** * Make a Map from BioEntity ID to List of Synonym values (Strings) for BioEntity objects * located on the chromosome with the given ID. * @param os the ObjectStore to read from * @param chromosomeId the chromosome ID of the BioEntity objects to examine * @return */ private Map makeSynonymMap(ObjectStore os, Integer chromosomeId) { Query q = new Query(); q.setDistinct(true); QueryClass qcEnt = new QueryClass(BioEntity.class); QueryField qfEnt = new QueryField(qcEnt, "id"); q.addFrom(qcEnt); q.addToSelect(qfEnt); QueryClass qcSyn = new QueryClass(Synonym.class); QueryField qfSyn = new QueryField(qcSyn, "value"); q.addFrom(qcSyn); q.addToSelect(qfSyn); QueryClass qcLoc = new QueryClass(Location.class); q.addFrom(qcLoc); QueryClass qcChr = new QueryClass(Chromosome.class); QueryField qfChr = new QueryField(qcChr, "id"); q.addFrom(qcChr); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryCollectionReference col = new QueryCollectionReference(qcEnt, "synonyms"); ContainsConstraint cc1 = new ContainsConstraint(col, ConstraintOp.CONTAINS, qcSyn); cs.addConstraint(cc1); QueryValue chrIdQueryValue = new QueryValue(chromosomeId); SimpleConstraint sc = new SimpleConstraint(qfChr, ConstraintOp.EQUALS, chrIdQueryValue); cs.addConstraint(sc); QueryObjectReference ref1 = new QueryObjectReference(qcLoc, "subject"); ContainsConstraint cc2 = new ContainsConstraint(ref1, ConstraintOp.CONTAINS, qcEnt); cs.addConstraint(cc2); QueryObjectReference ref2 = new QueryObjectReference(qcLoc, "object"); ContainsConstraint cc3 = new ContainsConstraint(ref2, ConstraintOp.CONTAINS, qcChr); cs.addConstraint(cc3); q.setConstraint(cs); Results res = new Results(q, os, os.getSequence()); res.setBatchSize(50000); Iterator resIter = res.iterator(); Map returnMap = new HashMap(); while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Integer bioEntityId = (Integer) rr.get(0); String synonymValue = (String) rr.get(1); List synonymValues = (List) returnMap.get(bioEntityId); if (synonymValues == null) { synonymValues = new ArrayList(); returnMap.put(bioEntityId, synonymValues); } synonymValues.add(synonymValue); } return returnMap; } private void writeChromosomeFasta(File destinationDirectory, Chromosome chr) throws IOException, IllegalArgumentException { Sequence chromosomeSequence = chr.getSequence(); FileOutputStream fileStream = new FileOutputStream(chromosomeFastaFile(destinationDirectory, chr)); PrintStream printStream = new PrintStream(fileStream); printStream.println(">" + chromosomeFileNamePrefix(chr)); String residues = chromosomeSequence.getResidues(); // code from BioJava's FastaFormat class: int length = residues.length(); for (int pos = 0; pos < length; pos += 60) { int end = Math.min(pos + 60, length); printStream.println(residues.substring(pos, end)); } printStream.close(); fileStream.close(); } private File chromosomeFastaFile(File destinationDirectory, Chromosome chr) { return new File(destinationDirectory, chromosomeFileNamePrefix(chr) + ".fa"); } private File chromosomeGFFFile(File destinationDirectory, Chromosome chr) { return new File(destinationDirectory, chromosomeFileNamePrefix(chr) + ".gff"); } private String chromosomeFileNamePrefix(Chromosome chr) { return chr.getOrganism().getGenus() + "_" + chr.getOrganism().getSpecies() + "_chr_" + chr.getIdentifier(); } }
package org.flymine.gbrowse; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.io.File; import java.io.PrintWriter; import java.io.FileWriter; import java.io.PrintStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.tools.ant.Task; import org.apache.tools.ant.BuildException; import org.biojava.bio.program.gff.SimpleGFFRecord; import org.biojava.bio.symbol.IllegalSymbolException; import org.intermine.objectstore.query.*; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.TypeUtil; import org.intermine.util.DynamicUtil; import org.intermine.objectstore.proxy.ProxyCollection; import org.flymine.postprocess.PostProcessUtil; import org.flymine.model.genomic.*; import org.apache.log4j.Logger; /** * A Task for creating GFF and FASTA files for use by GBrowse. Only those features that are * located on a Chromosome are written. * @author Kim Rutherford */ public class WriteGFFTask extends Task { protected static final Logger LOG = Logger.getLogger(WriteGFFTask.class); private String alias; private File destinationDirectory; /** * Set the ObjectStore alias to read from * @param alias name of the ObjectStore */ public void setAlias(String alias) { this.alias = alias; } /** * Set the name of the directory where the GFF and FASTA files should be created. * @param destinationDirectory the directory for creating new files in. */ public void setDest(File destinationDirectory) { this.destinationDirectory = destinationDirectory; } /** * @see Task#execute */ public void execute() throws BuildException { if (destinationDirectory == null) { throw new BuildException("dest attribute is not set"); } if (alias == null) { throw new BuildException("alias attribute is not set"); } ObjectStore os = null; try { os = ObjectStoreFactory.getObjectStore(alias); writeGFF(os, destinationDirectory); } catch (Exception e) { e.printStackTrace(System.out); throw new BuildException(e); } } void writeGFF(ObjectStore os, File destinationDirectory) throws ObjectStoreException, IOException, IllegalSymbolException { Results results = PostProcessUtil.findLocations(os, Chromosome.class, BioEntity.class, false); results.setBatchSize(2000); Iterator resIter = results.iterator(); PrintWriter gffWriter = null; // a Map of object classes to counts Map objectCounts = null; // Map from Transcript to Location (on Chromosome) Map seenTranscripts = new HashMap(); // Map from exon to Location (on Chromosome) Map seenTranscriptParts = new HashMap(); // the last Chromosome seen Integer currentChrId = null; Chromosome currentChr = null; Map synonymMap = null; while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Integer resultChrId = (Integer) rr.get(0); BioEntity feature = (BioEntity) rr.get(1); Location loc = (Location) rr.get(2); if (currentChrId == null || !currentChrId.equals(resultChrId)) { synonymMap = makeSynonymMap(os, resultChrId); if (currentChrId != null) { writeTranscriptsAndExons(gffWriter, currentChr, seenTranscripts, seenTranscriptParts, synonymMap); seenTranscripts = new HashMap(); seenTranscriptParts = new HashMap(); } currentChr = (Chromosome) os.getObjectById(resultChrId); if (!currentChr.getIdentifier().endsWith("_random") && !currentChr.getIdentifier().equals("M")) { writeChromosomeFasta(destinationDirectory, currentChr); File gffFile = chromosomeGFFFile(destinationDirectory, currentChr); if (gffWriter != null) { gffWriter.close(); } gffWriter = new PrintWriter(new FileWriter(gffFile)); writeFeature(gffWriter, currentChr, currentChr, null, chromosomeFileNamePrefix(currentChr), new Integer(0), "chromosome", "Chromosome", null, synonymMap, feature.getId()); objectCounts = new HashMap(); currentChrId = resultChrId; } } // process Transcripts but not tRNAs if (feature instanceof Transcript && !(feature instanceof NcRNA)) { seenTranscripts.put(feature, loc); } if (feature instanceof Exon) { seenTranscriptParts.put(feature, loc); } if (!currentChr.getIdentifier().endsWith("_random") && !currentChr.getIdentifier().equals("M")) { String identifier = feature.getIdentifier(); String featureType = getFeatureName(feature); if (identifier == null) { identifier = featureType + "_" + objectCounts.get(feature.getClass()); } writeFeature(gffWriter, currentChr, feature, loc, identifier, null, featureType.toLowerCase(), featureType, null, synonymMap, feature.getId()); } incrementCount(objectCounts, feature); } if (!currentChr.getIdentifier().endsWith("_random") && !currentChr.getIdentifier().equals("M")) { writeTranscriptsAndExons(gffWriter, currentChr, seenTranscripts, seenTranscriptParts, synonymMap); } gffWriter.close(); } private String getFeatureName(BioEntity feature) { Class bioEntityClass = feature.getClass(); Set classes = DynamicUtil.decomposeClass(bioEntityClass); StringBuffer nameBuffer = new StringBuffer(); Iterator iter = classes.iterator(); while (iter.hasNext()) { Class thisClass = (Class) iter.next(); if (nameBuffer.length() > 0) { nameBuffer.append("_"); } else { nameBuffer.append(TypeUtil.unqualifiedName(thisClass.getName())); } } return nameBuffer.toString(); } private void writeTranscriptsAndExons(PrintWriter gffWriter, Chromosome chr, Map seenTranscripts, Map seenTranscriptParts, Map synonymMap) throws IOException { Iterator transcriptIter = seenTranscripts.keySet().iterator(); while (transcriptIter.hasNext()) { Transcript transcript = (Transcript) transcriptIter.next(); Gene gene = transcript.getGene(); if (gene == null) { continue; } Location transcriptLocation = (Location) seenTranscripts.get(transcript); String transcriptFeatureType = null; if (gene instanceof Pseudogene) { transcriptFeatureType = "pseudogene_mRNA"; } else { transcriptFeatureType = "gene_mRNA"; } Map geneNameAttributeMap = new HashMap(); ArrayList geneNameList = new ArrayList(); geneNameList.add(gene.getIdentifier()); geneNameAttributeMap.put("Gene", geneNameList); writeFeature(gffWriter, chr, transcript, transcriptLocation, transcript.getIdentifier(), null, transcriptFeatureType, "mRNA", geneNameAttributeMap, synonymMap, transcript.getId()); Collection exons = transcript.getExons(); ProxyCollection exonsResults = (ProxyCollection) exons; // exon collections are small enough that optimisation just slows things down exonsResults.setNoOptimise(); exonsResults.setNoExplain(); String exonFeatureType = null; if (gene instanceof Pseudogene) { exonFeatureType = "pseudogene_CDS"; } else { exonFeatureType = "gene_CDS"; } Iterator exonIter = exons.iterator(); while (exonIter.hasNext()) { Exon exon = (Exon) exonIter.next(); Location exonLocation = (Location) seenTranscriptParts.get(exon); writeFeature(gffWriter, chr, exon, exonLocation, transcript.getIdentifier(), null, exonFeatureType, "mRNA", null, synonymMap, transcript.getId()); } } } private void incrementCount(Map objectCounts, Object object) { if (objectCounts.containsKey(object.getClass())) { int oldCount = ((Integer) objectCounts.get(object.getClass())).intValue(); objectCounts.put(object.getClass(), new Integer(oldCount + 1)); } else { objectCounts.put(object.getClass(), new Integer(1)); } } private static final String FLYMINE_STRING = "flymine"; /** * @param bioEntity the obejct to write * @param location the location of the object on the chromosome * @param index the index of this object (first object written is 0, then 1, ...) * @param featureType the type (third output column) to be used when writing - null means create * the featureType automatically from the java class name on the object to write * @param idType the type tag to use when storing the ID in the attributes Map - null means use * the featureType * @param flyMineId */ private void writeFeature(PrintWriter gffWriter, Chromosome chr, BioEntity bioEntity, Location location, String identifier, Integer index, String featureType, String idType, Map extraAttributes, Map synonymMap, Integer flyMineId) throws IOException { if (index == null) { index = new Integer(0); } StringBuffer lineBuffer = new StringBuffer(); lineBuffer.append(chromosomeFileNamePrefix(chr)).append("\t"); lineBuffer.append(FLYMINE_STRING).append("\t"); lineBuffer.append(featureType).append("\t"); if (location == null && bioEntity == chr) { // special case for Chromosome location lineBuffer.append(1).append("\t").append(chr.getLength()).append("\t"); } else { lineBuffer.append(location.getStart()).append("\t"); lineBuffer.append(location.getEnd()).append("\t"); } lineBuffer.append(0).append("\t"); int strand; if (location == null) { lineBuffer.append("."); } else { if (location.getStrand().intValue() == 1) { lineBuffer.append("+"); } else { if (location.getStrand().intValue() == -1) { lineBuffer.append("-"); } else { lineBuffer.append("."); } } } lineBuffer.append("\t"); if (location == null) { lineBuffer.append("."); } else { if (location.getPhase() == null) { lineBuffer.append("."); } else { lineBuffer.append(location.getPhase()); } } lineBuffer.append("\t"); Map attributes = new LinkedHashMap(); List identifiers = new ArrayList(); identifiers.add(identifier); attributes.put(idType, identifiers); ArrayList flyMineIDs = new ArrayList(); flyMineIDs.add("FlyMineInternalID_" + flyMineId); attributes.put("FlyMineInternalID", flyMineIDs.clone()); List allIds = (List) flyMineIDs.clone(); List synonymValues = (List) synonymMap.get(bioEntity.getId()); if (synonymValues == null) { LOG.warn("cannot find any synonyms for: " + bioEntity.getId() + " identifier: " + bioEntity.getIdentifier()); } else { Iterator synonymIter = synonymValues.iterator(); while (synonymIter.hasNext()) { String thisSynonymValue = (String) synonymIter.next(); if (!allIds.contains(thisSynonymValue)) { allIds.add(thisSynonymValue); } } } attributes.put("Alias", allIds); if (extraAttributes != null) { Iterator extraAttributesIter = extraAttributes.keySet().iterator(); while (extraAttributesIter.hasNext()) { String key = (String) extraAttributesIter.next(); attributes.put(key, extraAttributes.get(key)); } } if (bioEntity instanceof ChromosomeBand) { ArrayList indexList = new ArrayList(); indexList.add(index.toString()); attributes.put("Index", indexList); } if (bioEntity instanceof PCRProduct) { ArrayList promoterFlagList = new ArrayList(); promoterFlagList.add(((PCRProduct) bioEntity).getPromoter().toString()); attributes.put("promoter", promoterFlagList); } lineBuffer.append(SimpleGFFRecord.stringifyAttributes(attributes)); gffWriter.println(lineBuffer.toString()); } /** * Taken from BioJava's SimpleGFFRecord.java */ static String stringifyAttributes(Map attMap) { StringBuffer sBuff = new StringBuffer(); Iterator ki = attMap.keySet().iterator(); while (ki.hasNext()) { String key = (String) ki.next(); List values = (List) attMap.get(key); if (values.size() == 0) { sBuff.append(key); sBuff.append(";"); } else { for (Iterator vi = values.iterator(); vi.hasNext();) { sBuff.append(key); String value = (String) vi.next(); sBuff.append(" \"" + value + "\""); if (ki.hasNext() || vi.hasNext()) { sBuff.append(";"); } if (vi.hasNext()) { sBuff.append(" "); } } } if (ki.hasNext()) { sBuff.append(" "); } } return sBuff.toString(); } /** * Make a Map from BioEntity ID to List of Synonym values (Strings) for BioEntity objects * located on the chromosome with the given ID. * @param os the ObjectStore to read from * @param chromosomeId the chromosome ID of the BioEntity objects to examine * @return */ private Map makeSynonymMap(ObjectStore os, Integer chromosomeId) { Query q = new Query(); q.setDistinct(true); QueryClass qcEnt = new QueryClass(BioEntity.class); QueryField qfEnt = new QueryField(qcEnt, "id"); q.addFrom(qcEnt); q.addToSelect(qfEnt); QueryClass qcSyn = new QueryClass(Synonym.class); QueryField qfSyn = new QueryField(qcSyn, "value"); q.addFrom(qcSyn); q.addToSelect(qfSyn); QueryClass qcLoc = new QueryClass(Location.class); q.addFrom(qcLoc); QueryClass qcChr = new QueryClass(Chromosome.class); QueryField qfChr = new QueryField(qcChr, "id"); q.addFrom(qcChr); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryCollectionReference col = new QueryCollectionReference(qcEnt, "synonyms"); ContainsConstraint cc1 = new ContainsConstraint(col, ConstraintOp.CONTAINS, qcSyn); cs.addConstraint(cc1); QueryValue chrIdQueryValue = new QueryValue(chromosomeId); SimpleConstraint sc = new SimpleConstraint(qfChr, ConstraintOp.EQUALS, chrIdQueryValue); cs.addConstraint(sc); QueryObjectReference ref1 = new QueryObjectReference(qcLoc, "subject"); ContainsConstraint cc2 = new ContainsConstraint(ref1, ConstraintOp.CONTAINS, qcEnt); cs.addConstraint(cc2); QueryObjectReference ref2 = new QueryObjectReference(qcLoc, "object"); ContainsConstraint cc3 = new ContainsConstraint(ref2, ConstraintOp.CONTAINS, qcChr); cs.addConstraint(cc3); q.setConstraint(cs); Results res = new Results(q, os, os.getSequence()); res.setBatchSize(50000); Iterator resIter = res.iterator(); Map returnMap = new HashMap(); while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Integer bioEntityId = (Integer) rr.get(0); String synonymValue = (String) rr.get(1); List synonymValues = (List) returnMap.get(bioEntityId); if (synonymValues == null) { synonymValues = new ArrayList(); returnMap.put(bioEntityId, synonymValues); } synonymValues.add(synonymValue); } return returnMap; } private void writeChromosomeFasta(File destinationDirectory, Chromosome chr) throws IOException, IllegalArgumentException { Sequence chromosomeSequence = chr.getSequence(); FileOutputStream fileStream = new FileOutputStream(chromosomeFastaFile(destinationDirectory, chr)); PrintStream printStream = new PrintStream(fileStream); printStream.println(">" + chromosomeFileNamePrefix(chr)); String residues = chromosomeSequence.getResidues(); // code from BioJava's FastaFormat class: int length = residues.length(); for (int pos = 0; pos < length; pos += 60) { int end = Math.min(pos + 60, length); printStream.println(residues.substring(pos, end)); } printStream.close(); fileStream.close(); } private File chromosomeFastaFile(File destinationDirectory, Chromosome chr) { return new File(destinationDirectory, chromosomeFileNamePrefix(chr) + ".fa"); } private File chromosomeGFFFile(File destinationDirectory, Chromosome chr) { return new File(destinationDirectory, chromosomeFileNamePrefix(chr) + ".gff"); } private String chromosomeFileNamePrefix(Chromosome chr) { return chr.getOrganism().getGenus() + "_" + chr.getOrganism().getSpecies() + "_chr_" + chr.getIdentifier(); } }
package mitzi; import javax.swing.JFrame; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MitziGUI extends JFrame implements MouseListener, MouseMotionListener { private static final long serialVersionUID = -418000626395118246L; JLayeredPane layeredPane; JPanel chessBoard; JLabel chessPiece; int xAdjustment; int yAdjustment; int start_square; int end_square; private GameState state = new GameState(); Dimension boardSize = new Dimension(800, 800); public MitziGUI() { redraw(); } private void redraw() { // Use a Layered Pane for this this application layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(boardSize); layeredPane.addMouseListener(this); layeredPane.addMouseMotionListener(this); // Add a chess board to the Layered Pane chessBoard = new JPanel(); layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER); chessBoard.setLayout(new GridLayout(8, 8)); chessBoard.setPreferredSize(boardSize); chessBoard.setBounds(0, 0, boardSize.width, boardSize.height); // Color it b/w Color black = Color.getHSBColor((float) 0.10, (float) 0.40, (float) 0.80); Color white = Color.getHSBColor((float) 0.15, (float) 0.13, (float) 0.98); for (int i = 0; i < 64; i++) { JPanel square = new JPanel(new BorderLayout()); chessBoard.add(square); square.setBackground((i + i / 8) % 2 == 0 ? white : black); } getContentPane().removeAll(); getContentPane().add(layeredPane); } private int getSquare(int x, int y) { System.out.println(x + " " + y); x = x / 100 + 1; y = (800 - y) / 100 + 1; return x * 10 + y; } private Component squareToComponent(int squ) { int row = 8 - squ % 10; int col = ((int) squ / 10) - 1; Component c = chessBoard.getComponent(row * 8 + col); return c; } public void setToFEN(String fen) { redraw(); JPanel panel; String[] fen_parts = fen.split(" "); // populate the squares String[] fen_rows = fen_parts[0].split("/"); char[] pieces; for (int row = 0; row < 8; row++) { int offset = 0; for (int column = 0; column + offset < 8; column++) { pieces = fen_rows[row].toCharArray(); int square = row * 8 + column + offset; JLabel piece; switch (pieces[column]) { case 'P': piece = new JLabel(""); break; case 'R': piece = new JLabel(""); break; case 'N': piece = new JLabel(""); break; case 'B': piece = new JLabel(""); break; case 'Q': piece = new JLabel(""); break; case 'K': piece = new JLabel(""); break; case 'p': piece = new JLabel(""); break; case 'r': piece = new JLabel(""); break; case 'n': piece = new JLabel(""); break; case 'b': piece = new JLabel(""); break; case 'q': piece = new JLabel(""); break; case 'k': piece = new JLabel(""); break; default: piece = new JLabel(""); offset += Character.getNumericValue(pieces[column]) - 1; break; } panel = (JPanel) chessBoard.getComponent(square); piece.setFont(new Font("Serif", Font.PLAIN, 100)); panel.add(piece); } } chessBoard.updateUI(); } public void mousePressed(MouseEvent e) { chessPiece = null; Component c = chessBoard.findComponentAt(e.getX(), e.getY()); if (c instanceof JPanel) return; Point parentLocation = c.getParent().getLocation(); xAdjustment = parentLocation.x - e.getX(); yAdjustment = parentLocation.y - e.getY(); start_square = getSquare(e.getX(), e.getY()); chessPiece = (JLabel) c; chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment); chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight()); layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER); } // Move the chess piece around public void mouseDragged(MouseEvent me) { if (chessPiece == null) return; chessPiece .setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment); } // Drop the chess piece back onto the chess board public void mouseReleased(MouseEvent e) { if (chessPiece == null) return; chessPiece.setVisible(false); Component c = chessBoard.findComponentAt(e.getX(), e.getY()); end_square = getSquare(e.getX(), e.getY()); IMove move = new Move(start_square, end_square); try { state.doMove(move); } catch (IllegalArgumentException ex) { Container parent = (Container) squareToComponent(start_square); parent.add(chessPiece); chessPiece.setVisible(true); return; } IPosition position = state.getPosition(); setToFEN(position.toFEN()); // chessPiece.setVisible(false); } public void mouseClicked(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } private Piece askPromotion() { Object[] options = { "Queen", "Rook", "Bishop", "Knight" }; int n = JOptionPane.showOptionDialog(this, "Which piece do you want to promote to?", "Pawn Promotion", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == 0) { return Piece.QUEEN; } else if (n == 1) { return Piece.ROOK; } else if (n == 2) { return Piece.BISHOP; } else { return Piece.KNIGHT; } } public static void main(String[] args) { JFrame frame = new MitziGUI(); frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setTitle("Mitzi GUI"); MitziGUI gui = (MitziGUI) frame; String initialFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; gui.setToFEN(initialFEN); } }
package model; import java.io.*; import java.util.ArrayList; public class TitanDSM { private int sizeOfMatrix; private ArrayList<ArrayList<Boolean>> dataMatrix; private ArrayList<String> nameOfClass; public TitanDSM(int sizeOfMatrix) throws NotPositiveException { if (sizeOfMatrix <= 0) { throw new NotPositiveException(); } this.sizeOfMatrix = sizeOfMatrix; dataMatrix = new ArrayList<>(); nameOfClass = new ArrayList<>(); initDataMatrix(); initNameOfClass(); } public TitanDSM(File file) throws IOException, WrongDSMFormatException { dataMatrix = new ArrayList<>(); nameOfClass = new ArrayList<>(); loadFromFile(file); } private void initNameOfClass() { for(int i = 1; i <= sizeOfMatrix; i++) { nameOfClass.add("entity_" + i); } } private void initDataMatrix() { for(int i = 0; i < sizeOfMatrix; i++) { dataMatrix.add(new ArrayList<>()); for(int j = 0; j < sizeOfMatrix; j++) { dataMatrix.get(i).add(false); } } } public int getSize() { return sizeOfMatrix; } public Boolean getData(String row, String col) { return dataMatrix.get(getIndexByName(row)).get(getIndexByName(col)); } public void setData(boolean data, String row, String col) { dataMatrix.get(getIndexByName(row)).set(getIndexByName(col), data); } public void deleteData(String deleteName){ int index = getIndexByName(deleteName); nameOfClass.remove(index); for(int i = 0;i<sizeOfMatrix;i++) { dataMatrix.get(i).remove(index); } dataMatrix.remove(index); sizeOfMatrix } public String getName(String name) { return nameOfClass.get(getIndexByName(name)); } public void setName(String newName, String oldName) throws ItemAlreadyExistException { if(nameOfClass.contains(newName)) { throw new ItemAlreadyExistException(); } else { nameOfClass.set(getIndexByName(oldName), newName); } } public void addEntity(){ sizeOfMatrix++; nameOfClass.add("entity" + sizeOfMatrix); dataMatrix.add(new ArrayList<>()); for(int i = 0;i < sizeOfMatrix; i++){ dataMatrix.get(i).add(false); dataMatrix.get(sizeOfMatrix - 1).add(false); } dataMatrix.get(sizeOfMatrix - 1).remove(sizeOfMatrix); } private int getIndexByName(String name) { return nameOfClass.indexOf(name); } public void loadFromFile(File dsm) throws IOException, WrongDSMFormatException { BufferedReader fileReader = new BufferedReader(new FileReader(dsm)); String read; String[] temp; read = fileReader.readLine(); if(!isNum(read)){ throw new WrongDSMFormatException(); } sizeOfMatrix = Integer.parseInt(read); for (int i = 0; i < sizeOfMatrix; i++) { read = fileReader.readLine(); temp = read.split(" "); if(temp.length != sizeOfMatrix){ throw new WrongDSMFormatException(); } dataMatrix.add(new ArrayList<>()); for (int j = 0; j < sizeOfMatrix; j++) { if(!temp[j].equals("0") && !temp[j].equals("1")){ throw new WrongDSMFormatException(); } dataMatrix.get(i).add(Integer.parseInt(temp[j]) == 1); } } for (int i = 0; i < sizeOfMatrix; i++) { read = fileReader.readLine(); if(read == null){ throw new WrongDSMFormatException(); } temp = read.split(" "); if(temp.length != 1){ throw new WrongDSMFormatException(); } nameOfClass.add(read); } if(fileReader.read() != -1){ throw new WrongDSMFormatException(); } fileReader.close(); } public void saveToFile(File file) throws IOException{ BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(String.valueOf(sizeOfMatrix)); out.newLine(); for(int i = 0; i < sizeOfMatrix; i++) { for(int j = 0; j < sizeOfMatrix; j++) { if(dataMatrix.get(i).get(j) == Boolean.TRUE) { out.write("1 "); } else { out.write("0 "); } } out.newLine(); } for(int i = 0; i < sizeOfMatrix; i++) { out.write(nameOfClass.get(i)); out.newLine(); } out.close(); } private Boolean isNum(String toCheck){ return toCheck.matches("[1-9]\\d*"); } }
package de.tu_darmstadt.gdi1.gorillas.main; import de.tu_darmstadt.gdi1.gorillas.utils.Database; import java.util.ArrayList; import java.util.List; /** * Singleton Class, that contains all globals. * The reason for using a Singleton instead of a static class, are possible serialization * The reason for using this vs, Gorrillas is the different GameContainers * (special TestGameContainer) */ public class Game { /** State Definitions */ public static final int MAINMENUSTATE = 0; public static final int GAMESETUPSTATE = 1; public static final int GAMEPLAYSTATE = 2; public static final int HIGHSCORESTATE = 3; public static final int OPTIONSTATE = 4; public static final int TUTORIALSTATE = 5; public static final int INGAMEPAUSE = 6; public static final int HELPSTATE = 7; public static final int GAMEVICTORY = 8; // Constants public static float SUN_FROM_TOP = 60; public static final float GRAVITY_MIN = 0; public static final float GRAVITY_MAX = 24.79f; public static final float GRAVITY_DEFAULT = 9.80665f; public static final int MAX_NAMESIZE = 12; public static final float SOUND_VOLUME_MIN = 0; public static final float SOUND_VOLUME_MAX = 1f; public static final float SOUND_VOLUME_DEFAULT = 0.2f; public static final int ANGLE_MIN = 0; public static final int ANGLE_MAX = 360; public static int ANGLE_DEFAULT = 60; public static final int SPEED_MIN = 0; public static final int SPEED_MAX = 200; public static int SPEED_DEFAULT = 80; // Switches private boolean testmode = false; // Graphically debug private boolean debug = true; // Debug outputs private boolean developer = true; // Cheating options private boolean inverseControlKeys = false; // Possible, candidate for an internal Option Class private boolean storePlayerNames = true; // Possible candidate for an internal Option Class private boolean mute = false; private boolean wind = false; // Scaling Factors private float WIND_SCALE = 0.6f; private float TIME_SCALE = 1 / 500f; private float ROTATION_DRAG = 0.02f; private int EXPLOSION_RADIUS = 32; public static float BACKGROUND_SCALE = 1f; public static float CANVAS_SCALE = 2f; // Gameplay Variables private float gravity = GRAVITY_DEFAULT; private float soundVolume = SOUND_VOLUME_DEFAULT; // Settings private String databaseFile = "data_gorillas.hsc"; public float getGravity() { return gravity; } public String getDatabaseFile() { return databaseFile; } public float getSoundVolume() { return soundVolume; } public void setGravity(float value) { this.gravity = value > GRAVITY_MAX ? GRAVITY_MAX : value < GRAVITY_MIN ? GRAVITY_MIN : value; } public void setDatabaseFile(String value) { this.databaseFile = value; } public void setSoundVolume(float value) { this.soundVolume = value > SOUND_VOLUME_MAX ? SOUND_VOLUME_MAX : value < SOUND_VOLUME_MIN ? SOUND_VOLUME_MIN : value; } /** Singleton Pattern */ private Game() { players = new ArrayList<Player>(MAX_PLAYER_COUNT); } private static Game game; public static Game getInstance() { if (game == null) { game = new Game(); } return game; } public boolean isMute() { return mute; } public void setMute(boolean value) { mute = value; } public void toggleMute() { mute = !mute; if( getDebug() ) System.out.println("Mute: " + mute); } public boolean getInverseControlKeys() { return inverseControlKeys; } public void setInverseControlKeys(boolean enable) { inverseControlKeys = enable; } public void toggleInverseControlKeys() { inverseControlKeys = !inverseControlKeys; } public boolean getWind(){ return wind; } public void setWind(boolean enable) { wind = enable; } public void toggleWind() { wind = !wind; } public boolean getDebug() { return debug; } public void setDebug(boolean enable) { debug = enable; } public boolean isTestMode() { return testmode; } public void enableTestMode(boolean enable) { testmode = enable; if(testmode) { // Set Test-Defaults if(isTestMode()) { ANGLE_DEFAULT = 0; SPEED_DEFAULT = 0; gravity = 10; SUN_FROM_TOP = 5; } } } public boolean getStorePlayerNames() { return storePlayerNames; } public void setStorePlayerNames(boolean enable){ storePlayerNames = enable; } public void toggleStorePlayerNames() { storePlayerNames = !storePlayerNames; } public boolean isDeveloperMode() { return developer; } public void setDeveloperMode(boolean enable){ developer = enable; } /** Time Constants */ public float getTimeScale() { return !isTestMode() ? TIME_SCALE : 1/100f; } public float getWindScale() { return !isTestMode() ? WIND_SCALE : 1/5f; } public float getRotationFactor() { return ROTATION_DRAG; } public int getExplosionRadius() {return EXPLOSION_RADIUS; } /** We are using a RingBuffer for Player handling * One of the reasons we are doing things this way, * is in case we do want to try todo network play **/ public final int MAX_PLAYER_COUNT = 2; private List<Player> players = new ArrayList<>(MAX_PLAYER_COUNT); private int activePlayer = 0; public Player getActivePlayer() { return players.get(activePlayer); } public void setActivePlayer(Player activePlayer) { this.activePlayer = players.indexOf(activePlayer); } public Player toggleNextPlayerActive() { activePlayer = ++activePlayer % MAX_PLAYER_COUNT; return players.get(activePlayer); } public List<Player> getPlayers() {return players; } //public ListIterator<Player> getPlayers() { return players.listIterator(); } // Iterator is the safe way, but it's just to much boilerplate even for me !_! public Player getPlayer(int num){ if (players != null && num < players.size()) { return players.get(num); } else { throw new IllegalArgumentException(String.format("There is no Player at Index: %d currently there are %d players", num, players.size())); } } private void setPlayer(int num, Player player) { if (players != null && num < MAX_PLAYER_COUNT) { // size is zero for no players, player one has num zero. if(players.size()-1 < num) players.add(num, player); else players.set(num, player); } else { throw new IllegalArgumentException(String.format("There is no Player at Index: %d currently there are %d players", num, players.size())); } } private int lastAddedPlayer = -1; public void createPlayer(String name) { setPlayer(++lastAddedPlayer % MAX_PLAYER_COUNT, new Player(name)); } /** * Call exit game, to close the game * This will cleanup all loaded assets * as well as save all unsaved data */ public void exitGame() { cleanupOnExit(); System.exit(0); } /** * Call this on exit to cleanup all loaded assets * as well as save all unsaved data */ public static void cleanupOnExit() { // Store PlayerNames to the SQL-Database Database.getInstance().writeToFile(); } }
package com.sqh.buddiesgo; import com.google.firebase.database.IgnoreExtraProperties; @IgnoreExtraProperties public class User { public String username; public String email; public Double lati; public Double longi; public User() { // Default constructor required for calls to DataSnapshot.getValue(User.class) } public User(String username, String email, Double lati, Double longi) { this.username = username; this.email = email; this.lati = lati; this.longi = longi; } }
package com.vaadin.polymer.elemental; import com.google.gwt.core.client.js.JsFunction; @JsFunction public interface Function { public Object call(Object arg); }
/** * EPCglobal document properties for all messages. */ /** * Document.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package org.oliot.epcglobal; @SuppressWarnings("serial") public abstract class Document implements java.io.Serializable { private java.math.BigDecimal schemaVersion; // attribute private java.util.Calendar creationDate; // attribute public Document() {} public Document( java.math.BigDecimal schemaVersion, java.util.Calendar creationDate) { this.schemaVersion = schemaVersion; this.creationDate = creationDate; } /** * Gets the schemaVersion value for this Document. * * @return schemaVersion */ public java.math.BigDecimal getSchemaVersion() { return schemaVersion; } /** * Sets the schemaVersion value for this Document. * * @param schemaVersion */ public void setSchemaVersion(java.math.BigDecimal schemaVersion) { this.schemaVersion = schemaVersion; } /** * Gets the creationDate value for this Document. * * @return creationDate */ public java.util.Calendar getCreationDate() { return creationDate; } /** * Sets the creationDate value for this Document. * * @param creationDate */ public void setCreationDate(java.util.Calendar creationDate) { this.creationDate = creationDate; } private java.lang.Object __equalsCalc = null; @SuppressWarnings("unused") public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof Document)) return false; Document other = (Document) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.schemaVersion==null && other.getSchemaVersion()==null) || (this.schemaVersion!=null && this.schemaVersion.equals(other.getSchemaVersion()))) && ((this.creationDate==null && other.getCreationDate()==null) || (this.creationDate!=null && this.creationDate.equals(other.getCreationDate()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getSchemaVersion() != null) { _hashCode += getSchemaVersion().hashCode(); } if (getCreationDate() != null) { _hashCode += getCreationDate().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(Document.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("epcglobal.oliot.org", "Document")); org.apache.axis.description.AttributeDesc attrField = new org.apache.axis.description.AttributeDesc(); attrField.setFieldName("schemaVersion"); attrField.setXmlName(new javax.xml.namespace.QName("", "schemaVersion")); attrField.setXmlType(new javax.xml.namespace.QName("http: typeDesc.addFieldDesc(attrField); attrField = new org.apache.axis.description.AttributeDesc(); attrField.setFieldName("creationDate"); attrField.setXmlName(new javax.xml.namespace.QName("", "creationDate")); attrField.setXmlType(new javax.xml.namespace.QName("http: typeDesc.addFieldDesc(attrField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ @SuppressWarnings("rawtypes") public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ @SuppressWarnings("rawtypes") public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
package io.tetrapod.web; import static io.netty.handler.codec.http.HttpHeaders.*; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static io.tetrapod.protocol.core.Core.*; import static io.tetrapod.protocol.core.CoreContract.*; import java.io.IOException; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.TimeUnit; import io.tetrapod.core.tasks.TaskContext; import org.slf4j.*; import com.codahale.metrics.Timer; import com.codahale.metrics.Timer.Context; import io.netty.buffer.*; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.websocketx.*; import io.netty.util.*; import io.tetrapod.core.*; import io.tetrapod.core.json.*; import io.tetrapod.core.logging.CommsLogger; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.serialize.datasources.ByteBufDataSource; import io.tetrapod.core.utils.Util; import io.tetrapod.protocol.core.*; public class WebHttpSession extends WebSession { protected static final Logger logger = LoggerFactory.getLogger(WebHttpSession.class); public static final Timer requestTimes = Metrics.timer(WebHttpSession.class, "requests", "time"); private static final int FLOOD_TIME_PERIOD = 2000; private static final int FLOOD_WARN = 200; private static final int FLOOD_IGNORE = 300; private static final int FLOOD_KILL = 400; private volatile long floodPeriod; private int reqCounter = 0; private final String wsLocation; private WebSocketServerHandshaker handshaker; private Map<Integer, ChannelHandlerContext> contexts; private String httpReferrer = null; private String domain = null; private String build = null; public WebHttpSession(SocketChannel ch, Session.Helper helper, Map<String, WebRoot> roots, String wsLocation) { super(ch, helper); this.wsLocation = wsLocation; ch.pipeline().addLast("codec-http", new HttpServerCodec()); ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("api", this); ch.pipeline().addLast("deflater", new HttpContentCompressor(6)); ch.pipeline().addLast("maintenance", new MaintenanceHandler(roots.get("tetrapod"))); ch.pipeline().addLast("files", new WebStaticFileHandler(roots)); } @Override public void checkHealth() { TaskContext taskContext = TaskContext.pushNew(); try { if (isConnected()) { timeoutPendingRequests(); } } finally { taskContext.pop(); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { TaskContext taskContext = TaskContext.pushNew(); try { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } else if (msg instanceof WebSocketFrame) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); } } finally { taskContext.pop(); } } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { TaskContext taskContext = TaskContext.pushNew(); try { fireSessionStartEvent(); scheduleHealthCheck(); } finally { taskContext.pop(); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { TaskContext taskContext = TaskContext.pushNew(); try { fireSessionStopEvent(); cancelAllPendingRequests(); } finally { taskContext.pop(); } } public synchronized boolean isWebSocket() { return handshaker != null; } public synchronized void initLongPoll() { if (contexts == null) { contexts = new HashMap<>(); } } private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), new CloseWebSocketFrame()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof PongWebSocketFrame) { return; } if (frame instanceof ContinuationWebSocketFrame) { ctx.channel().write(frame, ctx.voidPromise()); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } String request = ((TextWebSocketFrame) frame).text(); ReferenceCountUtil.release(frame); try { JSONObject jo = new JSONObject(request); WebContext webContext = new WebContext(jo); RequestHeader header = webContext.makeRequestHeader(this, null); readAndDispatchRequest(header, webContext.getRequestParams()); return; } catch (IOException | JSONException e) { logger.error("error processing websocket request", e); ctx.channel().writeAndFlush(new TextWebSocketFrame("Illegal request: " + request)); } } private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception { if (logger.isTraceEnabled()) { synchronized (this) { logger.trace(String.format("%s REQUEST[%d] = %s : %s", this, ++reqCounter, ctx.channel().remoteAddress(), req.uri())); } } // Set the http referrer for this request, if not already set if (Util.isEmpty(getHttpReferrer())) { setHttpReferrer(req.headers().get("Referer")); logger.debug("•••• Referer: {} ", getHttpReferrer()); } // Set the domain for this request, if not already set if (Util.isEmpty(getDomain())) { setDomain(req.headers().get("Host")); logger.debug("•••• Domain: {} ", getDomain()); } // see if we need to start a web socket session if (wsLocation != null && wsLocation.equals(req.uri())) { if (Util.isProduction()) { String host = req.headers().get("Host"); String origin = req.headers().get("Origin"); if (origin != null && host != null) { if (!(origin.equals("http: logger.warn("origin [{}] doesn't match host [{}]", origin, host); sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED)); return; } } } WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(wsLocation, null, false); synchronized (this) { handshaker = wsFactory.newHandshaker(req); } if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } } else { final Context metricContext = requestTimes.time(); if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // this handles long-polling calls when we fall back to long-polling // for browsers with no websockets if (req.uri().equals("/poll")) { handlePoll(ctx, req); return; } // check for web-route handler final WebRoute route = relayHandler.getWebRoutes().findRoute(req.uri()); if (route != null) { handleWebRoute(ctx, req, route); } else { // pass request down the pipeline ctx.fireChannelRead(req); } metricContext.stop(); } } private String getContent(final FullHttpRequest req) { final ByteBuf contentBuf = req.content(); try { return contentBuf.toString(Charset.forName("UTF-8")); } finally { contentBuf.release(); } } private void handlePoll(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception { logger.debug("{} POLLER: {} keepAlive = {}", this, req.uri(), HttpUtil.isKeepAlive(req)); final JSONObject params = new JSONObject(getContent(req)); // authenticate this session, if needed if (params.has("_token")) { Integer clientId = LongPollToken.validateToken(params.getString("_token")); if (clientId != null) { setTheirEntityId(clientId); setTheirEntityType(Core.TYPE_CLIENT); LongPollQueue.getQueue(clientId, true); // init long poll queue } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } } initLongPoll(); if (params.has("_requestId")) { logger.debug("{} RPC: structId={}", this, params.getInt("_structId")); // dispatch a request final RequestHeader header = WebContext.makeRequestHeader(this, null, params); header.fromType = Core.TYPE_CLIENT; header.fromChildId = getTheirEntityId(); header.fromParentId = getMyEntityId(); synchronized (contexts) { contexts.put(header.requestId, ctx); } readAndDispatchRequest(header, params); } else if (getTheirEntityId() != 0) { getDispatcher().dispatch(() -> { final LongPollQueue messages = LongPollQueue.getQueue(getTheirEntityId(), false); final long startTime = System.currentTimeMillis(); // long poll -- wait until there are messages in queue, and // return them assert messages != null; // we grab a lock so only one poll request processes at a time longPoll(25, messages, startTime, ctx, req); }); } } private void longPoll(final int millis, final LongPollQueue messages, final long startTime, final ChannelHandlerContext ctx, final FullHttpRequest req) { getDispatcher().dispatch(millis, TimeUnit.MILLISECONDS, () -> { if (messages.tryLock()) { try { if (messages.size() > 0) { final JSONArray arr = new JSONArray(); while (!messages.isEmpty()) { JSONObject jo = messages.poll(); if (jo != null) { arr.put(jo); } } logger.debug("{} long poll {} has {} items\n", this, messages.getEntityId(), messages.size()); ctx.writeAndFlush(makeFrame(new JSONObject().put("messages", arr), HttpUtil.isKeepAlive(req))); } else { if (System.currentTimeMillis() - startTime > Util.ONE_SECOND * 10) { ctx.writeAndFlush(makeFrame(new JSONObject().put("messages", new JSONArray()), HttpUtil.isKeepAlive(req))); } else { // wait a bit and check again longPoll(50, messages, startTime, ctx, req); } } messages.setLastDrain(System.currentTimeMillis()); } finally { messages.unlock(); } } else { ctx.writeAndFlush(makeFrame(new JSONObject().put("error", "locked"), HttpUtil.isKeepAlive(req))); } }); } // handle a JSON API call private void handleWebRoute(final ChannelHandlerContext ctx, final FullHttpRequest req, final WebRoute route) throws Exception { final WebContext context = new WebContext(req, route.path); final RequestHeader header = context.makeRequestHeader(this, route); if (header != null) { // final long t0 = System.currentTimeMillis(); logger.debug("{} WEB API REQUEST: {} keepAlive = {}", this, req.uri(), HttpUtil.isKeepAlive(req)); header.requestId = requestCounter.incrementAndGet(); header.fromType = Core.TYPE_WEBAPI; header.fromParentId = getMyEntityId(); header.fromChildId = getTheirEntityId(); final ResponseHandler handler = new ResponseHandler() { @Override public void onResponse(Response res) { logger.info("{} WEB API RESPONSE: {} ", WebHttpSession.this, res); handleWebAPIResponse(ctx, req, res); } }; try { if (header.structId == WebAPIRequest.STRUCT_ID) { // @webapi() generic WebAPIRequest call String body = req.content().toString(CharsetUtil.UTF_8); if (body == null || body.trim().isEmpty()) { body = req.uri(); } final WebAPIRequest request = new WebAPIRequest(route.path, getHeaders(req).toString(), context.getRequestParams().toString(), body, req.uri()); final int toEntityId = relayHandler.getAvailableService(header.contractId); if (toEntityId != 0) { final Session ses = relayHandler.getRelaySession(toEntityId, header.contractId); if (ses != null) { header.contractId = Core.CONTRACT_ID; header.toId = toEntityId; logger.info("{} WEB API REQUEST ROUTING TO {} {}", this, toEntityId, header.dump()); relayRequest(header, request, ses, handler); } else { logger.debug("{} Could not find a relay session for {} {}", this, header.toId, header.contractId); handler.fireResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header); } } else { logger.debug("{} Could not find a service for {}", this, header.contractId); handler.fireResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header); } } else { // @web() specific Request mapping final Structure request = readRequest(header, context.getRequestParams()); if (request != null) { if (header.contractId == TetrapodContract.CONTRACT_ID && header.toId == 0) { header.toId = Core.DIRECT; } relayRequest(header, request, handler); } else { handler.fireResponse(new Error(ERROR_UNKNOWN_REQUEST), header); } } } finally { ReferenceCountUtil.release(req); } } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); } } private void handleWebAPIResponse(final ChannelHandlerContext ctx, final FullHttpRequest req, Response res) { final boolean keepAlive = HttpUtil.isKeepAlive(req); try { ChannelFuture cf = null; if (res.isError()) { if (res.errorCode() == CoreContract.ERROR_TIMEOUT) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, REQUEST_TIMEOUT)); } else { JSONObject jo = new JSONObject(); jo.put("result", "ERROR"); jo.put("error", res.errorCode()); jo.put("message", Contract.getErrorCode(res.errorCode(), res.getContractId())); cf = ctx.writeAndFlush(makeFrame(jo, keepAlive)); } } else if (isGenericSuccess(res)) { // bad form to allow two types of non-error response but most // calls will just want to return SUCCESS JSONObject jo = new JSONObject(); jo.put("result", "SUCCESS"); cf = ctx.writeAndFlush(makeFrame(jo, keepAlive)); } else if (res instanceof WebAPIResponse) { WebAPIResponse resp = (WebAPIResponse) res; if (resp.redirect != null && !resp.redirect.isEmpty()) { redirect(resp.redirect, ctx); } else { if (resp.json != null) { cf = ctx.writeAndFlush(makeFrame(new JSONObject(resp.json), keepAlive)); } else { logger.warn("{} WebAPIResponse JSON is null: {}", this, resp.dump()); } } } else { // a blank response ctx.writeAndFlush(makeFrame(new ResponseHeader(0, 0, 0, 0), res, ENVELOPE_RESPONSE)); } if (cf != null && !keepAlive) { cf.addListener(ChannelFutureListener.CLOSE); } } catch (Throwable e) { logger.error(e.getMessage(), e); } } private JSONObject getHeaders(FullHttpRequest req) { JSONObject jo = new JSONObject(); for (Map.Entry<String, String> e : req.headers()) { jo.put(e.getKey(), e.getValue()); } return jo; } protected void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); try { res.content().writeBytes(buf); } finally { buf.release(); } HttpUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } } @Override protected Object makeFrame(JSONObject jo, boolean keepAlive) { if (isWebSocket()) { return new TextWebSocketFrame(jo.toString(3)); } else { String payload = jo.optString("__httpPayload", null); if (payload == null) { payload = jo.toStringWithout("__http"); } ByteBuf buf = WebContext.makeByteBufResult(payload + '\n'); HttpResponseStatus status = HttpResponseStatus.valueOf(jo.optInt("__httpStatus", OK.code())); FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, status, buf); httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, jo.optString("__httpMime", "application/json")); httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes()); httpResponse.headers().set(HttpHeaderNames.CONNECTION, keepAlive ? HttpHeaderValues.KEEP_ALIVE : HttpHeaderValues.CLOSE); if (jo.has("__httpDisposition")) { httpResponse.headers().set("Content-Disposition", jo.optString("__httpDisposition")); } return httpResponse; } } private void relayRequest(RequestHeader header, Structure request, ResponseHandler handler) throws IOException { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { relayRequest(header, request, ses, handler); } else { logger.debug("{} Could not find a relay session for {} {}", this, header.toId, header.contractId); handler.fireResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header); } } protected Async relayRequest(RequestHeader header, Structure request, Session ses, ResponseHandler handler) throws IOException { final ByteBuf in = convertToByteBuf(request); try { return ses.sendRelayedRequest(header, in, this, handler); } finally { in.release(); } } protected ByteBuf convertToByteBuf(Structure struct) throws IOException { ByteBuf buffer = channel.alloc().buffer(32); ByteBufDataSource data = new ByteBufDataSource(buffer); struct.write(data); return buffer; } private void redirect(String newURL, ChannelHandlerContext ctx) { HttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); response.headers().set(HttpHeaderNames.LOCATION, newURL); response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } protected void readAndDispatchRequest(RequestHeader header, JSONObject params) { long now = System.currentTimeMillis(); lastHeardFrom.set(now); if (floodCheck(now, header)) { // could move flood check after comms log just for the logging return; } try { final Structure request = readRequest(header, params); if (request != null) { if (header.toId == DIRECT || header.toId == myId) { if (request instanceof Request) { dispatchRequest(header, (Request) request); } else { logger.error("Asked to process a request I can't deserialize {}", header.dump()); sendResponse(new Error(ERROR_SERIALIZATION), header); } } else { relayRequest(header, request); } } else { sendResponse(new Error(ERROR_UNKNOWN_REQUEST), header); } } catch (IOException e) { logger.error("Error processing request {}", header.dump()); sendResponse(new Error(ERROR_UNKNOWN), header); } } private ChannelHandlerContext getContext(int requestId) { synchronized (contexts) { return contexts.remove(requestId); } } @Override public void sendResponse(Response res, RequestHeader reqHeader) { if (isWebSocket()) { super.sendResponse(res, reqHeader); } else { // HACK: for http responses we need to write to the response to the // correct ChannelHandlerContext if (res != Response.PENDING) { final ResponseHeader header = new ResponseHeader(reqHeader.requestId, res.getContractId(), res.getStructId(), reqHeader.contextId); CommsLogger.append(this, true, header, res, reqHeader.structId); final Object buffer = makeFrame(header, res, ENVELOPE_RESPONSE); if (buffer != null && channel.isActive()) { ChannelHandlerContext ctx = getContext(reqHeader.requestId); if (ctx != null) { ctx.writeAndFlush(buffer); } else { logger.warn("{} Could not find context for {}", this, reqHeader.requestId); writeFrame(buffer); } } } } } @Override public void sendRelayedResponse(ResponseHeader header, Async async, ByteBuf payload) { if (isWebSocket()) { super.sendRelayedResponse(header, async, payload); } else { CommsLogger.append(this, true, header, payload, async.header.structId); // HACK: for http responses we need to write to the response to the // correct ChannelHandlerContext ChannelHandlerContext ctx = getContext(header.requestId); final Object buffer = makeFrame(header, payload, ENVELOPE_RESPONSE); if (ctx != null) { ctx.writeAndFlush(buffer); } else { writeFrame(buffer); } } } private Async relayRequest(RequestHeader header, Structure request) throws IOException { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { return relayRequest(header, request, ses, null); } else { logger.debug("Could not find a relay session for {} {}", header.toId, header.contractId); sendResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header); return null; } } @Override public void sendRelayedMessage(MessageHeader header, ByteBuf payload, boolean broadcast) { if (isWebSocket()) { super.sendRelayedMessage(header, payload, broadcast); } else { // queue the message for long poller to retrieve later CommsLogger.append(this, true, header, payload); final LongPollQueue messages = LongPollQueue.getQueue(getTheirEntityId(), false); if (messages != null) { // FIXME: Need a sensible way to protect against memory gobbling // if this queue isn't cleared fast enough messages.add(toJSON(header, payload, ENVELOPE_MESSAGE)); logger.debug("{} Queued {} messages for longPoller {}", this, messages.size(), messages.getEntityId()); } } } private boolean floodCheck(long now, RequestHeader header) { int reqs; long newFloodPeriod = now / FLOOD_TIME_PERIOD; if (newFloodPeriod != floodPeriod) { // race condition between read and write of floodPeriod. but is // benign as it means we reset // request count to 0 an extra time floodPeriod = newFloodPeriod; requestCount.set(0); reqs = 0; } else { reqs = requestCount.incrementAndGet(); } if (reqs > FLOOD_KILL) { logger.warn("{} flood killing {}/{}", this, header.contractId, header.structId); close(); return true; } if (reqs > FLOOD_IGNORE) { // do nothing, send no response logger.warn("{} flood ignoring {}/{}", this, header.contractId, header.structId); return true; } if (reqs > FLOOD_WARN) { // respond with error so client can slow down logger.warn("{} flood warning {}/{}", this, header.contractId, header.structId); sendResponse(new Error(ERROR_FLOOD), header); return true; } return false; } private boolean isGenericSuccess(Response r) { Response s = Response.SUCCESS; return s.getContractId() == r.getContractId() && s.getStructId() == r.getStructId(); } public synchronized String getHttpReferrer() { return httpReferrer; } public synchronized void setHttpReferrer(String httpReferrer) { this.httpReferrer = httpReferrer; } public synchronized String getDomain() { return domain; } public synchronized void setDomain(String domain) { this.domain = domain; } public synchronized void setBuild(String build) { this.build = build; } public synchronized String getBuild() { return build; } }
package my.KlarText; import java.awt.Color; import java.awt.Cursor; import java.awt.Desktop; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.ListModel; import javax.swing.RowSorter; import javax.swing.SortOrder; import javax.swing.Timer; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import static javax.xml.bind.DatatypeConverter.printHexBinary; import my.KlarText.KlarTextUI.MZ; import static my.KlarText.KlarTextUI.debugLevel; import static my.KlarText.KlarTextUI.rs232_or_rb_usb_2; /** * * @author ktams */ public class MC extends javax.swing.JFrame { public KlarTextUI KTUI = null; public String ReturnString = "Tams Elektronik"; private TwoWaySerialComm Com = null; private int gsBaudRateSaved = 0; private boolean bReadStatus; private boolean bReadCfg; private boolean bReadRC; private boolean bReadSo999 = false; private boolean bWriteSo999 = false; private boolean bReadS88num = false; private boolean bReadS88value = false; private boolean bWriteCfg; private boolean bWriteM3sid; private boolean bWriteM3sidList; private boolean bReadPTdirekt; private boolean bReadPTList; private boolean bUpdate; private int TimeOut; private int BlockNr = 0; private int MaxBlocks = 0; private int UpdateData[][] = new int[2][0x10000]; private int count = 0; private int nextWriteJob = 0; private int readWriteProgress = 0; private Timer timer = null; private boolean bFalscheEingabe = false; private int FehlerArt = 0; private int rcValue = -1; private int so999Value = -1; private boolean bWriteList; private boolean bProg_m3; private boolean bProg_MM; private boolean bMustAskStatus; private int DisplayCursor; private int DisplayState; private String OldDisplayString; private boolean bAskLokState; private int AskedLokAdr; private String AktLokState; private String AktLokFormat; private String LokName; private int Fahrstufen; private int[] Funktionen; private int AktLokAdr; private Color DefBackground; private enum Parser { INIT, INFO, LOCO, TRAKTIONS, ACCFMT, SYSTEM, END }; private int sysIdx = 0; private int locIdx = 0; private int traIdx = 0; private int magIdx = 0; private int locoTableSelRow = -1; private int locoTableSelCol = -1; private Boolean checkM3uidValidActive = false; private M3_Liste M3L = null; public S88monitor S88mon = null; public String M3liste[][] = null; public int M3used = 0; public int modulNr = 1; public int moduleValue = 0; private boolean bWaitAnswerInProgress = false; private byte[] bArray = new byte[0xFFFF]; private int bytesRead = 0; private int retries; private byte[] bArrayTmp = new byte[0xFFFF]; private int tmpBytesRead = 0; private String lastCmd = ""; private boolean validMcData = false; private ResourceBundle bundle; public JDialog frameInstanceHelpLC = null; public JDialog frameInstanceHelpHC = null; public JDialog frameInstanceHelpPC = null; public JDialog frameInstanceHelpSNC = null; public JDialog frameInstanceHelpXNC = null; public JDialog frameInstanceHelpWIW = null; public JDialog frameInstanceHelpMC = null; private String Hersteller(int data) { String file_name = "/manID.csv"; Class c = getClass(); InputStream is = c.getResourceAsStream (file_name); String s = null; String[] strArr1 = null; int bytesRead = 0; if( is != null) { try { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF8")); char[] ac = null; s = br.readLine() + "\n"; String s1 = "1"; while(s1 != null) { s1 = br.readLine(); s += s1 + "\n"; } br.close(); strArr1 = s.substring(0, s.length()).split("\n"); } catch (UnsupportedEncodingException ex) { System.out.println("Error reading File ManID.csv"); } catch (IOException ex) { System.out.println("Error reading File ManID.csv"); } } String ManIDstr = "" + data; if(s.length() != 0) { int i; for(i = 0; i < strArr1.length; i++) { if(strArr1[i].contains("" + data + ",")) { ManIDstr = strArr1[i]; strArr1 = ManIDstr.substring(0, ManIDstr.length()).split(","); ManIDstr = strArr1[0] + " [" + strArr1[1] + "]"; break; } } } return ManIDstr; } /** Creates new form MC */ public MC(KlarTextUI ktuiThis) { this.LokName = ""; this.Fahrstufen = 28; if( ktuiThis == null ) { return; } KTUI = ktuiThis; if( KTUI.frameInstanceDEVICE != null ) { KTUI.frameInstanceDEVICE.toFront(); KTUI.frameInstanceDEVICE.repaint(); return; } retries = KlarTextUI.timerRetries; initComponents(); Funktionen = new int[28]; for(int i = 0; i < 28; i++) Funktionen[i] = 0; ImageIcon II = null; ImageIcon II2 = null; II = new ImageIcon(getClass().getResource("/MasterControl.gif")); II2 = new ImageIcon(getClass().getResource("/RedBox.gif")); // replace with final version setTitle( KTUI.getMenutext( decoderList.MC ).trim() ); bundle = java.util.ResourceBundle.getBundle("my.KlarText/Bundle"); if( II != null ) { setIconImage(II.getImage()); jBild.setIcon(II); } if( II2 != null ) { setIconImage(II2.getImage()); jBild2.setIcon(II2); } jDatenQuelle.setText(KTUI.gsSchnittstelle); DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); centerRenderer.setHorizontalAlignment( JLabel.CENTER ); // nur Spalte 0 // jTableAccessory.getColumnModel().getColumn(0).setCellRenderer( centerRenderer ); // alle Spalten -> ganze Tabelle jTableLoco.getColumnModel().getColumn(0).setCellRenderer( centerRenderer ); jTableLoco.getColumnModel().getColumn(1).setCellRenderer( centerRenderer ); jTableLoco.getColumnModel().getColumn(2).setCellRenderer( centerRenderer ); jTableTraction.getColumnModel().getColumn(0).setCellRenderer( centerRenderer ); jTableTraction.getColumnModel().getColumn(2).setCellRenderer( centerRenderer ); jTableAccessory.setDefaultRenderer(String.class, centerRenderer); M3liste = new String[3][c.MAX_M3_ENTRIES]; Comparator<String> compAdrTra = new Comparator<String>() { @Override public int compare(String o1, String o2) { String s1 = ""+o1; String s2 = ""+o2; if( ( s1.length() == 0 ) && ( s2.length() == 0 ) ) { return 0; } boolean ascending = jTableTraction.getRowSorter().getSortKeys().get(0).getSortOrder() == SortOrder.ASCENDING; if( debugLevel > 2 ) { System.out.println("jTableTraction rows="+jTableTraction.getRowCount()+" s1="+s1+" s2="+s2+" ascending="+ascending); } if( s1.length() == 0 ) { if( ascending == true ) { return 1; } else { return -1; } } if( s2.length() == 0 ) { if( ascending == true ) { return -1; } else { return 1; } } if( s1.endsWith("!") ) { s1 = s1.replaceAll("!", ""); } if( s2.endsWith("!") ) { s2 = s2.replaceAll("!", ""); } int n1 = KTUI.checkAndGetStrNumRangeDef( null, s1, 1, c.MAX_M3_SID, 0, false); int n2 = KTUI.checkAndGetStrNumRangeDef( null, s2, 1, c.MAX_M3_SID, 0, false); return n1 - n2 ; } }; // Sortierung in der Loco-Tabelle anpassen... TableRowSorter<DefaultTableModel> rowSorter = (TableRowSorter<DefaultTableModel>)jTableLoco.getRowSorter(); // Spalte 3 (Name/Beschreibung) bitte nicht sortieren... rowSorter.setSortable(3, false); // ...die anderen Spalten nach speziellen Regeln... rowSorter.setComparator(0, new Comparator<String>() { @Override public int compare(String o1, String o2) { String s1 = ""+o1; String s2 = ""+o2; if( ( s1.length() == 0 ) && ( s2.length() == 0 ) ) { return 0; } boolean ascending = jTableLoco.getRowSorter().getSortKeys().get(0).getSortOrder() == SortOrder.ASCENDING; if( debugLevel > 2 ) { System.out.println("jTableLoco rows="+jTableLoco.getRowCount()+" s1="+s1+" s2="+s2+" ascending="+ascending); } if( s1.length() == 0 ) { if( ascending == true ) { return 1; } else { return -1; } } if( s2.length() == 0 ) { if( ascending == true ) { return -1; } else { return 1; } } int n1 = KTUI.checkAndGetStrNumRangeDef( null, o1, 1, c.MAX_M3_SID, 0, false); int n2 = KTUI.checkAndGetStrNumRangeDef( null, o2, 1, c.MAX_M3_SID, 0, false); return n1 - n2 ; } }); rowSorter.setComparator(1, new Comparator<String>() { @Override public int compare(String o1, String o2) { String s1 = ""+o1; String s2 = ""+o2; if( ( s1.length() == 0 ) && ( s2.length() == 0 ) ) { return 0; } boolean ascending = jTableLoco.getRowSorter().getSortKeys().get(0).getSortOrder() == SortOrder.ASCENDING; if( s1.length() == 0 ) { if( ascending == true ) { return 1; } else { return -1; } } if( s2.length() == 0 ) { if( ascending == true ) { return -1; } else { return 1; } } // Vergleiche Fahrstufen numerisch ( hier 27 ohne [aAbB] ) int n1 = KTUI.checkAndGetStrNumRangeDef( null, s1.replaceAll("[aAbB]", ""), 0, Integer.MAX_VALUE, 0, false); int n2 = KTUI.checkAndGetStrNumRangeDef( null, s2.replaceAll("[aAbB]", ""), 0, Integer.MAX_VALUE, 0, false); return n1 - n2; } }); rowSorter.setComparator(2, new Comparator<String>() { @Override public int compare(String o1, String o2) { String s1 = ""+o1; String s2 = ""+o2; if( ( s1.length() == 0 ) && ( s2.length() == 0 ) ) { return 0; } boolean ascending = jTableLoco.getRowSorter().getSortKeys().get(0).getSortOrder() == SortOrder.ASCENDING; if( s1.length() == 0 ) { if( ascending == true ) { return 1; } else { return -1; } } if( s2.length() == 0 ) { if( ascending == true ) { return -1; } else { return 1; } } return o1.compareTo(o2); } }); // Sortierung in der Traktions-Tabelle anpassen... rowSorter = (TableRowSorter<DefaultTableModel>)jTableTraction.getRowSorter(); // Spalten 1+3 (Name/Beschreibung) bitte nicht sortieren... rowSorter.setSortable(1, false); rowSorter.setSortable(3, false); // ...die anderen Spalten nach speziellen Regeln... rowSorter.setComparator(0, compAdrTra); rowSorter.setComparator(2, compAdrTra); // initialize M3 list if file is available readM3(); // set to top to avoid scrolling to bottom this.jTextPane1.setCaretPosition(0); setLocationRelativeTo(ktuiThis); setVisible(true); KTUI.frameInstanceDEVICE = this; } private int crc16(int s, int count,int[] data) { int i, j = 0; while (--count >= 0) { s = s ^ data[j++]; for (i = 0; i < 8; i++) { if ((s & 1) > 0) { s = (s >> 1) ^ 0xA001; } else { s = s >> 1; } } } return s; } private int hexval(byte c, byte c0) { int val = 0; if (c >= '0' && c <= '9') { val = (c - '0'); } switch(c) { case 'a': case 'A': val =10; break; case 'b': case 'B': val = 11; break; case 'c': case 'C': val = 12; break; case 'd': case 'D': val = 13; break; case 'e': case 'E': val = 14; break; case 'f': case 'F': val = 15; break; } if (c0 == '0') { return (val*16); } val *= 16; if (c0 >= '0' && c0 <= '9') { val += (c0 - '0'); } switch(c0) { case 'a': case 'A': val += 10; break; case 'b': case 'B': val += 11; break; case 'c': case 'C': val += 12; break; case 'd': case 'D': val += 13; break; case 'e': case 'E': val += 14; break; case 'f': case 'F': val += 15; break; } return val; } private String sModAdr( int mod ) { if( mod <= 0 ) { return ""; } String s = ""+mod+" ("+(((mod-1)*4)+1)+"-"+(((mod-1)*4)+4)+")"; return s; } private boolean parseInputArray( String quelle, String str1 ) { boolean ret = false; if( str1 != null && str1.length() > 0 ) { int locTabIdx = 0; int traTabIdx = 0; rcValue = -1; updateRailComCheckboxes( 0 ); so999Value = -1; updateSO999checkboxes( 0 ); initLocoTable(); initTractionTable(); initAccessoryTable(); String[] strArr = str1.split("[\r\n]+"); // file \r\n MC \r Parser mode = Parser.INIT ; jDatenQuelle.setText(quelle); jDatenQuelle.setForeground(Color.BLACK); jMcRwProgress.setMaximum(strArr.length); jMcRwProgress.setValue(0); jMcRwInfo.setText("parse config in progress"); for(int j = 0 ; j < strArr.length ; j++) { jMcRwProgress.setValue(j+1); String[] strArr1 = strArr[j].split(" "); try { // special handling of "]" needed, because prompt from MC has no correct string termination ! if( strArr[j].startsWith("]")) { if( debugLevel > 0 ) { System.out.println("inside parseInputArray SKIP BRACKET j["+j+"] strArr[0]=\""+strArr1[0]+"\" len["+strArr1[0].length()+"]"); } mode = Parser.END; continue; } // check for section change -> keep section in variable "mode" switch( strArr1[0] ) { case "[INFO]": mode = Parser.INFO; continue; case "[LOCO]": mode = Parser.LOCO; continue; case "[TRAKTIONS]": mode = Parser.TRAKTIONS; continue; case "[ACCFMT]": mode = Parser.ACCFMT; continue; case "[SYSTEM]": mode = Parser.SYSTEM; continue; case "*END*": mode = Parser.END; ret = true; if( debugLevel > 0 ) { System.out.println("inside parseInputArray search section found *END* SKIP j["+j+"] strArr[j]=["+strArr[j]+"]" ); } continue; default: // a "normal" entry if( debugLevel > 2 ) { System.out.println("inside parseInputArray search Section -> normal entry j=["+j+"] strArr[0]=["+strArr1[0]+"]" ); } } switch( mode ) { case INFO: switch( strArr1[0] ) { case "VERSION": jVersion.setText(strArr1[1]); break; case "HARDWARE": jHardWare.setText(strArr1[1]); break; case "MCU": jMCU.setText(strArr1[1]); break; case "SERIAL": jSerNr.setText(strArr1[1]); break; default: System.out.println("inside parseInputArray [INFO] -> UNKNOWN ENTRY j=["+j+"] strArr[j]=["+strArr[j]+"]"); } break; case LOCO: // re-split with "," and " " strArr1 = strArr[j].split("[, ]+"); if( locTabIdx > c.MAX_LOCS) { System.out.println("inside parseInputArray [LOCO] -> UNKNOWN ENTRY strArr["+j+"]=["+strArr[j]+"]"); System.out.println("inside parseInputArray [LOCO] locTabIdx=["+locTabIdx+"] out of bound -> skip/continue"); continue; } if (strArr1.length >= 3) { // 1st check if address is already known, if not x == locTabIdx int thisAdrIdx = 0; for( ; thisAdrIdx < locTabIdx ; thisAdrIdx++) { String s = ""+jTableLoco.getValueAt(thisAdrIdx, 0); if(s.trim().equals(strArr1[0].trim()) ) { // address already present -> overwrite break; } } jTableLoco.setValueAt(strArr1[0], thisAdrIdx, 0); jTableLoco.setValueAt(strArr1[1], thisAdrIdx, 1); jTableLoco.setValueAt(strArr1[2], thisAdrIdx, 2); if (strArr1.length >= 4) { // re-split with "," to get real name (may be with more than 1 consecutive space inside !) String[] strArrName = strArr[j].split(","); if( strArrName.length == 4 ) { jTableLoco.setValueAt(strArrName[3].trim(), thisAdrIdx, 3); } } if( thisAdrIdx == locTabIdx ) { locTabIdx++; } } break; case TRAKTIONS: // re-split with "," and " " strArr1 = strArr[j].split("[, ]+"); if( traTabIdx > c.MAX_TRACTIONS) { System.out.println("inside parseInputArray [TRAKTIONS] -> UNKNOWN ENTRY strArr["+j+"]=["+strArr[j]+"]"); System.out.println("inside parseInputArray [TRAKTIONS] traction["+traTabIdx+"] out of bound -> skip/continue" ); continue; } if( strArr1.length >= 2 ) { jTableTraction.setValueAt(strArr1[0], traTabIdx, 0); // ggf. Namen der Loks in Spalte 1 eintragen String traLocAddr = strArr1[0]; if(traLocAddr.substring(traLocAddr.length()-1).matches("!")) { traLocAddr = traLocAddr.substring(0, traLocAddr.length()-1); } // suche nach passender Adresse in der Loktabelle for(int i = 0; i < locTabIdx; i++) { if(traLocAddr.matches(""+jTableLoco.getValueAt(i, 0))) jTableTraction.setValueAt(jTableLoco.getValueAt(i, 3), traTabIdx, 1); } jTableTraction.setValueAt(strArr1[1], traTabIdx, 2); // ggf. Namen der Loks in Spalte 3 eintragen traLocAddr = strArr1[1]; if(traLocAddr.substring(traLocAddr.length()-1).matches("!")) { traLocAddr = traLocAddr.substring(0, traLocAddr.length()-1); } // suche nach passender Adresse in der Loktabelle for(int i = 0; i < locTabIdx; i++) { if(traLocAddr.matches(""+jTableLoco.getValueAt(i, 0))) jTableTraction.setValueAt(jTableLoco.getValueAt(i, 3), traTabIdx, 3); } traTabIdx++; } break; case ACCFMT: // re-split with "," and " " strArr1 = strArr[j].split("[, ]+"); if (strArr1.length >= 2) { int modNr = Integer.parseInt(strArr1[0]) + 1; if( (modNr < 1) || (modNr > c.MAX_MM1_ACCMOD) ) { System.out.println("inside parseInputArray [ACCFMT] modNr["+modNr+"] out of bound -> skip/continue line["+strArr[j]+"]" ); continue; } // jTableAccessory.setValueAt("" + modNr, modNr-1, 0); ZZZ jTableAccessory.setValueAt(sModAdr(modNr), modNr-1, 0); jTableAccessory.setValueAt(strArr1[1], modNr-1, 1); } break; case SYSTEM: switch( strArr1[0] ) { case "LONGPAUSE": jLangePause.setSelected(strArr1[1].matches("yes")); break; case "NEGATIVESHORT": jDCC_Booster.setSelected(strArr1[1].matches("yes")); break; case "DEFAULTDCC": jDCC_Loks.setSelected(strArr1[1].matches("yes")); break; case "SHORTTIME": int KSE; try { KSE = Integer.parseInt(strArr1[1]); } catch (NumberFormatException numberFormatException) { KSE = 20; } KSE *= 5; jKurzEmpf.setText(""+KSE); break; case "s88MODULES": js88.setText(strArr1[1]); updateS88field(Integer.parseInt(js88.getText())); break; case "MAGMINTIME": jMinMag.setText(strArr1[1]); break; case "MAGMAXTIME": jMaxMag.setText(strArr1[1]); break; case "BAUDRATE": jBaud.setText(strArr1[1]); break; case "RAILCOM": rcValue = Integer.parseInt(strArr1[1]); updateRailComCheckboxes( rcValue ); break; case "SO999": so999Value = Integer.parseInt(strArr1[1]); updateSO999checkboxes( so999Value ); break; default: System.out.println("inside parseInputArray [SYSTEM] -> UNKNOWN ENTRY j=["+j+"] strArr[0]=["+strArr1[0]+"]"); } break; case END: if( strArr[0].startsWith("]") ) { break; } else { switch( strArr1[0] ) { case "*END*": break; default: System.out.println("inside parseInputArray [END] -> UNKNOWN ENTRY j=["+j+"] strArr[0]=["+strArr1[0]+"]" ); } } break; default: System.out.println("inside parseInputArray [default] -> UNHANDLED MODE len["+strArr.length+"]"); } } catch (NumberFormatException ex) { System.out.println("inside parseInputArray [SYSTEM] SRCstr["+strArr[j]+"] -> DST.len["+strArr1.length+"] Eception ex["+ex+"]"); } } System.out.println("parseInputArray progess at end is "+jMcRwProgress.getValue() ); jMcRwInfo.setText("parse config finished"); Font f = jDatenQuelle.getFont(); Font f2 = new Font( f.getFontName(), Font.BOLD, f.getSize() ); jDatenQuelle.setFont(f2); } // sort table by first column TableRowSorter<DefaultTableModel> sorter = (TableRowSorter<DefaultTableModel>)jTableLoco.getRowSorter(); List<RowSorter.SortKey> sortKeys = new ArrayList<>(); if( ( sorter != null ) && ( sortKeys != null ) ) { int columnIndexToSort = 0; // 0 == 1st column (loco address) sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.ASCENDING)); sorter.setSortKeys(sortKeys); sorter.sort(); } return ret; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); buttonGroup2 = new javax.swing.ButtonGroup(); buttonGroup3 = new javax.swing.ButtonGroup(); buttonGroup4 = new javax.swing.ButtonGroup(); jTabbedPane1 = new javax.swing.JTabbedPane(); jSystem = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jVersion = new javax.swing.JTextField(); jHardWare = new javax.swing.JTextField(); jMCU = new javax.swing.JTextField(); jSerNr = new javax.swing.JTextField(); jLangePause = new javax.swing.JCheckBox(); jDCC_Booster = new javax.swing.JCheckBox(); jDCC_Loks = new javax.swing.JCheckBox(); jLabel6 = new javax.swing.JLabel(); jKurzEmpf = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); js88 = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jMinMag = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jMaxMag = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jBaud = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); jKonfLesen = new javax.swing.JButton(); jKonfSchreiben = new javax.swing.JButton(); jKonfLaden = new javax.swing.JButton(); jKonfSichern = new javax.swing.JButton(); jBild = new javax.swing.JLabel(); jMcRwProgress = new javax.swing.JProgressBar(); jCancel = new javax.swing.JButton(); jMcRwInfo = new javax.swing.JLabel(); jRailcomSupport = new javax.swing.JLabel(); jRailcomTailbits = new javax.swing.JCheckBox(); jRailcomIdNotify = new javax.swing.JCheckBox(); jRailcomAccessory = new javax.swing.JCheckBox(); jWRsys = new javax.swing.JCheckBox(); jWRloc = new javax.swing.JCheckBox(); jWRtra = new javax.swing.JCheckBox(); jWRmag = new javax.swing.JCheckBox(); jDatenQuelle = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jClose = new javax.swing.JButton(); jLabel17 = new javax.swing.JLabel(); jSysS88monitor = new javax.swing.JButton(); jBoosterOpts = new javax.swing.JLabel(); jBoostOptNoAccDrive = new javax.swing.JCheckBox(); jBoostOptNoAccBreak = new javax.swing.JCheckBox(); jBild2 = new javax.swing.JLabel(); jMRST = new javax.swing.JButton(); jLoks = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTableLoco = new javax.swing.JTable(); jLocDelAll = new javax.swing.JButton(); jLocCheck = new javax.swing.JButton(); jLocRepair = new javax.swing.JButton(); jLocM3sidWrite = new javax.swing.JButton(); jTextM3UID = new javax.swing.JTextField(); jLabelM3UID = new javax.swing.JLabel(); jLabelM3SID = new javax.swing.JLabel(); jTextM3SID = new javax.swing.JTextField(); jMcM3Progress = new javax.swing.JProgressBar(); jMcM3Info = new javax.swing.JTextField(); jLocM3cfgLoad = new javax.swing.JButton(); jLocM3cfgEdit = new javax.swing.JButton(); jLocM3cfgSave = new javax.swing.JButton(); jLocDel = new javax.swing.JButton(); jLoc2System = new javax.swing.JButton(); jLocM3sidWriteList = new javax.swing.JButton(); jM3count = new javax.swing.JLabel(); jTraktionen = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jTableTraction = new javax.swing.JTable(); jTraDelAll = new javax.swing.JButton(); jLabel15 = new javax.swing.JLabel(); jTraCheck = new javax.swing.JButton(); jTraRepair = new javax.swing.JButton(); jTraDel = new javax.swing.JButton(); jTra2System = new javax.swing.JButton(); jMagnetartikel = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); jTableAccessory = new javax.swing.JTable(); jMMM = new javax.swing.JButton(); jMDCC = new javax.swing.JButton(); jMagCheck = new javax.swing.JButton(); jMagRepair = new javax.swing.JButton(); jLabel16 = new javax.swing.JLabel(); jMag2System = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jScrollPane5 = new javax.swing.JScrollPane(); jCVListe = new javax.swing.JList(); jLabel25 = new javax.swing.JLabel(); jLabel26 = new javax.swing.JLabel(); jHauptGleis = new javax.swing.JRadioButton(); jProgGleis = new javax.swing.JRadioButton(); jListeLesen = new javax.swing.JButton(); jListeSchreiben = new javax.swing.JButton(); jListeBearbeiten = new javax.swing.JButton(); jLabel28 = new javax.swing.JLabel(); jHerstellerInfo = new javax.swing.JTextField(); jPanel8 = new javax.swing.JPanel(); jLabel29 = new javax.swing.JLabel(); jCV_Direkt = new javax.swing.JTextField(); jWertDirekt = new javax.swing.JTextField(); jLabel30 = new javax.swing.JLabel(); jDirektLesen = new javax.swing.JButton(); jDirektSchreiben = new javax.swing.JButton(); jLabel31 = new javax.swing.JLabel(); jDecAdr = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jm3Addr = new javax.swing.JTextField(); jmfxUID = new javax.swing.JTextField(); jm3Schreiben = new javax.swing.JButton(); jLabel27 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jLabel21 = new javax.swing.JLabel(); jMMRegister = new javax.swing.JTextField(); jMMWert = new javax.swing.JTextField(); jLabel22 = new javax.swing.JLabel(); jStartMMProg = new javax.swing.JButton(); jLabel23 = new javax.swing.JLabel(); jLabel24 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); jGeschwindigkeit = new javax.swing.JSlider(); jPanel7 = new javax.swing.JPanel(); j1 = new javax.swing.JButton(); j2 = new javax.swing.JButton(); j3 = new javax.swing.JButton(); j4 = new javax.swing.JButton(); j5 = new javax.swing.JButton(); j6 = new javax.swing.JButton(); j7 = new javax.swing.JButton(); j8 = new javax.swing.JButton(); j9 = new javax.swing.JButton(); jStern = new javax.swing.JButton(); j0 = new javax.swing.JButton(); jRaute = new javax.swing.JButton(); jf0 = new javax.swing.JButton(); jf1 = new javax.swing.JButton(); jf2 = new javax.swing.JButton(); jf3 = new javax.swing.JButton(); jf4 = new javax.swing.JButton(); jGO = new javax.swing.JButton(); jSTOP = new javax.swing.JButton(); jPanel9 = new javax.swing.JPanel(); jf5 = new javax.swing.JButton(); jf9 = new javax.swing.JButton(); jf6 = new javax.swing.JButton(); jf8 = new javax.swing.JButton(); jf7 = new javax.swing.JButton(); jf10 = new javax.swing.JButton(); jf11 = new javax.swing.JButton(); jf12 = new javax.swing.JButton(); jf18 = new javax.swing.JButton(); jf13 = new javax.swing.JButton(); jf17 = new javax.swing.JButton(); jf14 = new javax.swing.JButton(); jf19 = new javax.swing.JButton(); jf15 = new javax.swing.JButton(); jf16 = new javax.swing.JButton(); jf20 = new javax.swing.JButton(); jf22 = new javax.swing.JButton(); jf21 = new javax.swing.JButton(); jf23 = new javax.swing.JButton(); jf24 = new javax.swing.JButton(); jf26 = new javax.swing.JButton(); jf25 = new javax.swing.JButton(); jf27 = new javax.swing.JButton(); jf28 = new javax.swing.JButton(); jPanel10 = new javax.swing.JPanel(); jScrollPane6 = new javax.swing.JScrollPane(); jDisplay = new javax.swing.JTextArea(); jLabel33 = new javax.swing.JLabel(); jLabel34 = new javax.swing.JLabel(); jRueck = new javax.swing.JButton(); jVor = new javax.swing.JButton(); jUpdate = new javax.swing.JPanel(); jUpdDatei = new javax.swing.JTextField(); jUpdDateiAuswahl = new javax.swing.JButton(); jMcUpdProgress = new javax.swing.JProgressBar(); jUpdStartUpdate = new javax.swing.JButton(); jMcUpdInfo = new javax.swing.JLabel(); jUpdLastErrorLabel = new javax.swing.JLabel(); jUpdLastError = new javax.swing.JLabel(); jUpdCancel = new javax.swing.JButton(); jUpdClose = new javax.swing.JButton(); jUpd2System = new javax.swing.JButton(); jScrollPane4 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); helpLC = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); helpHC = new javax.swing.JButton(); helpPC = new javax.swing.JButton(); helpSNC = new javax.swing.JButton(); helpXNC = new javax.swing.JButton(); helpMC = new javax.swing.JButton(); helpWasIstWas = new javax.swing.JButton(); helpMCasLC = new javax.swing.JButton(); Firmware = new javax.swing.JButton(); jEasyNetUpdate = new javax.swing.JButton(); jUSB1 = new javax.swing.JRadioButton(); jUSB2 = new javax.swing.JRadioButton(); jLabel18 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setMaximumSize(new java.awt.Dimension(1212, 2147483647)); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); jTabbedPane1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTabbedPane1.setMaximumSize(new java.awt.Dimension(1115, 32767)); jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jTabbedPane1StateChanged(evt); } }); jSystem.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jSystem.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { jSystemComponentShown(evt); } }); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("my/KlarText/Bundle"); // NOI18N jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, bundle.getString("MC.jPanel1.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 12))); // NOI18N jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel2.setText(bundle.getString("MC.jLabel2.text")); // NOI18N jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel3.setText(bundle.getString("MC.jLabel3.text")); // NOI18N jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel4.setText(bundle.getString("MC.jLabel4.text")); // NOI18N jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel5.setText(bundle.getString("MC.jLabel5.text")); // NOI18N jVersion.setEditable(false); jVersion.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jVersion.setHorizontalAlignment(javax.swing.JTextField.CENTER); jVersion.setText(bundle.getString("MC.jVersion.text")); // NOI18N jHardWare.setEditable(false); jHardWare.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jHardWare.setHorizontalAlignment(javax.swing.JTextField.CENTER); jHardWare.setText(bundle.getString("MC.jHardWare.text")); // NOI18N jMCU.setEditable(false); jMCU.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMCU.setHorizontalAlignment(javax.swing.JTextField.CENTER); jMCU.setText(bundle.getString("MC.jMCU.text")); // NOI18N jSerNr.setEditable(false); jSerNr.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jSerNr.setHorizontalAlignment(javax.swing.JTextField.CENTER); jSerNr.setText(bundle.getString("MC.jSerNr.text")); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jSerNr) .addComponent(jMCU, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jHardWare, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jVersion, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jVersion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jHardWare, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jMCU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jSerNr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLangePause.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLangePause.setText(bundle.getString("MC.jLangePause.text")); // NOI18N jDCC_Booster.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jDCC_Booster.setText(bundle.getString("MC.jDCC_Booster.text")); // NOI18N jDCC_Loks.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jDCC_Loks.setText(bundle.getString("MC.jDCC_Loks.text")); // NOI18N jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel6.setText(bundle.getString("MC.jLabel6.text")); // NOI18N jKurzEmpf.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jKurzEmpf.setHorizontalAlignment(javax.swing.JTextField.CENTER); jKurzEmpf.setText(bundle.getString("MC.jKurzEmpf.text")); // NOI18N jKurzEmpf.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jKurzEmpfFocusLost(evt); } }); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel7.setText(bundle.getString("MC.jLabel7.text")); // NOI18N jLabel8.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel8.setText(bundle.getString("MC.jLabel8.text")); // NOI18N js88.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N js88.setHorizontalAlignment(javax.swing.JTextField.CENTER); js88.setText(bundle.getString("MC.js88.text")); // NOI18N js88.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { js88ActionPerformed(evt); } }); js88.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { js88FocusLost(evt); } }); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel9.setText(bundle.getString("MC.jLabel9.text")); // NOI18N jMinMag.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMinMag.setHorizontalAlignment(javax.swing.JTextField.CENTER); jMinMag.setText(bundle.getString("MC.jMinMag.text")); // NOI18N jMinMag.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jMinMagFocusLost(evt); } }); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel10.setText(bundle.getString("MC.jLabel10.text")); // NOI18N jLabel11.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel11.setText(bundle.getString("MC.jLabel11.text")); // NOI18N jMaxMag.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMaxMag.setHorizontalAlignment(javax.swing.JTextField.CENTER); jMaxMag.setText(bundle.getString("MC.jMaxMag.text")); // NOI18N jMaxMag.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jMaxMagFocusLost(evt); } }); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel12.setText(bundle.getString("MC.jLabel12.text")); // NOI18N jLabel13.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel13.setText(bundle.getString("MC.jLabel13.text")); // NOI18N jLabel13.setToolTipText(bundle.getString("MC.jLabel13.toolTipText")); // NOI18N jBaud.setEditable(false); jBaud.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jBaud.setHorizontalAlignment(javax.swing.JTextField.CENTER); jBaud.setText(bundle.getString("MC.jBaud.text")); // NOI18N jBaud.setToolTipText(bundle.getString("MC.jBaud.toolTipText")); // NOI18N jLabel14.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel14.setText(bundle.getString("MC.jLabel14.text")); // NOI18N jKonfLesen.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jKonfLesen.setText(bundle.getString("MC.jKonfLesen.text")); // NOI18N jKonfLesen.setMaximumSize(new java.awt.Dimension(220, 25)); jKonfLesen.setMinimumSize(new java.awt.Dimension(220, 25)); jKonfLesen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jKonfLesenActionPerformed(evt); } }); jKonfSchreiben.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jKonfSchreiben.setText(bundle.getString("MC.jKonfSchreiben.text")); // NOI18N jKonfSchreiben.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jKonfSchreibenActionPerformed(evt); } }); jKonfLaden.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jKonfLaden.setText(bundle.getString("MC.jKonfLaden.text")); // NOI18N jKonfLaden.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jKonfLadenActionPerformed(evt); } }); jKonfSichern.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jKonfSichern.setText(bundle.getString("MC.jKonfSichern.text")); // NOI18N jKonfSichern.setMaximumSize(new java.awt.Dimension(220, 25)); jKonfSichern.setMinimumSize(new java.awt.Dimension(220, 25)); jKonfSichern.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jKonfSichernActionPerformed(evt); } }); jMcRwProgress.setStringPainted(true); jCancel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jCancel.setText(bundle.getString("MC.jCancel.text")); // NOI18N jCancel.setMaximumSize(new java.awt.Dimension(220, 25)); jCancel.setMinimumSize(new java.awt.Dimension(220, 25)); jCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCancelActionPerformed(evt); } }); jMcRwInfo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMcRwInfo.setText(bundle.getString("MC.jMcRwInfo.text")); // NOI18N jMcRwInfo.setToolTipText(bundle.getString("MC.jMcRwInfo.toolTipText")); // NOI18N jRailcomSupport.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jRailcomSupport.setText(bundle.getString("MC.jRailcomSupport.text")); // NOI18N jRailcomTailbits.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jRailcomTailbits.setText(bundle.getString("MC.jRailcomTailbits.text")); // NOI18N jRailcomTailbits.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRailcomTailbitsActionPerformed(evt); } }); jRailcomIdNotify.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jRailcomIdNotify.setText(bundle.getString("MC.jRailcomIdNotify.text")); // NOI18N jRailcomIdNotify.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRailcomIdNotifyActionPerformed(evt); } }); jRailcomAccessory.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jRailcomAccessory.setText(bundle.getString("MC.jRailcomAccessory.text")); // NOI18N jRailcomAccessory.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRailcomAccessoryActionPerformed(evt); } }); jWRsys.setSelected(true); jWRsys.setText(bundle.getString("MC.jWRsys.text")); // NOI18N jWRsys.setToolTipText(bundle.getString("MC.jWRsys.toolTipText")); // NOI18N jWRloc.setSelected(true); jWRloc.setText(bundle.getString("MC.jWRloc.text")); // NOI18N jWRloc.setToolTipText(bundle.getString("MC.jWRloc.toolTipText")); // NOI18N jWRtra.setSelected(true); jWRtra.setText(bundle.getString("MC.jWRtra.text")); // NOI18N jWRtra.setToolTipText(bundle.getString("MC.jWRtra.toolTipText")); // NOI18N jWRmag.setSelected(true); jWRmag.setText(bundle.getString("MC.jWRmag.text")); // NOI18N jWRmag.setToolTipText(bundle.getString("MC.jWRmag.toolTipText")); // NOI18N jDatenQuelle.setEditable(false); jDatenQuelle.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jDatenQuelle.setHorizontalAlignment(javax.swing.JTextField.CENTER); jDatenQuelle.setText(bundle.getString("MC.jDatenQuelle.text")); // NOI18N jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel1.setText(bundle.getString("MC.jLabel1.text")); // NOI18N jClose.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jClose.setText(bundle.getString("MC.jClose.text")); // NOI18N jClose.setMaximumSize(new java.awt.Dimension(220, 25)); jClose.setMinimumSize(new java.awt.Dimension(220, 25)); jClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCloseActionPerformed(evt); } }); jLabel17.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel17.setText(bundle.getString("MC.jLabel17.text")); // NOI18N jLabel17.setToolTipText(bundle.getString("MC.jLabel17.toolTipText")); // NOI18N jSysS88monitor.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jSysS88monitor.setText(bundle.getString("MC.jSysS88monitor.text")); // NOI18N jSysS88monitor.setToolTipText(bundle.getString("MC.jSysS88monitor.toolTipText")); // NOI18N jSysS88monitor.setEnabled(false); jSysS88monitor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jSysS88monitorActionPerformed(evt); } }); jBoosterOpts.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jBoosterOpts.setText(bundle.getString("MC.jBoosterOpts.text")); // NOI18N jBoostOptNoAccDrive.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jBoostOptNoAccDrive.setText(bundle.getString("MC.jBoostOptNoAccDrive.text")); // NOI18N jBoostOptNoAccDrive.setEnabled(false); jBoostOptNoAccDrive.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBoostOptNoAccDriveActionPerformed(evt); } }); jBoostOptNoAccBreak.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jBoostOptNoAccBreak.setText(bundle.getString("MC.jBoostOptNoAccBreak.text")); // NOI18N jBoostOptNoAccBreak.setEnabled(false); jBoostOptNoAccBreak.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBoostOptNoAccBreakActionPerformed(evt); } }); jMRST.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jMRST.setForeground(java.awt.Color.red); jMRST.setText(bundle.getString("MC.jMRST.text")); // NOI18N jMRST.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jMRST.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMRSTActionPerformed(evt); } }); javax.swing.GroupLayout jSystemLayout = new javax.swing.GroupLayout(jSystem); jSystem.setLayout(jSystemLayout); jSystemLayout.setHorizontalGroup( jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jSystemLayout.createSequentialGroup() .addContainerGap() .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jSystemLayout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jDatenQuelle)) .addComponent(jMcRwProgress, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jMcRwInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jSystemLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jClose, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jSystemLayout.createSequentialGroup() .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRailcomTailbits, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jRailcomAccessory, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jRailcomIdNotify, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jSystemLayout.createSequentialGroup() .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRailcomSupport) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDCC_Booster) .addComponent(jLangePause) .addComponent(jDCC_Loks, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jSystemLayout.createSequentialGroup() .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jBoosterOpts) .addComponent(jBoostOptNoAccDrive) .addComponent(jBoostOptNoAccBreak)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE))) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jSystemLayout.createSequentialGroup() .addComponent(jBild, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBild2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)) .addGroup(jSystemLayout.createSequentialGroup() .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel13) .addComponent(jLabel11) .addComponent(jLabel9) .addComponent(jLabel8) .addComponent(jLabel6)) .addGap(15, 15, 15) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(js88, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jMinMag, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jMaxMag, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBaud, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jKurzEmpf, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jSystemLayout.createSequentialGroup() .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14) .addComponent(jLabel10) .addComponent(jLabel7) .addComponent(jLabel12)) .addGap(143, 143, 143)) .addGroup(jSystemLayout.createSequentialGroup() .addComponent(jLabel17) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSysS88monitor, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(74, 74, 74))) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jMRST) .addGroup(jSystemLayout.createSequentialGroup() .addComponent(jWRsys) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jWRloc) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jWRtra) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jWRmag)) .addComponent(jCancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jKonfLesen, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jKonfSchreiben, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jKonfSichern, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jKonfLaden, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); jSystemLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jWRloc, jWRmag, jWRsys, jWRtra}); jSystemLayout.setVerticalGroup( jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jSystemLayout.createSequentialGroup() .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jSystemLayout.createSequentialGroup() .addGap(57, 57, 57) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jKurzEmpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(js88, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8) .addComponent(jLabel17) .addComponent(jSysS88monitor)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jMinMag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jMaxMag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12) .addComponent(jLabel11)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jBaud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14) .addComponent(jLabel13))) .addGroup(jSystemLayout.createSequentialGroup() .addContainerGap() .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jDatenQuelle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jSystemLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jSystemLayout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(jMRST, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 99, Short.MAX_VALUE) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jSystemLayout.createSequentialGroup() .addComponent(jKonfLesen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jSystemLayout.createSequentialGroup() .addComponent(jKonfSchreiben) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jWRloc) .addComponent(jWRtra) .addComponent(jWRmag)) .addComponent(jWRsys)) .addGap(56, 56, 56) .addComponent(jKonfLaden) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jKonfSichern, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jSystemLayout.createSequentialGroup() .addComponent(jBild2, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addComponent(jCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jSystemLayout.createSequentialGroup() .addGroup(jSystemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jBild, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jSystemLayout.createSequentialGroup() .addComponent(jLangePause) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jDCC_Booster) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jDCC_Loks) .addGap(23, 23, 23) .addComponent(jRailcomSupport) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRailcomTailbits) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRailcomIdNotify) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRailcomAccessory) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jBoosterOpts) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBoostOptNoAccDrive) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBoostOptNoAccBreak))) .addGap(4, 4, 4))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jMcRwProgress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jMcRwInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jClose, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jMcRwInfo.getAccessibleContext().setAccessibleName(bundle.getString("MC.jMcRwInfo.AccessibleContext.accessibleName")); // NOI18N jTabbedPane1.addTab(bundle.getString("MC.jSystem.TabConstraints.tabTitle"), jSystem); // NOI18N jLoks.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLoks.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { jLoksComponentShown(evt); } }); jTableLoco.setAutoCreateRowSorter(true); jTableLoco.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTableLoco.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Adresse", "Fahrstufen", "Format", "Name" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jTableLoco.setToolTipText(bundle.getString("MC.jTableLoco.toolTipText")); // NOI18N jTableLoco.setDragEnabled(true); jTableLoco.setIntercellSpacing(new java.awt.Dimension(10, 10)); jTableLoco.setRowHeight(26); jTableLoco.getTableHeader().setReorderingAllowed(false); jTableLoco.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTableLocoFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTableLocoFocusLost(evt); } }); jTableLoco.addInputMethodListener(new java.awt.event.InputMethodListener() { public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) { } public void caretPositionChanged(java.awt.event.InputMethodEvent evt) { jTableLocoCaretPositionChanged(evt); } }); jTableLoco.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { jTableLocoPropertyChange(evt); } }); jTableLoco.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTableLocoKeyReleased(evt); } }); jScrollPane1.setViewportView(jTableLoco); if (jTableLoco.getColumnModel().getColumnCount() > 0) { jTableLoco.getColumnModel().getColumn(0).setResizable(false); jTableLoco.getColumnModel().getColumn(0).setPreferredWidth(50); jTableLoco.getColumnModel().getColumn(1).setResizable(false); jTableLoco.getColumnModel().getColumn(1).setPreferredWidth(50); jTableLoco.getColumnModel().getColumn(2).setResizable(false); jTableLoco.getColumnModel().getColumn(2).setPreferredWidth(50); jTableLoco.getColumnModel().getColumn(3).setResizable(false); } jLocDelAll.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLocDelAll.setText(bundle.getString("MC.jLocDelAll.text")); // NOI18N jLocDelAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLocDelAllActionPerformed(evt); } }); jLocCheck.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLocCheck.setText(bundle.getString("MC.jLocCheck.text")); // NOI18N jLocCheck.setToolTipText(bundle.getString("MC.jLocCheck.toolTipText")); // NOI18N jLocCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLocCheckActionPerformed(evt); } }); jLocRepair.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLocRepair.setText(bundle.getString("MC.jLocRepair.text")); // NOI18N jLocRepair.setToolTipText(bundle.getString("MC.jLocRepair.toolTipText")); // NOI18N jLocRepair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLocRepairActionPerformed(evt); } }); jLocM3sidWrite.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLocM3sidWrite.setText(bundle.getString("MC.jLocM3sidWrite.text")); // NOI18N jLocM3sidWrite.setToolTipText(bundle.getString("MC.jLocM3sidWrite.toolTipText")); // NOI18N jLocM3sidWrite.setEnabled(false); jLocM3sidWrite.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLocM3sidWriteActionPerformed(evt); } }); jTextM3UID.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextM3UID.setText(bundle.getString("MC.jTextM3UID.text")); // NOI18N jTextM3UID.setToolTipText(bundle.getString("MC.jTextM3UID.toolTipText")); // NOI18N jTextM3UID.setEnabled(false); jTextM3UID.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextM3UIDFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextM3UIDFocusLost(evt); } }); jTextM3UID.addInputMethodListener(new java.awt.event.InputMethodListener() { public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) { jTextM3UIDInputMethodTextChanged(evt); } public void caretPositionChanged(java.awt.event.InputMethodEvent evt) { } }); jTextM3UID.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { jTextM3UIDPropertyChange(evt); } }); jLabelM3UID.setText(bundle.getString("MC.jLabelM3UID.text")); // NOI18N jLabelM3UID.setToolTipText(bundle.getString("MC.jLabelM3UID.toolTipText")); // NOI18N jLabelM3UID.setEnabled(false); jLabelM3SID.setText(bundle.getString("MC.jLabelM3SID.text")); // NOI18N jLabelM3SID.setToolTipText(bundle.getString("MC.jLabelM3SID.toolTipText")); // NOI18N jLabelM3SID.setEnabled(false); jTextM3SID.setEditable(false); jTextM3SID.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextM3SID.setText(bundle.getString("MC.jTextM3SID.text")); // NOI18N jTextM3SID.setToolTipText(bundle.getString("MC.jTextM3SID.toolTipText")); // NOI18N jTextM3SID.setEnabled(false); jTextM3SID.setFocusable(false); jMcM3Progress.setStringPainted(true); jMcM3Info.setEditable(false); jLocM3cfgLoad.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLocM3cfgLoad.setText(bundle.getString("MC.jLocM3cfgLoad.text")); // NOI18N jLocM3cfgLoad.setToolTipText(bundle.getString("MC.jLocM3cfgLoad.toolTipText")); // NOI18N jLocM3cfgLoad.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLocM3cfgLoadActionPerformed(evt); } }); jLocM3cfgEdit.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLocM3cfgEdit.setText(bundle.getString("MC.jLocM3cfgEdit.text")); // NOI18N jLocM3cfgEdit.setToolTipText(bundle.getString("MC.jLocM3cfgEdit.toolTipText")); // NOI18N jLocM3cfgEdit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLocM3cfgEditActionPerformed(evt); } }); jLocM3cfgSave.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLocM3cfgSave.setText(bundle.getString("MC.jLocM3cfgSave.text")); // NOI18N jLocM3cfgSave.setToolTipText(bundle.getString("MC.jLocM3cfgSave.toolTipText")); // NOI18N jLocM3cfgSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLocM3cfgSaveActionPerformed(evt); } }); jLocDel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLocDel.setText(bundle.getString("MC.jLocDel.text")); // NOI18N jLocDel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLocDelActionPerformed(evt); } }); jLoc2System.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLoc2System.setText(bundle.getString("MC.jLoc2System.text")); // NOI18N jLoc2System.setMaximumSize(new java.awt.Dimension(220, 25)); jLoc2System.setMinimumSize(new java.awt.Dimension(220, 25)); jLoc2System.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLoc2SystemActionPerformed(evt); } }); jLocM3sidWriteList.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLocM3sidWriteList.setText(bundle.getString("MC.jLocM3sidWriteList.text")); // NOI18N jLocM3sidWriteList.setToolTipText(bundle.getString("MC.jLocM3sidWriteList.toolTipText")); // NOI18N jLocM3sidWriteList.setEnabled(false); jLocM3sidWriteList.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jLocM3sidWriteListActionPerformed(evt); } }); jM3count.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jM3count.setText("(0)"); // NOI18N jM3count.setToolTipText(bundle.getString("MC.jM3count.toolTipText")); // NOI18N jM3count.setRequestFocusEnabled(false); jM3count.setVerifyInputWhenFocusTarget(false); javax.swing.GroupLayout jLoksLayout = new javax.swing.GroupLayout(jLoks); jLoks.setLayout(jLoksLayout); jLoksLayout.setHorizontalGroup( jLoksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jLoksLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 663, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jLoksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLocDelAll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLocCheck, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLocRepair, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLocM3sidWrite, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jLoksLayout.createSequentialGroup() .addGap(0, 156, Short.MAX_VALUE) .addComponent(jLabelM3UID) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextM3UID, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jLoksLayout.createSequentialGroup() .addComponent(jLabelM3SID, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextM3SID)) .addComponent(jMcM3Progress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jMcM3Info) .addComponent(jLocM3cfgLoad, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLocDel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLoc2System, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLocM3sidWriteList, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLocM3cfgEdit, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLocM3cfgSave, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jM3count, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jLoksLayout.setVerticalGroup( jLoksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jLoksLayout.createSequentialGroup() .addContainerGap() .addGroup(jLoksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jLoksLayout.createSequentialGroup() .addComponent(jLocDel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLocDelAll) .addGap(18, 18, 18) .addComponent(jLocCheck) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLocRepair) .addGap(18, 18, 18) .addGroup(jLoksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextM3SID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelM3SID)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jLoksLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelM3UID) .addComponent(jTextM3UID, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLocM3sidWrite, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jMcM3Progress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jMcM3Info, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLocM3sidWriteList) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLocM3cfgLoad) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLocM3cfgEdit) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLocM3cfgSave) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jM3count) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLoc2System, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)) .addContainerGap()) ); jLocM3sidWrite.getAccessibleContext().setAccessibleDescription(bundle.getString("MC.jLocM3sidWrite.AccessibleContext.accessibleDescription")); // NOI18N jTabbedPane1.addTab(bundle.getString("MC.jLoks.TabConstraints.tabTitle"), jLoks); // NOI18N jTraktionen.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTraktionen.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { jTraktionenComponentShown(evt); } }); jTableTraction.setAutoCreateRowSorter(true); jTableTraction.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTableTraction.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Adresse 1", "Name 1", "Adresse 2", "Name 2" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { true, false, true, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTableTraction.setToolTipText(bundle.getString("MC.jTableTraction.toolTipText")); // NOI18N jTableTraction.setDragEnabled(true); jTableTraction.setIntercellSpacing(new java.awt.Dimension(10, 10)); jTableTraction.setRowHeight(26); jTableTraction.getTableHeader().setReorderingAllowed(false); jTableTraction.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTableTractionKeyReleased(evt); } }); jScrollPane2.setViewportView(jTableTraction); if (jTableTraction.getColumnModel().getColumnCount() > 0) { jTableTraction.getColumnModel().getColumn(1).setResizable(false); jTableTraction.getColumnModel().getColumn(3).setResizable(false); } jTraDelAll.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTraDelAll.setText(bundle.getString("MC.jTraDelAll.text")); // NOI18N jTraDelAll.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTraDelAllActionPerformed(evt); } }); jLabel15.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel15.setText(bundle.getString("MC.jLabel15.text")); // NOI18N jTraCheck.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTraCheck.setText(bundle.getString("MC.jTraCheck.text")); // NOI18N jTraCheck.setToolTipText(bundle.getString("MC.jTraCheck.toolTipText")); // NOI18N jTraCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTraCheckActionPerformed(evt); } }); jTraRepair.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTraRepair.setText(bundle.getString("MC.jTraRepair.text")); // NOI18N jTraRepair.setToolTipText(bundle.getString("MC.jTraRepair.toolTipText")); // NOI18N jTraRepair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTraRepairActionPerformed(evt); } }); jTraDel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTraDel.setText(bundle.getString("MC.jTraDel.text")); // NOI18N jTraDel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTraDelActionPerformed(evt); } }); jTra2System.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jTra2System.setText(bundle.getString("MC.jTra2System.text")); // NOI18N jTra2System.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTra2SystemActionPerformed(evt); } }); javax.swing.GroupLayout jTraktionenLayout = new javax.swing.GroupLayout(jTraktionen); jTraktionen.setLayout(jTraktionenLayout); jTraktionenLayout.setHorizontalGroup( jTraktionenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jTraktionenLayout.createSequentialGroup() .addContainerGap() .addGroup(jTraktionenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel15) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 942, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jTraktionenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTraDelAll, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE) .addComponent(jTraDel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTraCheck, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTraRepair, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTra2System, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jTraktionenLayout.setVerticalGroup( jTraktionenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jTraktionenLayout.createSequentialGroup() .addGroup(jTraktionenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jTraktionenLayout.createSequentialGroup() .addGap(58, 58, 58) .addComponent(jTraDel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTraDelAll) .addGap(18, 18, 18) .addComponent(jTraCheck) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTraRepair) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTra2System)) .addGroup(jTraktionenLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE))) .addGap(18, 18, 18) .addComponent(jLabel15) .addGap(14, 14, 14)) ); jTabbedPane1.addTab(bundle.getString("MC.jTraktionen.TabConstraints.tabTitle"), jTraktionen); // NOI18N jMagnetartikel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMagnetartikel.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { jMagnetartikelComponentShown(evt); } }); jTableAccessory.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Gruppe (Adressen)", "Format" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, true }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTableAccessory.setIntercellSpacing(new java.awt.Dimension(10, 10)); jTableAccessory.setRowHeight(26); jTableAccessory.getTableHeader().setReorderingAllowed(false); jTableAccessory.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTableAccessoryKeyReleased(evt); } }); jScrollPane3.setViewportView(jTableAccessory); if (jTableAccessory.getColumnModel().getColumnCount() > 0) { jTableAccessory.getColumnModel().getColumn(0).setResizable(false); } jMMM.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMMM.setText(bundle.getString("MC.jMMM.text")); // NOI18N jMMM.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMMMActionPerformed(evt); } }); jMDCC.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMDCC.setText(bundle.getString("MC.jMDCC.text")); // NOI18N jMDCC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMDCCActionPerformed(evt); } }); jMagCheck.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMagCheck.setText(bundle.getString("MC.jMagCheck.text")); // NOI18N jMagCheck.setToolTipText(bundle.getString("MC.jMagCheck.toolTipText")); // NOI18N jMagCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMagCheckActionPerformed(evt); } }); jMagRepair.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMagRepair.setText(bundle.getString("MC.jMagRepair.text")); // NOI18N jMagRepair.setToolTipText(bundle.getString("MC.jMagRepair.toolTipText")); // NOI18N jMagRepair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMagRepairActionPerformed(evt); } }); jLabel16.setText(bundle.getString("MC.jLabel16.text")); // NOI18N jMag2System.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMag2System.setText(bundle.getString("MC.jMag2System.text")); // NOI18N jMag2System.setMaximumSize(new java.awt.Dimension(220, 25)); jMag2System.setMinimumSize(new java.awt.Dimension(220, 25)); jMag2System.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMag2SystemActionPerformed(evt); } }); javax.swing.GroupLayout jMagnetartikelLayout = new javax.swing.GroupLayout(jMagnetartikel); jMagnetartikel.setLayout(jMagnetartikelLayout); jMagnetartikelLayout.setHorizontalGroup( jMagnetartikelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jMagnetartikelLayout.createSequentialGroup() .addContainerGap() .addGroup(jMagnetartikelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 861, Short.MAX_VALUE) .addComponent(jLabel16)) .addGap(29, 29, 29) .addGroup(jMagnetartikelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jMag2System, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jMMM, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jMDCC, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jMagCheck, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jMagRepair, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)) .addContainerGap()) ); jMagnetartikelLayout.setVerticalGroup( jMagnetartikelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jMagnetartikelLayout.createSequentialGroup() .addGroup(jMagnetartikelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jMagnetartikelLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)) .addGroup(jMagnetartikelLayout.createSequentialGroup() .addGap(107, 107, 107) .addComponent(jMMM) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jMDCC) .addGap(52, 52, 52) .addComponent(jMagCheck) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jMagRepair) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jMag2System, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel16) .addGap(20, 20, 20)) ); jTabbedPane1.addTab(bundle.getString("MC.jMagnetartikel.TabConstraints.tabTitle"), jMagnetartikel); // NOI18N jPanel2.setMaximumSize(new java.awt.Dimension(1110, 32767)); jPanel2.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { jPanel2ComponentShown(evt); } }); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("MC.jPanel3.border.title"))); // NOI18N jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jCVListe.setModel(new javax.swing.AbstractListModel() { String[] strings = { " 0002", " 0003", " 0004", " 0005", " 0029" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane5.setViewportView(jCVListe); jPanel3.add(jScrollPane5, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 45, 224, 275)); jLabel25.setText(bundle.getString("MC.jLabel25.text")); // NOI18N jPanel3.add(jLabel25, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 24, -1, -1)); jLabel26.setText(bundle.getString("MC.jLabel26.text")); // NOI18N jPanel3.add(jLabel26, new org.netbeans.lib.awtextra.AbsoluteConstraints(75, 24, -1, -1)); buttonGroup1.add(jHauptGleis); jHauptGleis.setText(bundle.getString("MC.jHauptGleis.text")); // NOI18N jHauptGleis.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jHauptGleisActionPerformed(evt); } }); jPanel3.add(jHauptGleis, new org.netbeans.lib.awtextra.AbsoluteConstraints(247, 27, -1, -1)); buttonGroup1.add(jProgGleis); jProgGleis.setText(bundle.getString("MC.jProgGleis.text")); // NOI18N jProgGleis.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jProgGleisActionPerformed(evt); } }); jPanel3.add(jProgGleis, new org.netbeans.lib.awtextra.AbsoluteConstraints(247, 52, -1, -1)); jListeLesen.setText(bundle.getString("MC.jListeLesen.text")); // NOI18N jListeLesen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jListeLesenActionPerformed(evt); } }); jPanel3.add(jListeLesen, new org.netbeans.lib.awtextra.AbsoluteConstraints(241, 221, 160, -1)); jListeSchreiben.setText(bundle.getString("MC.jListeSchreiben.text")); // NOI18N jListeSchreiben.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jListeSchreibenActionPerformed(evt); } }); jPanel3.add(jListeSchreiben, new org.netbeans.lib.awtextra.AbsoluteConstraints(241, 258, 160, -1)); jListeBearbeiten.setText(bundle.getString("MC.jListeBearbeiten.text")); // NOI18N jListeBearbeiten.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jListeBearbeitenActionPerformed(evt); } }); jPanel3.add(jListeBearbeiten, new org.netbeans.lib.awtextra.AbsoluteConstraints(241, 184, 160, -1)); jLabel28.setText(bundle.getString("MC.jLabel28.text")); // NOI18N jPanel3.add(jLabel28, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 300, -1, -1)); jHerstellerInfo.setEditable(false); jHerstellerInfo.setText(bundle.getString("MC.jHerstellerInfo.text")); // NOI18N jHerstellerInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jHerstellerInfoActionPerformed(evt); } }); jPanel3.add(jHerstellerInfo, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 300, 180, -1)); jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("MC.jPanel8.border.title"))); // NOI18N jLabel29.setText(bundle.getString("MC.jLabel29.text")); // NOI18N jCV_Direkt.setText(bundle.getString("MC.jCV_Direkt.text")); // NOI18N jWertDirekt.setText(bundle.getString("MC.jWertDirekt.text")); // NOI18N jLabel30.setText(bundle.getString("MC.jLabel30.text")); // NOI18N jDirektLesen.setText(bundle.getString("MC.jDirektLesen.text")); // NOI18N jDirektLesen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jDirektLesenActionPerformed(evt); } }); jDirektSchreiben.setText(bundle.getString("MC.jDirektSchreiben.text")); // NOI18N jDirektSchreiben.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jDirektSchreibenActionPerformed(evt); } }); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel30) .addComponent(jLabel29)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jCV_Direkt) .addComponent(jWertDirekt, javax.swing.GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jDirektLesen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jDirektSchreiben, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel29) .addComponent(jCV_Direkt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jDirektLesen)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel30) .addComponent(jWertDirekt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jDirektSchreiben)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel3.add(jPanel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(241, 77, 254, 95)); jLabel31.setText(bundle.getString("MC.jLabel31.text")); // NOI18N jPanel3.add(jLabel31, new org.netbeans.lib.awtextra.AbsoluteConstraints(357, 31, -1, -1)); jDecAdr.setText(bundle.getString("MC.jDecAdr.text")); // NOI18N jPanel3.add(jDecAdr, new org.netbeans.lib.awtextra.AbsoluteConstraints(403, 29, 55, -1)); jPanel2.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 12, 510, 340)); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("MC.jPanel4.border.title"))); // NOI18N jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel19.setText(bundle.getString("MC.jLabel19.text")); // NOI18N jPanel4.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(204, 80, -1, -1)); jLabel20.setText(bundle.getString("MC.jLabel20.text")); // NOI18N jPanel4.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(17, 80, -1, -1)); jm3Addr.setText(bundle.getString("MC.jm3Addr.text")); // NOI18N jPanel4.add(jm3Addr, new org.netbeans.lib.awtextra.AbsoluteConstraints(96, 78, 96, -1)); jmfxUID.setEditable(false); jmfxUID.setText(bundle.getString("MC.jmfxUID.text")); // NOI18N jPanel4.add(jmfxUID, new org.netbeans.lib.awtextra.AbsoluteConstraints(249, 78, 90, -1)); jm3Schreiben.setText(bundle.getString("MC.jm3Schreiben.text")); // NOI18N jm3Schreiben.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jm3SchreibenActionPerformed(evt); } }); jPanel4.add(jm3Schreiben, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 70, 110, -1)); jLabel27.setText(bundle.getString("MC.jLabel27.text")); // NOI18N jPanel4.add(jLabel27, new org.netbeans.lib.awtextra.AbsoluteConstraints(17, 28, -1, -1)); jLabel32.setText(bundle.getString("MC.jLabel32.text")); // NOI18N jPanel4.add(jLabel32, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 50, -1, -1)); jPanel2.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 361, 510, 110)); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("MC.jPanel5.border.title"))); // NOI18N jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel21.setText(bundle.getString("MC.jLabel21.text")); // NOI18N jPanel5.add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(23, 81, -1, -1)); jMMRegister.setText(bundle.getString("MC.jMMRegister.text")); // NOI18N jPanel5.add(jMMRegister, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 79, 90, -1)); jMMWert.setText(bundle.getString("MC.jMMWert.text")); // NOI18N jMMWert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMMWertActionPerformed(evt); } }); jPanel5.add(jMMWert, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 80, 70, -1)); jLabel22.setText(bundle.getString("MC.jLabel22.text")); // NOI18N jPanel5.add(jLabel22, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 80, -1, -1)); jStartMMProg.setText(bundle.getString("MC.jStartMMProg.text")); // NOI18N jStartMMProg.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jStartMMProgActionPerformed(evt); } }); jPanel5.add(jStartMMProg, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 70, 111, -1)); jLabel23.setText(bundle.getString("MC.jLabel23.text")); // NOI18N jPanel5.add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(17, 28, -1, -1)); jLabel24.setText(bundle.getString("MC.jLabel24.text")); // NOI18N jPanel5.add(jLabel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(91, 49, -1, -1)); jPanel2.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 490, 510, 110)); jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("MC.jPanel6.border.title"))); // NOI18N jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jGeschwindigkeit.setMaximum(126); jGeschwindigkeit.setValue(0); jGeschwindigkeit.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jGeschwindigkeitStateChanged(evt); } }); jGeschwindigkeit.addInputMethodListener(new java.awt.event.InputMethodListener() { public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) { } public void caretPositionChanged(java.awt.event.InputMethodEvent evt) { jGeschwindigkeitCaretPositionChanged(evt); } }); jPanel6.add(jGeschwindigkeit, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 510, 180, -1)); jPanel7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); j1.setText(bundle.getString("MC.j1.text")); // NOI18N j1.setPreferredSize(new java.awt.Dimension(44, 44)); j1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j1ActionPerformed(evt); } }); j2.setText(bundle.getString("MC.j2.text")); // NOI18N j2.setPreferredSize(new java.awt.Dimension(44, 44)); j2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j2ActionPerformed(evt); } }); j3.setText(bundle.getString("MC.j3.text")); // NOI18N j3.setPreferredSize(new java.awt.Dimension(44, 44)); j3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j3ActionPerformed(evt); } }); j4.setText(bundle.getString("MC.j4.text")); // NOI18N j4.setPreferredSize(new java.awt.Dimension(44, 44)); j4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j4ActionPerformed(evt); } }); j5.setText(bundle.getString("MC.j5.text")); // NOI18N j5.setPreferredSize(new java.awt.Dimension(44, 44)); j5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j5ActionPerformed(evt); } }); j6.setText(bundle.getString("MC.j6.text")); // NOI18N j6.setPreferredSize(new java.awt.Dimension(44, 44)); j6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j6ActionPerformed(evt); } }); j7.setText(bundle.getString("MC.j7.text")); // NOI18N j7.setPreferredSize(new java.awt.Dimension(44, 44)); j7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j7ActionPerformed(evt); } }); j8.setText(bundle.getString("MC.j8.text")); // NOI18N j8.setPreferredSize(new java.awt.Dimension(44, 44)); j8.setRequestFocusEnabled(false); j8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j8ActionPerformed(evt); } }); j9.setText(bundle.getString("MC.j9.text")); // NOI18N j9.setPreferredSize(new java.awt.Dimension(44, 44)); j9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j9ActionPerformed(evt); } }); jStern.setText(bundle.getString("MC.jStern.text")); // NOI18N jStern.setPreferredSize(new java.awt.Dimension(44, 44)); jStern.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jSternActionPerformed(evt); } }); j0.setText(bundle.getString("MC.j0.text")); // NOI18N j0.setPreferredSize(new java.awt.Dimension(44, 44)); j0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { j0ActionPerformed(evt); } }); jRaute.setText(bundle.getString("MC.jRaute.text")); // NOI18N jRaute.setPreferredSize(new java.awt.Dimension(44, 44)); jRaute.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRauteActionPerformed(evt); } }); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(j1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(j2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(j3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(j4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(j5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(j6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jStern, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(j7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(j8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(j9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(j0, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jRaute, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(j1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(j2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(j3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(j4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(j5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(j6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(j7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(j8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(j9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jStern, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(j0, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRaute, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel6.add(jPanel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(26, 214, -1, -1)); jf0.setText(bundle.getString("MC.jf0.text")); // NOI18N jf0.setPreferredSize(new java.awt.Dimension(47, 45)); jf0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf0ActionPerformed(evt); } }); jPanel6.add(jf0, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 260, -1, -1)); jf1.setText(bundle.getString("MC.jf1.text")); // NOI18N jf1.setPreferredSize(new java.awt.Dimension(47, 45)); jf1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf1ActionPerformed(evt); } }); jPanel6.add(jf1, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 260, -1, -1)); jf2.setText(bundle.getString("MC.jf2.text")); // NOI18N jf2.setPreferredSize(new java.awt.Dimension(47, 45)); jf2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf2ActionPerformed(evt); } }); jPanel6.add(jf2, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 260, -1, -1)); jf3.setText(bundle.getString("MC.jf3.text")); // NOI18N jf3.setPreferredSize(new java.awt.Dimension(47, 45)); jf3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf3ActionPerformed(evt); } }); jPanel6.add(jf3, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 330, -1, -1)); jf4.setText(bundle.getString("MC.jf4.text")); // NOI18N jf4.setPreferredSize(new java.awt.Dimension(47, 45)); jf4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf4ActionPerformed(evt); } }); jPanel6.add(jf4, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 330, -1, -1)); jGO.setText(bundle.getString("MC.jGO.text")); // NOI18N jGO.setPreferredSize(new java.awt.Dimension(52, 45)); jGO.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jGOActionPerformed(evt); } }); jPanel6.add(jGO, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 400, 70, -1)); jSTOP.setText(bundle.getString("MC.jSTOP.text")); // NOI18N jSTOP.setPreferredSize(new java.awt.Dimension(66, 45)); jSTOP.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jSTOPActionPerformed(evt); } }); jPanel6.add(jSTOP, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 400, 70, -1)); jPanel9.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jf5.setText(bundle.getString("MC.jf5.text")); // NOI18N jf5.setPreferredSize(new java.awt.Dimension(55, 39)); jf5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf5ActionPerformed(evt); } }); jf9.setText(bundle.getString("MC.jf9.text")); // NOI18N jf9.setPreferredSize(new java.awt.Dimension(55, 39)); jf9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf9ActionPerformed(evt); } }); jf6.setText(bundle.getString("MC.jf6.text")); // NOI18N jf6.setPreferredSize(new java.awt.Dimension(55, 39)); jf6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf6ActionPerformed(evt); } }); jf8.setText(bundle.getString("MC.jf8.text")); // NOI18N jf8.setPreferredSize(new java.awt.Dimension(55, 39)); jf8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf8ActionPerformed(evt); } }); jf7.setText(bundle.getString("MC.jf7.text")); // NOI18N jf7.setPreferredSize(new java.awt.Dimension(55, 39)); jf7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf7ActionPerformed(evt); } }); jf10.setText(bundle.getString("MC.jf10.text")); // NOI18N jf10.setPreferredSize(new java.awt.Dimension(55, 39)); jf10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf10ActionPerformed(evt); } }); jf11.setText(bundle.getString("MC.jf11.text")); // NOI18N jf11.setPreferredSize(new java.awt.Dimension(55, 39)); jf11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf11ActionPerformed(evt); } }); jf12.setText(bundle.getString("MC.jf12.text")); // NOI18N jf12.setPreferredSize(new java.awt.Dimension(55, 39)); jf12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf12ActionPerformed(evt); } }); jf18.setText(bundle.getString("MC.jf18.text")); // NOI18N jf18.setPreferredSize(new java.awt.Dimension(55, 39)); jf18.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf18ActionPerformed(evt); } }); jf13.setText(bundle.getString("MC.jf13.text")); // NOI18N jf13.setPreferredSize(new java.awt.Dimension(55, 39)); jf13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf13ActionPerformed(evt); } }); jf17.setText(bundle.getString("MC.jf17.text")); // NOI18N jf17.setPreferredSize(new java.awt.Dimension(55, 39)); jf14.setText(bundle.getString("MC.jf14.text")); // NOI18N jf14.setPreferredSize(new java.awt.Dimension(55, 39)); jf14.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf14ActionPerformed(evt); } }); jf19.setText(bundle.getString("MC.jf19.text")); // NOI18N jf19.setPreferredSize(new java.awt.Dimension(55, 39)); jf15.setText(bundle.getString("MC.jf15.text")); // NOI18N jf15.setPreferredSize(new java.awt.Dimension(55, 39)); jf15.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf15ActionPerformed(evt); } }); jf16.setText(bundle.getString("MC.jf16.text")); // NOI18N jf16.setMaximumSize(new java.awt.Dimension(47, 55)); jf16.setPreferredSize(new java.awt.Dimension(55, 39)); jf16.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf16ActionPerformed(evt); } }); jf20.setText(bundle.getString("MC.jf20.text")); // NOI18N jf20.setPreferredSize(new java.awt.Dimension(55, 39)); jf22.setText(bundle.getString("MC.jf22.text")); // NOI18N jf22.setPreferredSize(new java.awt.Dimension(55, 39)); jf21.setText(bundle.getString("MC.jf21.text")); // NOI18N jf21.setPreferredSize(new java.awt.Dimension(55, 39)); jf23.setText(bundle.getString("MC.jf23.text")); // NOI18N jf23.setPreferredSize(new java.awt.Dimension(55, 39)); jf24.setText(bundle.getString("MC.jf24.text")); // NOI18N jf24.setPreferredSize(new java.awt.Dimension(55, 39)); jf24.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf24ActionPerformed(evt); } }); jf26.setText(bundle.getString("MC.jf26.text")); // NOI18N jf26.setPreferredSize(new java.awt.Dimension(55, 39)); jf26.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf26ActionPerformed(evt); } }); jf25.setText(bundle.getString("MC.jf25.text")); // NOI18N jf25.setPreferredSize(new java.awt.Dimension(55, 39)); jf27.setText(bundle.getString("MC.jf27.text")); // NOI18N jf27.setPreferredSize(new java.awt.Dimension(55, 39)); jf28.setText(bundle.getString("MC.jf28.text")); // NOI18N jf28.setPreferredSize(new java.awt.Dimension(55, 39)); jf28.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jf28ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jf19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jf20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jf15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jf16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jf9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jf12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel9Layout.createSequentialGroup() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jf7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jf6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jf13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jf14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jf17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jf18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jf21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jf22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jf23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jf24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jf25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jf26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jf27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jf28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap()) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jf5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jf8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jf10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jf12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jf14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jf15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jf17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jf19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jf21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jf23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jf25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jf27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jf28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(57, 57, 57)) ); jPanel6.add(jPanel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 10, -1, 562)); jPanel10.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 4)); jPanel10.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jDisplay.setEditable(false); jDisplay.setFont(new java.awt.Font("Liberation Mono", 1, 32)); // NOI18N jDisplay.setTabSize(1); jDisplay.setText(bundle.getString("MC.jDisplay.text")); // NOI18N jDisplay.setAutoscrolls(false); jDisplay.setFocusable(false); jDisplay.setMaximumSize(new java.awt.Dimension(304, 66)); jDisplay.setRequestFocusEnabled(false); jScrollPane6.setViewportView(jDisplay); jPanel10.add(jScrollPane6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 320, 90)); jPanel6.add(jPanel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 70, 340, 110)); jLabel33.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 12)); // NOI18N jLabel33.setText(bundle.getString("MC.jLabel33.text")); // NOI18N jPanel6.add(jLabel33, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 230, -1, -1)); jLabel34.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 18)); // NOI18N jLabel34.setText(bundle.getString("MC.jLabel34.text")); // NOI18N jPanel6.add(jLabel34, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 230, -1, -1)); jRueck.setText(bundle.getString("MC.jRueck.text")); // NOI18N jRueck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRueckActionPerformed(evt); } }); jPanel6.add(jRueck, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 540, -1, -1)); jVor.setText(bundle.getString("MC.jVor.text")); // NOI18N jVor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jVorActionPerformed(evt); } }); jPanel6.add(jVor, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 540, -1, -1)); jPanel2.add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 12, 570, 590)); jTabbedPane1.addTab(bundle.getString("MC.jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N jUpdate.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jUpdate.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { jUpdateComponentShown(evt); } }); jUpdDatei.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jUpdDatei.setText(bundle.getString("MC.jUpdDatei.text")); // NOI18N jUpdDateiAuswahl.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jUpdDateiAuswahl.setText(bundle.getString("MC.jUpdDateiAuswahl.text")); // NOI18N jUpdDateiAuswahl.setToolTipText(bundle.getString("MC.jUpdDateiAuswahl.toolTipText")); // NOI18N jUpdDateiAuswahl.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jUpdDateiAuswahlActionPerformed(evt); } }); jMcUpdProgress.setStringPainted(true); jUpdStartUpdate.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jUpdStartUpdate.setText(bundle.getString("MC.jUpdStartUpdate.text")); // NOI18N jUpdStartUpdate.setToolTipText(bundle.getString("MC.jUpdStartUpdate.toolTipText")); // NOI18N jUpdStartUpdate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jUpdStartUpdateActionPerformed(evt); } }); jMcUpdInfo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jMcUpdInfo.setText(bundle.getString("MC.jMcUpdInfo.text")); // NOI18N jUpdLastErrorLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jUpdLastErrorLabel.setText(bundle.getString("MC.jUpdLastErrorLabel.text")); // NOI18N jUpdLastError.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jUpdLastError.setText(bundle.getString("MC.jUpdLastError.text")); // NOI18N jUpdCancel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jUpdCancel.setText(bundle.getString("MC.jUpdCancel.text")); // NOI18N jUpdCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jUpdCancelActionPerformed(evt); } }); jUpdClose.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jUpdClose.setText(bundle.getString("MC.jUpdClose.text")); // NOI18N jUpdClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jUpdCloseActionPerformed(evt); } }); jUpd2System.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jUpd2System.setText(bundle.getString("MC.jUpd2System.text")); // NOI18N jUpd2System.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jUpd2SystemActionPerformed(evt); } }); jTextPane1.setEditable(false); jTextPane1.setBackground(new java.awt.Color(238, 238, 238)); jTextPane1.setBorder(null); jTextPane1.setContentType("text/html"); // NOI18N jTextPane1.setText(bundle.getString("MC.jTextPane1.text")); // NOI18N jTextPane1.setFocusable(false); jScrollPane4.setViewportView(jTextPane1); helpLC.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N helpLC.setText(bundle.getString("MC.helpLC.text")); // NOI18N helpLC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpLCActionPerformed(evt); } }); jTextField1.setBackground(new java.awt.Color(238, 238, 238)); jTextField1.setText(bundle.getString("MC.jTextField1.text")); // NOI18N helpHC.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N helpHC.setText(bundle.getString("MC.helpHC.text")); // NOI18N helpHC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpHCActionPerformed(evt); } }); helpPC.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N helpPC.setText(bundle.getString("MC.helpPC.text")); // NOI18N helpPC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpPCActionPerformed(evt); } }); helpSNC.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N helpSNC.setText(bundle.getString("MC.helpSNC.text")); // NOI18N helpSNC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpSNCActionPerformed(evt); } }); helpXNC.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N helpXNC.setText(bundle.getString("MC.helpXNC.text")); // NOI18N helpXNC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpXNCActionPerformed(evt); } }); helpMC.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N helpMC.setText(bundle.getString("MC.helpMC.text")); // NOI18N helpMC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpMCActionPerformed(evt); } }); helpWasIstWas.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N helpWasIstWas.setText(bundle.getString("MC.helpWasIstWas.text")); // NOI18N helpWasIstWas.setToolTipText(bundle.getString("MC.helpWasIstWas.toolTipText")); // NOI18N helpWasIstWas.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpWasIstWasActionPerformed(evt); } }); helpMCasLC.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N helpMCasLC.setText(bundle.getString("MC.helpMCasLC.text")); // NOI18N helpMCasLC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpMCasLCActionPerformed(evt); } }); Firmware.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N Firmware.setText(bundle.getString("MC.Firmware.text")); // NOI18N Firmware.setToolTipText(bundle.getString("MC.Firmware.toolTipText")); // NOI18N Firmware.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FirmwareActionPerformed(evt); } }); jEasyNetUpdate.setText(bundle.getString("MC.jEasyNetUpdate.text")); // NOI18N jEasyNetUpdate.setToolTipText(bundle.getString("MC.jEasyNetUpdate.toolTipText")); // NOI18N jEasyNetUpdate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jEasyNetUpdateActionPerformed(evt); } }); buttonGroup1.add(jUSB1); jUSB1.setText(bundle.getString("MC.jUSB1.text")); // NOI18N jUSB1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jUSB1ActionPerformed(evt); } }); buttonGroup1.add(jUSB2); jUSB2.setText(bundle.getString("MC.jUSB2.text")); // NOI18N jUSB2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jUSB2ActionPerformed(evt); } }); jLabel18.setText(bundle.getString("MC.jLabel18.text")); // NOI18N jLabel18.setToolTipText(bundle.getString("MC.jLabel18.toolTipText")); // NOI18N javax.swing.GroupLayout jUpdateLayout = new javax.swing.GroupLayout(jUpdate); jUpdate.setLayout(jUpdateLayout); jUpdateLayout.setHorizontalGroup( jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jUpdateLayout.createSequentialGroup() .addContainerGap() .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jMcUpdProgress, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jUpdateLayout.createSequentialGroup() .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jUpdateLayout.createSequentialGroup() .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jUpdateLayout.createSequentialGroup() .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jMcUpdInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jUpdateLayout.createSequentialGroup() .addComponent(jLabel18) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jUSB1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jUSB2))) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jUpdDatei)) .addGap(4, 4, 4)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jUpdateLayout.createSequentialGroup() .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jUpdateLayout.createSequentialGroup() .addComponent(jUpdLastErrorLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jUpdLastError, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 152, Short.MAX_VALUE) .addComponent(jEasyNetUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jUpdateLayout.createSequentialGroup() .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(helpHC, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(helpLC, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(helpPC, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(helpXNC, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jUpdateLayout.createSequentialGroup() .addComponent(helpMC, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(helpMCasLC, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jUpdateLayout.createSequentialGroup() .addComponent(helpSNC, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Firmware)))) .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGap(15, 15, 15))) .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jUpd2System, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE) .addComponent(jUpdClose, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jUpdDateiAuswahl, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jUpdCancel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jUpdStartUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(helpWasIstWas)))) .addContainerGap()) ); jUpdateLayout.setVerticalGroup( jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jUpdateLayout.createSequentialGroup() .addContainerGap() .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jUpdDatei, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jUpdDateiAuswahl)) .addGap(6, 6, 6) .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jUSB1) .addComponent(jUSB2) .addComponent(helpWasIstWas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jMcUpdInfo) .addGap(18, 18, 18) .addComponent(jMcUpdProgress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jUpdateLayout.createSequentialGroup() .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jUpdStartUpdate) .addComponent(jEasyNetUpdate)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jUpdCancel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jUpd2System) .addComponent(helpXNC) .addComponent(helpHC)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jUpdClose) .addComponent(helpPC) .addComponent(helpMC) .addComponent(helpMCasLC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) .addGroup(jUpdateLayout.createSequentialGroup() .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jUpdLastError) .addComponent(jUpdLastErrorLabel)) .addGap(11, 11, 11) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jUpdateLayout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(helpLC) .addComponent(helpSNC))) .addComponent(Firmware, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(88, 88, 88)))) ); jTabbedPane1.addTab(bundle.getString("MC.jUpdate.TabConstraints.tabTitle"), jUpdate); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed // falls Schnittstelle offen und verbunden -> schliessen if( debugLevel > 0 ) { System.out.println("formWindowClosed"); } KTUI.frameInstanceDEVICE = null; stopIOAction(); Com = KTUI.safelyCloseCom( this, Com ); KTUI.setNumS88(0); KTUI.setFocus(); }//GEN-LAST:event_formWindowClosed private void initLocoTable(){ for (int i = 0; i < c.MAX_LOCS; i++) { for (int j = 0; j < jTableLoco.getColumnCount(); j++) { jTableLoco.setValueAt("", i, j); } } jTableLoco.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { locoTableSelRow = jTableLoco.getSelectedRow(); locoTableSelCol = jTableLoco.getSelectedColumn(); if( debugLevel > 0 ) { System.out.println("LOCO ListSelectionListener valueChanged row="+locoTableSelRow+" col="+locoTableSelCol); } if( locoTableSelRow >= 0 ) { checkM3sid(locoTableSelRow); } } }); } private void checkM3sid( int row ) { String sFormat = ""+jTableLoco.getValueAt(row, 2); Boolean showM3 = "M3".equalsIgnoreCase(sFormat); jLabelM3SID.setEnabled(showM3); jTextM3SID.setEnabled(showM3); jLabelM3UID.setEnabled(showM3); jTextM3UID.setEnabled(showM3); jLocM3sidWrite.setEnabled(showM3); if( showM3 ) { jTextM3SID.setText(""+jTableLoco.getValueAt(row, 0)); jTextM3UID.setText(""+getM3UID( jTableLoco.getValueAt(row, 0))); jMcM3Info.setText(""); jMcM3Progress.setValue(0); } } private String getM3UID( Object loco ) { String sLoco = ""+loco; if( debugLevel > 0 ) { System.out.println("getM3UID sLoco="+sLoco ); } for( int i = 0 ; i < M3used ; i++ ) { String sM3uid = ""+M3liste[0][i]; String sM3sid = ""+M3liste[1][i]; if( debugLevel > 0 ) { System.out.println("getM3UID sM3uid="+sM3uid+" sM3sid="+sM3sid ); } if( sM3sid.equals(sLoco) ) { if( sM3uid != null ) { return sM3uid; } } } return ""; } private void initTractionTable(){ for (int i = 0; i < jTableTraction.getRowCount(); i++) { for (int j = 0; j < jTableTraction.getColumnCount(); j++) { jTableTraction.setValueAt("", i, j); } } } private void initAccessoryTable(){ for (int i = 0; i < jTableAccessory.getRowCount(); i++) { for (int j = 0; j < jTableAccessory.getColumnCount(); j++) { jTableAccessory.setValueAt("", i, j); } } } private void setAccessoryTableWithProto(String str){ for (int i = 0; i < jTableAccessory.getRowCount(); i++) { jTableAccessory.setValueAt(str, i, 1); } } private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // Ist die TamsMC auch eingestellt ? if ( KTUI.getZentrale() != c.cuMasterControl ) { KTUI.mbNoTamsMC( this ); this.dispose(); return; } gsBaudRateSaved = KTUI.gsBaudRate; jLabel18.setText(jLabel18.getText().replace("COMx", KTUI.gsSchnittstelle)); if( KTUI.rs232_or_rb_usb_2 ) { jUSB1.setSelected(false); jUSB2.setSelected(true); } else { jUSB1.setSelected(true); jUSB2.setSelected(false); } setFocusUpdStart(); setFocusDateiAuswahl(); Com = KTUI.safelyOpenCom( this, Com, false ); System.out.println("call Com.connect OUT: Com "+((Com == null)?"==":"!=")+" NULL" ); System.out.println("call Com.connect OUT: isopen["+((Com == null)?"Com is undefined":Com.isconnected())+"]" ); if( (Com == null) || (! Com.isconnected()) ) { // continue -> prepare offline use with default values jKonfLesen.setEnabled(false); jKonfSchreiben.setEnabled(false); jWRsys.setEnabled(false); jWRloc.setEnabled(false); jWRtra.setEnabled(false); jWRmag.setEnabled(false); if( KTUI.updateAlwaysVisible == false ) { jTabbedPane1.remove(this.jUpdate); } //jDatenQuelle.setText("invalid"); jDatenQuelle.setForeground(Color.red); jBaud.setText("-"); Com = null; KTUI.mbDeviceConnectProblemOffline( this ); } else { // jBaud.setText(Integer.toString(KTUI.gsBaudRate)); Com = KTUI.safelyCloseCom( this, Com ); } jCancel.setEnabled(false); jUpdCancel.setEnabled(false); initLocoTable(); initTractionTable(); initAccessoryTable(); jKonfLesen.setSelected(true); jKonfLesen.grabFocus(); // store pointer to instance in a final variable -> useable inside ActionListener final MC outerThis = this; final ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { if( bWaitAnswerInProgress ) { if( debugLevel > 2 ) { System.out.println("bWaitAnswerInProgress"); } tmpBytesRead = Com.read(bArrayTmp); // was gibts Neues ? if( tmpBytesRead > 0 ) { System.arraycopy(bArrayTmp, 0, bArray, bytesRead, tmpBytesRead); if( KlarTextUI.debugLevel > 2 ) { System.out.println("2875 MERGE PRE bytesRead="+bytesRead+" tmpBytesRead="+tmpBytesRead+" res="+(bytesRead+tmpBytesRead) ); } bytesRead += tmpBytesRead; bArray[bytesRead] = 0; if( KlarTextUI.debugLevel > 2 ) { System.out.println("2880 current: bytesRead="+bytesRead ); KTUI.dumpbArray(bArray); } } if( tmpBytesRead == 0 ) { System.out.print("->"+retries+" "); // no newline retries if(bProg_MM) { switch(retries) { case 3: System.out.println(" -> MM-Prog ende" ); jStartMMProg.setEnabled(true); jMMRegister.setEnabled(true); jMMWert.setEnabled(true); jMcRwProgress.setString(null); Com.write((byte)0x61); // STOP stopIOAction(); return; case 6: int MM_Wert; MM_Wert = Integer.parseInt(jMMWert.getText()); Com.write((byte)0); Com.write((byte)MM_Wert); break; case 7: MM_Wert = Integer.parseInt(jMMWert.getText()); Com.write((byte)15); Com.write((byte)MM_Wert); break; case 8: try { MM_Wert = Integer.parseInt(jMMWert.getText()); } catch (NumberFormatException numberFormatException) { stopIOAction(); jStartMMProg.setEnabled(true); jMMRegister.setEnabled(true); jMMWert.setEnabled(true); jMcRwProgress.setString(null); KTUI.mbGeneric(null, "Eingabe falsch: Wert"); return; } if(MM_Wert > 255 || MM_Wert == 0) { MM_Wert = 255; jMMWert.setText("255"); } Com.write((byte)0); Com.write((byte)MM_Wert); break; case 9: int MM_Adr; MM_Adr = Integer.parseInt(jMMRegister.getText()); Com.write((byte)0); Com.write((byte)MM_Adr); break; case 10: MM_Adr = 0; MM_Adr = Integer.parseInt(jMMRegister.getText()); Com.write((byte)15); Com.write((byte)MM_Adr); break; case 11: try { MM_Adr = Integer.parseInt(jMMRegister.getText()); } catch (NumberFormatException numberFormatException) { stopIOAction(); jStartMMProg.setEnabled(true); jMMRegister.setEnabled(true); jMMWert.setEnabled(true); jMcRwProgress.setString(null); KTUI.mbGeneric(null, "Eingabe falsch: Register"); return; } if(MM_Adr > 255 || MM_Adr == 0) { MM_Adr = 255; jMMRegister.setText("255"); } Com.write((byte)0); Com.write((byte)MM_Adr); break; case 12: Com.write((byte)0); Com.write((byte)80); break; } } if( retries == 0 ) { jMcRwProgress.setString(null); System.out.println(" -> retries ende" ); stopIOAction(); return; } jMcRwProgress.setString(bundle.getString("ReadWriteCV.Warte")+retries); return; } tmpBytesRead = 0; bArray[bytesRead] = 0; if(bAskLokState) { if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } bWaitAnswerInProgress = false; String s = new String(bArray); String str; if(s.contains("L ")) { s = s.substring(2); AktLokState = s.substring(0, s.indexOf("]")-1); String text = jDisplay.getText(); s = s.substring(s.indexOf(" ")+1); str = s.substring(0, s.indexOf(" ")); int V = 0; try { V = Integer.parseInt(str); } catch (NumberFormatException numberFormatException) { } jGeschwindigkeit.setValue(V); switch(Fahrstufen) { case 14: V = (V + 8)/9; break; case 27: V = (V*3 + 11)/14; break; case 28: V = (V*2 + 7)/9; break; } str = "" + V +" "; str = text.substring(0, 12) + str.substring(0, 3); s = s.substring(s.indexOf(" ")+1); if(s.contains("f")) { text = str + "^" + text.substring(16,28); } else { text = str + "v" + text.substring(16,28); } if(s.substring(0, 1).contains("1")) text += "*"; else text += "-"; if(s.substring(4, 5).contains("1")) { text += "*"; Funktionen[0] = 1; } else { text += "-"; Funktionen[0] = 0; } if(s.substring(6, 7).contains("1")) { text += "*"; Funktionen[1] = 1; } else { text += "-"; Funktionen[1] = 0; } if(s.substring(8, 9).contains("1")) { text += "*"; Funktionen[2] = 1; } else { text += "-"; Funktionen[2] = 0; } if(s.substring(10, 11).contains("1")) { text += "*"; Funktionen[3] = 1; } else { text += "-"; Funktionen[3] = 0; } jDisplay.setText(text); if(bMustAskStatus) { s = "XLC " + AskedLokAdr + "\r"; KTUI.flushReadBuffer( Com ); resetbArray(); bMustAskStatus = false; Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = KlarTextUI.timerRetries; timer.start(); } else { bAskLokState = false; } } else if(s.contains("unused")) { s = "XL " + AskedLokAdr + " 0 0 f 0 0 0 0\r"; KTUI.flushReadBuffer( Com ); resetbArray(); bMustAskStatus = true; Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = KlarTextUI.timerRetries; timer.start(); } else { if(s.contains("DCC")) { str = "DCC "; AktLokFormat = "DCC "; jf5.setEnabled(true); jf6.setEnabled(true); jf7.setEnabled(true); jf8.setEnabled(true); jf9.setEnabled(true); jf10.setEnabled(true); jf11.setEnabled(true); jf12.setEnabled(true); jf13.setEnabled(true); jf14.setEnabled(true); jf15.setEnabled(true); jf16.setEnabled(true); jf17.setEnabled(true); jf18.setEnabled(true); jf19.setEnabled(true); jf20.setEnabled(true); jf21.setEnabled(true); jf22.setEnabled(true); jf23.setEnabled(true); jf24.setEnabled(true); jf25.setEnabled(true); jf26.setEnabled(true); jf27.setEnabled(true); jf28.setEnabled(true); Fahrstufen = 28; } else if(s.contains("m3")) { str = "m3 "; AktLokFormat = "m3 "; jf5.setEnabled(true); jf6.setEnabled(true); jf7.setEnabled(true); jf8.setEnabled(true); jf9.setEnabled(true); jf10.setEnabled(true); jf11.setEnabled(true); jf12.setEnabled(true); jf13.setEnabled(true); jf14.setEnabled(true); jf15.setEnabled(true); jf16.setEnabled(false); jf17.setEnabled(false); jf18.setEnabled(false); jf19.setEnabled(false); jf20.setEnabled(false); jf21.setEnabled(false); jf22.setEnabled(false); jf23.setEnabled(false); jf24.setEnabled(false); jf25.setEnabled(false); jf26.setEnabled(false); jf27.setEnabled(false); jf28.setEnabled(false); Fahrstufen = 126; } else if(s.contains("Old")) { str = "MM1 "; AktLokFormat = "MM1 "; jf5.setEnabled(false); jf6.setEnabled(false); jf7.setEnabled(false); jf8.setEnabled(false); jf9.setEnabled(false); jf10.setEnabled(false); jf11.setEnabled(false); jf12.setEnabled(false); jf13.setEnabled(false); jf14.setEnabled(false); jf15.setEnabled(false); jf16.setEnabled(false); jf17.setEnabled(false); jf18.setEnabled(false); jf19.setEnabled(false); jf20.setEnabled(false); jf21.setEnabled(false); jf22.setEnabled(false); jf23.setEnabled(false); jf24.setEnabled(false); jf25.setEnabled(false); jf26.setEnabled(false); jf27.setEnabled(false); jf28.setEnabled(false); Fahrstufen = 14; } else if(s.contains("New")) { str = "MM2 "; AktLokFormat = "MM2 "; jf5.setEnabled(false); jf6.setEnabled(false); jf7.setEnabled(false); jf8.setEnabled(false); jf9.setEnabled(false); jf10.setEnabled(false); jf11.setEnabled(false); jf12.setEnabled(false); jf13.setEnabled(false); jf14.setEnabled(false); jf15.setEnabled(false); jf16.setEnabled(false); jf17.setEnabled(false); jf18.setEnabled(false); jf19.setEnabled(false); jf20.setEnabled(false); jf21.setEnabled(false); jf22.setEnabled(false); jf23.setEnabled(false); jf24.setEnabled(false); jf25.setEnabled(false); jf26.setEnabled(false); jf27.setEnabled(false); jf28.setEnabled(false); Fahrstufen = 14; } else { jf5.setEnabled(true); jf6.setEnabled(true); jf7.setEnabled(true); jf8.setEnabled(true); jf9.setEnabled(true); jf10.setEnabled(true); jf11.setEnabled(true); jf12.setEnabled(true); jf13.setEnabled(true); jf14.setEnabled(true); jf15.setEnabled(true); jf16.setEnabled(true); jf17.setEnabled(true); jf18.setEnabled(true); jf19.setEnabled(true); jf20.setEnabled(true); jf21.setEnabled(true); jf22.setEnabled(true); jf23.setEnabled(true); jf24.setEnabled(true); jf25.setEnabled(true); jf26.setEnabled(true); jf27.setEnabled(true); jf28.setEnabled(true); bAskLokState = false; return; } AktLokAdr = AskedLokAdr; String txt = jDisplay.getText(); jDisplay.setText(txt.substring(0, 6) + " \n "); LokName = " "; for (int i = 0; i < jTableLoco.getRowCount(); i++) { Object oAdr = jTableLoco.getValueAt(i, 0); String Adr = (String)oAdr; try { if (AktLokAdr == Integer.parseInt(Adr)) { Adr = (String) jTableLoco.getValueAt(i, 1); if(Adr.charAt(0) == '2') { Adr = Adr.substring(0, 2); //27a oder 27b kann parseInt nicht. Muss sich um Zahlen handeln... } Fahrstufen = Integer.parseInt(Adr); LokName = (String) jTableLoco.getValueAt(i, 3); } } catch (NumberFormatException numberFormatException) { break; } } String text = jDisplay.getText(); if(LokName.length() > 0) { s = LokName + " "; s = s.substring(0, 11); jDisplay.setText(text.substring(0, 7) + str + text.substring(12, 17) + s + text.substring(29)); } else { jDisplay.setText(text.substring(0, 7) + str + text.substring(12, 17) + " " + text.substring(29)); } s = "XL " + AskedLokAdr + "\r"; KTUI.flushReadBuffer( Com ); resetbArray(); Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = KlarTextUI.timerRetries; timer.start(); } } if(bReadPTdirekt) { if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } bWaitAnswerInProgress = false; String s = new String(bArray); int indexOf = s.indexOf(" "); s = s.substring(0, indexOf); int cvWert = 0; try { cvWert = Integer.parseInt(s); } catch (NumberFormatException numberFormatException) { cvWert = 255; } jWertDirekt.setText("" + cvWert); bReadPTdirekt = false; stopIOAction(); int CV = Integer.parseInt(jCV_Direkt.getText()); if(CV == 8) jHerstellerInfo.setText(Hersteller(cvWert)); } if(bReadPTList) { if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } bWaitAnswerInProgress = false; String s = new String(bArray); int indexOf = s.indexOf(" "); s = s.substring(0, indexOf); int cvWert = 0; try { cvWert = Integer.parseInt(s); } catch (NumberFormatException numberFormatException) { cvWert = 255; } int Index = jCVListe.getSelectedIndex(); if(Index >= 0) { s = (String)jCVListe.getSelectedValue(); s = s.substring(0, 5) + " " + cvWert; ListModel model = jCVListe.getModel(); DefaultListModel dlm = new DefaultListModel(); for(int i = 0; i < model.getSize(); i++) { if(i == Index) { dlm.add(i, s); } else { Object elementAt = model.getElementAt(i); dlm.add(i, elementAt); } } jCVListe.setModel(dlm); int j = dlm.getSize(); if(j > Index) { KTUI.flushReadBuffer( Com ); resetbArray(); jCVListe.setSelectedIndex(Index + 1); s = (String)jCVListe.getSelectedValue(); s = "XPTRD" + s + "\r"; Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = KlarTextUI.timerRetries * 2; timer.start(); } else { bReadPTList = false; stopIOAction(); } } else { bReadPTList = false; stopIOAction(); } } if(bWriteList) { if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } bWaitAnswerInProgress = false; String s = new String(bArray); if(s.contains("Ok")) { int Index = jCVListe.getSelectedIndex(); if(Index >= 0) { s = (String)jCVListe.getSelectedValue(); ListModel model = jCVListe.getModel(); int j = model.getSize(); if(j != Index + 1) { KTUI.flushReadBuffer( Com ); resetbArray(); jCVListe.setSelectedIndex(Index + 1); s = (String)jCVListe.getSelectedValue(); if(jHauptGleis.isSelected()) { int DecAdr; try { DecAdr = Integer.parseInt(jDecAdr.getText()); } catch (NumberFormatException numberFormatException) { DecAdr = 3; } s = "XPD" + DecAdr + s + "\r"; } else { s = "XPTWD" + s + "\r"; } Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = KlarTextUI.timerRetries * 2; timer.start(); } else { bWriteList = false; stopIOAction(); } } } else { bWriteList = false; stopIOAction(); } } if(bProg_m3) { if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } bWaitAnswerInProgress = false; String s = new String(bArray); s = "0x" + s.substring(0, 8); jmfxUID.setText(s); bProg_m3 = false; jm3Schreiben.setEnabled(true); stopIOAction(); } if(bReadStatus){ System.out.println("2903 PRE checkCfgReadComplete: bytesRead="+bytesRead ); if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more System.out.println("2775 POST checkCfgReadComplete: INCOMPLETE"); return; } timer.stop(); System.out.println("2910 POST checkCfgReadComplete: COMPLETE"); bWaitAnswerInProgress = false; } if(bReadCfg) { jMcRwInfo.setText("read: MC config read in progress ("+bytesRead+")"); if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } timer.stop(); bWaitAnswerInProgress = false; jMcRwProgress.setValue(++readWriteProgress); } if(bReadRC) { jMcRwInfo.setText("read: MC RailCom option read in progress ("+bytesRead+")"); if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } timer.stop(); System.out.println("2809 POST checkRCReadComplete: COMPLETE bytesRead="+bytesRead); bWaitAnswerInProgress = false; jMcRwProgress.setValue(++readWriteProgress); } if(bReadSo999) { jMcRwInfo.setText("read: MC SO 999 option read in progress ("+bytesRead+")"); if( bytesRead == 0 ) { return; } // check 1st byte for error code byte[] mYbArray = new byte[1]; System.arraycopy(bArray, 0, mYbArray, 0, 1); Boolean ok = KTUI.checkMCAnswerByte( outerThis, mYbArray, (debugLevel > 0)); if( ( ! ok) && ( debugLevel == 0 ) ) { KTUI.checkMCAnswerByte( outerThis, mYbArray, true); } if( debugLevel > 0 ) { System.out.println("mYbArray("+bytesRead+")=0x"+printHexBinary(mYbArray)+ " OK="+ok); System.out.println("readProgress="+readWriteProgress); } if( ok && ( bytesRead == 1 ) ) { // "OK" arrived but data byte missing return; } if( ok && (bytesRead == 2 )) { so999Value = bArray[1] & 0xFF ; System.out.println("bReadSo999 : new value = "+ so999Value ); updateSO999checkboxes( so999Value ); } timer.stop(); System.out.println("3030 POST checkSO999ReadComplete: COMPLETE bytesRead="+bytesRead); bWaitAnswerInProgress = false; jMcRwProgress.setValue(++readWriteProgress); } if(bWriteCfg) { if( KlarTextUI.debugLevel > 1 ) { jMcRwInfo.setText("read: MC config write in progress ("+bytesRead+")"); } if( bWriteSo999 ) { // expect exaclty one byte as answer from MC System.out.println("bWriteCfg && bWriteSo999 : #bytes="+ bytesRead); if( bytesRead == 0 ) { return; } byte[] mYbArray = new byte[bytesRead]; System.arraycopy(bArray, 0, mYbArray, 0, bytesRead); Boolean ok = KTUI.checkMCAnswerByte( outerThis, mYbArray, (debugLevel > 0)); if( ( ! ok ) && ( debugLevel == 0 ) ) { KTUI.checkMCAnswerByte( outerThis, mYbArray, true); } if( debugLevel > 0 ) { System.out.println("mYbArray("+bytesRead+")=0x"+printHexBinary(mYbArray)+ " OK="+ok); System.out.println("readProgress="+readWriteProgress); } bWriteSo999 = false; } else if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } timer.stop(); bWaitAnswerInProgress = false; jMcRwProgress.setValue(++readWriteProgress); } if(bReadS88num) { if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } stopIOAction(); bWaitAnswerInProgress = false; bReadS88num = false; checkS88num(bArray, bytesRead); } if(bReadS88value) { if( ! KTUI.checkReadComplete(bArray) ) { // incomplete -> wait for more return; } pauseS88read(); if( debugLevel > 2 ) { System.out.println("bReadS88value: bytesRead="+bytesRead); } bWaitAnswerInProgress = false; checkS88read(bArray, bytesRead); startS88read(); } } // Tests und Analysen if( bWriteM3sid ) { // Xm3Sid expects exaclty one byte as answer from MC int nBytes; nBytes = Com.read(bArray); timer.stop(); jMcM3Info.setText("Xm3Sid: write in progress"); jMcM3Progress.setValue(++readWriteProgress); byte[] mYbArray = new byte[nBytes]; System.arraycopy(bArray, 0, mYbArray, 0, nBytes); Boolean ok = KTUI.checkMCAnswerByte( outerThis, mYbArray, (debugLevel > 0)); if( debugLevel > 0 ) { System.out.println("mYbArray("+nBytes+")=0x"+printHexBinary(mYbArray)+ " OK="+ok); System.out.println("readProgress="+readWriteProgress); } if(nBytes < 1) { KTUI.mbTimeout( outerThis, c.mbMCRDcommitErr ); jMcM3Info.setText("Xm3Sid: write finished with error"); } else { jMcM3Info.setText("Xm3Sid: write finished"); } bWriteM3sid = false; stopIOAction(); return; } if( bWriteM3sidList ) { // Xm3Sid expects exaclty one byte as answer from MC int nBytes; nBytes = Com.read(bArray); timer.stop(); jMcM3Info.setText("Xm3Sid: write list in progress"); jMcM3Progress.setValue(++readWriteProgress); byte[] mYbArray = new byte[nBytes]; System.arraycopy(bArray, 0, mYbArray, 0, nBytes); Boolean ok = KTUI.checkMCAnswerByte( outerThis, mYbArray, (debugLevel > 0)); if( debugLevel > 0 ) { System.out.println("mYbArray("+nBytes+")=0x"+printHexBinary(mYbArray)+ " OK="+ok); System.out.println("readProgress="+readWriteProgress+" M3used="+M3used); } if(nBytes < 1) { KTUI.mbTimeout( outerThis, c.mbMCRDcommitErr ); jMcM3Info.setText("Xm3Sid: write list commit missing"); bWriteM3sidList = false; stopIOAction(); return; } else { jMcM3Info.setText("Xm3Sid: write committed"); } if( ( readWriteProgress / 2 ) == M3used ) { // commit for last dataset if( debugLevel > 0 ) { System.out.println("last dataset commited readProgress="+readWriteProgress); } bWriteM3sidList = false; stopIOAction(); jMcM3Info.setText("Xm3Sid: write list finished"); return; } // write next int listIdx = readWriteProgress / 2 ; long lM3UID = Long.decode( M3liste[0][listIdx] ); int iAdr = Integer.decode( M3liste[1][listIdx] ); if( debugLevel > 0 ) { System.out.println("lM3UID="+String.format("%8s", Long.toHexString( lM3UID )).replace(' ', '0') + " iAdr="+iAdr); } byte[] wArray = new byte[8]; wArray[0] = (byte) 0x78; wArray[1] = (byte) 0x87; // Xm3Sid (requires 1.4.7b) wArray[2] = (byte) ( iAdr & 0xFF ); wArray[3] = (byte) ( ( iAdr >> 8 ) & 0xFF ); wArray[4] = (byte) ( lM3UID & 0xFF ); wArray[5] = (byte) ( ( lM3UID >> 8 ) & 0xFF ); wArray[6] = (byte) ( ( lM3UID >> 16 ) & 0xFF ); wArray[7] = (byte) ( ( lM3UID >> 24 ) & 0xFF ); Com.write(wArray); if( debugLevel > 0 ) { System.out.println("written to MC wArray=0x"+printHexBinary(wArray)); } jMcM3Info.setText("Xm3Sid: write list in progress"); jMcM3Progress.setValue(++readWriteProgress); timer.start(); } if(bReadStatus) { bReadStatus = false; String str = new String(bArray); String[] strArr = str.split("\r"); stopIOAction(); resetbArray(); MZ pre = KTUI.getMZ(); if( debugLevel > 0 ) { System.out.println("bReadStatus="+strArr[0]+ " MZ pre="+pre.toString() ); } KTUI.setModeZentrale(strArr[0]); return; } if(bReadCfg) { timer.stop(); bReadCfg = false; String str = new String(bArray); if( debugLevel > 0 ) { System.out.println("Parser 1 nBytes="+bytesRead+" str.length="+str.length() ); } int tmpMcRwMax = jMcRwProgress.getMaximum(); validMcData = parseInputArray( KTUI.gsSchnittstelle, str ); if( validMcData ) { reCheckVersionInfo(); } jMcRwProgress.setMaximum(tmpMcRwMax); jDatenQuelle.setText(KTUI.gsSchnittstelle); jMcRwInfo.setText("read: MC config read finished"); jMcRwProgress.setValue(++readWriteProgress); String s = "xRC\r"; Com.write(s); resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; timer.setInitialDelay(KlarTextUI.MCtimer1); timer.setDelay(KlarTextUI.MCtimer2); timer.start(); jMcRwInfo.setText("read: MC RailCom option read started"); jMcRwProgress.setValue(++readWriteProgress); bReadRC = true; return; } if(bReadRC) { String str = new String(bArray); String[] strArr = str.split("\r"); bReadRC = false; if (strArr[0].startsWith("RC ")) { try { rcValue = Integer.parseInt(strArr[0].substring(3)); updateRailComCheckboxes(rcValue); if( debugLevel > 0 ) { System.out.println("readRC strArr[0].length["+strArr[0].length()+"] rcValue["+rcValue+"]" ); } } catch ( Exception ex ) { System.out.println("readRC EXCEPTION="+ex.toString() ); System.out.println("readRC bArray=" ); KTUI.dumpbArray(bArray); } if( debugLevel > 0 ) { System.out.println("readRC bArray=" ); KTUI.dumpbArray(bArray); } jMcRwInfo.setText("read: MC read finished"); } else { System.out.println("readRC ERROR strArr[0].length["+strArr[0].length()+"] strArr[0]=\""+strArr[0]+"\"" ); jMcRwInfo.setText("read: MC read finished with ERROR"); } jMcRwInfo.setText("read: MC read finished"); jMcRwProgress.setValue(++readWriteProgress); if( debugLevel > 0 ) { System.out.println("readProgress="+readWriteProgress); } if( KlarTextUI.bUseSo999 ) { // (at least 1.4.8c was detected) lastCmd = "XSoGet 999 " ; System.out.println("read: Booster option s["+lastCmd+"]" ); byte[] wArray = new byte[4]; wArray[0] = (byte) 0x78; wArray[1] = (byte) 0xa4; // XSoGet (requires 1.4.8c) wArray[2] = (byte) ( 999 & 0xFF ); // SO low byte wArray[3] = (byte) ( ( 999 >> 8 ) & 0xFF ); // SO high byte Com.write(wArray); bReadSo999 = true; resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; timer.setInitialDelay(KlarTextUI.MCtimer1); timer.setDelay(KlarTextUI.MCtimer2); timer.start(); jMcRwInfo.setText("read: MC SO 999 option read started"); jMcRwProgress.setValue(++readWriteProgress); } else { stopIOAction(); resetbArray(); } return; } if(bReadSo999) { jMcRwInfo.setText("read: MC SO 999 read finished"); bReadSo999 = false; stopIOAction(); resetbArray(); } if(bWriteCfg) { if( debugLevel > 0 ) { System.out.println("bWriteCfg bWaitAnswerInProgresss["+bWaitAnswerInProgress+"] bytesRead=["+bytesRead+"] nextWriteJob["+nextWriteJob+"] locIdx["+locIdx+"] traIdx["+traIdx+"] magIdx["+magIdx+"]" ); } if( bytesRead > 0 ) { String str = new String(bArray); String[] strArr = str.split("\r"); if( debugLevel > 0 ) { System.out.println("bWriteCfg bWaitAnswerInProgresss["+bWaitAnswerInProgress+"] nextWriteJob["+nextWriteJob+"] locIdx["+locIdx+"] traIdx["+traIdx+"] magIdx["+magIdx+"]" ); System.out.println("bWriteCfg bytesRead=["+bytesRead+"] strArr.length="+strArr.length ); if( debugLevel >= 3 ) { for( int i = 0 ; i < strArr.length ; i++ ) { System.out.println("bWriteCfg strArr["+i+"]=\""+strArr[i]+"\"" ); } } } if( strArr[0].toUpperCase().startsWith("ERROR: ")) { System.out.println("ERROR detected : "+strArr[0] ); KTUI.mbConfigWriteError(KTUI, strArr[0] ); } } switch( nextWriteJob ) { case 0: // system basics nextWriteJob++; sysIdx++; if( ! jWRsys.isSelected()) { jMcRwInfo.setText("write: skip basic config"); System.out.println("write: skip basic config"); } else { jMcRwInfo.setText("write: basic config"); lastCmd = "xcfgsys "; if(jDCC_Booster.isSelected()) lastCmd += "DCC, "; else lastCmd += "MM, "; int KSE = 0; try { KSE = Integer.parseInt(jKurzEmpf.getText()); KSE /= 5; } catch (NumberFormatException numberFormatException) { KSE = 20; } lastCmd += KSE; lastCmd += ", "; if(jDCC_Loks.isSelected()) lastCmd += "DCC, "; else lastCmd += "MM, "; if(jLangePause.isSelected()) lastCmd += "Y, "; else lastCmd += "N, "; lastCmd += js88.getText(); lastCmd += ", "; lastCmd += jBaud.getText(); System.out.println("write: basic config cmd["+lastCmd+"]"); lastCmd += "\r"; Com.write(lastCmd); resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; } timer.start(); break; case 1: // accessory timer nextWriteJob++; sysIdx++; if( ! jWRsys.isSelected() ) { jMcRwInfo.setText("write: skip accessory timer option"); System.out.println("write: skip accessory timer option"); } else { jMcRwInfo.setText("write: accessory timer options\n"); int minMag = Integer.parseInt(jMinMag.getText())/50; int maxMag = Integer.parseInt(jMaxMag.getText())/50; lastCmd = "XMT " + minMag + ", " + maxMag + "\r"; if( debugLevel > 0 ) { System.out.println("write: accessory timer options min["+jMinMag.getText()+"] max["+jMaxMag.getText()+"] -> cmd["+lastCmd+"]" ); } System.out.println("write: accessory timer options s["+lastCmd+"]" ); Com.write(lastCmd); resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; } timer.start(); break; case 2: // railcom option nextWriteJob++; sysIdx++; if( jWRsys.isSelected() ) { jMcRwInfo.setText("write: RailCom option"); rcValue = getRailComValueFromCheckboxes(); if( debugLevel > 0 ) { System.out.println("write: RailCom option ["+rcValue+"]"); } lastCmd = "XRC " + rcValue + "\r"; System.out.println("write: RailCom option s["+lastCmd+"]" ); Com.write(lastCmd); resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; } else { jMcRwInfo.setText("write: skip RailCom option"); System.out.println("write: skip RailCom option"); } timer.start(); break; case 3: // booster option nextWriteJob++; sysIdx++; if( jWRsys.isSelected() && KlarTextUI.bUseSo999 ) { // (at least 1.4.8c was detected) jMcRwInfo.setText("write: Booster option"); updateSo999Value(); if( debugLevel > 0 ) { System.out.println("write: Booster option ["+so999Value+"]"); } lastCmd = "XSoSet 999 " + so999Value ; System.out.println("write: Booster option s["+lastCmd+"]" ); byte[] wArray = new byte[5]; wArray[0] = (byte) 0x78; wArray[1] = (byte) 0xa3; // XSoSet (requires 1.4.8c) wArray[2] = (byte) ( 999 & 0xFF ); // SO low byte wArray[3] = (byte) ( ( 999 >> 8 ) & 0xFF ); // SO high byte wArray[4] = (byte) ( so999Value & 0xFF ); // SO value (1 byte) Com.write(wArray); bWriteSo999 = true; resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; } else { jMcRwInfo.setText("write: skip Booster option"); System.out.println("write: skip Booster option"); } timer.start(); break; case 4: // clear loco list nextWriteJob++; sysIdx++; if( ! jWRloc.isSelected() ) { jMcRwInfo.setText("write: skip clear loco list"); System.out.println("write: skip clear loco list"); } else { jMcRwInfo.setText("write: clear loco list"); lastCmd = "XLOCCLEAR\r"; System.out.println("write: clear loco list s["+lastCmd+"]" ); Com.write(lastCmd); resetbArray(); retries = Math.max(KlarTextUI.timerRetries, 50); jMcRwProgress.setString(null); bWaitAnswerInProgress = true; } timer.start(); break; case 5: // locos if( ! jWRloc.isSelected() ) { nextWriteJob++; jMcRwInfo.setText("write: skip locos"); System.out.println("write: skip locos"); locIdx = c.MAX_LOCS; break; } while( (bWaitAnswerInProgress == false) && (locIdx < c.MAX_LOCS) ) { // assumption jTableLoco was checked successfully (or automatically repaired) // -> all jTableLoco entries are OK and we can skip most validation checks here // send only valid loco addresses Object oAdr = jTableLoco.getValueAt(locIdx, 0); String sAdr = "" + oAdr; if( sAdr.trim().length() > 0) { String sFS = "" + jTableLoco.getValueAt( locIdx, 1); String sFormat = "" + jTableLoco.getValueAt( locIdx, 2); String sName = null; Object oName = jTableLoco.getValueAt( locIdx, 3); if( oName != null ) sName = "" + oName; if( (sName != null) && (sName.length() > 0) ) lastCmd = "XLOCADD " + oAdr + ", " + sFS + ", " + sFormat + ", \"" + sName + "\"\r"; else lastCmd = "XLOCADD " + oAdr + ", " + sFS + ", " + sFormat + "\r"; System.out.println("write: loco s["+lastCmd+"]" ); Com.write(lastCmd); resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; jMcRwInfo.setText("write: loco ("+(locIdx+1)+"/"+c.MAX_LOCS+")"); if( debugLevel >= 2 ) { System.out.println("write: loco ("+locIdx+"/"+c.MAX_LOCS+") ["+lastCmd+"]" ); } } locIdx++; } if( locIdx >= c.MAX_LOCS ) { // end of loco list nextWriteJob++; } timer.start(); break; case 6: // clear traction list nextWriteJob++; sysIdx++; if( ! jWRtra.isSelected() ) { jMcRwInfo.setText("write: skip clear traction list"); System.out.println("write: skip clear traction list"); } else { jMcRwInfo.setText("write: clear traction list"); lastCmd = "XTRKCLEAR\r"; System.out.println("write: traction s["+lastCmd+"]" ); Com.write(lastCmd); resetbArray(); retries = Math.max(KlarTextUI.timerRetries, 30); jMcRwProgress.setString(null); bWaitAnswerInProgress = true; } timer.start(); break; case 7: // tractions if( ! jWRtra.isSelected() ) { nextWriteJob++; jMcRwInfo.setText("write: skip tractions"); System.out.println("write: skip tractions"); traIdx = c.MAX_TRACTIONS; break; } while( (bWaitAnswerInProgress == false) && (traIdx < c.MAX_TRACTIONS) ) { // assumption jTableTraction was checked successfully // -> all jTableTraction entries are OK and we can skip validation checks here String sAdr1 = (""+jTableTraction.getValueAt(traIdx, 0)).trim(); String sAdr2 = (""+jTableTraction.getValueAt(traIdx, 2)).trim(); if( (sAdr1.length() > 0) && (sAdr2.length() > 0) ) { lastCmd = "XTRKADD " + sAdr1 + ", " + sAdr2 + "\r"; System.out.println("write: traction s["+lastCmd+"]" ); Com.write(lastCmd); resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; jMcRwInfo.setText("write: traction ("+traIdx+"/"+c.MAX_TRACTIONS+")"); if( debugLevel >= 2 ) { System.out.println("write: traction ("+traIdx+"/"+c.MAX_TRACTIONS+")"); } } traIdx++; } if( traIdx >= c.MAX_TRACTIONS ) { // end of traction list nextWriteJob++; } timer.start(); break; case 8: // accessories if( ! jWRmag.isSelected() ) { nextWriteJob++; jMcRwInfo.setText("write: skip accessory list"); System.out.println("write: skip accessory list"); traIdx = c.MAX_MM1_ACCMOD; break; } while( (bWaitAnswerInProgress == false) && (magIdx < c.MAX_MM1_ACCMOD) ) { // assumption jTableAccessory was checked successfully // -> all jTableAccessory entries are OK and we can skip some validation checks here String sIdx = (""+jTableAccessory.getValueAt(magIdx, 0)).trim(); String sFmt = (""+jTableAccessory.getValueAt(magIdx, 1)).trim().toUpperCase(); if( (sIdx.length() > 0) && (sFmt.length() > 0 ) ) { String[] sIdxArr = sIdx.split(" "); int n = KTUI.checkAndGetStrNumRangeDef( null, sIdxArr[0], 1, c.MAX_MM1_ACCMOD, 0, false); // module# is 1 less than displayed in table lastCmd = "XCFGACC " + (n-1) + ", " + sFmt + "\r"; if( KlarTextUI.debugLevel > 0 ) { System.out.println("magIdx="+magIdx+" sIdx="+sIdx+" sIdxArr[0]="+sIdxArr[0]+" n="+n); System.out.println("write: accessories s["+lastCmd+"]" ); } System.out.print("write: accessories s["+lastCmd+"]" ); Com.write(lastCmd); resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; jMcRwInfo.setText("write: accessories ("+magIdx+"/"+c.MAX_MM1_ACCMOD+")"); if( debugLevel >= 3 ) { System.out.println("write: accessories ("+magIdx+"/"+c.MAX_MM1_ACCMOD+") "+lastCmd); } } magIdx++; } if( magIdx >= c.MAX_MM1_ACCMOD ) { // end of traction list nextWriteJob++; } timer.start(); break; case 9: nextWriteJob++; sysIdx++; timer.start(); break; default: System.out.println("write: sysIdx["+sysIdx+"] locIdx["+locIdx+"] traIdx["+traIdx+"] magIdx["+magIdx+"]" ); jMcRwProgress.setValue(c.MAX_SYSWRITES+c.MAX_LOCS+c.MAX_TRACTIONS+c.MAX_MM1_ACCMOD); jMcRwInfo.setText("write: finished"); bWriteCfg = false; stopIOAction(); return; } // calculate sM3UID for count if( debugLevel >= 2 ) { System.out.println("write: sysIdx["+sysIdx+"] locIdx["+locIdx+"] traIdx["+traIdx+"] magIdx["+magIdx+"]" ); } // jMcRwProgress.setValue(count); jMcRwProgress.setValue(sysIdx+locIdx+traIdx+magIdx); return; } if(bUpdate) { int BlockNrTemp; int blockSize = 256; bArray[0] = 0; int n = Com.read(bArray); if( n == 0 ) { if( debugLevel >= 2 ) { System.out.println("update: read 0 bytes and TimeOut="+TimeOut ); } TimeOut++; jMcUpdProgress.setValue(TimeOut * 5); if( TimeOut > 20 ) { bUpdate = false; stopIOAction(); Com = KTUI.safelyCloseCom( outerThis, Com ); KTUI.gsBaudRate = gsBaudRateSaved; jUpdLastError.setText(bundle.getString("MC.Protokollfehler")); System.out.println("update: read 0 bytes" ); KTUI.mbUpdateReadAnswerError( outerThis ); } return; } if(bArray[n-1] != 0) { switch(bArray[n-1]) { case '*': BlockNr++; case '#': //Block wiederholen (256 Bytes) blockSize = 256; int data1[] = new int[262]; if (UpdateData[1][0] != 0) { MaxBlocks = (count / 128) + 513; } else { MaxBlocks = (count / 128) + 1; } jMcUpdProgress.setMaximum(MaxBlocks); //CRC berechnen for(int g = 0; g < 256; g++) { long nr = BlockNr * 256 + g; if (nr < 0xFFFB) { data1[g + 4] = UpdateData[0][BlockNr * 256 + g]; } else { int index = (int)(nr - 0xFFFB); data1[g + 4] = UpdateData[1][index]; } } if(BlockNr > MaxBlocks/2) { data1[1] = 0x00FF; data1[0] = 0x00FF ; data1[2] = 0x00FF ; data1[3] = 0x00FF ; BlockNr = MaxBlocks/2 + 1; } else { data1[1] = BlockNr % 256; data1[2] = BlockNr / 256; } int crc = crc16(0xFFFF, 260, data1); data1[261] = crc / 256; data1[260] = crc % 256; Com.write(data1); break; case '+': BlockNr++; case '?': //Block wiederholen (128 Bytes) blockSize = 128; int data[] = new int[132]; MaxBlocks = (count / 64) + 1; jMcUpdProgress.setMaximum(MaxBlocks); //CRC berechnen for(int g = 0; g < 128; g++) { data[g + 2] = UpdateData[0][BlockNr * 128 + g]; } if(BlockNr > MaxBlocks/2 + 1) { BlockNr = 480; data[1] = BlockNr / 2; data[0] = (BlockNr * 128) % 256; BlockNr = MaxBlocks/2 + 1; } else { data[1] = BlockNr / 2; data[0] = (BlockNr * 128) % 256; } crc = crc16(0xFFFF, 130, data); data[131] = crc / 256; data[130] = crc % 256; Com.write(data); break; case 'F': //Fertich KTUI.mbUpdateWriteSuccess( outerThis, BlockNr*4); Com = KTUI.safelyCloseCom( outerThis, Com ); KTUI.gsBaudRate = gsBaudRateSaved; bUpdate = false; timer.stop(); count = 0; BlockNr = 0; jMcUpdInfo.setText(bundle.getString("MC.Updateerfolg")); stopIOAction(); return; case 'A': //Adress-Error BlockNrTemp = BlockNr * 4; if (BlockNr != 0) { jUpdLastError.setText(bundle.getString("MC.Adressfehler_1") + BlockNrTemp + bundle.getString("MC.Adressfehler_2")); } BlockNr = 0; break; case 'C': //CRC-Error BlockNrTemp = BlockNr * 4; jUpdLastError.setText(bundle.getString("MC.CRC_Fehler_1") + BlockNrTemp + bundle.getString("MC.CRC_Fehler_2")); break; case 'T': //Time out Error break; case 'L': //Length Error BlockNrTemp = BlockNr * 4; jUpdLastError.setText(bundle.getString("MC.Blockfehler_1") + BlockNrTemp + bundle.getString("MC.Adressfehler_2")); BlockNr = 0; break; default: BlockNrTemp = BlockNr * 4; jUpdLastError.setText(bundle.getString("MC.UnbekannterFehler_1") + BlockNrTemp + bundle.getString("MC.UnbekannterFehler_2")); System.out.println("mbUpdateWriteError: numBytes from MC="+n+" Content:"); KTUI.dumpbArrayBIN( bArray, n ); if( debugLevel == 0 ) { stopIOAction(); Com = KTUI.safelyCloseCom( outerThis, Com ); KTUI.mbUpdateWriteError( outerThis, (char)bArray[0]); count = 0; BlockNr = 0; } else { String strOut; if( debugLevel == 1 ) { strOut = KTUI.dumpbArrayHexAsString( bArray ); KTUI.mbUpdateWriteError( outerThis, strOut ); stopIOAction(); Com = KTUI.safelyCloseCom( outerThis, Com ); count = 0; BlockNr = 0; } else { // may be dangerous // do not reset the count and BlockNr, just ignore } } break; } BlockNrTemp = BlockNr * 4; jMcUpdProgress.setValue(BlockNrTemp/2); jMcUpdInfo.setText(bundle.getString("MC.Transferblock") + BlockNrTemp + " / " + (MaxBlocks/2+1)*4 + " a "+blockSize+" Bytes" ); } else { if (BlockNr == 0) { TimeOut++; jMcUpdProgress.setValue(TimeOut * 5); if (TimeOut > 20) { Com = KTUI.safelyCloseCom( outerThis, Com ); KTUI.gsBaudRate = gsBaudRateSaved; bUpdate = false; TimeOut = 0; jMcUpdProgress.setValue(0); stopIOAction(); jUpdLastError.setText(bundle.getString("MC.keineVerbindung")); KTUI.mbTimeoutMcUpdStart( outerThis ); bArray[0] = 0; } } } } } }; timer = new javax.swing.Timer(5000, actionListener); timer.setRepeats(true); actionListener.actionPerformed(null); if( KTUI.bGotoUpdate ) { // jump immediately to the update page KTUI.bGotoUpdate = false; jTabbedPane1.setSelectedIndex(jTabbedPane1.getTabCount()-1); jUpdDateiAuswahl.grabFocus(); } else { // is there a valid number of s88 modules ? if( KTUI.getNumS88() == 0 ) { // no -> start reading number from command station readS88num(); } } }//GEN-LAST:event_formWindowOpened private void resetbArray() { // Reset bArray with '0' for( int i = 0 ; i < bArray.length ; i++ ) { bArray[i] = 0; } // also reset counter for valid bytes read into this array bytesRead = 0; } private void updateRailComCheckboxes( int bits ) { if( bits == -1 ) return; jRailcomTailbits.setSelected((bits & 0x01) == 0x01); jRailcomIdNotify.setSelected((bits & 0x02) == 0x02); jRailcomAccessory.setSelected((bits & 0x04) == 0x04); } private int getRailComValueFromCheckboxes() { int bits = 0x00; if( jRailcomTailbits.isSelected() ) bits += 0x01; if( jRailcomIdNotify.isSelected() ) bits += 0x02; if( jRailcomAccessory.isSelected() ) bits += 0x04; return bits; } private void updateRailComValue() { rcValue = getRailComValueFromCheckboxes(); } private void updateSO999checkboxes( int bits ) { if( bits == -1 ) return; jBoostOptNoAccDrive.setSelected((bits & 0x01) == 0x01); jBoostOptNoAccBreak.setSelected((bits & 0x02) == 0x02); } private int getSO999ValueFromCheckboxes() { int val = 0; val += jBoostOptNoAccDrive.isSelected()?1:0 ; val += jBoostOptNoAccBreak.isSelected()?2:0 ; return val; } private void updateSo999Value() { so999Value = getSO999ValueFromCheckboxes(); } private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing stopIOAction(); KTUI.frameInstanceDEVICE = null; }//GEN-LAST:event_formWindowClosing private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1StateChanged // TODO add your handling code here: int selIdx = jTabbedPane1.getSelectedIndex(); if( debugLevel >= 2 ) { System.out.println("jTabbedPane1StateChanged selIdx="+selIdx); } }//GEN-LAST:event_jTabbedPane1StateChanged private void jUpdateComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jUpdateComponentShown Cursor c = new Cursor(Cursor.DEFAULT_CURSOR ); setCursor(c); }//GEN-LAST:event_jUpdateComponentShown private void jUpdCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUpdCloseActionPerformed this.dispose(); }//GEN-LAST:event_jUpdCloseActionPerformed private void jUpdCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUpdCancelActionPerformed stopIOAction(); Com = KTUI.safelyCloseCom( this, Com ); jMcUpdInfo.setText(bundle.getString("MC.Updatecancelled")); }//GEN-LAST:event_jUpdCancelActionPerformed private void jUpdStartUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUpdStartUpdateActionPerformed jMcUpdInfo.setText(bundle.getString("MC.waitingforconnection")); jUpdLastError.setText(bundle.getString("MC.noerror")); RandomAccessFile inputStream = null; File f = new File(jUpdDatei.getText()); long l = f.length(); int i = 0; UpdateData[1][0] = 0; count = 0; TimeOut = 0; byte ac[] = new byte[0xFFFF]; try { inputStream = new RandomAccessFile(f, "r"); } catch (FileNotFoundException ex) { KTUI.mbFileOpenError( this, jUpdDatei.getText()); stopIOAction(); return; } try { int n = 0; inputStream.seek(0); long lSeek = 0; n = inputStream.read(ac); if(ac[0] != ':') { KTUI.mbFileHexFormatError( null ); return; } int Anzahl = 0; for(int m = 0; m < n;) { while(ac[m] != ':') { m++; } if(ac[m+8] == '1') break; //Ende-Record m++; if(ac[m+7] != '0') continue; Anzahl = hexval(ac[m], ac[m+1]); m += 6; for(int k = 0; k < Anzahl; k++) { m += 2; UpdateData[0][count++] = hexval(ac[m], ac[m+1]); } if (n == 0xFFFF) { if (m > 0xFFC0) { lSeek = m - 1; break; } } } if( debugLevel > 0 ) { System.out.println("strtDwnl A count["+count+"] lSeek="+lSeek); } if(n == 0xFFFF) { try { inputStream.seek(lSeek); n = inputStream.read(ac); } catch (IOException iOException) { KTUI.mbFileReadError( this ); stopIOAction(); return; } i = 0; Anzahl = 0; for(int m = 0; m < n;) { while(ac[m] != ':') m++; if(m > 0xFFF6) break; if(ac[m+8] == '1') break; //Ende-Record m++; if(ac[m+7] != '0') continue; Anzahl = hexval(ac[m], ac[m+1]); m += 6; for(int k = 0; k < Anzahl; k++) { m += 2; UpdateData[i][count] = hexval(ac[m], ac[m+1]); if(count < 0xFFFA) { count++; } else { if( debugLevel > 0 ) { System.out.println("strtDwnl A count["+count+"] reset to 0 i["+i+"]"); } count = 0; i++; } } if (n == 0xFFFF) { if (m > 0xFFC0) { lSeek += m - 1; break; } } } if( debugLevel > 0 ) { System.out.println("strtDwnl B count["+count+"] lSeek="+lSeek); } if(n == 0xFFFF) { try { inputStream.seek(lSeek); n = inputStream.read(ac); } catch (IOException iOException) { KTUI.mbFileReadError( this ); stopIOAction(); return; } Anzahl = 0; for(int m = 0; m < n;) { while(ac[m] != ':') { m++; } if(m > 0xFFF6) break; if(ac[m+8] == '1') break; //Ende-Record m++; if(ac[m+7] != '0') continue; Anzahl = hexval(ac[m], ac[m+1]); m += 6; for(int k = 0; k < Anzahl; k++) { m += 2; UpdateData[i][count] = hexval(ac[m], ac[m+1]); if(count < 0xFFFA) { count++; } else { if( debugLevel > 0 ) { System.out.println("strtDwnl B count["+count+"] reset to 0 i["+i+"]"); } count = 0; i++; } } if (n == 0xFFFF) { if (m > 0xFFC0) { lSeek += m - 1; break; } } } if( debugLevel > 0 ) { System.out.println("strtDwnl C count["+count+"] lSeek="+lSeek); } if(n == 0xFFFF) { try { inputStream.seek(lSeek); n = inputStream.read(ac); } catch (IOException iOException) { KTUI.mbFileReadError( this ); stopIOAction(); return; } Anzahl = 0; for(int m = 0; m < n;) { while(ac[m] != ':') m++; if(m > 0xFFF6) break; if(ac[m+8] == '1') break; //Ende-Record m++; if(ac[m+7] != '0') continue; Anzahl = hexval(ac[m], ac[m+1]); m += 6; for(int k = 0; k < Anzahl; k++) { m += 2; UpdateData[i][count] = hexval(ac[m], ac[m+1]); if(count < 0xFFFA) { count++; } else { if( debugLevel > 0 ) { System.out.println("strtDwnl C count["+count+"] reset to 0 i["+i+"]"); } count = 0; i++; } } if (n == 0xFFFF) { if (m > 0xFFC0) { lSeek += m - 1; break; } } } } } } if( debugLevel > 0 ) { System.out.println("strtDwnl D count["+count+"] i["+i+"] lSeek="+lSeek+" n="+n); } BlockNr = 0; inputStream.close(); // force 38400 baud for firmware updates for RS232 on MC and USB-2 (!) on RedBox if( KTUI.rs232_or_rb_usb_2 ) { int oldBaudRate = KTUI.gsBaudRate; if( KTUI.gsBaudRate != 38400 ) { System.out.println("forcing baud rate for updates to 38400"); Com = KTUI.safelyCloseCom( this, Com); KTUI.gsBaudRate = 38400; Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ){ KTUI.gsBaudRate = oldBaudRate; Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ){ // geht nicht -> Abbruch stopIOAction(); jUpdLastError.setText(bundle.getString("MC.Schnitttstellenfehler")); return; } } } KTUI.gsBaudRate = oldBaudRate; } KTUI.flushReadBuffer(Com); bUpdate = true; timer.setInitialDelay(KlarTextUI.userTimerFwUp); timer.setDelay(KlarTextUI.userTimerFwUp); timer.setRepeats(true); jMcUpdProgress.setMaximum(100); startIOAction(); jMcUpdInfo.setText(bundle.getString("MC.waitingforconnection")); } catch (IOException ex) { KTUI.mbFileReadError( this ); stopIOAction(); return; } }//GEN-LAST:event_jUpdStartUpdateActionPerformed private void jUpdDateiAuswahlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUpdDateiAuswahlActionPerformed SaveOpenDialog od = new SaveOpenDialog( this, true, true, null, this, "hex", c.HEX); return; }//GEN-LAST:event_jUpdDateiAuswahlActionPerformed public void setUpdDatei( String fileName ) { jUpdDatei.setText( fileName ); } private void jMagnetartikelComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jMagnetartikelComponentShown Cursor c = new Cursor(Cursor.DEFAULT_CURSOR ); setCursor(c); }//GEN-LAST:event_jMagnetartikelComponentShown private void jMagRepairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMagRepairActionPerformed if( jTableAccessory.isEditing() ) { jTableAccessory.getCellEditor().stopCellEditing(); } FehlerArt = 0; checkTableAccessory( true, true ); }//GEN-LAST:event_jMagRepairActionPerformed private void jMagCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMagCheckActionPerformed if( jTableAccessory.isEditing() ) { jTableAccessory.getCellEditor().stopCellEditing(); } FehlerArt = 0; checkTableAccessory( false, true ); }//GEN-LAST:event_jMagCheckActionPerformed private void jMDCCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMDCCActionPerformed setAccessoryTableWithProto("DCC"); }//GEN-LAST:event_jMDCCActionPerformed private void jMMMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMMMActionPerformed setAccessoryTableWithProto("MM"); }//GEN-LAST:event_jMMMActionPerformed private void jTableAccessoryKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableAccessoryKeyReleased // TODO add your handling code here: }//GEN-LAST:event_jTableAccessoryKeyReleased private void jTraktionenComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jTraktionenComponentShown Cursor c = new Cursor(Cursor.DEFAULT_CURSOR ); setCursor(c); }//GEN-LAST:event_jTraktionenComponentShown private void jTraRepairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTraRepairActionPerformed if( jTableTraction.isEditing() ) { jTableTraction.getCellEditor().stopCellEditing(); } FehlerArt = 0; checkTableTraction( true, true ); }//GEN-LAST:event_jTraRepairActionPerformed private void jTraCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTraCheckActionPerformed if( jTableTraction.isEditing() ) { jTableTraction.getCellEditor().stopCellEditing(); } FehlerArt = 0; checkTableTraction( false, true ); }//GEN-LAST:event_jTraCheckActionPerformed private void jTraDelAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTraDelAllActionPerformed if( jTableTraction.isEditing() ) { jTableTraction.getCellEditor().stopCellEditing(); } initTractionTable(); jTableTraction.getSelectionModel().clearSelection(); }//GEN-LAST:event_jTraDelAllActionPerformed private void jTableTractionKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableTractionKeyReleased if(evt.getKeyCode() == KeyEvent.VK_DELETE) { delMultipleTractionLines(); } }//GEN-LAST:event_jTableTractionKeyReleased private void jLoksComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jLoksComponentShown Cursor c = new Cursor(Cursor.DEFAULT_CURSOR ); setCursor(c); }//GEN-LAST:event_jLoksComponentShown private void jLocM3sidWriteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLocM3sidWriteActionPerformed String sAdr = ""+jTableLoco.getValueAt( this.locoTableSelRow, 0); int iAdr = Integer.parseInt(sAdr); if( ! checkM3uidValid() ) { return; } if( ! KTUI.bUseXm3sid ) { String sFW = KTUI.fwVersion; if( (sFW == null) || ( sFW.length() == 0) ) { sFW = bundle.getString("MC.unbekannt"); } if( KTUI.bSpracheDE) { KTUI.mbGeneric( this, "HINWEIS", "Tams MC mit Firmware ab Version \"1.4.7b\" notwendig", "Diese Zentrale hat Firmware \""+sFW+"\"", 5, true ); } else { KTUI.mbGeneric( this, "NOTE", "Tams MC with firmware version \"1.4.7b\" or newer necessary", "This MC has firmware \""+sFW+"\"", 5, true ); } return; } String sM3UID = jTextM3UID.getText(); // int iM3UID = Integer.decode(sM3UID); long lM3UID = Long.decode(sM3UID); if( debugLevel > 0 ) { System.out.println("lM3UID="+String.format("%8s", Long.toHexString( lM3UID )).replace(' ', '0')); } Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ){ return; } byte[] wArray = new byte[8]; wArray[0] = (byte) 0x78; wArray[1] = (byte) 0x87; // Xm3Sid (requires 1.4.7b) wArray[2] = (byte) ( iAdr & 0xFF ); wArray[3] = (byte) ( ( iAdr >> 8 ) & 0xFF ); wArray[4] = (byte) ( lM3UID & 0xFF ); wArray[5] = (byte) ( ( lM3UID >> 8 ) & 0xFF ); wArray[6] = (byte) ( ( lM3UID >> 16 ) & 0xFF ); wArray[7] = (byte) ( ( lM3UID >> 24 ) & 0xFF ); KTUI.flushReadBuffer(Com); Com.write((byte)0x60); KTUI.flushReadBuffer(Com); if( debugLevel > 0 ) { // TODO evtl this durch this.getContentPane() ersetzen KTUI.mbGeneric( this, "MC", "Xm3Sid adr(sid)="+iAdr+" MAC(uid)="+sM3UID, "writing to MC wArray=0x"+printHexBinary(wArray), 10, false ); } Com.write(wArray); if( debugLevel > 0 ) { System.out.println("written to MC wArray=0x"+printHexBinary(wArray)); } bWriteM3sid = true; readWriteProgress = 0; jMcM3Progress.setMaximum(2); timer.setInitialDelay(KlarTextUI.MCtimer1); timer.setDelay(KlarTextUI.MCtimer2); startIOAction(); jMcM3Info.setText("Xm3Sid: write in progress"); jMcM3Progress.setValue(++readWriteProgress); }//GEN-LAST:event_jLocM3sidWriteActionPerformed private void jLocRepairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLocRepairActionPerformed if( jTableLoco.isEditing() ) { jTableLoco.getCellEditor().stopCellEditing(); } FehlerArt = 0; checkTableLoco( true, true ); }//GEN-LAST:event_jLocRepairActionPerformed private void jLocCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLocCheckActionPerformed if( jTableLoco.isEditing() ) { jTableLoco.getCellEditor().stopCellEditing(); } FehlerArt = 0; checkTableLoco( false, true ); }//GEN-LAST:event_jLocCheckActionPerformed private void jLocDelAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLocDelAllActionPerformed if( jTableLoco.isEditing() ) { jTableLoco.getCellEditor().stopCellEditing(); } initLocoTable(); jTableLoco.getSelectionModel().clearSelection(); }//GEN-LAST:event_jLocDelAllActionPerformed private void jTableLocoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableLocoKeyReleased if(evt.getKeyCode() == KeyEvent.VK_DELETE) { delMultipleLocoLines(); } }//GEN-LAST:event_jTableLocoKeyReleased private void jTableLocoPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTableLocoPropertyChange if( debugLevel > 0 ) { System.out.println("jTableLocoPropertyChange col="+jTableLoco.getEditingColumn()+" row="+jTableLoco.getEditingRow()); } int edRow = jTableLoco.getEditingRow(); int edCol = jTableLoco.getEditingColumn(); String str; if( edRow >= 0 && edCol >= 0 ) { switch( edCol ) { case 1: str = (""+jTableLoco.getValueAt(edRow, edCol)).toLowerCase().replaceAll("\\s",""); jTableLoco.setValueAt(str, edRow, edCol); break; case 2: str = (""+jTableLoco.getValueAt(edRow, edCol)).toUpperCase().replaceAll("\\s",""); jTableLoco.setValueAt(str, edRow, edCol); checkM3sid(edRow); break; } } }//GEN-LAST:event_jTableLocoPropertyChange private void jTableLocoCaretPositionChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jTableLocoCaretPositionChanged if( debugLevel > 0 ) { System.out.println("jTableLocoCaretPositionChanged col="+jTableLoco.getEditingColumn()+" row="+jTableLoco.getEditingRow()); } }//GEN-LAST:event_jTableLocoCaretPositionChanged private void jTableLocoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTableLocoFocusLost if( debugLevel > 0 ) { System.out.println("jTableLocoFocusLost col="+jTableLoco.getEditingColumn()+" row="+jTableLoco.getEditingRow()); } }//GEN-LAST:event_jTableLocoFocusLost private void jTableLocoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTableLocoFocusGained if( debugLevel > 0 ) { System.out.println("jTableLocoFocusGained col="+jTableLoco.getEditingColumn()+" row="+jTableLoco.getEditingRow()); } }//GEN-LAST:event_jTableLocoFocusGained private void jSystemComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jSystemComponentShown Cursor c = new Cursor(Cursor.DEFAULT_CURSOR ); setCursor(c); }//GEN-LAST:event_jSystemComponentShown private void jCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCloseActionPerformed if( debugLevel > 0 ) { System.out.println("jCloseActionPerformed"); } this.dispose(); }//GEN-LAST:event_jCloseActionPerformed private void jRailcomAccessoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRailcomAccessoryActionPerformed if( jRailcomAccessory.isSelected() ) { jRailcomTailbits.setSelected(true); jRailcomIdNotify.setSelected(true); } updateRailComValue(); }//GEN-LAST:event_jRailcomAccessoryActionPerformed private void jRailcomIdNotifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRailcomIdNotifyActionPerformed if( jRailcomIdNotify.isSelected() ) { jRailcomTailbits.setSelected(true); } else { jRailcomAccessory.setSelected(false); } updateRailComValue(); }//GEN-LAST:event_jRailcomIdNotifyActionPerformed private void jRailcomTailbitsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRailcomTailbitsActionPerformed if( ! jRailcomTailbits.isSelected() ) { jRailcomIdNotify.setSelected(false); jRailcomAccessory.setSelected(false); } updateRailComValue(); }//GEN-LAST:event_jRailcomTailbitsActionPerformed private void jCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCancelActionPerformed if( debugLevel > 0 ) { System.out.println("jCancelActionPerformed"); } stopIOAction(); }//GEN-LAST:event_jCancelActionPerformed private void jKonfSichernActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jKonfSichernActionPerformed this.jMcRwInfo.setText("write to file: preparing data"); this.jMcRwProgress.setMaximum(100); this.jMcRwProgress.setValue(0); String str = "[INFO]\r\nVERSION " + jVersion.getText() + "\r\nHARDWARE " + jHardWare.getText() + "\r\nMCU " + jMCU.getText() + "\r\nSERIAL " + jSerNr.getText() + "\r\n[LOCO]\r\n"; if( debugLevel > 0 ) { System.out.println("jKonfSichernActionPerformed Version["+jVersion.getText()+"]" ); } this.jMcRwProgress.setValue(10); for(int i = 0; i < c.MAX_LOCS; i++) { String s1 = (""+jTableLoco.getValueAt(i, 0)).trim(); String s2 = (""+jTableLoco.getValueAt(i, 1)).trim(); String s3 = (""+jTableLoco.getValueAt(i, 2)).trim(); String s4 = (""+jTableLoco.getValueAt(i, 3)).trim(); if((s1.length() > 0) && (s2.length() > 0) && (s3.length() > 0 )) { if( debugLevel > 0 ) { System.out.println("jKonfSichernActionPerformed i["+i+"] s1["+s1+"] s2["+s2+"] s3["+s3+"]"); } str += s1 + ", " + s2 + ", " + s3; if(s4.length() > 0) { str += ", " + s4; } str += "\r\n"; } } this.jMcRwProgress.setValue(35); str += "[TRAKTIONS]\r\n"; if( debugLevel > 0 ) { System.out.println("jKonfSichernActionPerformed TRAKTIONS"); } for(int i = 0; i < c.MAX_TRACTIONS; i++) { String s1 = (""+jTableTraction.getValueAt(i, 0)).trim(); String s2 = (""+jTableTraction.getValueAt(i, 2)).trim(); if( (s1.length() > 0) && (s2.length() > 0) ) { str += s1 + ", " + s2; str += "\r\n"; } else { break; } } this.jMcRwProgress.setValue(55); if( debugLevel > 0 ) { System.out.println("jKonfSichernActionPerformed ACCFMT"); } str += "[ACCFMT]\r\n"; for(int i = 0; i < c.MAX_MM1_ACCMOD; i++) { String s1 = (""+jTableAccessory.getValueAt(i, 0)).trim(); String s2 = (""+jTableAccessory.getValueAt(i, 1)).trim(); if( (s1.length() > 0) && (s2.length() > 0) ) { String[] s1Arr = s1.split(" "); int j = -1; try { j = Integer.parseInt(s1Arr[0]) - 1; } catch (Exception ex) { System.out.println("jKonfSichernActionPerformed: EXCEPTION s1="+s1+" s1Arr[0]="+s1Arr[0]); } if( j >= 0 ) { str += ""+j+", "+s2+"\r\n"; } } else { break; } } this.jMcRwProgress.setValue(75); str += "[SYSTEM]\r\nLONGPAUSE "; if(jLangePause.isSelected()) { str += "yes\r\n"; } else { str += "no\r\n"; } str += "NEGATIVESHORT "; if(jDCC_Booster.isSelected()) { str += "yes\r\n"; } else { str += "no\r\n"; } str += "DEFAULTDCC "; if(jDCC_Loks.isSelected()) { str += "yes\r\n"; } else { str += "no\r\n"; } int KSE; try { KSE = Integer.parseInt(jKurzEmpf.getText()); KSE /= 5; } catch (NumberFormatException numberFormatException) { KSE = 20; } str += "SHORTTIME " + KSE + "\r\n"; str += "s88MODULES " + js88.getText() + "\r\n"; str += "MAGMINTIME " + jMinMag.getText() + "\r\n"; str += "MAGMAXTIME " + jMaxMag.getText() + "\r\n"; str += "BAUDRATE " + jBaud.getText() + "\r\n"; if( rcValue != -1 ) { str += "RAILCOM " + rcValue + "\r\n"; } if( so999Value != -1 ) { str += "SO999 " + so999Value + "\r\n"; } str += "*END*\r\n"; this.jMcRwProgress.setValue(90); setMcRwInfo("write to file: select filename"); SaveOpenDialog od = new SaveOpenDialog( this, true, false, str, this, "mc", c.MC); }//GEN-LAST:event_jKonfSichernActionPerformed public void setMcRwProgess( int i ) { this.jMcRwProgress.setValue( i ); } public void setMcRwInfo( String s ) { this.jMcRwInfo.setText( s ); } public void callParser( String fileName ) { if( ( ReturnString != null ) && ( ReturnString.length() > 0 ) ) { validMcData = parseInputArray( (fileName != null)?fileName:"unknown", ReturnString ); if( validMcData ) { reCheckVersionInfo(); } ReturnString = ""; } } private void jKonfLadenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jKonfLadenActionPerformed setMcRwInfo("read from file: select filename"); setMcRwProgess( 0 ); SaveOpenDialog od = new SaveOpenDialog( this, true, true, null, this, "m3 conf txt", c.MC); }//GEN-LAST:event_jKonfLadenActionPerformed private void jKonfSchreibenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jKonfSchreibenActionPerformed Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ) { return; } jMcRwInfo.setText("write: prepare"); bFalscheEingabe = false; FehlerArt = 0; if( jWRsys.isSelected()) { // check all critical fields for reasonable values OR init with defaults KTUI.checkTextFieldUnit( this, jKurzEmpf, 0, 1000, 100, 5, false); KTUI.checkTextField( this, js88, 0, 52, 52, false); KTUI.checkTextFieldUnit( this, jMinMag, 0, 1000, 100, 50, false); KTUI.checkTextFieldUnit( this, jMaxMag, 100, 25500, 300, 100, false); } if( jWRloc.isSelected() ) { jMcRwInfo.setText("write: prepare loco table"); // check loco table without "repair"-Option in silent mode (no show) Boolean chkLocOK = checkTableLoco( false, false ); if( debugLevel > 0 ) { System.out.println("KonfSchreiben chkLoc=["+chkLocOK+"]" ); } if( chkLocOK == false ) { // KTUI.mbTableCheck( FehlerArt, false ); if( debugLevel > 0 ) { System.out.println("KonfSchreiben chkLoc=["+chkLocOK+"] RETURN"); } jMcRwInfo.setText("write: prepare -> loco list with errors -> cancel"); jTabbedPane1.setSelectedIndex(1); return; } // check loco table with "repair"-Option in silent mode (no show) using defaults checkTableLoco( true, false ); } if( jWRtra.isSelected() ) { jMcRwInfo.setText("write: prepare traction table"); // check traction table without "repair"-Option in silent mode (no show) Boolean chkTraOK = checkTableTraction( false, false ); if( debugLevel > 0 ) { System.out.println("KonfSchreiben chkTra=["+chkTraOK+"]" ); } if( chkTraOK == false ) { // KTUI.mbTableCheck( FehlerArt, false ); if( debugLevel > 0 ) { System.out.println("KonfSchreiben chkTra=["+chkTraOK+"] RETURN" ); } jMcRwInfo.setText("write: prepare -> traction list with errors -> cancel"); jTabbedPane1.setSelectedIndex(2); return; } // check traction table with "repair"-Option in silent mode (no show) using defaults checkTableTraction( true, false ); } if( jWRmag.isSelected() ) { jMcRwInfo.setText("write: prepare accessory table"); // check accesory table without "repair"-Option in silent mode (no show) Boolean chkAccOK = checkTableAccessory( false, false ); if( debugLevel > 0 ) { System.out.println("KonfSchreiben chkAcc=["+chkAccOK+"]" ); } if( chkAccOK == false ) { // KTUI.mbTableCheck( FehlerArt, false ); if( debugLevel > 0 ) { System.out.println("KonfSchreiben chkAcc=["+chkAccOK+"] RETURN" ); } jMcRwInfo.setText("write: prepare -> accessory list with errors -> cancel"); jTabbedPane1.setSelectedIndex(3); return; } // check accessory table with "repair"-Option in silent mode (no show) using defaults checkTableAccessory( true, false ); } jMcRwInfo.setText("write: prepare"); if ( validMcData ) { // TODO current data was not read from MC or file ! // Are U sure ? Do you want to write ? YesNo // if( NO ) // return; } bFalscheEingabe = false; FehlerArt = 0; int nR = KTUI.flushReadBuffer(Com); if( debugLevel > 0 ) { System.out.println("KonfSchreiben clean buffer pre 0x61 write read "+nR+" bytes" ); } resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = false; // STOP as 0x61 byte does not return a prompt "]" -> start writing in loop ! nextWriteJob = 0; bWriteCfg = true; count = 0; // used for FW-Upadate jMcRwProgress.setMaximum(c.MAX_SYSWRITES+c.MAX_LOCS+c.MAX_TRACTIONS+c.MAX_MM1_ACCMOD); jMcRwProgress.setValue(0); timer.setInitialDelay(KlarTextUI.MCtimer1); timer.setDelay(KlarTextUI.MCtimer2); startIOAction(); }//GEN-LAST:event_jKonfSchreibenActionPerformed private void jKonfLesenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jKonfLesenActionPerformed Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ){ return; } KTUI.flushReadBuffer(Com); String s = "xcfgdump\r"; Com.write(s); resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); bWaitAnswerInProgress = true; bReadCfg = true; readWriteProgress = 0; jMcRwProgress.setMaximum(6); jMcRwProgress.setValue(0); timer.setInitialDelay(KlarTextUI.MCtimer1); timer.setDelay(KlarTextUI.MCtimer2); startIOAction(); jMcRwInfo.setText("read: MC config read in progress"); jMcRwProgress.setValue(++readWriteProgress); }//GEN-LAST:event_jKonfLesenActionPerformed private void jMaxMagFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jMaxMagFocusLost KTUI.checkTextFieldUnit( this, jMaxMag, 100, 25500, 300, 100, true); }//GEN-LAST:event_jMaxMagFocusLost private void jMinMagFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jMinMagFocusLost KTUI.checkTextFieldUnit( this, jMinMag, 0, 1000, 100, 50, true); }//GEN-LAST:event_jMinMagFocusLost private void js88FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_js88FocusLost KTUI.checkTextField( this, js88, 0, 52, 52, true); updateS88field(Integer.parseInt(js88.getText())); }//GEN-LAST:event_js88FocusLost private void js88ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_js88ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_js88ActionPerformed private void jKurzEmpfFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jKurzEmpfFocusLost KTUI.checkTextFieldUnit( this, jKurzEmpf, 0, 1000, 100, 5, true); }//GEN-LAST:event_jKurzEmpfFocusLost private void jTextM3UIDFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextM3UIDFocusGained // TODO add your handling code here: System.out.println("jTextM3UIDFocusGained"); }//GEN-LAST:event_jTextM3UIDFocusGained private void jTextM3UIDFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextM3UIDFocusLost System.out.println("jTextM3UIDFocusLost"); if( KTUI.frameInstanceDEVICE == null ) { return; } if( ! checkM3uidValidActive ) { checkM3uidValid(); } }//GEN-LAST:event_jTextM3UIDFocusLost private void jTextM3UIDPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTextM3UIDPropertyChange // TODO add your handling code here: System.out.println("jTextM3UIDPropertyChange"); }//GEN-LAST:event_jTextM3UIDPropertyChange private void jTextM3UIDInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jTextM3UIDInputMethodTextChanged // TODO add your handling code here: System.out.println("jTextM3UIDInputMethodTextChanged"); }//GEN-LAST:event_jTextM3UIDInputMethodTextChanged private void jLocM3cfgLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLocM3cfgLoadActionPerformed // TODO add your handling code here: SaveOpenDialog od = new SaveOpenDialog( this, true, true, null, this, "m3", c.M3); }//GEN-LAST:event_jLocM3cfgLoadActionPerformed private void jLocM3cfgEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLocM3cfgEditActionPerformed // TODO add your handling code here: M3L = new M3_Liste( this, true ); }//GEN-LAST:event_jLocM3cfgEditActionPerformed private void jLocM3cfgSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLocM3cfgSaveActionPerformed // TODO add your handling code here: String str = "[M3UID]\r\n"; System.out.println("M3 [<MAC>][<SID>][<Beschreibung>]"); for( int i = 0 ; i < M3used ; i++ ) { str += M3liste[0][i]+", "+M3liste[1][i]+", "+M3liste[2][i]+"\r\n"; System.out.println("M3 ["+M3liste[0][i]+"]["+M3liste[1][i]+"]["+M3liste[2][i]+"]"); } SaveOpenDialog od = new SaveOpenDialog( this, true, false, str, this, "m3", c.M3); }//GEN-LAST:event_jLocM3cfgSaveActionPerformed private void jLocDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLocDelActionPerformed delMultipleLocoLines(); }//GEN-LAST:event_jLocDelActionPerformed private void jTraDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTraDelActionPerformed delMultipleTractionLines(); }//GEN-LAST:event_jTraDelActionPerformed private void jLoc2SystemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLoc2SystemActionPerformed jTabbedPane1.setSelectedIndex(0); }//GEN-LAST:event_jLoc2SystemActionPerformed private void jTra2SystemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTra2SystemActionPerformed jTabbedPane1.setSelectedIndex(0); }//GEN-LAST:event_jTra2SystemActionPerformed private void jMag2SystemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMag2SystemActionPerformed jTabbedPane1.setSelectedIndex(0); }//GEN-LAST:event_jMag2SystemActionPerformed private void jUpd2SystemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUpd2SystemActionPerformed jTabbedPane1.setSelectedIndex(0); }//GEN-LAST:event_jUpd2SystemActionPerformed private void jLocM3sidWriteListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jLocM3sidWriteListActionPerformed // for all in M3list do jLocM3sidWriteActionPerformed() System.out.println("jLocM3sidWriteListActionPerformed"); if( M3used == 0 ) { return; } if( ! KTUI.bUseXm3sid ) { String sFW = KTUI.fwVersion; if( (sFW == null) || ( sFW.length() == 0) ) { if( KTUI.bSpracheDE) { sFW = "unbekannt"; } else { sFW = "unknown"; } } if( KTUI.bSpracheDE) { KTUI.mbGeneric( this, "HINWEIS", "Tams MC mit Firmware ab Version \"1.4.7b\" notwendig", "Diese Zentrale hat Firmware \""+sFW+"\"", 5, true ); } else { KTUI.mbGeneric( this, "NOTE", "Tams MC with firmware version \"1.4.7b\" or newer necessary", "This MC has firmware \""+sFW+"\"", 5, true ); } return; } if( debugLevel > 0 ) { for( int i = 0 ; i < M3used ; i++ ){ System.out.println("jLocM3sidWriteListActionPerformed: Liste["+i+"] : uid="+ M3liste[0][i] +" sid="+ M3liste[1][i] ); } } long lM3UID = Long.decode( M3liste[0][0] ); int iAdr = Integer.decode( M3liste[1][0] ); if( debugLevel > 0 ) { System.out.println("lM3UID="+String.format("%8s", Long.toHexString( lM3UID )).replace(' ', '0') + " iAdr="+iAdr); } Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ){ return; } byte[] wArray = new byte[8]; wArray[0] = (byte) 0x78; wArray[1] = (byte) 0x87; // Xm3Sid (requires 1.4.7b) wArray[2] = (byte) ( iAdr & 0xFF ); wArray[3] = (byte) ( ( iAdr >> 8 ) & 0xFF ); wArray[4] = (byte) ( lM3UID & 0xFF ); wArray[5] = (byte) ( ( lM3UID >> 8 ) & 0xFF ); wArray[6] = (byte) ( ( lM3UID >> 16 ) & 0xFF ); wArray[7] = (byte) ( ( lM3UID >> 24 ) & 0xFF ); KTUI.flushReadBuffer(Com); Com.write((byte)0x60); KTUI.flushReadBuffer(Com); if( debugLevel > 0 ) { // TODO evtl this durch this.getContentPane() ersetzen KTUI.mbGeneric( this, "MC", "Xm3Sid adr(sid)="+iAdr+" MAC(uid)="+lM3UID, "writing to MC wArray=0x"+printHexBinary(wArray), 10, false ); } Com.write(wArray); if( debugLevel > 0 ) { System.out.println("written to MC wArray=0x"+printHexBinary(wArray)); } bWriteM3sidList = true; readWriteProgress = 0; jMcM3Progress.setMaximum(2*M3used); timer.setInitialDelay(KlarTextUI.MCtimer1); timer.setDelay(KlarTextUI.MCtimer2); startIOAction(); jMcM3Info.setText("Xm3Sid: write list in progress"); jMcM3Progress.setValue(++readWriteProgress); }//GEN-LAST:event_jLocM3sidWriteListActionPerformed private void helpLCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpLCActionPerformed HelpInfoLC hLC = new HelpInfoLC( this, false ); return; }//GEN-LAST:event_helpLCActionPerformed private void helpHCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpHCActionPerformed HelpInfoHC hHC = new HelpInfoHC( this, false ); return; }//GEN-LAST:event_helpHCActionPerformed private void helpPCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpPCActionPerformed HelpInfoPC hPC = new HelpInfoPC( this, false ); return; }//GEN-LAST:event_helpPCActionPerformed private void helpSNCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpSNCActionPerformed HelpInfoSNC hSNC = new HelpInfoSNC( this, false ); return; }//GEN-LAST:event_helpSNCActionPerformed private void helpXNCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpXNCActionPerformed HelpInfoXNC hXNC = new HelpInfoXNC( this, false ); return; }//GEN-LAST:event_helpXNCActionPerformed private void helpMCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpMCActionPerformed HelpInfoMC hMC = new HelpInfoMC( this, false ); return; }//GEN-LAST:event_helpMCActionPerformed private void helpWasIstWasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpWasIstWasActionPerformed new HelpInfoWasIstWas( this, false ); return; }//GEN-LAST:event_helpWasIstWasActionPerformed private void helpMCasLCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpMCasLCActionPerformed System.out.println("KTUI.rs232_or_rb_usb_2="+KTUI.rs232_or_rb_usb_2+" KTUI.rs232_mode_was_forced="+KTUI.rs232_mode_was_forced); }//GEN-LAST:event_helpMCasLCActionPerformed private void FirmwareActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FirmwareActionPerformed Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(new URL(c.TamsFirmwareURL).toURI()); } catch (Exception e) { e.printStackTrace(); } } return; }//GEN-LAST:event_FirmwareActionPerformed private void jSysS88monitorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jSysS88monitorActionPerformed if( debugLevel > 0 ) { System.out.println("jSysS88monitorActionPerformed pre NEW"); } if( KTUI.getNumS88() <= 0 ) { KTUI.mbNoS88modules( this ); return; } S88mon = new S88monitor( this, false ); if( debugLevel > 0 ) { System.out.println("jSysS88monitorActionPerformed post NEW S88mon valid="+(S88mon != null)); } }//GEN-LAST:event_jSysS88monitorActionPerformed private void jEasyNetUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jEasyNetUpdateActionPerformed if( KTUI.debugOffline == false ) { Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ){ return; } KTUI.flushReadBuffer(Com); String s = "xSWUPDATE\r"; Com.write(s); } resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); jMcRwInfo.setText("MC/RedBox set to SWUPDATE mode"); jEasyNetUpdate.setText(bundle.getString("MC.jEasyNetUpdate.EasyNetActivated")); jEasyNetUpdate.setForeground(Color.red); // keine Antwort von MC/RB }//GEN-LAST:event_jEasyNetUpdateActionPerformed private void jBoostOptNoAccDriveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBoostOptNoAccDriveActionPerformed updateSo999Value(); }//GEN-LAST:event_jBoostOptNoAccDriveActionPerformed private void jBoostOptNoAccBreakActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBoostOptNoAccBreakActionPerformed updateSo999Value(); }//GEN-LAST:event_jBoostOptNoAccBreakActionPerformed private void jMRSTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMRSTActionPerformed // Sicherheitsabfrage int YNresult = KTUI.yesNoResetFactoryDefault(); System.out.println("yesNoResetFactoryDefault() : YNresult="+YNresult); // 0 = JA , 1 = NEIN if( YNresult != 0 ) { System.out.println("yesNoResetFactoryDefault() : YNresult="+YNresult+" NO -> SKIP"); return; } if( KTUI.debugOffline == false ) { Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ){ return; } KTUI.flushReadBuffer(Com); String s = "xMRST\r"; Com.write(s); } resetbArray(); retries = KlarTextUI.timerRetries; jMcRwProgress.setString(null); jMcRwInfo.setText("MC/RedBox reset to factory default"); // keine Antwort von MC/RB }//GEN-LAST:event_jMRSTActionPerformed private void jUSB1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUSB1ActionPerformed rs232_or_rb_usb_2 = false; jUSB2.setSelected(false); KTUI.rs232_mode_was_forced = false; }//GEN-LAST:event_jUSB1ActionPerformed private void jUSB2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUSB2ActionPerformed rs232_or_rb_usb_2 = true; jUSB1.setSelected(false); KTUI.rs232_mode_was_forced = false; }//GEN-LAST:event_jUSB2ActionPerformed private void jf10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf10ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[9] == 0) { Funktionen[9] = 1; jf10.setBackground(Color.yellow); } else { Funktionen[9] = 0; jf10.setBackground(DefBackground); } String s = "XFX " + AktLokAdr; for(int i = 8; i < 16; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf10ActionPerformed private void jf18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf18ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jf18ActionPerformed private void jf12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf12ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[11] == 0) { Funktionen[11] = 1; jf12.setBackground(Color.yellow); } else { Funktionen[11] = 0; jf12.setBackground(DefBackground); } String s = "XFX " + AktLokAdr; for(int i = 8; i < 16; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf12ActionPerformed private void jf24ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf24ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jf24ActionPerformed private void jf26ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf26ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jf26ActionPerformed private void jf28ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf28ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jf28ActionPerformed private void jPanel2ComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jPanel2ComponentShown Com = KTUI.safelyOpenCom(this, Com); if(Com == null) { // LRLRLR: Todo Message-Box and return return; } Com.write((byte)0x60); jDisplay.setAutoscrolls(false); jDisplay.setText(" DisplayCursor = 0; DisplayState = -1; jHauptGleis.setSelected(true); jDirektLesen.setEnabled(false); jListeLesen.setEnabled(false); DefBackground = jf5.getBackground(); jf5.setEnabled(false); jf6.setEnabled(false); jf7.setEnabled(false); jf8.setEnabled(false); jf9.setEnabled(false); jf10.setEnabled(false); jf11.setEnabled(false); jf12.setEnabled(false); jf13.setEnabled(false); jf14.setEnabled(false); jf15.setEnabled(false); jf16.setEnabled(false); jf17.setEnabled(false); jf18.setEnabled(false); jf19.setEnabled(false); jf20.setEnabled(false); jf21.setEnabled(false); jf22.setEnabled(false); jf23.setEnabled(false); jf24.setEnabled(false); jf25.setEnabled(false); jf26.setEnabled(false); jf27.setEnabled(false); jf28.setEnabled(false); if(jSerNr.getText().contains("-")) this.jKonfLesenActionPerformed(null); }//GEN-LAST:event_jPanel2ComponentShown private void jDirektSchreibenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jDirektSchreibenActionPerformed Com = KTUI.safelyOpenCom(this, Com); if(Com == null) { // LRLRLR: Todo Message-Box and return return; } try { int CV = Integer.parseInt(jCV_Direkt.getText()); int Wert = Integer.parseInt(jWertDirekt.getText()); String s; if(jHauptGleis.isSelected()) { int DecAdr = Integer.parseInt(jDecAdr.getText()); s = "XPD " + DecAdr + " " + CV + " " + Wert + "\r"; System.out.println("497 jCVSchreibenActionPerformed POM : XPD " + DecAdr + " " + CV + " " + Wert ); retries = 1; } else { s = "XPTWD " + " " + CV + " " + Wert + "\r"; System.out.println("505 jCVSchreibenActionPerformed not POM : XPTWD " + CV + " " + Wert ); retries = KlarTextUI.timerRetries; } KTUI.flushReadBuffer( Com ); Com.write(s); } catch (NumberFormatException numberFormatException) { KTUI.mbGeneric( this, "Eingabefehler"); } }//GEN-LAST:event_jDirektSchreibenActionPerformed private void jProgGleisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jProgGleisActionPerformed jDirektLesen.setEnabled(true); jListeLesen.setEnabled(true); }//GEN-LAST:event_jProgGleisActionPerformed private void jHauptGleisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jHauptGleisActionPerformed Com = KTUI.safelyOpenCom(this, Com); if(Com == null) { // LRLRLR: Todo Message-Box and return return; } Com.write((byte)0x60); jDirektLesen.setEnabled(false); jListeLesen.setEnabled(false); }//GEN-LAST:event_jHauptGleisActionPerformed private void jDirektLesenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jDirektLesenActionPerformed Com = KTUI.safelyOpenCom(this, Com); if(Com == null) { // LRLRLR: Todo Message-Box and return return; } bReadPTdirekt = true; bAskLokState = false; KTUI.flushReadBuffer( Com ); resetbArray(); int cvAnfrage = KTUI.checkTextField( this, jCV_Direkt, 1, 1024, 8, false); System.out.print("525 jCVLesenActionPerformed cvAnfrage["+cvAnfrage+"]"); String s = "XPTRD " + cvAnfrage + "\r"; Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = KlarTextUI.timerRetries * 2; // LRLRLR warum doppelte Anzahl ??? startIOAction(); }//GEN-LAST:event_jDirektLesenActionPerformed private void jListeLesenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jListeLesenActionPerformed Com = KTUI.safelyOpenCom(this, Com); if(Com == null) { // LRLRLR: Todo Message-Box and return return; } bReadPTList = true; KTUI.flushReadBuffer( Com ); resetbArray(); jCVListe.clearSelection(); jCVListe.setSelectedIndex(0); String s = (String)jCVListe.getSelectedValue(); s = "XPTRD" + s + "\r"; Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = KlarTextUI.timerRetries * 2; // LRLRLR warum doppelte Anzahl ??? startIOAction(); }//GEN-LAST:event_jListeLesenActionPerformed public ListModel getList() { return jCVListe.getModel(); } public void setList(String s) { DefaultListModel dlm = new DefaultListModel(); String[] split = s.split("\n"); for(int i = 0; i < split.length; i++) { if(split[i].contains("\t")) { split[i] = split[i].replace("\t", " "); } dlm.add(i, split[i]); } jCVListe.setModel(dlm); } private void jListeBearbeitenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jListeBearbeitenActionPerformed new MC_RB_CV_List(this, true).setVisible(true); /* if(!jHauptGleis.isSelected()) jDirektLesen.setEnabled(true); jListeBearbeiten.setEnabled(true); if(!jHauptGleis.isSelected()) jListeLesen.setEnabled(true); jListeSchreiben.setEnabled(true); jDirektSchreiben.setEnabled(true); */ }//GEN-LAST:event_jListeBearbeitenActionPerformed private void jListeSchreibenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jListeSchreibenActionPerformed Com = KTUI.safelyOpenCom(this, Com); if(Com == null) { // LRLRLR: Todo Message-Box and return return; } bWriteList = true; KTUI.flushReadBuffer( Com ); resetbArray(); jCVListe.clearSelection(); jCVListe.setSelectedIndex(0); String s = (String)jCVListe.getSelectedValue(); if(jHauptGleis.isSelected()) { int DecAdr; try { DecAdr = Integer.parseInt(jDecAdr.getText()); } catch (NumberFormatException numberFormatException) { DecAdr = 3; } s = "XPD" + DecAdr + s + "\r"; System.out.println("497 jCVSchreibenActionPerformed POM : " + s ); } else { s = "XPTWD" + s + "\r"; System.out.println("497 jCVSchreibenActionPerformed PT : " + s ); } Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = KlarTextUI.timerRetries * 2; // LRLRLR warum doppelte Anzahl ??? startIOAction(); }//GEN-LAST:event_jListeSchreibenActionPerformed private void jm3SchreibenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jm3SchreibenActionPerformed Com = KTUI.safelyOpenCom(this, Com); if(Com == null) { // LRLRLR: Todo Message-Box and return return; } bProg_m3 = true; KTUI.flushReadBuffer( Com ); resetbArray(); String s = "xMFX " + jm3Addr.getText() + "\r"; Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = 0; //KlarTextUI.timerRetries * 4; startIOAction(); }//GEN-LAST:event_jm3SchreibenActionPerformed private void jMMWertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMMWertActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMMWertActionPerformed private void jHerstellerInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jHerstellerInfoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jHerstellerInfoActionPerformed private void jStartMMProgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jStartMMProgActionPerformed Com = KTUI.safelyOpenCom(this, Com); if(Com == null) { // LRLRLR: Todo Message-Box and return return; } bProg_MM = true; Com.write((byte)0x61); // STOP KTUI.flushReadBuffer( Com ); resetbArray(); KTUI.mbGeneric(this, "Hinweis", "Für die Lokadressen " + jMMRegister.getText() + " und " + jMMWert.getText() + " muss das MM Protokoll eingestellt werde.", "Bitte stellen Sie an Ihrer MM-Lok nun den Programmiermodus ein."); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = 14; // LRLRLR Warum genau 14 ? startIOAction(); }//GEN-LAST:event_jStartMMProgActionPerformed private void j1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j1ActionPerformed if(DisplayState != 0) { DisplayState = 0; OldDisplayString = jDisplay.getText(); jDisplay.setText("ADR: 1 " + jDisplay.getText().substring(12, 17) + "*=Abbruch "); DisplayCursor = 5; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '1'; } text = new String(ba); jDisplay.setText(text); }//GEN-LAST:event_j1ActionPerformed private void jSternActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jSternActionPerformed if(DisplayState == 0) { jDisplay.setText(OldDisplayString); DisplayState = -1; } }//GEN-LAST:event_jSternActionPerformed private void j2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j2ActionPerformed if(DisplayState != 0) { DisplayState = 0; OldDisplayString = jDisplay.getText(); jDisplay.setText("ADR: 2 " + jDisplay.getText().substring(12, 17) + "*=Abbruch "); DisplayCursor = 5; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '2'; } text = new String(ba); jDisplay.setText(text); }//GEN-LAST:event_j2ActionPerformed private void j3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j3ActionPerformed if(DisplayState != 0) { DisplayState = 0; OldDisplayString = jDisplay.getText(); jDisplay.setText("ADR: 3 " + jDisplay.getText().substring(12, 17) + "*=Abbruch "); DisplayCursor = 5; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '3'; } text = new String(ba); jDisplay.setText(text); // TODO add your handling code here: }//GEN-LAST:event_j3ActionPerformed private void j4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j4ActionPerformed if(DisplayState != 0) { DisplayState = 0; OldDisplayString = jDisplay.getText(); jDisplay.setText("ADR: 4 " + jDisplay.getText().substring(12, 17) + "*=Abbruch "); DisplayCursor = 5; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '4'; } text = new String(ba); jDisplay.setText(text); }//GEN-LAST:event_j4ActionPerformed private void j5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j5ActionPerformed if(DisplayState != 0) { DisplayState = 0; OldDisplayString = jDisplay.getText(); jDisplay.setText("ADR: 5 " + jDisplay.getText().substring(12, 17) + "*=Abbruch "); DisplayCursor = 5; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '5'; } text = new String(ba); jDisplay.setText(text); }//GEN-LAST:event_j5ActionPerformed private void j6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j6ActionPerformed if(DisplayState != 0) { DisplayState = 0; OldDisplayString = jDisplay.getText(); jDisplay.setText("ADR: 6 " + jDisplay.getText().substring(12, 17) + "*=Abbruch "); DisplayCursor = 5; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '6'; } text = new String(ba); jDisplay.setText(text); }//GEN-LAST:event_j6ActionPerformed private void j7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j7ActionPerformed if(DisplayState != 0) { DisplayState = 0; OldDisplayString = jDisplay.getText(); jDisplay.setText("ADR: 7 " + jDisplay.getText().substring(12, 17) + "*=Abbruch "); DisplayCursor = 5; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '7'; } text = new String(ba); jDisplay.setText(text); }//GEN-LAST:event_j7ActionPerformed private void j8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j8ActionPerformed if(DisplayState != 0) { DisplayState = 0; OldDisplayString = jDisplay.getText(); jDisplay.setText("ADR: 8 " + jDisplay.getText().substring(12, 17) + "*=Abbruch "); DisplayCursor = 5; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '8'; } text = new String(ba); jDisplay.setText(text); }//GEN-LAST:event_j8ActionPerformed private void j9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j9ActionPerformed if(DisplayState != 0) { DisplayState = 0; OldDisplayString = jDisplay.getText(); jDisplay.setText("ADR: 9 " + jDisplay.getText().substring(12, 17) + "*=Abbruch "); DisplayCursor = 5; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '9'; } text = new String(ba); jDisplay.setText(text); }//GEN-LAST:event_j9ActionPerformed private void j0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j0ActionPerformed if(DisplayState != 0) { return; } String text = jDisplay.getText(); byte[] ba = text.getBytes(); if(DisplayCursor < 10) { ba[DisplayCursor++] = '0'; } text = new String(ba); jDisplay.setText(text); }//GEN-LAST:event_j0ActionPerformed private void jRauteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRauteActionPerformed if(DisplayState == 0) { String text = jDisplay.getText(); int parseInt; String substring = text.substring(5, DisplayCursor); try { parseInt = Integer.parseInt(substring); } catch (NumberFormatException numberFormatException) { parseInt = 16384; } if(parseInt > 16384) return; if(substring.length() < 5) { substring += " "; substring = substring.substring(0, 5); } text = substring + " \nplease wait " ; jDisplay.setText(text); DisplayState = -1; bAskLokState = true; if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); resetbArray(); System.out.print("LokAnfrage Adr.: "+parseInt); String s = "XLC " + parseInt + "\r"; AskedLokAdr = parseInt; AktLokAdr = 0; Com.write(s); timer.setInitialDelay(KlarTextUI.timer1); timer.setDelay(KlarTextUI.timer2); timer.setRepeats(true); bWaitAnswerInProgress = true; retries = KlarTextUI.timerRetries * 2; timer.start(); } }//GEN-LAST:event_jRauteActionPerformed private void jGeschwindigkeitCaretPositionChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jGeschwindigkeitCaretPositionChanged }//GEN-LAST:event_jGeschwindigkeitCaretPositionChanged private void jGeschwindigkeitStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jGeschwindigkeitStateChanged //AktLokState = z.B. 3 20 0 r 1 0 0 1 int v = jGeschwindigkeit.getValue(); String s = AktLokState.substring(AktLokState.indexOf(" ")+1); s = s.substring(0, s.indexOf(" ")); int Vrb = Integer.parseInt(s); if(Vrb != v) { //neue Geschwindigkeit senden s = AktLokState.substring(0, AktLokState.indexOf(" ")); s = "XL " + s + " " + v + "\r"; if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } Com.write(s); s = jDisplay.getText(); s = s.substring(0, 12); int V = v; switch(Fahrstufen) { case 14: V = (V + 8)/9; break; case 27: V = (V*3 + 11)/14; break; case 28: V = (V*2 + 7)/9; break; } s += V + " "; s = s.substring(0, 15); s += jDisplay.getText().substring(15); jDisplay.setText(s); s = "" + v + " "; s = s.substring(0, 3); int i = AktLokState.indexOf(" ")+1; String str = AktLokState.substring(AktLokState.indexOf(" ")+1); str = str.substring(str.indexOf(" ")); AktLokState = AktLokState.substring(0, i) + v + str; try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(MC.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jGeschwindigkeitStateChanged private void jGOActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jGOActionPerformed if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } Com.write((byte)0x60); String s = jDisplay.getText().substring(0, 7) + AktLokFormat + jDisplay.getText().substring(11); jDisplay.setText(s); }//GEN-LAST:event_jGOActionPerformed private void jSTOPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jSTOPActionPerformed if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } Com.write((byte)0x61); // STOP String s = jDisplay.getText().substring(0, 7) + "STOP" + jDisplay.getText().substring(11); jDisplay.setText(s); }//GEN-LAST:event_jSTOPActionPerformed private void jf0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf0ActionPerformed //AktLokState = z.B. 3 20 0 r 1 0 0 1 String s = AktLokState.substring(AktLokState.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(0, s.indexOf(" ")); if(s.contains("0")) { s = jDisplay.getText(); s = s.substring(0, 28); s += "*"; s += jDisplay.getText().substring(29); jDisplay.setText(s); AktLokState = AktLokState.substring(0, AktLokState.indexOf(" ", AktLokState.indexOf(" ")+1)) + " 1" + AktLokState.substring(AktLokState.indexOf(" ", AktLokState.indexOf(" ")+3)); } else { s = jDisplay.getText(); s = s.substring(0, 28); s += "-"; s += jDisplay.getText().substring(29); jDisplay.setText(s); AktLokState = AktLokState.substring(0, AktLokState.indexOf(" ", AktLokState.indexOf(" ")+1)) + " 0" + AktLokState.substring(AktLokState.indexOf(" ", AktLokState.indexOf(" ")+3)); } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s = "XL " + AktLokState + "\r"; Com.write(s); }//GEN-LAST:event_jf0ActionPerformed private void jf1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf1ActionPerformed if(DisplayState == 0) { String text = jDisplay.getText(); int parseInt; String substring = text.substring(5, DisplayCursor); try { parseInt = Integer.parseInt(substring); } catch (NumberFormatException numberFormatException) { parseInt = 16384; } if(parseInt > 16384) return; jDisplay.setText(OldDisplayString); DisplayState = -1; if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); resetbArray(); System.out.print("Weiche: "+parseInt + "gerade"); String s = "XT " + parseInt + " g 1\r"; Com.write(s); return; } //AktLokState = z.B. 3 20 0 r 1 0 0 1 String s = AktLokState.substring(AktLokState.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(0, s.indexOf(" ")); int Index; String str; if(s.contains("0")) { s = jDisplay.getText(); s = s.substring(0, 29); s += "*"; s += jDisplay.getText().substring(30); jDisplay.setText(s); Index = AktLokState.indexOf(" ")+1; s = AktLokState.substring(0,Index); str = AktLokState.substring(Index); s += str.substring(0, str.indexOf(" ")+1); str = str.substring(str.indexOf(" ")+1); s += str.substring(0, 4) + "1 "; AktLokState = s + str.substring(6, str.length()); Funktionen[0] = 1; } else { s = jDisplay.getText(); s = s.substring(0, 29); s += "-"; s += jDisplay.getText().substring(30); jDisplay.setText(s); Index = AktLokState.indexOf(" ")+1; s = AktLokState.substring(0,Index); str = AktLokState.substring(Index); s += str.substring(0, str.indexOf(" ")+1); str = str.substring(str.indexOf(" ")+1); s += str.substring(0, 4) + "0 "; AktLokState = s + str.substring(6, str.length()); Funktionen[0] = 0; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s = "XL " + AktLokState + "\r"; Com.write(s); }//GEN-LAST:event_jf1ActionPerformed private void jf2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf2ActionPerformed if(DisplayState == 0) { String text = jDisplay.getText(); int parseInt; String substring = text.substring(5, DisplayCursor); try { parseInt = Integer.parseInt(substring); } catch (NumberFormatException numberFormatException) { parseInt = 16384; } if(parseInt > 16384) return; jDisplay.setText(OldDisplayString); DisplayState = -1; if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); resetbArray(); System.out.print("Weiche: "+parseInt + "Abzweig"); String s = "XT " + parseInt + " r 1\r"; Com.write(s); return; } //AktLokState = z.B. 3 20 0 r 1 0 0 1 String s = AktLokState.substring(AktLokState.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(0, s.indexOf(" ")); int Index; String str; if(s.contains("0")) { s = jDisplay.getText(); s = s.substring(0, 30); s += "*"; s += jDisplay.getText().substring(31); jDisplay.setText(s); Index = AktLokState.indexOf(" ")+1; s = AktLokState.substring(0,Index); str = AktLokState.substring(Index); s += str.substring(0, str.indexOf(" ")+1); str = str.substring(str.indexOf(" ")+1); s += str.substring(0, 6) + "1 "; AktLokState = s + str.substring(8, str.length()); Funktionen[1] = 1; } else { s = jDisplay.getText(); s = s.substring(0, 30); s += "-"; s += jDisplay.getText().substring(31); jDisplay.setText(s); Index = AktLokState.indexOf(" ")+1; s = AktLokState.substring(0,Index); str = AktLokState.substring(Index); s += str.substring(0, str.indexOf(" ")+1); str = str.substring(str.indexOf(" ")+1); s += str.substring(0, 6) + "0 "; AktLokState = s + str.substring(8, str.length()); Funktionen[1] = 0; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s = "XL " + AktLokState + "\r"; Com.write(s); }//GEN-LAST:event_jf2ActionPerformed private void jf3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf3ActionPerformed //AktLokState = z.B. 3 20 0 r 1 0 0 1 String s = AktLokState.substring(AktLokState.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); s = s.substring(0, s.indexOf(" ")); int Index; String str; if(s.contains("0")) { s = jDisplay.getText(); s = s.substring(0, 31); s += "*"; s += jDisplay.getText().substring(32); jDisplay.setText(s); Index = AktLokState.indexOf(" ")+1; s = AktLokState.substring(0,Index); str = AktLokState.substring(Index); s += str.substring(0, str.indexOf(" ")+1); str = str.substring(str.indexOf(" ")+1); s += str.substring(0, 8) + "1 "; AktLokState = s + str.substring(10, str.length()); Funktionen[2] = 1; } else { s = jDisplay.getText(); s = s.substring(0, 31); s += "-"; s += jDisplay.getText().substring(32); jDisplay.setText(s); Index = AktLokState.indexOf(" ")+1; s = AktLokState.substring(0,Index); str = AktLokState.substring(Index); s += str.substring(0, str.indexOf(" ")+1); str = str.substring(str.indexOf(" ")+1); s += str.substring(0, 8) + "0 "; AktLokState = s + str.substring(10, str.length()); Funktionen[2] = 0; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s = "XL " + AktLokState + "\r"; Com.write(s); }//GEN-LAST:event_jf3ActionPerformed private void jf4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf4ActionPerformed //AktLokState = z.B. 3 20 0 r 1 0 0 1 String s = AktLokState.substring(AktLokState.indexOf(" ")+1); s = s.substring(s.lastIndexOf(" ")+1); int Index; String str; if(s.contains("0")) { s = jDisplay.getText(); s = s.substring(0, 32); s += "*"; s += jDisplay.getText().substring(33); jDisplay.setText(s); Index = AktLokState.indexOf(" ")+1; s = AktLokState.substring(0,Index); str = AktLokState.substring(Index); s += str.substring(0, str.indexOf(" ")+1); str = str.substring(str.indexOf(" ")+1); AktLokState = s + str.substring(0, 10) + "1"; Funktionen[3] = 1; } else { s = jDisplay.getText(); s = s.substring(0, 32); s += "-"; s += jDisplay.getText().substring(33); jDisplay.setText(s); Index = AktLokState.indexOf(" ")+1; s = AktLokState.substring(0,Index); str = AktLokState.substring(Index); s += str.substring(0, str.indexOf(" ")+1); str = str.substring(str.indexOf(" ")+1); AktLokState = s + str.substring(0, 10) + "0"; Funktionen[3] = 0; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s = "XL " + AktLokState + "\r"; Com.write(s); }//GEN-LAST:event_jf4ActionPerformed private void jf5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf5ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[4] == 0) { Funktionen[4] = 1; jf5.setBackground(Color.yellow); } else { Funktionen[4] = 0; jf5.setBackground(DefBackground); } String s = "XF " + AktLokAdr; for(int i = 0; i < 8; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf5ActionPerformed private void jf6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf6ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[5] == 0) { Funktionen[5] = 1; jf6.setBackground(Color.yellow); } else { Funktionen[5] = 0; jf6.setBackground(DefBackground); } String s = "XF " + AktLokAdr; for(int i = 0; i < 8; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf6ActionPerformed private void jf7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf7ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[6] == 0) { Funktionen[6] = 1; jf7.setBackground(Color.yellow); } else { Funktionen[6] = 0; jf7.setBackground(DefBackground); } String s = "XF " + AktLokAdr; for(int i = 0; i < 8; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf7ActionPerformed private void jf8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf8ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[7] == 0) { Funktionen[7] = 1; jf8.setBackground(Color.yellow); } else { Funktionen[7] = 0; jf8.setBackground(DefBackground); } String s = "XF " + AktLokAdr; for(int i = 0; i < 8; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf8ActionPerformed private void jf9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf9ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[8] == 0) { Funktionen[8] = 1; jf9.setBackground(Color.yellow); } else { Funktionen[8] = 0; jf9.setBackground(DefBackground); } String s = "XFX " + AktLokAdr; for(int i = 8; i < 16; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf9ActionPerformed private void jf11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf11ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[10] == 0) { Funktionen[10] = 1; jf11.setBackground(Color.yellow); } else { Funktionen[10] = 0; jf11.setBackground(DefBackground); } String s = "XFX " + AktLokAdr; for(int i = 8; i < 16; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf11ActionPerformed private void jf13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf13ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[12] == 0) { Funktionen[12] = 1; jf13.setBackground(Color.yellow); } else { Funktionen[12] = 0; jf13.setBackground(DefBackground); } String s = "XFX " + AktLokAdr; for(int i = 8; i < 16; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf13ActionPerformed private void jf14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf14ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[13] == 0) { Funktionen[13] = 1; jf14.setBackground(Color.yellow); } else { Funktionen[13] = 0; jf14.setBackground(DefBackground); } String s = "XFX " + AktLokAdr; for(int i = 8; i < 16; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf14ActionPerformed private void jf15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf15ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[14] == 0) { Funktionen[14] = 1; jf15.setBackground(Color.yellow); } else { Funktionen[14] = 0; jf15.setBackground(DefBackground); } String s = "XFX " + AktLokAdr; for(int i = 8; i < 16; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf15ActionPerformed private void jf16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jf16ActionPerformed if(AktLokAdr == 0) return; if(Funktionen[15] == 0) { Funktionen[15] = 1; jf16.setBackground(Color.yellow); } else { Funktionen[15] = 0; jf16.setBackground(DefBackground); } String s = "XFX " + AktLokAdr; for(int i = 8; i < 16; i++) { if(Funktionen[i] == 0) s += " 0"; else s += " 1"; } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s += "\r"; Com.write(s); }//GEN-LAST:event_jf16ActionPerformed private void jRueckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRueckActionPerformed //AktLokState = z.B. 3 20 0 r 1 0 0 1 String s = AktLokState.substring(AktLokState.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); AktLokState = AktLokState.substring(0, AktLokState.indexOf(" ")+1) + "0 " + s; jGeschwindigkeit.setValue(0); if(AktLokState.contains("f")) { s = jDisplay.getText(); s = s.substring(0, 12); s += "0 v"; s += jDisplay.getText().substring(16); jDisplay.setText(s); AktLokState = AktLokState.replace('f', 'r'); } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s = "XL " + AktLokState + "\r"; Com.write(s); }//GEN-LAST:event_jRueckActionPerformed private void jVorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jVorActionPerformed //AktLokState = z.B. 3 20 0 r 1 0 0 1 String s = AktLokState.substring(AktLokState.indexOf(" ")+1); s = s.substring(s.indexOf(" ")+1); AktLokState = AktLokState.substring(0, AktLokState.indexOf(" ")+1) + "0 " + s; jGeschwindigkeit.setValue(0); if(AktLokState.contains("r")) { s = jDisplay.getText(); s = s.substring(0, 12); s += "0 ^"; s += jDisplay.getText().substring(16); jDisplay.setText(s); AktLokState = AktLokState.replace('r', 'f'); } if(Com == null) { Com = KTUI.safelyOpenCom(this, Com); } KTUI.flushReadBuffer( Com ); s = "XL " + AktLokState + "\r"; Com.write(s); }//GEN-LAST:event_jVorActionPerformed private Boolean checkM3uidValid() { if( checkM3uidValidActive ) return false; checkM3uidValidActive = true; String sM3UID = ""+jTextM3UID.getText().trim(); if( debugLevel > 0 ) { System.out.println("checkM3uidValid sM3UID="+sM3UID); } if( sM3UID.length() == 0 ) { jTextM3UID.setText(sM3UID); // jTextM3UID.requestFocus(); checkM3uidValidActive = false; KTUI.mbGeneric( this, "Eingabefehler", "M3 UID ungültig", sM3UID, 9, true ); return false; } // int iM3UID = 0; long lM3UID = 0; // if not present add a hex prefix if( ! sM3UID.toUpperCase().startsWith("0X") ) { sM3UID = "0x"+sM3UID; } try { // iM3UID = Integer.decode(sM3UID); lM3UID = Long.decode(sM3UID); } catch (NumberFormatException ex) { System.out.println("checkM3uidValid NumberFormatException (LONG)" ); jTextM3UID.setText(sM3UID); KTUI.mbGeneric( this, "Eingabefehler", "M3 UID ungültig", sM3UID, 9, true ); jTextM3UID.requestFocus(); checkM3uidValidActive = false; return false; } if( debugLevel > 0 ) { System.out.println("checkM3uidValid lM3UID="+lM3UID ); System.out.println("checkM3uidValid l3UID=0x"+String.format("%8s", Long.toHexString( lM3UID )).replace(' ', '0')); } sM3UID = String.format("0x%8s", Long.toHexString( lM3UID )).replace(' ', '0'); if( sM3UID.length() > 10 ) { if( debugLevel > 0 ) { System.out.println("checkM3uidValid NumberFormatException (INTEGER)" ); } jTextM3UID.setText(sM3UID); KTUI.mbGeneric( this, "Eingabefehler", "M3 UID ungültig (zu groß)", sM3UID, 9, true ); jTextM3UID.requestFocus(); checkM3uidValidActive = false; return false; } jTextM3UID.setText(sM3UID); checkM3uidValidActive = false; return true; } public String checkM3uidValid( String sIn ) { if( (sIn == null) || (sIn.length() == 0) ) return null; String sM3UID = sIn.trim(); if( debugLevel > 2 ) { System.out.println("checkM3uidValid sM3UID="+sM3UID); } // int iM3UID = 0; long lM3UID = 0; // if not present add a hex prefix if( ! sM3UID.toUpperCase().startsWith("0X") ) { sM3UID = "0x"+sM3UID; } try { // iM3UID = Integer.decode(sM3UID); lM3UID = Long.decode(sM3UID); } catch (NumberFormatException ex) { System.out.println("checkM3uidValid NumberFormatException (LONG) sM3UID="+sM3UID ); return null; } if( debugLevel > 2 ) { System.out.println("checkM3uidValid l3UID=0x"+String.format("%8s", Long.toHexString( lM3UID )).replace(' ', '0')); } sM3UID = String.format("0x%8s", Long.toHexString( lM3UID )).replace(' ', '0'); if( sM3UID.length() > 10 ) { System.out.println("checkM3uidValid too long after conversion" ); return null; } return sM3UID; } private void startIOAction() { Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ) { stopIOAction(); return; } // Reset some variables sysIdx = 0; locIdx = 0; traIdx = 0; magIdx = 0; // set buttons for IO in progress jCancel.setEnabled(true); jUpdCancel.setEnabled(true); jKonfLesen.setEnabled(false); jKonfSchreiben.setEnabled(false); jWRsys.setEnabled(false); jWRloc.setEnabled(false); jWRtra.setEnabled(false); jWRmag.setEnabled(false); jKonfLaden.setEnabled(false); jKonfSichern.setEnabled(false); // loco tab (while writing m3sid/uid jLocDel.setEnabled(false); jLocDelAll.setEnabled(false); jLocCheck.setEnabled(false); jLocRepair.setEnabled(false); jLocM3sidWriteList.setEnabled(false); jLocM3cfgLoad.setEnabled(false); jLocM3cfgEdit.setEnabled(false); jLocM3cfgSave.setEnabled(false); jLoc2System.setEnabled(false); // disable some editable fields jLangePause.setEnabled(false); jDCC_Booster.setEnabled(false); jDCC_Loks.setEnabled(false); jRailcomTailbits.setEnabled(false); jRailcomIdNotify.setEnabled(false); jRailcomAccessory.setEnabled(false); jBoostOptNoAccDrive.setEnabled(false); jBoostOptNoAccBreak.setEnabled(false); jKurzEmpf.setEnabled(false); js88.setEnabled(false); jMinMag.setEnabled(false); jMaxMag.setEnabled(false); jTableLoco.setEnabled(false); jTableTraction.setEnabled(false); jTableAccessory.setEnabled(false); jUpdDatei.setEnabled(false); jUpdDateiAuswahl.setEnabled(false); jUpdStartUpdate.setEnabled(false); jEasyNetUpdate.setEnabled(false); jMRST.setEnabled(false); jDirektLesen.setEnabled(false); jListeLesen.setEnabled(false); jListeBearbeiten.setEnabled(false); jListeSchreiben.setEnabled(false); jDirektSchreiben.setEnabled(false); jm3Addr.setEnabled(false); jm3Schreiben.setEnabled(false); jMMRegister.setEnabled(false); jMMWert.setEnabled(false); jStartMMProg.setEnabled(false); // init progress bars jMcRwProgress.setValue(0); // set cursor to WAIT Cursor c = new Cursor(Cursor.WAIT_CURSOR); this.setCursor(c); //start timer timer.start(); } private void stopIOAction() { // stop timer timer.stop(); if( bReadCfg ) { bReadCfg = false; jMcRwInfo.setText("read config cancelled"); KTUI.mbConfigReadCancelled( this, 5 ); } if( bReadRC ) { bReadRC = false; jMcRwInfo.setText("read RC cancelled"); KTUI.mbConfigReadCancelled( this, 5 ); } if( bWriteCfg ) { bWriteCfg = false; jMcRwInfo.setText("write config cancelled"); KTUI.mbConfigWriteCancelled( this, 5 ); } if( bWriteM3sid ) { bWriteM3sid = false; jMcRwInfo.setText("write M3SID cancelled"); jMcM3Info.setText("write M3SID cancelled"); } if( bWriteM3sidList ) { bWriteM3sidList = false; jMcRwInfo.setText("write M3SID list cancelled"); jMcM3Info.setText("write M3SID list cancelled"); } if( bUpdate ) { bUpdate = false; KTUI.gsBaudRate = gsBaudRateSaved; if( KTUI.bSpracheDE ) jMcUpdInfo.setText("Aktualisierung abgebrochen"); else jMcUpdInfo.setText("update cancelled"); } if( bAskLokState ) { bAskLokState = false; } if( bReadPTdirekt ) { bReadPTdirekt = false; } if( bReadPTList ) { bReadPTList = false; } if( bWriteList ) { bWriteList = false; } if( bProg_m3 ) { bProg_m3 = false; } if( bProg_MM ) { bProg_MM = false; } // set buttons to normal operation jKonfLesen.setEnabled(true); jKonfSchreiben.setEnabled(true); jWRsys.setEnabled(true); jWRloc.setEnabled(true); jWRtra.setEnabled(true); jWRmag.setEnabled(true); jKonfLaden.setEnabled(true); jKonfSichern.setEnabled(true); jCancel.setEnabled(false); jUpdCancel.setEnabled(false); // (re-)enable some editable fields jLangePause.setEnabled(true); jDCC_Booster.setEnabled(true); jDCC_Loks.setEnabled(true); jRailcomTailbits.setEnabled(true); jRailcomIdNotify.setEnabled(true); jRailcomAccessory.setEnabled(true); if( KlarTextUI.bUseSo999 ) { jBoostOptNoAccDrive.setEnabled(true); jBoostOptNoAccBreak.setEnabled(true); } jKurzEmpf.setEnabled(true); js88.setEnabled(true); jMinMag.setEnabled(true); jMaxMag.setEnabled(true); jTableLoco.setEnabled(true); jTableTraction.setEnabled(true); jTableAccessory.setEnabled(true); // loco tab (while writing m3sid/uid jLocDel.setEnabled(true); jLocDelAll.setEnabled(true); jLocCheck.setEnabled(true); jLocRepair.setEnabled(true); if( M3used > 0 ) { jLocM3sidWriteList.setEnabled(true); } jLocM3cfgLoad.setEnabled(true); jLocM3cfgEdit.setEnabled(true); jLocM3cfgSave.setEnabled(true); jLoc2System.setEnabled(true); jUpdDatei.setEnabled(true); jUpdDateiAuswahl.setEnabled(true); jUpdStartUpdate.setEnabled(true); jEasyNetUpdate.setEnabled(true); jMRST.setEnabled(true); if( ! jHauptGleis.isSelected() ) { jDirektLesen.setEnabled(true); jListeLesen.setEnabled(true); } jListeBearbeiten.setEnabled(true); jListeSchreiben.setEnabled(true); jDirektSchreiben.setEnabled(true); jm3Addr.setEnabled(true); jm3Schreiben.setEnabled(true); jMMRegister.setEnabled(true); jMMWert.setEnabled(true); jStartMMProg.setEnabled(true); // set cursor Cursor c = new Cursor(Cursor.DEFAULT_CURSOR ); setCursor(c); // close interface /* TODO auch hier ??? */ Com = KTUI.safelyCloseCom( this, Com); } private void updateS88field( int num ) { KTUI.setNumS88(num); js88.setText(""+num); jSysS88monitor.setEnabled(num > 0); } public void readS88num() { if( debugLevel > 0 ) { System.out.println("readS88num()" ); } Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ){ System.out.println("readS88num() Com == null" ); return; } KTUI.flushReadBuffer(Com); String s = "XSE\r"; Com.write(s); timer.setInitialDelay(KlarTextUI.MCtimer1); timer.setDelay(KlarTextUI.MCtimer2); retries = KlarTextUI.timerRetries; bWaitAnswerInProgress = true; bReadS88num = true; startIOAction(); } public void initS88read() { if( debugLevel > 0 ) { System.out.println("initS88read()" ); } Com = KTUI.safelyOpenCom( this, Com ); if( Com == null ){ System.out.println("initS88read() Com == null" ); return; } KTUI.flushReadBuffer(Com); String s = "XSR 0\r"; Com.write(s); timer.setInitialDelay(KlarTextUI.MCtimer1); timer.setDelay(KlarTextUI.MCtimer2); startIOAction(); jCancel.setEnabled(false); jUpdCancel.setEnabled(false); jKonfLesen.setEnabled(false); jSysS88monitor.setEnabled(false); } public void startS88read() { if( Com == null ){ System.out.println("startS88read() ERROR Com == null" ); return; } if( debugLevel > 1 ) { System.out.println("startS88read() moduleNr "+this.modulNr ); } if( this.modulNr <= 0 ) { System.out.println("startS88read() moduleNr="+this.modulNr+" <= 0 -> skip reading" ); return; } String s = "XSS "+this.modulNr+"\r"; Com.write(s); resetbArray(); retries = KlarTextUI.timerRetries; bWaitAnswerInProgress = true; bReadS88value = true; timer.start(); } public void stopS88read() { if( debugLevel > 0 ) { System.out.println("stopS88read()" ); } stopIOAction(); jSysS88monitor.setEnabled(true); bReadS88value = false; } public void pauseS88read() { if( debugLevel > 1 ) { System.out.println("pauseS88read()" ); } timer.stop(); bReadS88value = false; } private boolean checkS88num( byte[] bArray, int num ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = | |\r|\\000"); if( debugLevel > 1 ) { for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkS88num strParts["+i+"]=\""+strParts[i]+"\""+((strParts[i].startsWith("]"))?" (ENDE)":"" )); } } if( strParts.length == 3) { if( strParts[0].startsWith("SE") && strParts[2].startsWith("]") ) { // answer is complete ! // answer is number of 8 sensor modules ! System.out.println("checkS88num strParts[1]=\""+strParts[1]+"\""); int num8 = Integer.parseInt(strParts[1]); int num16 = (num8+1)/2 ; System.out.println("checkS88num #modules(16)="+num16); updateS88field(num16); return true; } } return false; } private boolean checkS88read( byte[] bArray, int num ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = | |\r|\\000"); if( debugLevel > 1 ) { for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkS88read strParts["+i+"]=\""+strParts[i]+"\""+((strParts[i].startsWith("]"))?" (ENDE)":"" )); } } if( strParts.length == 9) { if( strParts[8].startsWith("]") ) { // answer is complete ! if( debugLevel > 2 ) { System.out.println("checkS88read strParts.length="+strParts.length+" strParts["+(strParts.length-1)+"]=["+strParts[strParts.length-1]+"] COMPLETE"); } int readMod = Integer.parseInt(strParts[1].substring(1)); if( readMod != this.modulNr ) { System.out.println("checkS88read: wanted #"+modulNr+" read #"+readMod+" -> ignore"); return true; } int newValue = 0; for( int j = 0 ; j <= 7 ; j++ ) { if( strParts[6].charAt(7-j) == '1' ) { newValue |= (1 << j) ; } if( strParts[7].charAt(7-j) == '1' ) { newValue |= (1 << (j+8)) ; } } // first check for changes by user... int shownValue = S88mon.getShownValue(); if( shownValue != moduleValue ) { // reset to correct value System.out.println("checkS88read moduleNr "+modulNr+" :"+ " shownValue="+shownValue+" != moduleValue="+moduleValue ); if( S88mon != null ) { if( debugLevel > 0 ) { System.out.println("checkS88read redrawValues()"); } S88mon.redrawValues(); } else { System.out.println("checkS88read S88mon == null, no redraw"); } } int oldValue = moduleValue; moduleValue |= newValue; if( moduleValue != oldValue ) { if( debugLevel > 1 ) { System.out.println("checkS88read moduleNr "+modulNr+" :"+ " len6="+ strParts[6].length()+" "+strParts[6]+ " len7="+ strParts[7].length()+" "+strParts[7] ); } if( debugLevel > 0 ) { System.out.printf("checkS88read value changed: old %s new %s moduleValue %s\n", String.format("%16s", Integer.toBinaryString(oldValue)).replace(' ', '0'), String.format("%16s", Integer.toBinaryString(newValue)).replace(' ', '0'), String.format("%16s", Integer.toBinaryString(moduleValue)).replace(' ', '0')); } if( S88mon != null ) { if( debugLevel > 0 ) { System.out.println("checkS88read redrawValues()"); } S88mon.redrawValues(); } else { System.out.println("checkS88read S88mon == null, no redraw"); } } return true; } } return false; } private boolean checkTableLoco( boolean repair, boolean show ) { boolean retVal = true; String errorIdxList = ""; bFalscheEingabe = false; String sAdr = ""; String sFS = ""; String sFormat = ""; String sName = ""; for( int localLocIdx = 0 ; localLocIdx < c.MAX_LOCS; localLocIdx++) { sAdr = ""; sFS = ""; sFormat = ""; sName = ""; if( debugLevel >= 2 ) { System.out.println("check: loco ("+(localLocIdx+1)+"/"+c.MAX_LOCS+")" ); } // check parameters Object oAdr = jTableLoco.getValueAt(localLocIdx, 0); if( oAdr != null ) sAdr += oAdr; if( sAdr.trim().length() > 0 ) { Object oFS = jTableLoco.getValueAt( localLocIdx, 1); Object oFormat = jTableLoco.getValueAt( localLocIdx, 2); Object oName = jTableLoco.getValueAt( localLocIdx, 3); if( oFS != null ) sFS += oFS; if( oFormat != null ) sFormat += oFormat; if(oName != null) sName += oName; // 1st check protocol format sFormat = sFormat.trim().toUpperCase(); jTableLoco.setValueAt( sFormat, localLocIdx, 2); switch( sFormat ) { case "DCC": if( ! KTUI.checkNumRange( sAdr, 1, 10239 ) ) { if( repair ) { oAdr = 3; jTableLoco.setValueAt( ""+oAdr, localLocIdx, 0); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0001; errorIdxList += " " + (localLocIdx+1); } break; case "MM1": case "MM2": if( ! KTUI.checkNumRange( sAdr, 1, 255 ) ) { if( repair ) { oAdr = 3; jTableLoco.setValueAt( ""+oAdr, localLocIdx, 0); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0002; errorIdxList += " " + (localLocIdx+1); } break; case "M3": if( ! KTUI.checkNumRange( sAdr, 1, c.MAX_M3_SID ) ) { if( repair ) { oAdr = 3; jTableLoco.setValueAt( ""+oAdr, localLocIdx, 0); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0004; errorIdxList += " " + (localLocIdx+1); } break; default: // others if( repair ) { sFS = "28"; jTableLoco.setValueAt(sFS, localLocIdx, 1); sFormat = "DCC"; jTableLoco.setValueAt(sFormat, localLocIdx, 2); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0008; errorIdxList += " " + (localLocIdx+1); if( ! KTUI.checkNumRange( sAdr, 1, 10239 ) ) { if( repair ) { oAdr = 3; jTableLoco.setValueAt( ""+oAdr, localLocIdx, 0); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0001; errorIdxList += " " + (localLocIdx+1); } break; } // 2nd check speed steps according to format switch( sFormat.toUpperCase() ) { case "DCC": switch( sFS.toLowerCase() ) { case "14": case "28": case "126": break; default: if( repair ) { sFS = "14"; jTableLoco.setValueAt( sFS, localLocIdx, 1); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0010; errorIdxList += " " + (localLocIdx+1); } break; case "MM1": case "MM2": switch( sFS.toLowerCase() ) { case "14": case "27a": case "27b": break; default: if( repair ) { sFS = "14"; jTableLoco.setValueAt( sFS, localLocIdx, 1); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0010; errorIdxList += " " + (localLocIdx+1); } break; case "M3": switch( sFS.toLowerCase() ) { case "126": break; default: if( repair ) { sFS = "126"; jTableLoco.setValueAt( sFS, localLocIdx, 1); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0010; errorIdxList += " " + (localLocIdx+1); } break; } // 3rd check name if(sName.length() > c.MAX_LOC_NAME_LENGTH) { sName = sName.substring(0, c.MAX_LOC_NAME_LENGTH); if( repair ) { jTableLoco.setValueAt(sName, localLocIdx, 3); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0020; errorIdxList += " " + (localLocIdx+1); } } } if( errorIdxList.trim().length() > 0 ) { String[] szArr = errorIdxList.trim().split(" "); System.out.println("jTableLoco errorIdxList=["+errorIdxList+"]"); System.out.println("jTableLoco "+szArr.length+" fehlerhafte Zeilen: " ); if( szArr.length > 0 ) { jTableLoco.clearSelection(); for( int i = 0 ; i < szArr.length ; i++ ) { System.out.println("jTableLoco szArr["+i+"]=\""+ szArr[i]+"\"" ); int selection = Integer.parseInt(szArr[i])-1; jTableLoco.addRowSelectionInterval(selection, selection); } } } if( retVal ) { if( show ) { KTUI.mbTableCheckOK( this, repair, 3 ); } } else { KTUI.mbTableCheck( this, FehlerArt, repair, errorIdxList ); } if( debugLevel >= 2 ) { System.out.println("checkTableLoco returns["+(retVal?"true":"false")+"]"); } return retVal; } private boolean checkTableTraction( boolean repair, boolean show ) { boolean retVal = true; String errorIdxList = ""; bFalscheEingabe = false; for( int localTraIdx = 0 ; localTraIdx < c.MAX_TRACTIONS; localTraIdx++) { if( debugLevel >= 2 ) { System.out.println("check: traction ("+(localTraIdx+1)+"/"+c.MAX_TRACTIONS+")" ); } // check parameters String sAdr1 = ""+jTableTraction.getValueAt(localTraIdx, 0); String sNam1 = ""+jTableTraction.getValueAt(localTraIdx, 1); String sAdr2 = ""+jTableTraction.getValueAt(localTraIdx, 2); String sNam2 = ""+jTableTraction.getValueAt(localTraIdx, 3); // cleanup any problem strings (from previous tests) if( sNam1.equals(c.ERR_PROBLEM_LEFT) ) { jTableTraction.setValueAt("", localTraIdx, 1); } if( sNam2.equals(c.ERR_PROBLEM_LEFT) ) { jTableTraction.setValueAt("", localTraIdx, 3); } if( repair ) { String sTmp; sTmp = sAdr1.replaceAll("\\s",""); if( ! sAdr1.matches(sTmp)) { // difference in address strings // write back to table jTableTraction.setValueAt(sTmp, localTraIdx, 0); // reread for further usage... sAdr1 = ""+jTableTraction.getValueAt(localTraIdx, 0); } sTmp = sAdr2.replaceAll("\\s",""); if( ! sAdr2.matches(sTmp)) { // difference in address strings // write back to table jTableTraction.setValueAt(sTmp, localTraIdx, 2); // reread for further usage... sAdr2 = ""+jTableTraction.getValueAt(localTraIdx, 2); } } if( sAdr1.length() > 0 ) { if( sAdr1.substring(sAdr1.length()-1, sAdr1.length()).matches("!") ) { sAdr1 = sAdr1.substring(0, sAdr1.length()-1); } if( ! KTUI.checkNumRange( sAdr1, 1, c.MAX_M3_SID ) ) { jTableTraction.setValueAt(c.ERR_PROBLEM_LEFT, localTraIdx, 1); retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0040; errorIdxList += " " + (localTraIdx+1); } else { jTableTraction.setValueAt("", localTraIdx, 1); for(int l = 0; l < c.MAX_LOCS; l++) { if(sAdr1.matches(""+jTableLoco.getValueAt(l, 0))) jTableTraction.setValueAt(jTableLoco.getValueAt(l, 3), localTraIdx, 1); } } } if( sAdr2.length() > 0) { if( sAdr2.substring(sAdr2.length()-1, sAdr2.length()).matches("!") ) { sAdr2 = sAdr2.substring(0, sAdr2.length()-1); } if( ! KTUI.checkNumRange( sAdr2, 1, c.MAX_M3_SID ) ) { jTableTraction.setValueAt(c.ERR_PROBLEM_LEFT, localTraIdx, 3); retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0040; errorIdxList += " " + (localTraIdx+1); } else { jTableTraction.setValueAt("", localTraIdx, 3); for(int l = 0; l < c.MAX_LOCS; l++) { if(sAdr2.matches(""+jTableLoco.getValueAt(l, 0))) jTableTraction.setValueAt(jTableLoco.getValueAt(l, 3), localTraIdx, 3); } } } if( sAdr1.length() == 0 && sAdr2.length() > 0 ) { jTableTraction.setValueAt(c.ERR_PROBLEM_LEFT, localTraIdx, 1); retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0040; errorIdxList += " " + (localTraIdx+1); } if( sAdr1.length() > 0 && sAdr2.length() == 0 ) { jTableTraction.setValueAt(c.ERR_PROBLEM_LEFT, localTraIdx, 3); retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0040; errorIdxList += " " + (localTraIdx+1); } } if( errorIdxList.trim().length() > 0 ) { String[] szArr = errorIdxList.trim().split(" "); System.out.println("checkTableTraction errorIdxList=["+errorIdxList+"]"); System.out.println("checkTableTraction "+szArr.length+" fehlerhafte Zeilen: " ); if( szArr.length > 0 ) { jTableTraction.clearSelection(); for( int i = 0 ; i < szArr.length ; i++ ) { System.out.println("checkTableTraction szArr["+i+"]=\""+ szArr[i]+"\"" ); int selection = Integer.parseInt(szArr[i])-1; jTableTraction.addRowSelectionInterval(selection, selection); } } } if( bFalscheEingabe ) { KTUI.mbTableCheck( this, FehlerArt, false, errorIdxList ); } else { if( show ) { KTUI.mbTableCheckOK( this, repair, 3 ); } } if( debugLevel >= 2 ) { System.out.println("checkTableTraction returns["+retVal+"]"); } return retVal; } private boolean checkTableAccessory( boolean repair, boolean show ) { boolean retVal = true; String errorIdxList = ""; bFalscheEingabe = false; for( int localMagIdx = 0 ; localMagIdx < c.MAX_MM1_ACCMOD; localMagIdx++) { if( debugLevel >= 2 ) { System.out.println("check: accessory ("+(localMagIdx+1)+"/"+c.MAX_MM1_ACCMOD+")" ); } // check parameters String sIdx = (""+jTableAccessory.getValueAt(localMagIdx, 0)).trim(); String sFmt = (""+jTableAccessory.getValueAt(localMagIdx, 1)).trim(); if( (sIdx.length() > 0) && (sFmt.length() > 0) ) { int n = -1; String[] sArr = sIdx.split(" "); if( KTUI.checkNumRange(sArr[0], 1, c.MAX_MM1_ACCMOD)) { n = KTUI.checkAndGetStrNumRangeDef( null, sArr[0], 1, c.MAX_MM1_ACCMOD, 0, false); } else { if( repair ) { // jTableAccessory.setValueAt("", localMagIdx, 0); jTableAccessory.setValueAt( sModAdr(0), localMagIdx, 0); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0080; errorIdxList += " " + (localMagIdx+1); } // internal module# is 0 based -> 1 less than tableIdx n sFmt = sFmt.toUpperCase(); switch( sFmt ) { case "DCC": case "MM": break; default: if( sFmt.startsWith("D") ) sFmt = "DCC"; else sFmt = "MM"; if( repair ) { jTableAccessory.setValueAt(sFmt, localMagIdx, 1); } retVal = false; bFalscheEingabe = true; FehlerArt |= 0x0080; errorIdxList += " " + (localMagIdx+1); } } } if( errorIdxList.trim().length() > 0 ) { String[] szArr = errorIdxList.trim().split(" "); System.out.println("jTableAccessory errorIdxList=["+errorIdxList+"]"); System.out.println("jTableAccessory "+szArr.length+" fehlerhafte Zeilen: " ); if( szArr.length > 0 ) { jTableAccessory.clearSelection(); for( int i = 0 ; i < szArr.length ; i++ ) { System.out.println("jTableAccessory szArr["+i+"]=\""+ szArr[i]+"\"" ); int selection = Integer.parseInt(szArr[i])-1; jTableAccessory.addRowSelectionInterval(selection, selection); } } } if( retVal ) { if( show ) { KTUI.mbTableCheckOK( this, repair, 3 ); } } else { KTUI.mbTableCheck( this, FehlerArt, repair, errorIdxList ); } if( debugLevel >= 2 ) { System.out.println("checkTableAccessory returns["+retVal+"]" ); } return retVal; } private Boolean readM3() { if( debugLevel > 0 ) { System.out.println("Read M3 data from DIR: "+KTUI.gsSaveOpenM3Directory+" NAME: \""+KTUI.gsSaveOpenM3Filename+"\"" ); } if( (KTUI.gsSaveOpenM3Filename.length() <= 1) && (KTUI.gsSaveOpenM3Filename.contentEquals(" ")) ) { System.out.println("Read M3 data from DIR: "+KTUI.gsSaveOpenM3Directory+" NAME is empty :\""+KTUI.gsSaveOpenM3Filename+"\"" ); return false; } String filenameM3 = KTUI.gsSaveOpenM3Directory+"/"+KTUI.gsSaveOpenM3Filename; File f = new File( filenameM3 ); long filelen = f.length(); if( debugLevel > 0 ) { System.out.println("Read M3 data from file: "+filenameM3+" ("+filelen+" bytes)" ); } //Datei lesen String s = ""; char ac[] = new char[(int)filelen+1]; if(f.isFile()) { FileReader inputStream = null; try { try { inputStream = new FileReader(f); try { int n = inputStream.read(ac, 0, (int) filelen); if(n == -1) { KTUI.mbFileReadError(this); return false; } String str1 = new String(ac); ReturnString = str1.substring(0, n); } catch (IOException ex) { Logger.getLogger(SaveOpenDialog.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException ex) { Logger.getLogger(SaveOpenDialog.class.getName()).log(Level.SEVERE, null, ex); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { Logger.getLogger(SaveOpenDialog.class.getName()).log(Level.SEVERE, null, ex); } } } } else { KTUI.mbFileNotFound( this, filenameM3 ); return false; } updateM3uid(); return true; } public void updateM3uid() { System.out.println("updateM3uid: Gelesen "+ReturnString.length()+" Bytes"); if( (ReturnString == null) || (ReturnString.length() == 0) ) { // nichts gelesen oder es wurde geschrieben ! return; } String[] strArr = ReturnString.split("\r\n"); int n = strArr.length; System.out.println("updateM3uid: Gelesen "+ReturnString.length()+" Bytes, "+n+" Zeilen"); Boolean parseData = false; for( int i = 0 ; i < n ; i++ ) { String[] zeilenArr = strArr[i].split(","); if( zeilenArr.length == 0 ) { // empty line continue; } if( zeilenArr[0].equalsIgnoreCase("[M3UID]")) { // M3UID-Tabelle startet // setze altes Array auf 0 M3used = 0; updateM3count(); parseData = true; continue; } if( parseData == false ) { // no valid section header -> skip line continue; } if( zeilenArr[0].trim().startsWith("[")) { System.out.println("updateM3uid: Ende nach "+M3used+" Datensätzen"); if( debugLevel > 0 ) { KTUI.mbConfigReadSuccess( this, 3 ); } ReturnString = ""; jLocM3sidWriteList.setEnabled(true); locoTableSelRow = jTableLoco.getSelectedRow(); if( locoTableSelRow >= 0 ) { checkM3sid(locoTableSelRow); } return; } if( zeilenArr.length < 2 ) { // less than 2 item -> skip line continue; } // check for data String sM3UID = checkM3uidValid(zeilenArr[0]); if( (sM3UID != null) && KTUI.checkNumRange(zeilenArr[1].trim(), 1, c.MAX_M3_SID) ) { M3liste[0][M3used] = sM3UID; M3liste[1][M3used] = ""+Integer.parseInt(zeilenArr[1].trim()); if( strArr.length > 2 ) { // alles nach dem 2. Komma (nur einmal trim um Alles !) int jIdx = strArr[i].indexOf(","); jIdx = strArr[i].indexOf(",", jIdx+1); String rest = strArr[i].substring(jIdx+1); M3liste[2][M3used] = rest.trim(); } else { M3liste[2][M3used] = ""; } M3used++; } updateM3count(); if( M3used == c.MAX_M3_ENTRIES) { KTUI.mbM3TooMany(this); KTUI.mbConfigReadAbort( this, 5 ); ReturnString = ""; return; } } System.out.println("updateM3uid: Ende nach "+M3used+" Datensätzen"); updateM3count(); if( debugLevel > 0 ) { KTUI.mbConfigReadSuccess( this, 3 ); } jLocM3cfgSave.setEnabled(true); ReturnString = ""; jLocM3sidWriteList.setEnabled(true); locoTableSelRow = jTableLoco.getSelectedRow(); if( locoTableSelRow >= 0 ) { checkM3sid(locoTableSelRow); } } public void updateM3count() { jM3count.setText("( "+M3used+" )"); return; } void delMultipleLocoLines() { int selRow = -1; try { selRow = jTableLoco.getSelectedRow(); } catch (IndexOutOfBoundsException ex) { System.out.println("delMultipleLocoLines IndexOutOfBoundsException"); } if( selRow == -1 ) { // no valid selection -> leave System.out.println("delMultipleLocoLines invalid selection (no row seletced) selRow="+selRow ); return; } int[] selMulti = jTableLoco.getSelectedRows(); int selMultiLength = selMulti.length; jTableLoco.getSelectionModel().clearSelection(); System.out.println("Loco_Liste selMultiLength="+selMultiLength); for( int i = (selMultiLength-1) ; i >= 0 ; i int row = selMulti[i]; int viewRow = jTableLoco.convertRowIndexToModel(row); System.out.println("Loco_Liste DELETE selMulti["+i+"] row="+row+" viewRow="+viewRow); delOneLocoLine( row ); // set a selected row only if we had a single selection if( selMultiLength == 1 ) { // set selection to previous selection System.out.println("Loco_Liste set selection to row="+row); jTableLoco.setRowSelectionInterval(row, row); } } System.out.println("delMultipleLocoLines END"); } void delOneLocoLine( int selRow ) { if( selRow == -1 ) { return; } // unset current cell selection to allow moving cell contents jTableLoco.getSelectionModel().clearSelection(); if( jTableLoco.isEditing() ) { jTableLoco.getCellEditor().stopCellEditing(); } // delete selRow by moving all following rows 1 to front... for (int k = selRow; k < (c.MAX_LOCS - 1); k++) { Object o = jTableLoco.getValueAt(k+1, 0); jTableLoco.setValueAt(o, k, 0); o = jTableLoco.getValueAt(k+1, 1); jTableLoco.setValueAt(o, k, 1); o = jTableLoco.getValueAt(k+1, 2); jTableLoco.setValueAt(o, k, 2); o = jTableLoco.getValueAt(k+1, 3); jTableLoco.setValueAt(o, k, 3); } // ... and set last to defaults jTableLoco.setValueAt("", (c.MAX_LOCS - 1), 0); jTableLoco.setValueAt("", (c.MAX_LOCS - 1), 1); jTableLoco.setValueAt("", (c.MAX_LOCS - 1), 2); jTableLoco.setValueAt("", (c.MAX_LOCS - 1), 3); } void delMultipleTractionLines() { System.out.println("delMultipleTractionLines START"); int selRow = -1; try { selRow = jTableTraction.getSelectedRow(); } catch (IndexOutOfBoundsException ex) { System.out.println("delMultipleTractionLines IndexOutOfBoundsException"); } if( selRow == -1 ) { // no valid selection -> leave System.out.println("delMultipleTractionLines invalid selection (no row seletced) selRow="+selRow ); return; } int[] selMulti = jTableTraction.getSelectedRows(); int selMultiLength = selMulti.length; jTableTraction.getSelectionModel().clearSelection(); System.out.println("Traction_Liste selMultiLength="+selMultiLength); for( int i = (selMultiLength-1) ; i >= 0 ; i int row = selMulti[i]; int viewRow = jTableTraction.convertRowIndexToModel(row); System.out.println("Traction_Liste DELETE selMulti["+i+"] row="+row+" viewRow="+viewRow); delOneTractionLine( row ); // set a selected row only if we had a single selection if( selMultiLength == 1 ) { // set selection to previous selection System.out.println("Traction_Liste set selection to row="+row); jTableTraction.setRowSelectionInterval(row, row); } } System.out.println("delMultipleTractionLines END"); } void delOneTractionLine( int selRow ) { if( selRow == -1 ) { return; } // unset current cell selection to allow moving cell contents jTableTraction.getSelectionModel().clearSelection(); if( jTableTraction.isEditing() ) { jTableTraction.getCellEditor().stopCellEditing(); } // delete selRow by moving all following rows 1 to front... for (int k = selRow; k < (c.MAX_TRACTIONS - 1); k++) { Object o = jTableTraction.getValueAt(k+1, 0); jTableTraction.setValueAt(o, k, 0); o = jTableTraction.getValueAt(k+1, 1); jTableTraction.setValueAt(o, k, 1); o = jTableTraction.getValueAt(k+1, 2); jTableTraction.setValueAt(o, k, 2); o = jTableTraction.getValueAt(k+1, 3); jTableTraction.setValueAt(o, k, 3); } // ... and set last to defaults jTableTraction.setValueAt("", (c.MAX_TRACTIONS - 1), 0); jTableTraction.setValueAt("", (c.MAX_TRACTIONS - 1), 1); jTableTraction.setValueAt("", (c.MAX_TRACTIONS - 1), 2); jTableTraction.setValueAt("", (c.MAX_TRACTIONS - 1), 3); } void setFocusUpdStart() { if( KTUI.bSpracheDE ) { jMcUpdInfo.setText("Aktualisierung kann gestartet werden"); } else { jMcUpdInfo.setText("you may start the update"); } jUpdStartUpdate.grabFocus(); } void setFocusDateiAuswahl() { if( KTUI.bSpracheDE ) { jMcUpdInfo.setText("Bitte Datei auswählen"); } else { jMcUpdInfo.setText("please select file"); } jUpdDateiAuswahl.grabFocus(); } void reCheckVersionInfo() { String jVer = jVersion.getText(); byte[] bVersion = jVer.replace(".", "").getBytes(); System.out.println("jVer="+jVer+" bVersion.length="+bVersion.length ); if( bVersion.length < 3 ) { System.out.println("Version too short! jVer="+jVer ); return; } long lSwVersion = 0; lSwVersion += (long)(((bVersion[0] & 0xFF)-'0') << 24 ); lSwVersion += (long)(((bVersion[1] & 0xFF)-'0') << 16 ); lSwVersion += (long)(((bVersion[2] & 0xFF)-'0') << 8 ); if( bVersion.length > 3 ) { lSwVersion += (long) (bVersion[3] & 0xFF); } KlarTextUI.bUseXfuncs = ( lSwVersion >= c.MIN_MC_XFUNCS_VERSION ); KlarTextUI.bUseXm3sid = ( lSwVersion >= c.MIN_MC_XM3SID_VERSION ); KlarTextUI.bUseSo999 = ( lSwVersion >= c.MIN_MC_SO999_VERSION ); jBoostOptNoAccDrive.setEnabled(KlarTextUI.bUseSo999); jBoostOptNoAccBreak.setEnabled(KlarTextUI.bUseSo999); KTUI.fwVersion = jVer; String sSwVersion = "MasterControl Version "+KTUI.fwVersion; System.out.println(" if( lSwVersion > 0 ) { System.out.println("lSwVersion="+lSwVersion+" in HEX="+String.format("0x%16s", Long.toHexString(lSwVersion)).replace(' ', '0') ); System.out.println("bUseXfuncs="+KlarTextUI.bUseXfuncs+" bUseXm3sid="+KlarTextUI.bUseXm3sid+" bUseSo999="+KlarTextUI.bUseSo999); } KTUI.fillMenuSelection(); } void updateTabs() { int idx = jTabbedPane1.getSelectedIndex(); for( int i = 0 ; i < jTabbedPane1.getComponentCount() ; i ++ ) { jTabbedPane1.setSelectedIndex(i); } jTabbedPane1.setSelectedIndex(idx); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Firmware; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.ButtonGroup buttonGroup2; private javax.swing.ButtonGroup buttonGroup3; private javax.swing.ButtonGroup buttonGroup4; private javax.swing.JButton helpHC; private javax.swing.JButton helpLC; private javax.swing.JButton helpMC; private javax.swing.JButton helpMCasLC; private javax.swing.JButton helpPC; private javax.swing.JButton helpSNC; private javax.swing.JButton helpWasIstWas; private javax.swing.JButton helpXNC; private javax.swing.JButton j0; private javax.swing.JButton j1; private javax.swing.JButton j2; private javax.swing.JButton j3; private javax.swing.JButton j4; private javax.swing.JButton j5; private javax.swing.JButton j6; private javax.swing.JButton j7; private javax.swing.JButton j8; private javax.swing.JButton j9; private javax.swing.JTextField jBaud; private javax.swing.JLabel jBild; private javax.swing.JLabel jBild2; private javax.swing.JCheckBox jBoostOptNoAccBreak; private javax.swing.JCheckBox jBoostOptNoAccDrive; private javax.swing.JLabel jBoosterOpts; private javax.swing.JList jCVListe; private javax.swing.JTextField jCV_Direkt; private javax.swing.JButton jCancel; private javax.swing.JButton jClose; private javax.swing.JCheckBox jDCC_Booster; private javax.swing.JCheckBox jDCC_Loks; private javax.swing.JTextField jDatenQuelle; private javax.swing.JTextField jDecAdr; private javax.swing.JButton jDirektLesen; private javax.swing.JButton jDirektSchreiben; private javax.swing.JTextArea jDisplay; private javax.swing.JButton jEasyNetUpdate; private javax.swing.JButton jGO; private javax.swing.JSlider jGeschwindigkeit; private javax.swing.JTextField jHardWare; private javax.swing.JRadioButton jHauptGleis; private javax.swing.JTextField jHerstellerInfo; private javax.swing.JButton jKonfLaden; private javax.swing.JButton jKonfLesen; private javax.swing.JButton jKonfSchreiben; private javax.swing.JButton jKonfSichern; private javax.swing.JTextField jKurzEmpf; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel34; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JLabel jLabelM3SID; private javax.swing.JLabel jLabelM3UID; private javax.swing.JCheckBox jLangePause; private javax.swing.JButton jListeBearbeiten; private javax.swing.JButton jListeLesen; private javax.swing.JButton jListeSchreiben; private javax.swing.JButton jLoc2System; private javax.swing.JButton jLocCheck; private javax.swing.JButton jLocDel; private javax.swing.JButton jLocDelAll; private javax.swing.JButton jLocM3cfgEdit; private javax.swing.JButton jLocM3cfgLoad; private javax.swing.JButton jLocM3cfgSave; private javax.swing.JButton jLocM3sidWrite; private javax.swing.JButton jLocM3sidWriteList; private javax.swing.JButton jLocRepair; private javax.swing.JPanel jLoks; private javax.swing.JLabel jM3count; private javax.swing.JTextField jMCU; private javax.swing.JButton jMDCC; private javax.swing.JButton jMMM; private javax.swing.JTextField jMMRegister; private javax.swing.JTextField jMMWert; private javax.swing.JButton jMRST; private javax.swing.JButton jMag2System; private javax.swing.JButton jMagCheck; private javax.swing.JButton jMagRepair; private javax.swing.JPanel jMagnetartikel; private javax.swing.JTextField jMaxMag; private javax.swing.JTextField jMcM3Info; private javax.swing.JProgressBar jMcM3Progress; private javax.swing.JLabel jMcRwInfo; private javax.swing.JProgressBar jMcRwProgress; private javax.swing.JLabel jMcUpdInfo; private javax.swing.JProgressBar jMcUpdProgress; private javax.swing.JTextField jMinMag; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JRadioButton jProgGleis; private javax.swing.JCheckBox jRailcomAccessory; private javax.swing.JCheckBox jRailcomIdNotify; private javax.swing.JLabel jRailcomSupport; private javax.swing.JCheckBox jRailcomTailbits; private javax.swing.JButton jRaute; private javax.swing.JButton jRueck; private javax.swing.JButton jSTOP; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JTextField jSerNr; private javax.swing.JButton jStartMMProg; private javax.swing.JButton jStern; private javax.swing.JButton jSysS88monitor; private javax.swing.JPanel jSystem; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable jTableAccessory; private javax.swing.JTable jTableLoco; private javax.swing.JTable jTableTraction; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextM3SID; private javax.swing.JTextField jTextM3UID; private javax.swing.JTextPane jTextPane1; private javax.swing.JButton jTra2System; private javax.swing.JButton jTraCheck; private javax.swing.JButton jTraDel; private javax.swing.JButton jTraDelAll; private javax.swing.JButton jTraRepair; private javax.swing.JPanel jTraktionen; private javax.swing.JRadioButton jUSB1; private javax.swing.JRadioButton jUSB2; private javax.swing.JButton jUpd2System; private javax.swing.JButton jUpdCancel; private javax.swing.JButton jUpdClose; private javax.swing.JTextField jUpdDatei; private javax.swing.JButton jUpdDateiAuswahl; private javax.swing.JLabel jUpdLastError; private javax.swing.JLabel jUpdLastErrorLabel; private javax.swing.JButton jUpdStartUpdate; private javax.swing.JPanel jUpdate; private javax.swing.JTextField jVersion; private javax.swing.JButton jVor; private javax.swing.JCheckBox jWRloc; private javax.swing.JCheckBox jWRmag; private javax.swing.JCheckBox jWRsys; private javax.swing.JCheckBox jWRtra; private javax.swing.JTextField jWertDirekt; private javax.swing.JButton jf0; private javax.swing.JButton jf1; private javax.swing.JButton jf10; private javax.swing.JButton jf11; private javax.swing.JButton jf12; private javax.swing.JButton jf13; private javax.swing.JButton jf14; private javax.swing.JButton jf15; private javax.swing.JButton jf16; private javax.swing.JButton jf17; private javax.swing.JButton jf18; private javax.swing.JButton jf19; private javax.swing.JButton jf2; private javax.swing.JButton jf20; private javax.swing.JButton jf21; private javax.swing.JButton jf22; private javax.swing.JButton jf23; private javax.swing.JButton jf24; private javax.swing.JButton jf25; private javax.swing.JButton jf26; private javax.swing.JButton jf27; private javax.swing.JButton jf28; private javax.swing.JButton jf3; private javax.swing.JButton jf4; private javax.swing.JButton jf5; private javax.swing.JButton jf6; private javax.swing.JButton jf7; private javax.swing.JButton jf8; private javax.swing.JButton jf9; private javax.swing.JTextField jm3Addr; private javax.swing.JButton jm3Schreiben; private javax.swing.JTextField jmfxUID; private javax.swing.JTextField js88; // End of variables declaration//GEN-END:variables }
package tla2sany.modanalyzer; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import tla2sany.semantic.AbortException; import tla2sany.semantic.Errors; import tla2sany.semantic.ExternalModuleTable; import tla2sany.st.TreeNode; import tla2sany.utilities.Vector; import util.ToolIO; public class SpecObj { String primaryFileName; // The raw file name for the root (top) module, unprocessed by adding // ".tla" or by prepending the full file system path to it) ExternalModuleTable externalModuleTable = new ExternalModuleTable(); // This is the one ExternalModuleTable for the entire specification; // it includes ModuleNode's for the root module, and for all modules // that it depends on directly or indirectly by EXTENDS or INSTANCE public Vector semanticAnalysisVector = new Vector(); // Stack of units parsed, in the order in which semantic analysis // must be done, i.e. if MODULE A references B, A is lower // on the stack. The same module name can occur multiple times. public Hashtable parseUnitContext = new Hashtable(); // Holds all known ParseUnit objects, i.e external, top-level // modules that have so far been encountered, keyed by module // (parseUnit) string name private ModuleRelationships moduleRelationshipsSpec = new ModuleRelationships(); // Maps ModulePointers to ModuleRelatives objects for all modules // in the specification, including all inner modules and all top-level // external modules. private StringToNamedInputStream ntfis = null; ParseUnit rootParseUnit = null; // The ParseUnit object for the first (i.e. "root") file, roughly // the file that is named in the command line; null until the root // file is parsed ModulePointer rootModule = null; // The top level module of the rootParseUnit; // null until rootParseUnit is parsed String rootModuleName; // The String name of rootModule, unknown until rootParseUnit is parsed, // although it is supposed to be closely related to the file name public Errors initErrors = new Errors(); // The Errors object for reporting errors that happen at initialization // time. public Errors parseErrors = new Errors(); // The Errors object for reporting errors that occur during parsing, // including the retrieval of files (ParseUnits) for extention and // instantiation or the root and their extentions and instantiations, etc. Errors globalContextErrors = new Errors(); // The Errors object for reporting errors in creating the global // context from the file that stores it. public Errors semanticErrors = new Errors(); // The Errors object for reporting errors discovered during semantic // analysis, including level checking. public int errorLevel = 0; /** * Default constructor of the SpecObj with a given primary filename and the default * NameToFileIStream for its resolution * @pfn primary filename of the specification */ public SpecObj(String pfn) { this(pfn, new NameToFileIStream()); } /** * Constructs a SpecObj for the given filename using a specified filename resolver * @param pfn primary filename of the specification * @param ntfis */ public SpecObj(String pfn, StringToNamedInputStream ntfis) { this.primaryFileName = pfn; this.ntfis = ntfis; } /** * Any integer other than 0 returned from this method indicates a * fatal error while processing the TLA+ spec. No further use * should be made of this object except by the maintainer. */ public final int getErrorLevel() { return errorLevel; } /** * Returns the name of the top-level module as passed to the method * Specification.frontEndMain(). */ public final String getName() { return rootModuleName; } public final void setName(String name) { rootModuleName = name; } /** * Returns the raw file name of the top-level module as passed to * the method Specification.frontEndMain(). */ public final String getFileName() { return primaryFileName; } /** * Returns the ExternalModuleTable object that contains all of the * definitions for this Specification. May be null or incomplete if * getErrorLevel() returns a nonzero number. */ public final ExternalModuleTable getExternalModuleTable() { return externalModuleTable; } /** * Returns Errors object produced during initialization of the FrontEnd. * Should never be interesting. */ public final Errors getInitErrors() { return initErrors; } /** * Returns Errors object containing errors found during parsing. */ public final Errors getParseErrors() { return parseErrors; } /** * Returns Errors object containing errors found while parsing the * built-in operator and synonym tables. Should never be interesting. */ public final Errors getGlobalContextErrors() { return globalContextErrors; } /** * Returns Errors object containing errors found during semantic * processing and level checking. */ public final Errors getSemanticErrors() { return semanticErrors; } // Returns enumeration of the modules so far included in the spec public final Enumeration getModules() { return moduleRelationshipsSpec.getKeys(); } // Returns the moduleRelationshipsSpec object final ModuleRelationships getModuleRelationships() { return moduleRelationshipsSpec; } // Prints the context of one ParseUnit public final void printParseUnitContext() { Enumeration enumerate = parseUnitContext.keys(); ToolIO.out.println("parseUnitContext ="); while (enumerate.hasMoreElements()) { String key = (String) enumerate.nextElement(); ToolIO.out.println(" " + key + "-->" + ((ParseUnit) parseUnitContext.get(key)).getName()); } } // This method looks up a ParseUnit "name" in the parseUnitContext // table. If it is not found, then the corresponding file is looked // up in the file system and parsed, and a new ParseUnit is created // for it and an entry for it added to the parseUnitContext table. // The argument firstCall should be true iff this is the first call // to this method; it is used to determine that the name of the // module in the ParseUnit created is the name of the entire // SpecObj. Returns the ParseUnit found or created. Aborts if // neither happens. private final ParseUnit findOrCreateParsedUnit(String name, Errors errors, boolean firstCall) throws AbortException { ParseUnit parseUnit; // See if ParseUnit "name" is already in parseUnitContext table parseUnit = (ParseUnit) parseUnitContext.get(name); // if not, then we have to get it from the file system if (parseUnit == null) { // if module "name" is not already in parseUnitContext table // find a file derived from the name and create a // NamedInputStream for it if possible NamedInputStream nis = this.ntfis.toIStream(name); if (nis != null) { // if a non-null NamedInputStream exists, create ParseUnit // from "nis", but don't parse it yet parseUnit = new ParseUnit(this, nis); // put "parseUnit" and its name in "parseUnitContext" table parseUnitContext.put(parseUnit.getName(), parseUnit); } else { errors.addAbort("Cannot find source file for module " + name + " imported in module " + nextExtenderOrInstancerModule.getName() + "."); } } // Actually parse the file named in "parseUnit" (or no-op if it // has already been parsed) parseUnit.parseFile(errors, firstCall); return parseUnit; // return a non-null "parseUnit" iff named module has been found, // either already parsed or in the file system } // Fill the Vector used to drive the semantic analysis of external // modules. The basic requirement is that if ParseUnit A extends or // instances ParseUnit B, then A must have a higher index in the // Vector than B. private void calculateDependencies(ParseUnit currentParseUnit) { Vector extendees = currentParseUnit.getExtendees(); Vector instancees = currentParseUnit.getInstancees(); // Make sure all extendees of currentModule are in the semanticAnalysisVector for (int i = 0; i < extendees.size(); i++) { calculateDependencies((ParseUnit) extendees.elementAt(i)); } // And then make sure all instancees of currentModule are in the // semanticAnalysisVector for (int i = 0; i < instancees.size(); i++) { calculateDependencies((ParseUnit) instancees.elementAt(i)); } // Then put self in the Vector, if not already there if (!semanticAnalysisVector.contains(currentParseUnit.getName())) { semanticAnalysisVector.addElement(currentParseUnit.getName()); } return; } // Converts a Vector of ParseUnits to a string representing a // circular chain of references, for purposes of the error message // in nonCircularityBody method below. private String pathToString(Vector path) { String ret = ""; for (int i = 0; i < path.size(); i++) { ret += ((ParseUnit) path.elementAt(i)).getFileName() + " } return ret + ((ParseUnit) path.elementAt(0)).getFileName(); } // This method determines whether the there is any circularity // detectable this far among ParseUnits that involves the one named // parseUnitName. If there is, cause an abort; otherwise return. private void nonCircularityTest(ParseUnit parseUnit, Errors errors) throws AbortException { HashSet alreadyVisited = new HashSet(); Vector circularPath = new Vector(); circularPath.addElement(parseUnit); nonCircularityBody(parseUnit, parseUnit, errors, alreadyVisited, circularPath); } // Recursive depth-first search method to see if there is a circular // dependence from 'parseUnit' to 'parseUnit' through another // ParseUnit, candidate. If so, an abort message is posted on // errors, and the method aborts. The set alreadyVisited is // used to prevent searching paths through the same candidate // multiple times. private void nonCircularityBody(ParseUnit parseUnit, ParseUnit candidate, Errors errors, HashSet alreadyVisited, Vector circularPath) throws AbortException { // If we have already checked for circularities through this // parseUnit, just return if (alreadyVisited.contains(candidate)) return; alreadyVisited.add(candidate); // Vector referencees holds ParseUnits either extended by or // instanced by "candidate" Vector referencees = candidate.getExtendees(); referencees.appendNoRepeats(candidate.getInstancees()); for (int i = 0; i < referencees.size(); i++) { ParseUnit referencee = (ParseUnit) referencees.elementAt(i); // See if our search has reached "parseUnit"; // if so, we have a circularity if (referencee == parseUnit) { // Circularity detected errors.addAbort("Circular dependency among .tla files; " + "dependency cycle is:\n\n " + pathToString(circularPath)); } else { circularPath.addElement(referencee); // See if there is a circular path continuing through this referencee nonCircularityBody(parseUnit, referencee, errors, alreadyVisited, circularPath); circularPath.removeElementAt(circularPath.size() - 1); } // end if } // end for return; } // The next two methods and the variables declared before them // traverse the tree of module relationships recursively, starting // at "currentModule", to find a name in an EXTENDS decl that is as // yet unresolved, if any, and set "nextParseUnit" to its name. // Return false iff there are no more unresolved EXTENDS names in // the entire specification. String nextParseUnitName = ""; // The place where name of the next unresolved extention // or instance module is stored by the next methods ModulePointer nextExtenderOrInstancerModule = null; // The place where a reference to the module that extends // or instances the next parse unit is stored by the next method boolean extentionFound; boolean instantiationFound; // A wrapper for the next method, which empties the alreadyVisited // table calling the recursive method below private boolean findNextUnresolvedExtention(ModulePointer currentModule) { HashSet alreadyVisited = new HashSet(); return findNextUnresolvedExtentionBody(currentModule, alreadyVisited); } // Traverse the tree of module relationships recursively, starting // at "currentModule", to find a name in an EXTENDS decl that is as // yet unresolved, if any, and set "nextParseUnit" to its name. // Return false iff there are no more unresolved EXTENDS names in // the entire specification. private boolean findNextUnresolvedExtentionBody(ModulePointer currentModule, HashSet alreadyVisited) { if (alreadyVisited.contains(currentModule)) { extentionFound = false; return false; } alreadyVisited.add(currentModule); ModuleContext currentContext = currentModule.getContext(); Vector extendees = currentModule.getNamesOfModulesExtended(); Vector instancees = currentModule.getNamesOfModulesInstantiated(); // for all of the modules named as extendees of the current // module, but which may or not be resolved yet for (int i = 0; i < extendees.size(); i++) { // if one of them is unresolved if (currentContext.resolve((String) extendees.elementAt(i)) == null) { // then it is the next unresolved extention; return it nextParseUnitName = (String) extendees.elementAt(i); nextExtenderOrInstancerModule = currentModule; extentionFound = true; return true; } } // end for // See if one of the already-resolved extendees has any unresolved // extentions for (int i = 0; i < extendees.size(); i++) { // by recursive invocation of this method on the extendees if (findNextUnresolvedExtentionBody(currentContext.resolve((String) extendees.elementAt(i)), alreadyVisited)) { extentionFound = true; return true; } } // end for // See if one of the already-resolved instancees of currentModule // has any unresolved extentions for (int i = 0; i < instancees.size(); i++) { // if this instancee has been resolved if (currentContext.resolve((String) instancees.elementAt(i)) != null) { // check by recursive invocation of this method on the instancees if (findNextUnresolvedExtentionBody(currentContext.resolve((String) instancees.elementAt(i)), alreadyVisited)) { extentionFound = true; return true; } // end if } // end if } // end for // Finally, see if any of "currentModule"'s inner modules (or any // they extend or instance) have any unresolved extentions by // invoking this method recursively on them. Vector innerModules = currentModule.getDirectInnerModules(); for (int i = 0; i < innerModules.size(); i++) { if (findNextUnresolvedExtentionBody((ModulePointer) innerModules.elementAt(i), alreadyVisited)) { extentionFound = true; return true; } } // end for // Iff there are no unresolved extention module names, we return false extentionFound = false; return false; } // end findNextUnresolvedExtentionBody() // A wrapper for the next method, which empties the alreadyVisited // table calling the recursive method below private boolean findNextUnresolvedInstantiation(ModulePointer currentModule) { HashSet alreadyVisited = new HashSet(); return findNextUnresolvedInstantiationBody(currentModule, alreadyVisited); } // Determines whether an INSTANCE statement for the module named // "instancee" refers to an earlier-defined internal module within // the same module "module". This is accomplished essentially by a // linear search of the declaration in the syntactic tree of // "module". Note: this does NOT scale when there are large numbers // of INSTANCE decls in a long module. private boolean instanceResolvesToInternalModule(ModulePointer currentModule, String instanceeName) { // Find the body part of module tree TreeNode body = currentModule.getBody(); // We will be accumulating the set of names of internal modules // defined before the INSTANCE declaration. HashSet internalModulesSeen = new HashSet(); // loop through the top level definitions in the body of the // module looking for embedded modules instantiations, and module // definitions for (int i = 0; i < body.heirs().length; i++) { TreeNode def = body.heirs()[i]; // if we encounter an new (inner) module if (def.getImage().equals("N_Module")) { // Pick off name of inner module String innerModuleName = def.heirs()[0].heirs()[1].getImage(); // Add to the set of names of inner modules seen so far internalModulesSeen.add(innerModuleName); } // if we encounter an INSTANCE decl else if (def.getImage().equals("N_Instance")) { TreeNode[] instanceHeirs = def.heirs(); int nonLocalInstanceNodeIX; // The modifier "LOCAL" may or may not appear in the syntax tree; // if so, offset by 1 if (instanceHeirs[0].getImage().equals("LOCAL")) { nonLocalInstanceNodeIX = 1; } else { nonLocalInstanceNodeIX = 0; } // Find the name of the module being instantiated String instanceModuleName = instanceHeirs[nonLocalInstanceNodeIX].heirs()[1].getImage(); // if this is the module name we are searching for, then if it // corresponds to an inner module defined earlier, then return // true; else return false. if (instanceModuleName.equals(instanceeName)) { return internalModulesSeen.contains(instanceeName); } // end if } // end if // if we encounter a module definition (i.e. D(x,y) == INSTANCE // Modname WITH ...) that counts as an instance also else if (def.getImage().equals("N_ModuleDefinition")) { TreeNode[] instanceHeirs = def.heirs(); int nonLocalInstanceNodeIX; // The modifier "LOCAL" may or may not appear in the syntax tree; // if so, offset by 1 if (instanceHeirs[0].getImage().equals("LOCAL")) { nonLocalInstanceNodeIX = 3; } else { nonLocalInstanceNodeIX = 2; } // Find the name of the module being instantiated String instanceModuleName = instanceHeirs[nonLocalInstanceNodeIX].heirs()[1].getImage(); // if this is the module name we are searching for, then if it // corresponds to an inner module defined earlier, then return // true; else return false. if (instanceModuleName.equals(instanceeName)) { return internalModulesSeen.contains(instanceeName); } // end if } // end else } // end for return false; } // end instanceResolvesToInternalModule() // Traverse the tree of module relationships recursively to find a // name in an INSTANCE decl that is as yet unresolved, if any, and // set "nextParseUnit" to its name. Return false iff there are no // more unresolved INSTANCES names in the entire specification. private boolean findNextUnresolvedInstantiationBody(ModulePointer currentModule, HashSet alreadyVisited) { if (alreadyVisited.contains(currentModule)) { instantiationFound = false; return false; } alreadyVisited.add(currentModule); ModuleContext currentContext = currentModule.getContext(); Vector extendees = currentModule.getNamesOfModulesExtended(); Vector instancees = currentModule.getNamesOfModulesInstantiated(); // for all of the modules named as instancees of the current // module, but which may or not be resolved yet. for (int i = 0; i < instancees.size(); i++) { // if one of them is unresolved if (currentContext.resolve((String) instancees.elementAt(i)) == null) { // See if it can be resolved WITHIN the module in which the // INSTANCE stmt occurs, i.e. does it resolve to an inner // module declared above this INSTANCE stmt? Nothing in the // logic so far covers this (most common) case, so we have to // insert logic here to check now. if (!instanceResolvesToInternalModule(currentModule, (String) instancees.elementAt(i))) { // then it is the next unresolved instantiation; return it nextParseUnitName = (String) instancees.elementAt(i); nextExtenderOrInstancerModule = currentModule; instantiationFound = true; return true; } } } // See if one of the already-resolved extendees has any // unresolved instantiations for (int i = 0; i < extendees.size(); i++) { // by recursive invocation of this method on the extendees if (findNextUnresolvedInstantiationBody(currentContext.resolve((String) extendees.elementAt(i)), alreadyVisited)) { instantiationFound = true; return true; } } // See if one of the already-resolved instancees of currentModule // has any unresolved extentions. for (int i = 0; i < instancees.size(); i++) { // if this instancee has been resolved if (currentContext.resolve((String) instancees.elementAt(i)) != null) { if (findNextUnresolvedInstantiationBody(currentContext.resolve((String) instancees.elementAt(i)), alreadyVisited)) { instantiationFound = true; return true; } } } // Finally, see if any of "currentModule"'s inner modules (or any // they extend) have any unresolved instantiations by invoking // this method recursively on them. Vector innerModules = currentModule.getDirectInnerModules(); for (int i = 0; i < innerModules.size(); i++) { if (findNextUnresolvedInstantiationBody((ModulePointer) innerModules.elementAt(i), alreadyVisited)) { instantiationFound = true; return true; } } // Iff there are no unresolved Instantiation module names, // we return false instantiationFound = false; return false; } // Returns true iff mod1 is known to directly extend mod2 private boolean directlyExtends(ModulePointer mod1, ModulePointer mod2) { ModuleRelatives mod1Rels = mod1.getRelatives(); Vector extendees = mod1Rels.directlyExtendedModuleNames; ModuleContext mod1Context = mod1Rels.context; for (int i = 0; i < extendees.size(); i++) { if (mod1Context.resolve((String) extendees.elementAt(i)) == mod2) return true; } ; return false; } // Returns a Vector of all modules and submodules in the spec so far // that directly or indirectly extend "module", including "module" // itself. This method is horribly inefficient when there are a // large number of modules, looping as it does through ALL modules; // it must be rewritten recursively!! private Vector getModulesIndirectlyExtending(ModulePointer module) { // The Vector of Modules that equals, or directly or indirectly // extends, "module" Vector extenders = new Vector(); extenders.addElement(module); // initializations for the following nested loop boolean additions = true; int lastAdditionsStart = 0; int lastAdditionsEnd = extenders.size(); // while there were more additions to the Vector of modules // indirectly extending "module" while (additions) { additions = false; // for all newly added modules, see if there are any others that // extend them for (int i = lastAdditionsStart; i < lastAdditionsEnd; i++) { // Check ALL modules in the entire specification (!) to see if // they extend the i'th element of the vector Enumeration enumModules = getModules(); while (enumModules.hasMoreElements()) { ModulePointer modPointer = (ModulePointer) enumModules.nextElement(); if (directlyExtends(modPointer, (ModulePointer) extenders.elementAt(i))) { if (!additions) lastAdditionsStart = lastAdditionsEnd; extenders.addElement(modPointer); additions = true; } } lastAdditionsStart = lastAdditionsEnd; lastAdditionsEnd = extenders.size(); } } return extenders; } // This modules binds the name used in an INSTANCE definition in // module "instancer" to the top-level module in ParseUnit instancee private void resolveNamesBetweenSpecAndInstantiation(ModulePointer instancer, ParseUnit instancee) { // Bind the name of the instancee in the instancer's context ModuleContext instancerContext = instancer.getRelatives().context; instancerContext.bindIfNotBound(instancee.getName(), instancee.getRootModule()); } // This method adds names to various module contexts (the context of // "extender" and any modules that extend it) that come from the // top-level inner modules in a ParseUnit (extendee) which is // extended by "extender". For any module "extender", and any // module xx that extends "extender", directly or indirectly, we // must resolve module names in xx to top level internal modules in // extendeeParseUnit private void resolveNamesBetweenSpecAndExtention(ModulePointer extender, ParseUnit extendee) { // First, bind the name of the extendee in the extender's context ModuleContext extenderContext = extender.getRelatives().context; extenderContext.bindIfNotBound(extendee.getName(), extendee.getRootModule()); // Vextor of ModulePointers for modules that either are // "extender", or extend "extender" directly, of extend it // indirectly. Vector modulesIndirectlyExtending = getModulesIndirectlyExtending(extender); for (int i = 0; i < modulesIndirectlyExtending.size(); i++) { resolveNamesBetweenModuleAndExtention((ModulePointer) modulesIndirectlyExtending.elementAt(i), extendee); } } // Add all of the top level inner modules of extendeeParseUnit to // the contexts of extenderModule by doing appropriate bindings, and // do the same for all of extenderModule's submodules private void resolveNamesBetweenModuleAndExtention(ModulePointer extenderModule, ParseUnit extendeeParseUnit) { ModuleRelatives extenderRelatives = extenderModule.getRelatives(); ModuleContext extenderContext = extenderRelatives.context; Vector instantiatedNames = extenderRelatives.directlyInstantiatedModuleNames; Vector extendedNames = extenderRelatives.directlyExtendedModuleNames; // find all unresolved names in extenderModule and its submodules // and see if they can be resolved in extendeeParseUnit // for each module name extended by extenderModule, try to resolve // it in the module it extends for (int i = 0; i < extendedNames.size(); i++) { String extendedName = (String) extendedNames.elementAt(i); // Pick up vector of top level inner modules of extendeeParseUnit Vector extendeeInnerModules = extendeeParseUnit.getRootModule().getDirectInnerModules(); // See if the name occurs among the direct inner modules of extendee for (int j = 0; j < extendeeInnerModules.size(); j++) { ModulePointer extendeeInnerModule = ((ModulePointer) extendeeInnerModules.elementAt(j)); String extendeeInnerName = extendeeInnerModule.getName(); // if we have a match... if (extendedName.equals(extendeeInnerName)) { // bind the name to the inner module of extendee in the // context of the extender iff it is unbound before this extenderContext.bindIfNotBound(extendedName, extendeeInnerModule); // and move on to the next instanceName break; } // end if } // end for j } // end for i // for each module name instantiated at the top level of // extenderModule, try to resolve it in the module it extends for (int i = 0; i < instantiatedNames.size(); i++) { String instanceName = (String) instantiatedNames.elementAt(i); // Pick up vector of top level inner modules of extendeeParseUnit Vector extendeeInnerModules = extendeeParseUnit.getRootModule().getDirectInnerModules(); // See if the name occurs among the direct inner modules of extendee for (int j = 0; j < extendeeInnerModules.size(); j++) { ModulePointer extendeeInnerModule = ((ModulePointer) extendeeInnerModules.elementAt(j)); String extendeeInnerName = extendeeInnerModule.getName(); // if we have a match... if (instanceName.equals(extendeeInnerName)) { // bind the name to the inner module of extendee in the // context of the extender iff it is unbound before this extenderContext.bindIfNotBound(instanceName, extendeeInnerModule); // and move on to the next instanceName break; } // end if } // end for j } // end for i // Now, for each inner module (recursively) of the extender // modules, try to resolve ITS unresolved module names in the same // extendee ParseUnit. Vector extenderInnerModules = extenderRelatives.directInnerModules; for (int i = 0; i < extenderInnerModules.size(); i++) { ModulePointer nextInner = (ModulePointer) extenderInnerModules.elementAt(i); resolveNamesBetweenModuleAndExtention(nextInner, extendeeParseUnit); } } /** * This method "loads" an entire specification, starting with the * top-level rootExternalModule and followed by all of the external * modules it references via EXTENDS and INSTANCE statements. */ public boolean loadSpec(String rootExternalModuleName, Errors errors) throws AbortException { // If rootExternalModuleName" has *not* already been parsed, then // go to the file system and find the file containing it, create a // ParseUnit for it, and parse it. Parsing includes determining // module relationships. Aborts if not found in file system rootParseUnit = findOrCreateParsedUnit(rootExternalModuleName, errors, true /* first call */); rootModule = rootParseUnit.getRootModule(); // Retrieve and parse all module extentions: As long as there is // another unresolved module name... // 0. Find the ParseUnit in corresponding to the name; go to the // file system to find it and parse it if necessary. Not its // relationship with other ParseUnits // 1. Verify that next unresolved module is not a circular // dependency among ParseUnits. // 2. Read, parse, and analyze module relationships for next // unresolved module name, and create a ParseUnit for it. // 3. Integrate the ModuleRelationships information from the new // ParseUnit into that for this entire SpecObj // 4. Select the next unresolved module name for processing. ParseUnit nextExtentionOrInstantiationParseUnit = null; while (findNextUnresolvedExtention(rootModule) || findNextUnresolvedInstantiation(rootModule)) { // nextParseUnitName has not already been processed through some // other path, if (parseUnitContext.get(nextParseUnitName) == null) { // find it in the file system (if there) and parse and analyze it. nextExtentionOrInstantiationParseUnit = findOrCreateParsedUnit(nextParseUnitName, errors, false /* not first call */); } else { // or find it in the known parseUnitContext nextExtentionOrInstantiationParseUnit = (ParseUnit) parseUnitContext.get(nextParseUnitName); } // Record that extenderOrInstancerParseUnit EXTENDs or INSTANCEs // nextExtentionOrInstantiationParseUnit, and that // nextExtentionOrInstantiationParseUnit is extended or // instanced by extenderOrInstancerParseUnit. ParseUnit extenderOrInstancerParseUnit = nextExtenderOrInstancerModule.getParseUnit(); if (extentionFound) { extenderOrInstancerParseUnit.addExtendee(nextExtentionOrInstantiationParseUnit); nextExtentionOrInstantiationParseUnit.addExtendedBy(extenderOrInstancerParseUnit); } if (instantiationFound) { extenderOrInstancerParseUnit.addInstancee(nextExtentionOrInstantiationParseUnit); nextExtentionOrInstantiationParseUnit.addInstancedBy(extenderOrInstancerParseUnit); } // Check for circular references among parseUnits; abort if found nonCircularityTest(nextExtentionOrInstantiationParseUnit, errors); // If this ParseUnit is loaded because of an EXTENDS decl, then // it may have inner modules that are the resolvants for // unresolved module names in the nextExtenderOrInstancerModule; // resolve the ones that are possible if (extentionFound) { resolveNamesBetweenSpecAndExtention(nextExtenderOrInstancerModule, nextExtentionOrInstantiationParseUnit); } // If this ParseUnit is loaded because of an INSTANCE stmt, then // the outer module of the ParseUnit is the resolution of the // previously unresolved instantiation. if (instantiationFound) { resolveNamesBetweenSpecAndInstantiation(nextExtenderOrInstancerModule, nextExtentionOrInstantiationParseUnit); } } // end while // Walk the moduleRelationshipsSpec graph to set up // semanticAnalysisVector; this vector determines the order in // which semantic analysis is done on parseUnits calculateDependencies(rootParseUnit); return true; // loadUnresolvedRelatives(moduleRelationshipsSpec, rootModule, errors); } }
package dr.app.beauti.options; import dr.app.beauti.enumTypes.FixRateType; import dr.app.beauti.enumTypes.OperatorType; import dr.app.beauti.enumTypes.PriorType; import dr.app.beauti.enumTypes.RelativeRatesType; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.tree.UPGMATree; import dr.evolution.util.Taxa; import dr.math.MathUtils; import dr.stats.DiscreteStatistics; import java.util.ArrayList; import java.util.List; import javax.swing.JCheckBox; import javax.swing.JOptionPane; /** * @author Alexei Drummond * @author Andrew Rambaut * @author Walter Xie * @version $Id$ */ public class ClockModelOptions extends ModelOptions { // Instance variables private final BeautiOptions options; private FixRateType rateOptionClockModel = FixRateType.RElATIVE_TO; private double meanRelativeRate = 1.0; public ClockModelOptions(BeautiOptions options) { this.options = options; initGlobalClockModelParaAndOpers(); fixRateOfFirstClockPartition(); } private void initGlobalClockModelParaAndOpers() { createParameter("allClockRates", "All the relative rates regarding clock models"); createOperator("deltaAllClockRates", RelativeRatesType.CLOCK_RELATIVE_RATES.toString(), "Delta exchange operator for all the relative rates regarding clock models", "allClockRates", OperatorType.DELTA_EXCHANGE, 0.75, rateWeights); // only available for *BEAST and EBSP createUpDownAllOperator("upDownAllRatesHeights", "Up down all rates and heights", "Scales all rates inversely to node heights of the tree", demoTuning, branchWeights); } /** * return a list of parameters that are required * * @param params the parameter list */ public void selectParameters(List<Parameter> params) { } /** * return a list of operators that are required * * @param ops the operator list */ public void selectOperators(List<Operator> ops) { if (rateOptionClockModel == FixRateType.FIX_MEAN) { Operator deltaOperator = getOperator("deltaAllClockRates"); // update delta clock operator weight deltaOperator.weight = options.getPartitionClockModels().size(); ops.add(deltaOperator); } //up down all rates and trees operator only available for *BEAST and EBSP if (rateOptionClockModel == FixRateType.RElATIVE_TO && //TODO what about Calibration? (options.starBEASTOptions.isSpeciesAnalysis() || options.isEBSPSharingSamePrior())) { ops.add(getOperator("upDownAllRatesHeights")); } } public FixRateType getRateOptionClockModel() { return rateOptionClockModel; } // public void setRateOptionClockModel(FixRateType rateOptionClockModel) { // this.rateOptionClockModel = rateOptionClockModel; public void setMeanRelativeRate(double meanRelativeRate) { this.meanRelativeRate = meanRelativeRate; } public double[] calculateInitialRootHeightAndRate(List<PartitionData> partitions) { double avgInitialRootHeight = 1; double avgInitialRate = 1; double avgMeanDistance = 1; if (options.hasData()) { avgMeanDistance = options.getAveWeightedMeanDistance(partitions); } if (options.getPartitionClockModels().size() > 0) { avgInitialRate = options.clockModelOptions.getSelectedRate(partitions); // all clock models } switch (options.clockModelOptions.getRateOptionClockModel()) { case FIX_MEAN: case RElATIVE_TO: if (options.hasData()) { avgInitialRootHeight = avgMeanDistance / avgInitialRate; } break; case TIP_CALIBRATED: avgInitialRootHeight = options.maximumTipHeight * 10.0;//TODO avgInitialRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case NODE_CALIBRATED: avgInitialRootHeight = getCalibrationEstimateOfRootTime(partitions); avgInitialRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case RATE_CALIBRATED: break; default: throw new IllegalArgumentException("Unknown fix rate type"); } avgInitialRootHeight = MathUtils.round(avgInitialRootHeight, 2); avgInitialRate = MathUtils.round(avgInitialRate, 2); return new double[]{avgInitialRootHeight, avgInitialRate}; } public double getSelectedRate(List<PartitionData> partitions) { double selectedRate = 1; double avgInitialRootHeight = 1; double avgMeanDistance = 1; // calibration: all isEstimatedRate = true switch (options.clockModelOptions.getRateOptionClockModel()) { case FIX_MEAN: selectedRate = meanRelativeRate; break; case RElATIVE_TO: List<PartitionClockModel> models = options.getPartitionClockModels(partitions); // fix ?th partition if (models.size() == 1) { selectedRate = models.get(0).getRate(); } else { selectedRate = getAverageRate(models); } break; case TIP_CALIBRATED: if (options.hasData()) { avgMeanDistance = options.getAveWeightedMeanDistance(partitions); } avgInitialRootHeight = options.maximumTipHeight * 10.0;//TODO selectedRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case NODE_CALIBRATED: if (options.hasData()) { avgMeanDistance = options.getAveWeightedMeanDistance(partitions); } avgInitialRootHeight = getCalibrationEstimateOfRootTime(partitions); selectedRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case RATE_CALIBRATED: //TODO break; default: throw new IllegalArgumentException("Unknown fix rate type"); } return selectedRate; } private List<PartitionData> getAllPartitionDataGivenClockModels(List<PartitionClockModel> models) { List<PartitionData> allData = new ArrayList<PartitionData>(); for (PartitionClockModel model : models) { for (PartitionData partition : model.getAllPartitionData()) { if (partition != null && (!allData.contains(partition))) { allData.add(partition); } } } return allData; } private double getCalibrationEstimateOfRootTime(List<PartitionData> partitions) { // TODO - shouldn't this method be in the PartitionTreeModel?? List<Taxa> taxonSets = options.taxonSets; if (taxonSets != null && taxonSets.size() > 0) { // tmrca statistic // estimated root times based on each of the taxon sets double[] rootTimes = new double[taxonSets.size()]; for (int i = 0; i < taxonSets.size(); i++) { Taxa taxa = taxonSets.get(i); Parameter tmrcaStatistic = options.getStatistic(taxa); double taxonSetCalibrationTime = tmrcaStatistic.getPriorExpectation(); // the calibration distance is the patristic genetic distance back to the common ancestor of // the set of taxa. double calibrationDistance = 0; // the root distance is the patristic genetic distance back to the root of the tree. double rootDistance = 0; int siteCount = 0; for (PartitionData partition : partitions) { Tree tree = new UPGMATree(partition.distances); NodeRef node = Tree.Utils.getCommonAncestorNode(tree, Taxa.Utils.getTaxonListIdSet(taxa)); calibrationDistance += tree.getNodeHeight(node); rootDistance += tree.getNodeHeight(tree.getRoot()); siteCount += partition.getAlignment().getSiteCount(); } rootDistance /= partitions.size(); calibrationDistance /= partitions.size(); if (calibrationDistance == 0.0) { calibrationDistance = 0.25 / siteCount; } if (rootDistance == 0) { rootDistance = 0.25 / siteCount; } rootTimes[i] += (rootDistance / calibrationDistance) * taxonSetCalibrationTime; } // return the mean estimate of the root time for this set of partitions return DiscreteStatistics.mean(rootTimes); } else { // prior on treeModel.rootHight double avgInitialRootHeight = 0; double count = 0; for (PartitionTreeModel tree : options.getPartitionTreeModels(partitions)) { avgInitialRootHeight = avgInitialRootHeight + tree.getInitialRootHeight(); count = count + 1; } if (count != 0) avgInitialRootHeight = avgInitialRootHeight / count; return avgInitialRootHeight; } } // FixRateType.FIX_MEAN public double getMeanRelativeRate() { return meanRelativeRate; } // FixRateType.ESTIMATE public double getAverageRate(List<PartitionClockModel> models) { //TODO average per tree, but how to control the estimate clock => tree? double averageRate = 0; double count = 0; for (PartitionClockModel model : models) { if (!model.isEstimatedRate()) { averageRate = averageRate + model.getRate(); count = count + 1; } } if (count > 0) { averageRate = averageRate / count; } else { averageRate = 1; //TODO how to calculate rate when estimate all } return averageRate; } // Calibration Series Data public double getAverageRateForCalibrationSeriesData() { double averageRate = 0; //TODO return averageRate; } // Calibration TMRCA public double getAverageRateForCalibrationTMRCA() { double averageRate = 0; //TODO return averageRate; } public boolean isTipCalibrated() { return options.maximumTipHeight > 0; } public boolean isNodeCalibrated(Parameter para) { if ((para.taxa != null && hasProperPriorOn(para)) // param.taxa != null is TMRCA || (para.getBaseName().endsWith("treeModel.rootHeight") && hasProperPriorOn(para))) { return true; } else { return false; } } private boolean hasProperPriorOn(Parameter para) { if (para.priorType == PriorType.LOGNORMAL_PRIOR || para.priorType == PriorType.NORMAL_PRIOR || para.priorType == PriorType.LAPLACE_PRIOR || para.priorType == PriorType.TRUNC_NORMAL_PRIOR || (para.priorType == PriorType.GAMMA_PRIOR && para.gammaAlpha > 1) || (para.priorType == PriorType.GAMMA_PRIOR && para.gammaOffset > 0) || (para.priorType == PriorType.UNIFORM_PRIOR && para.uniformLower > 0 && para.uniformUpper < Double.POSITIVE_INFINITY) || (para.priorType == PriorType.EXPONENTIAL_PRIOR && para.exponentialOffset > 0)) { return true; } else { return false; } } public boolean isRateCalibrated() { return false;//TODO } public int[] getPartitionClockWeights() { int[] weights = new int[options.getPartitionClockModels().size()]; // use List? int k = 0; for (PartitionClockModel model : options.getPartitionClockModels()) { for (PartitionData partition : model.getAllPartitionData()) { int n = partition.getSiteCount(); weights[k] += n; } k += 1; } assert (k == weights.length); return weights; } public void fixRateOfFirstClockPartition() { this.rateOptionClockModel = FixRateType.RElATIVE_TO; // fix rate of 1st partition int i = 0; for (PartitionClockModel model : options.getPartitionClockModels()) { if (i < 1) { model.setEstimatedRate(false); } else { model.setEstimatedRate(true); } i = i + 1; } } public void fixMeanRate() { this.rateOptionClockModel = FixRateType.FIX_MEAN; for (PartitionClockModel model : options.getPartitionClockModels()) { model.setEstimatedRate(true); // all set to NOT fixed, because detla exchange } } public void tipTimeCalibration() { this.rateOptionClockModel = FixRateType.TIP_CALIBRATED; for (PartitionClockModel model : options.getPartitionClockModels()) { model.setEstimatedRate(true); } } public void nodeCalibration() { this.rateOptionClockModel = FixRateType.NODE_CALIBRATED; for (PartitionClockModel model : options.getPartitionClockModels()) { model.setEstimatedRate(true); } } public void rateCalibration() { this.rateOptionClockModel = FixRateType.RATE_CALIBRATED; for (PartitionClockModel model : options.getPartitionClockModels()) { model.setEstimatedRate(true); } } public String statusMessageClockModel() { if (rateOptionClockModel == FixRateType.RElATIVE_TO) { if (options.getPartitionClockModels().size() == 1) { // single partition clock if (options.getPartitionClockModels().get(0).isEstimatedRate()) { return "Estimate clock rate"; } else { return "Fix clock rate to " + options.getPartitionClockModels().get(0).getRate(); } } else { String t = rateOptionClockModel.toString() + " "; int c = 0; for (PartitionClockModel model : options.getPartitionClockModels()) { if (!model.isEstimatedRate()) { if (c > 0) t = t + ", "; c = c + 1; t = t + model.getName(); } } if (c == 0) t = "Estimate all clock rates"; if (c == options.getPartitionClockModels().size()) t = "Fix all clock rates"; return t; } } else { return rateOptionClockModel.toString(); } } //+++++++++++++++++++++++ Validation ++++++++++++++++++++++++++++++++ // true => valid, false => warning message public boolean validateFixMeanRate(JCheckBox fixedMeanRateCheck) { return !(fixedMeanRateCheck.isSelected() && options.getPartitionClockModels().size() < 2); } // public boolean validateRelativeTo() { // for (PartitionClockModel model : options.getPartitionClockModels()) { // if (!model.isEstimatedRate()) { // fixed // return true; // return false; }
package dr.app.tools; import dr.app.beagle.evomodel.branchmodel.HomogeneousBranchModel; import dr.app.beagle.evomodel.parsers.GammaSiteModelParser; import dr.app.beast.BeastVersion; import dr.app.util.Arguments; import dr.app.util.Utils; import dr.evolution.alignment.Alignment; import dr.evolution.alignment.ConvertAlignment; import dr.evolution.alignment.PatternList; import dr.evolution.alignment.SimpleAlignment; //import dr.evolution.datatype.AminoAcids; //import dr.evolution.datatype.GeneralDataType; import dr.evolution.datatype.*; import dr.evolution.io.*; import dr.evolution.sequence.Sequence; import dr.evolution.tree.*; import dr.evolution.util.Taxon; import dr.evolution.util.TaxonList; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.StrictClockBranchRates; //import dr.evomodel.sitemodel.GammaSiteModel; //import dr.evomodel.sitemodel.SiteModel; //import dr.evomodel.substmodel.*; import dr.evomodel.substmodel.JTT; import dr.evomodel.substmodel.LG; import dr.evomodel.substmodel.WAG; import dr.evomodel.tree.TreeModel; import dr.evomodelxml.substmodel.GeneralSubstitutionModelParser; import dr.inference.model.Parameter; import dr.stats.DiscreteStatistics; import dr.util.HeapSort; import dr.util.Version; import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel; import dr.app.beagle.evomodel.substmodel.*; import dr.app.beagle.evomodel.sitemodel.HomogenousBranchSubstitutionModel; import dr.app.beagle.evomodel.treelikelihood.PartialsRescalingScheme; import dr.app.beagle.evomodel.treelikelihood.AncestralStateBeagleTreeLikelihood; import java.io.*; import java.util.*; import java.util.logging.Logger; /* * @author Marc A. Suchard * @author Wai Lok Sibon Li */ public class AncestralSequenceAnnotator { private final static Version version = new BeastVersion(); public final static int MAX_CLADE_CREDIBILITY = 0; public final static int MAX_SUM_CLADE_CREDIBILITY = 1; public final static int USER_TARGET_TREE = 2; public final static int KEEP_HEIGHTS = 0; public final static int MEAN_HEIGHTS = 1; public final static int MEDIAN_HEIGHTS = 2; public final String[] GENERAL_MODELS_LIST = {"EQU"}; public final String[] NUCLEOTIDE_MODELS_LIST = {"HKY", "TN", "GTR"}; public final String[] AMINO_ACID_MODELS_LIST = {"JTT1992", "WAG2001", "LG2008", "Empirical\\(.+\\)"}; public final String[] TRIPLET_MODELS_LIST = {"HKYx3", "TNx3", "GTRx3"}; public final String[] CODON_MODELS_LIST = {"M0HKY", "M0TN", "M0GTR"};//"M0", "M0\\[.+\\]", ""}; public AncestralSequenceAnnotator(int burnin, int heightsOption, double posteriorLimit, int targetOption, String targetTreeFileName, String inputFileName, String outputFileName, String kalignExecutable ) throws IOException { this.posteriorLimit = posteriorLimit; this.kalignExecutable = kalignExecutable; attributeNames.add("height"); attributeNames.add("length"); System.out.println("Reading trees and simulating internal node states..."); CladeSystem cladeSystem = new CladeSystem(); boolean firstTree = true; FileReader fileReader = new FileReader(inputFileName); TreeImporter importer = new NexusImporter(fileReader); TreeExporter exporter; if (outputFileName != null) exporter = new NexusExporter(new PrintStream(new FileOutputStream(outputFileName))); else exporter = new NexusExporter(System.out); TreeExporter simulationResults = new NexusExporter(new PrintStream(new FileOutputStream(inputFileName + ".out"))); List<Tree> simulatedTree = new ArrayList<Tree>(); // burnin = 0; // java.util.logging.Logger.getLogger("dr.evomodel"). try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (firstTree) { Tree unprocessedTree = tree; tree = processTree(tree); setupTreeAttributes(tree); setupAttributes(tree); tree = unprocessedTree; //This actually does nothing since unprocessedTree was a reference to processedTree in the first place firstTree = false; } if (totalTrees >= burnin) { addTreeAttributes(tree); // Tree savedTree = tree; tree = processTree(tree); // System.err.println(Tree.Utils.newick(tree)); exporter.exportTree(tree); // simulationResults.exportTree(tree); // System.exit(-1); simulatedTree.add(tree); cladeSystem.add(tree); totalTreesUsed += 1; } totalTrees += 1; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } fileReader.close(); cladeSystem.calculateCladeCredibilities(totalTreesUsed); System.out.println("\tTotal trees read: " + totalTrees); if (burnin > 0) { System.out.println("\tIgnoring first " + burnin + " trees."); } simulationResults.exportTrees(simulatedTree.toArray(new Tree[simulatedTree.size()])); MutableTree targetTree; if (targetOption == USER_TARGET_TREE) { if (targetTreeFileName != null) { System.out.println("Reading user specified target tree, " + targetTreeFileName); importer = new NexusImporter(new FileReader(targetTreeFileName)); try { targetTree = new FlexibleTree(importer.importNextTree()); } catch (Importer.ImportException e) { System.err.println("Error Parsing Target Tree: " + e.getMessage()); return; } } else { System.err.println("No user target tree specified."); return; } } else if (targetOption == MAX_CLADE_CREDIBILITY) { System.out.println("Finding maximum credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, false)); } else if (targetOption == MAX_SUM_CLADE_CREDIBILITY) { System.out.println("Finding maximum sum clade credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, true)); } else { throw new RuntimeException("Unknown target tree option"); } System.out.println("Annotating target tree... (this may take a long time)"); // System.out.println("Starting processing...."); // System.out.println("calling annotateTree"); // System.out.println("targetTree has "+targetTree.getNodeCount()+" nodes."); cladeSystem.annotateTree(targetTree, targetTree.getRoot(), null, heightsOption); System.out.println("Processing ended."); System.out.println("Writing annotated tree...."); if (outputFileName != null) { exporter = new NexusExporter(new PrintStream(new FileOutputStream(outputFileName))); exporter.exportTree(targetTree); } else { exporter = new NexusExporter(System.out); exporter.exportTree(targetTree); } } private abstract class SubstitutionModelLoader { public final char[] AA_ORDER = AminoAcids.AMINOACID_CHARS; public final char[] NUCLEOTIDE_ORDER = Nucleotides.NUCLEOTIDE_CHARS; public final String[] CODON_ORDER = Codons.CODON_TRIPLETS; protected SubstitutionModel substModel; protected FrequencyModel freqModel; private String modelType; protected String substModelName; protected String[] charList; protected DataType dataType; SubstitutionModelLoader(Tree tree, String modelType, DataType dataType) { this.dataType = dataType; this.modelType = modelType; load(tree, modelType); } /* An artifact of old code? */ SubstitutionModelLoader(String name) { this.substModelName = name; } public SubstitutionModel getSubstitutionModel() { return substModel; } public FrequencyModel getFrequencyModel() { return freqModel; } public String getModelType() { return modelType; } public String getSubstModel() { return substModelName; } public String[] getCharList() { return charList; } public void setCharList(String[] cl) { System.arraycopy(cl, 0, charList, 0, cl.length); //charList = cl.clone(); } public abstract DataType getDataType(); protected abstract void modelSpecifics(Tree tree, String modelType); public void load(Tree tree, String modelType) { substModelName = modelType.replaceFirst("\\*.+","").replaceFirst("\\+.+","").trim(); loadFrequencyModel(tree); modelSpecifics(tree, modelType); printLogLikelihood(tree); } private void loadFrequencyModel(Tree tree) { final String[] AA_ORDER = {"A","C","D","E","F","G","H","I","K","L","M","N","P","Q","R", "S","T","V","W","Y"}; //"ACDEFGHIKLMNPQRSTVWY".split("");//AminoAcids.AMINOACID_CHARS; final String[] DNA_NUCLEOTIDE_ORDER = {"A", "C", "G", "T"};//"ACGT".split(""); //Nucleotides.NUCLEOTIDE_CHARS; final String[] RNA_NUCLEOTIDE_ORDER = {"A", "C", "G", "U"};//"ACGU".split(""); //Nucleotides.NUCLEOTIDE_CHARS; // final String[] CODON_ORDER = {"AAA", "AAC", "AAG", "AAT", "ACA", "ACC", "ACG", "ACT", // "AGA", "AGC", "AGG", "AGT", "ATA", "ATC", "ATG", "ATT", // "CAA", "CAC", "CAG", "CAT", "CCA", "CCC", "CCG", "CCT", // "CGA", "CGC", "CGG", "CGT", "CTA", "CTC", "CTG", "CTT", // "GAA", "GAC", "GAG", "GAT", "GCA", "GCC", "GCG", "GCT", // "GGA", "GGC", "GGG", "GGT", "GTA", "GTC", "GTG", "GTT", // "TAA", "TAC", "TAG", "TAT", "TCA", "TCC", "TCG", "TCT", // "TGA", "TGC", "TGG", "TGT", "TTA", "TTC", "TTG", "TTT"};// Codons.CODON_TRIPLETS; final String[] DNA_CODON_ORDER = {"AAA", "AAC", "AAG", "AAT", "ACA", "ACC", "ACG", "ACT", "AGA", "AGC", "AGG", "AGT", "ATA", "ATC", "ATG", "ATT", "CAA", "CAC", "CAG", "CAT", "CCA", "CCC", "CCG", "CCT", "CGA", "CGC", "CGG", "CGT", "CTA", "CTC", "CTG", "CTT", "GAA", "GAC", "GAG", "GAT", "GCA", "GCC", "GCG", "GCT", "GGA", "GGC", "GGG", "GGT", "GTA", "GTC", "GTG", "GTT", /*"TAA",*/ "TAC", /*"TAG",*/ "TAT", "TCA", "TCC", "TCG", "TCT", /* Minus the stop and start codons */ /*"TGA",*/ "TGC", "TGG", "TGT", "TTA", "TTC", "TTG", "TTT"};// Codons.CODON_TRIPLETS; final String[] RNA_CODON_ORDER = {"AAA", "AAC", "AAG", "AAU", "ACA", "ACC", "ACG", "ACU", "AGA", "AGC", "AGG", "AGU", "AUA", "AUC", "AUG", "AUU", "CAA", "CAC", "CAG", "CAU", "CCA", "CCC", "CCG", "CCU", "CGA", "CGC", "CGG", "CGU", "CUA", "CUC", "CUG", "CUU", "GAA", "GAC", "GAG", "GAU", "GCA", "GCC", "GCG", "GCU", "GGA", "GGC", "GGG", "GGU", "GUA", "GUC", "GUG", "GUU", /*"UAA",*/ "UAC", /*"UAG",*/ "UAU", "UCA", "UCC", "UCG", "UCU", /* Minus the stop and start codons */ /*"UGA",*/ "UGC", "UGG", "UGU", "UUA", "UUC", "UUG", "UUU"};// Codons.CODON_TRIPLETS; /* For BAli-Phy, even if F=constant, you can still extract the frequencies this way. */ /* Obtain the equilibrium base frequencies for the model */ double[] freq = new double[0]; String[] charOrder = new String[0]; if(getDataType().getClass().equals(GeneralDataType.class)) { ArrayList<String> tempCharOrder = new ArrayList<String>(freq.length); for (Iterator<String> i = tree.getAttributeNames(); i.hasNext();) { String name = i.next(); if (name.startsWith("pi")) { /* the pi in the output files contains the frequencies */ String character = name.substring(2, name.length()); tempCharOrder.add(character); } } charOrder = tempCharOrder.toArray(new String[tempCharOrder.size()]); //this.charList = tempCharOrder.toArray(new String[tempCharOrder.size()]); freq = new double[charOrder.length]; } else if(getDataType().getClass().equals(Nucleotides.class)) { if(tree.getAttribute("piT") != null) { charOrder = DNA_NUCLEOTIDE_ORDER; freq = new double[charOrder.length]; } else if(tree.getAttribute("piU") != null) { charOrder = RNA_NUCLEOTIDE_ORDER; freq = new double[charOrder.length]; } else { throw new RuntimeException("Not proper nucleotide data"); } } else if(getDataType().getClass().equals(AminoAcids.class)) { charOrder = AA_ORDER; freq = new double[charOrder.length]; } else if(getDataType().getClass().equals(Codons.class)) { if(tree.getAttribute("piAAT") != null) { charOrder = DNA_CODON_ORDER; freq = new double[charOrder.length]; } else if(tree.getAttribute("piAAU") != null) { charOrder = RNA_CODON_ORDER; freq = new double[charOrder.length]; } else{ throw new RuntimeException("Base frequencies do not fit those for a codon model or not proper nucleotide data for codons\n" + "If you are using F=nucleotides models for codon models, they are currently not supported in BEAST"); } } else { throw new RuntimeException("Datatype unknown! (This error message should never be seen, contact Sibon)"); } // // This if statement is reserved for triplet data // else if(getDataType().getClass().equals(Nucleotides.class)) { // // This is wrong because for triplets // freq = new double[Nucleotides.NUCLEOTIDE_CHARS.length]; int cnt = 0; double sum = 0; //charList = ""; ArrayList<String> tempCharList = new ArrayList<String>(freq.length); for (Iterator<String> i = tree.getAttributeNames(); i.hasNext();) { String name = i.next(); if (name.startsWith("pi")) { /* the pi in the output files contains the frequencies */ String character = name.substring(2, name.length()); tempCharList.add(character); //charList = charList.concat(character); Double value = (Double) tree.getAttribute(name); freq[cnt++] = value; sum += value; } } charList = tempCharList.toArray(new String[tempCharList.size()]); // for(int j=0; j<charList.length; j++) { // System.out.println("charizard lists " + charList[j]); /* Order the frequencies correctly */ double[] freqOrdered = new double[freq.length]; for (int i = 0; i < freqOrdered.length; i++) { int index = -5; search: for (int j = 0; j < charList.length; j++) { if(charList[j].equals(charOrder[i])) { index = j; break search; } } freqOrdered[i] = freq[index] / sum; //System.out.println(" no fried " + freqOrdered.length + "\t" + freq.length + "\t" + charOrder[i] + "\t" + freqOrdered[i]); //ddd } this.freqModel = new FrequencyModel(getDataType(), new Parameter.Default(freqOrdered)); } protected boolean doPrint = false; private void printLogLikelihood(Tree tree) { if (doPrint) { Double logLikelihood = Double.parseDouble(tree.getAttribute(LIKELIHOOD).toString()); if (logLikelihood != null) System.err.printf("%5.1f", logLikelihood); } } } private class GeneralSubstitutionModelLoader extends SubstitutionModelLoader { private final String EQU_TEXT = "EQU"; private GeneralSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, new GeneralDataType(new String[0])); setGeneralDataType(); throw new RuntimeException("General substitution model is currently not stable and should not be used"); } protected void modelSpecifics(Tree tree, String modelType) { if(substModelName.equals(EQU_TEXT)) { if(freqModel.getFrequencyCount() != charList.length) { System.err.println("Frequency model length does not match character list length, " + "GeneralSubstitutionModelLoader"); System.exit(-1); } /* Equivalent to a JC model but for all states */ //TODO CHECK IF THIS IS CORRECT double[] rates = new double[(charList.length * (charList.length - 1)) / 2]; for(int i=0; i<rates.length; i++) { rates[i] = 1.0; } System.out.println("Number of site transition rate categories (debuggin): " + rates.length); //substModel = new GeneralSubstitutionModel(freqModel.getDataType(), freqModel, new Parameter.Default(rates), 1); substModel = new GeneralSubstitutionModel(GeneralSubstitutionModelParser.GENERAL_SUBSTITUTION_MODEL, freqModel.getDataType(), freqModel, new Parameter.Default(rates), 1, null); } } public DataType getDataType() { setGeneralDataType(); return dataType; } public void setGeneralDataType() { if(charList!=null && dataType.getStateCount()!=charList.length) { GeneralDataType gdt = new GeneralDataType(charList); gdt.addAmbiguity("-", charList); gdt.addAmbiguity("X", charList); gdt.addAmbiguity("?", charList); dataType = gdt; } } } private class NucleotideSubstitutionModelLoader extends SubstitutionModelLoader { protected static final String HKY_TEXT = "HKY"; protected static final String TN_TEXT = "TN"; protected static final String GTR_TEXT = "GTR"; private NucleotideSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, Nucleotides.INSTANCE); } protected void modelSpecifics(Tree tree, String modelType) { if(substModelName.equals(HKY_TEXT)) { double kappa = Double.parseDouble(tree.getAttribute("HKY_kappa").toString()); //double kappa = (Double) tree.getAttribute("HKY_kappa"); //double kappa = (Double) tree.getAttribute("HKY\\:\\:kappa"); //double kappa = (Double) tree.getAttribute("HKY::kappa"); //double kappa = (Double) tree.getAttribute("kappa"); substModel = new HKY(new Parameter.Default(kappa), freqModel); } if(substModelName.equals(TN_TEXT)) { double kappa1 = Double.parseDouble(tree.getAttribute("TN_kappa(pur)").toString()); double kappa2 = Double.parseDouble(tree.getAttribute("TN_kappa(pyr)").toString()); //double kappa1 = (Double) tree.getAttribute("TN_kappa(pur)"); //double kappa2 = (Double) tree.getAttribute("TN_kappa(pyr)"); System.err.println("Sorry, TN substitution model is not yet implemented in BEAST-Beagle"); System.exit(0); //TODO Tamura-Nei model //substModel = new TN93(new Parameter.Default(kappa1), new Parameter.Default(kappa2), freqModel); } if(substModelName.equals(GTR_TEXT)) { /* It should be noted that BAli-Phy uses TC instead of CT and GC instead of CG */ //double rateACValue = (Double) tree.getAttribute("GTR_AC"); //double rateAGValue = (Double) tree.getAttribute("GTR_AG"); //double rateATValue = (Double) tree.getAttribute("GTR_AT"); //double rateCGValue = (Double) tree.getAttribute("GTR_GC"); //double rateCTValue = (Double) tree.getAttribute("GTR_TC"); //double rateGTValue = (Double) tree.getAttribute("GTR_GT"); double rateACValue = Double.parseDouble(tree.getAttribute("GTR_AC").toString()); double rateAGValue = Double.parseDouble(tree.getAttribute("GTR_AG").toString()); double rateATValue = Double.parseDouble(tree.getAttribute("GTR_AT").toString()); double rateCGValue = Double.parseDouble(tree.getAttribute("GTR_GC").toString()); double rateCTValue = Double.parseDouble(tree.getAttribute("GTR_TC").toString()); double rateGTValue = Double.parseDouble(tree.getAttribute("GTR_GT").toString()); substModel = new GTR(new Parameter.Default(rateACValue), new Parameter.Default(rateAGValue), new Parameter.Default(rateATValue), new Parameter.Default(rateCGValue), new Parameter.Default(rateCTValue), new Parameter.Default(rateGTValue), freqModel); } } public DataType getDataType() { return dataType; //Potential } } private class AminoAcidSubstitutionModelLoader extends SubstitutionModelLoader { protected final String JTT_TEXT = "JTT1992"; protected final String WAG_TEXT = "WAG2001"; protected final String LG_TEXT = "LG2008"; protected final String Empirical_TEXT = "Empirical(.+).+"; private AminoAcidSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, AminoAcids.INSTANCE); } protected void modelSpecifics(Tree tree, String modelType) { if(substModelName.equals(JTT_TEXT)) { substModel = new EmpiricalAminoAcidModel(JTT.INSTANCE, freqModel); } if(substModelName.equals(WAG_TEXT)) { substModel = new EmpiricalAminoAcidModel(WAG.INSTANCE, freqModel); } if(substModelName.equals(LG_TEXT)) { substModel = new EmpiricalAminoAcidModel(LG.INSTANCE, freqModel); } //todo Allow proper file input of Empirical amino-acid models if(substModelName.matches(Empirical_TEXT)) { String empiricalModelFileName = substModelName.replaceFirst("Empirical\\(", "").replaceFirst("\\).*",""); if (empiricalModelFileName.equals("wag.dat")) { substModel = new EmpiricalAminoAcidModel(WAG.INSTANCE, freqModel); } else if(empiricalModelFileName.equals("jtt.dat")) { substModel = new EmpiricalAminoAcidModel(JTT.INSTANCE, freqModel); } else if(empiricalModelFileName.equals("lg.dat")) { substModel = new EmpiricalAminoAcidModel(LG.INSTANCE, freqModel); } else { System.err.println("Sorry, AncestralSequenceAnnotator does not currently support other files"); System.err.println("Soon, we will allow users to enter a file"); System.exit(0); } } } public DataType getDataType() { return dataType; //Potential } } private class TripletSubstitutionModelLoader extends SubstitutionModelLoader { protected final String HKYx3_TEXT = "HKYx3"; protected final String TNx3_TEXT = "TNx3"; protected final String GTRx3_TEXT = "GTRx3"; private TripletSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, Nucleotides.INSTANCE); } protected void modelSpecifics(Tree tree, String modelType) { if(substModelName.equals(HKYx3_TEXT)) { System.err.println("Sorry, HKYx3 substitution model is not yet implemented in BEAST"); System.exit(0); //substModel = new HKY(); } if(substModelName.equals(TNx3_TEXT)) { System.err.println("Sorry, TNx3 substitution model is not yet implemented in BEAST"); System.exit(0); //substModel = new TN93(); } if(substModelName.equals(GTRx3_TEXT)) { System.err.println("Sorry, GTRx3 substitution model is not yet implemented in BEAST"); System.exit(0); //substModel = new GTR(); } } public DataType getDataType() { return dataType; // Is this right? } } private class CodonSubstitutionModelLoader extends SubstitutionModelLoader { // private final String M0_TEXT = "M0"; // Not necessary since this never actually shows up in BAli-Phy output protected final String M0_NUC_TEXT = "M0\\w+"; //private final String HKY_TEXT = "HKY"; //private final String TN_TEXT = "TN"; //private final String GTR_TEXT = "GTR"; private CodonSubstitutionModelLoader(Tree tree, String modelType) { super(tree, modelType, Codons.UNIVERSAL); //Potential } protected void modelSpecifics(Tree tree, String modelType) { //String codonNucleotideModel = substModelName.substring(substModelName.indexOf("\\\\[")+1, substModelName.indexOf("\\\\]")); String codonNucleotideModel = substModelName.substring(substModelName.indexOf("M0")+2, substModelName.length()); // if(substModelName.equals(M0_TEXT)) { // /* HKY is default */ // codonNucleotideModel = NucleotideSubstitutionModelLoader.HKY_TEXT; if(substModelName.matches(M0_NUC_TEXT)) { /* M0_omega may be *M0_omega, depending on whether M2 etc. are used */ double omega = Double.parseDouble(tree.getAttribute("M0_omega").toString()); //omega = (Double) tree.getAttribute("\\M0_omega"); if(codonNucleotideModel.equals(NucleotideSubstitutionModelLoader.HKY_TEXT)) { //double kappa = (Double) tree.getAttribute("HKY_kappa"); double kappa = Double.parseDouble(tree.getAttribute("HKY_kappa").toString()); //substModel = new YangCodonModel(Codons.UNIVERSAL, new Parameter.Default(omega), //new Parameter.Default(kappa), freqModel); substModel = new GY94CodonModel(Codons.UNIVERSAL, new Parameter.Default(omega), new Parameter.Default(kappa), freqModel); } if(codonNucleotideModel.equals(NucleotideSubstitutionModelLoader.TN_TEXT)) { //double kappa1 = (Double) tree.getAttribute("TN_kappa(pur)"); //double kappa2 = (Double) tree.getAttribute("TN_kappa(pyr)"); double kappa1 = Double.parseDouble(tree.getAttribute("TN_kappa(pur)").toString()); double kappa2 = Double.parseDouble(tree.getAttribute("TN_kappa(pyr)").toString()); System.err.println("Sorry, M0[TN] substitution model is not yet implemented in BEAST"); System.exit(0); } if(codonNucleotideModel.equals(NucleotideSubstitutionModelLoader.GTR_TEXT)) { double rateACValue = Double.parseDouble(tree.getAttribute("GTR_AC").toString()); double rateAGValue = Double.parseDouble(tree.getAttribute("GTR_AG").toString()); double rateATValue = Double.parseDouble(tree.getAttribute("GTR_AT").toString()); double rateCGValue = Double.parseDouble(tree.getAttribute("GTR_GC").toString()); double rateCTValue = Double.parseDouble(tree.getAttribute("GTR_TC").toString()); double rateGTValue = Double.parseDouble(tree.getAttribute("GTR_GT").toString()); //double rateACValue = (Double) tree.getAttribute("GTR_AC"); //double rateAGValue = (Double) tree.getAttribute("GTR_AG"); //double rateATValue = (Double) tree.getAttribute("GTR_AT"); //double rateCGValue = (Double) tree.getAttribute("GTR_GC"); //double rateCTValue = (Double) tree.getAttribute("GTR_TC"); //double rateGTValue = (Double) tree.getAttribute("GTR_GT"); System.err.println("Sorry, M0[GTR] substitution model is not yet implemented in BEAST"); System.exit(0); } // If +m2 then *M0 } } public DataType getDataType() { return dataType; // Is this right too? Just use the universal codon table? } } /* * This method is equivalent to the SubstitutionModelLoader without having to * be object orientated and can be much more flexible. */ private GammaSiteRateModel loadSiteModel(Tree tree) { String modelType = (String) tree.getAttribute(SUBST_MODEL); /* Identify the datatype and substitution model. Load the model */ SubstitutionModelLoader sml = null; String substModelName = modelType.replaceFirst("\\*.+","").replaceFirst("\\+.+","").trim(); System.out.println("Basic Substitution Model is " + substModelName); for(int i = 0; i<GENERAL_MODELS_LIST.length; i++) { if(substModelName.matches(GENERAL_MODELS_LIST[i])) { sml = new GeneralSubstitutionModelLoader(tree, modelType); } } for(int i = 0; i<NUCLEOTIDE_MODELS_LIST.length; i++) { if(substModelName.matches(NUCLEOTIDE_MODELS_LIST[i])) { sml = new NucleotideSubstitutionModelLoader(tree, modelType); } } for(int i = 0; i<AMINO_ACID_MODELS_LIST.length; i++) { if(substModelName.matches(AMINO_ACID_MODELS_LIST[i])) { sml = new AminoAcidSubstitutionModelLoader(tree, modelType); } } for(int i = 0; i<TRIPLET_MODELS_LIST.length; i++) { if(substModelName.matches(TRIPLET_MODELS_LIST[i])) { sml = new TripletSubstitutionModelLoader(tree, modelType); } } for(int i = 0; i<CODON_MODELS_LIST.length; i++) { if(substModelName.matches(CODON_MODELS_LIST[i])) { sml = new CodonSubstitutionModelLoader(tree, modelType); } } if (sml.getSubstitutionModel() == null) { System.err.println("Substitution model type '" + modelType + "' not implemented"); System.exit(-1); } //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), new Parameter.Default(1.0), null, 0, null); //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), null, null, 0, null); String siteRatesModels = modelType.substring(modelType.indexOf("+")+1, modelType.length()); //String[] siteRatesModels = siteRatesParameters.split(" + "); System.out.println("Site rate models: " + siteRatesModels); if(sml.getSubstitutionModel().getDataType().getClass().equals(Codons.class) && siteRatesModels.length() > 0) { /* For codon site models */ if(siteRatesModels.indexOf("+M2") >= 0) { System.out.println("Site model - M2 Codon site model used"); Parameter m2FrequencyAAInv = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_f[AA INV]").toString())); Parameter m2FrequencyNeutral = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_f[Neutral]").toString())); Parameter m2FrequencySelected = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_f[Selected]").toString())); Parameter m2Omega = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_omega").toString())); //Parameter m2FrequencyAAInv = new Parameter.Default((Double) tree.getAttribute("M2_f[AA INV]")); //Parameter m2FrequencyNeutral = new Parameter.Default((Double) tree.getAttribute("M2_f[Neutral]")); //Parameter m2FrequencySelected = new Parameter.Default((Double) tree.getAttribute("M2_f[Selected]")); //Parameter m2Omega = new Parameter.Default((Double) tree.getAttribute("M2_omega")); System.err.println("Sorry, M2 substitution model is not yet implemented in BEAST"); System.exit(0); } else if(siteRatesModels.indexOf("+M3") >= 0) { System.out.println("Site model - M3 Codon site model used"); int numberOfBins = Integer.parseInt(siteRatesModels.replaceFirst(".+M3\\[","").replaceFirst("\\].+", "")); System.out.println(" + M3 n value: " + numberOfBins); Parameter[] m3Frequencies = new Parameter[numberOfBins]; Parameter[] m3Omegas = new Parameter[numberOfBins]; for(int i=1; i<=numberOfBins; i++) { m3Frequencies[i-1] = new Parameter.Default(Double.parseDouble(tree.getAttribute("M3_f"+i).toString())); m3Omegas[i-1] = new Parameter.Default(Double.parseDouble(tree.getAttribute("M3_omega"+i).toString())); //m3Frequencies[i-1] = new Parameter.Default((Double) tree.getAttribute("M3_f"+i)); //m3Omegas[i-1] = new Parameter.Default((Double) tree.getAttribute("M3_omega"+i)); } System.err.println("Sorry, M3 substitution model is not yet implemented in BEAST"); System.exit(0); } else if(siteRatesModels.indexOf("+M0_omega~Beta(") >= 0) { System.out.println("Site model - M7 Codon site model used"); int numberOfBins = Integer.parseInt(siteRatesModels.replaceFirst("M0_omega~Beta\\(","").replaceFirst("\\)", "")); System.out.println(" + M7 n value: " + numberOfBins); Parameter m7BetaMu = new Parameter.Default(Double.parseDouble(tree.getAttribute("beta_mu").toString())); Parameter m7BetaVarMu = new Parameter.Default(Double.parseDouble(tree.getAttribute("beta_Var/mu").toString())); //Parameter m7BetaMu = new Parameter.Default((Double) tree.getAttribute("beta_mu")); //Parameter m7BetaVarMu = new Parameter.Default((Double) tree.getAttribute("beta_Var/mu")); System.err.println("Sorry, M7 substitution model is not yet implemented in BEAST"); System.exit(0); } } else if(siteRatesModels.length() > 0) { /* i.e. for other data types. */ /* Do gamma/lognormal + pinv */ Parameter pInvParameter = null; int categories = -1; Parameter alphaParameter = null; //System.out.println("Greatest story ever told! " + siteRatesModels); if(siteRatesModels.indexOf("+INV") >= 0) { System.out.println("Site model - proportion of invariable sites used"); //pInvParameter = new Parameter.Default(((Double) tree.getAttribute("INV_p")).doubleValue()); pInvParameter = new Parameter.Default(Double.parseDouble(tree.getAttribute("INV_p").toString())); } if(siteRatesModels.indexOf("+rate~Gamma(") >= 0) { System.out.println("Site model - gamma site rate heterogeneity used"); categories = Integer.parseInt(siteRatesModels.replaceFirst(".+rate~Gamma\\(", "").replaceFirst("\\).*","")); //double sigmaMu = (Double) tree.getAttribute("gamma_sigma/mu"); double sigmaMu = Double.parseDouble(tree.getAttribute("gamma_sigma/mu").toString()); sigmaMu = (1.0/sigmaMu) * (1.0/sigmaMu); /* BAli-Phy is parameterised by sigma/mu instead of alpha */ alphaParameter = new Parameter.Default(sigmaMu); } else if(siteRatesModels.indexOf("+rate~LogNormal(") >= 0) { // TODO implement lognormal site model System.out.println("Site model - lognormal site rate heterogeneity used"); System.err.println("Sorry, lognormal site rates are not yet implemented in BEAST"); System.exit(0); categories = Integer.parseInt(siteRatesModels.replaceFirst(".+rate~LogNormal\\(", "").replaceFirst("\\).*","")); //double sigmaMu = (Double) tree.getAttribute("log-normal_sigma/mu"); double sigmaMu = Double.parseDouble(tree.getAttribute("log-normal_sigma/mu").toString()); sigmaMu = (1.0/sigmaMu) * (1.0/sigmaMu); /* BAli-Phy is parameterised by sigma/mu instead of alpha */ alphaParameter = new Parameter.Default(sigmaMu); } else if(siteRatesModels.indexOf("+GAMMA(") >= 0) { /* For BEAST output */ System.out.println("Site model - gamma site rate heterogeneity used"); categories = Integer.parseInt(siteRatesModels.replaceFirst(".+GAMMA\\(", "").replaceFirst("\\).*","")); //double sigmaMu = (Double) tree.getAttribute("gamma_sigma/mu"); double alpha = Double.parseDouble(tree.getAttribute("alpha").toString()); alphaParameter = new Parameter.Default(alpha); } //System.out.println("alpha and pinv parameters: " + alphaParameter.getParameterValue(0) + "\t" + pInvParameter.getParameterValue(0)); //GammaSiteRateModel siteModel = new GammaSiteRateModel(sml.getSubstitutionModel(), new Parameter.Default(1.0), alphaParameter, categories, pInvParameter); GammaSiteRateModel siteModel = new GammaSiteRateModel(GammaSiteModelParser.SITE_MODEL, new Parameter.Default(1.0), alphaParameter, categories, pInvParameter); siteModel.setSubstitutionModel(sml.getSubstitutionModel()); //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), new Parameter.Default(1.0), new Parameter.Default(1.0), 1, new Parameter.Default(0.5)); //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), null, null, 0, null); return siteModel; } /* Default with no gamma or pinv */ //SiteRateModel siteModel = new GammaSiteRateModel(sml.getSubstitutionModel()); GammaSiteRateModel siteModel = new GammaSiteRateModel(GammaSiteModelParser.SITE_MODEL); siteModel.setSubstitutionModel(sml.getSubstitutionModel()); return siteModel; } public static final String KAPPA_STRING = "kappa"; //public static final String SEQ_STRING = "states"; // For BEAST input files public static String SEQ_STRING = "seq"; //public static final String SEQ_STRING_2 = "states"; // For BEAST input files public static final String NEW_SEQ = "newSeq"; public static final String TAG = "tag"; public static final String LIKELIHOOD = "lnL"; public static final String SUBST_MODEL = "subst"; // public static final String WAG_STRING = "Empirical(Data/wag.dat)*pi"; private final int die = 0; private Tree processTree(Tree tree) { // Remake tree to fix node ordering - Marc GammaSiteRateModel siteModel = loadSiteModel(tree); SimpleAlignment alignment = new SimpleAlignment(); alignment.setDataType(siteModel.getSubstitutionModel().getDataType()); if(siteModel.getSubstitutionModel().getDataType().getClass().equals(Codons.class)) { //System.out.println("trololo"); alignment.setDataType(Nucleotides.INSTANCE); } //System.out.println("BOO BOO " + siteModel.getSubstitutionModel().getDataType().getClass().getName()+"\t" + Codons.UNIVERSAL.getClass().getName() + "\t" + alignment.getDataType().getClass().getName()); // Get sequences String[] sequence = new String[tree.getNodeCount()]; for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); sequence[i] = (String) tree.getNodeAttribute(node, SEQ_STRING); if (tree.isExternal(node)) { Taxon taxon = tree.getNodeTaxon(node); alignment.addSequence(new Sequence(taxon, sequence[i])); //System.out.println("seq " + sequence[i]); } } // Make evolutionary model BranchRateModel rateModel = new StrictClockBranchRates(new Parameter.Default(1.0)); FlexibleTree flexTree; if(siteModel.getSubstitutionModel().getDataType().getClass().equals(Codons.class)) { ConvertAlignment convertAlignment = new ConvertAlignment(siteModel.getSubstitutionModel().getDataType(), ((Codons) siteModel.getSubstitutionModel().getDataType()).getGeneticCode(), alignment); flexTree = sampleTree(tree, convertAlignment, siteModel, rateModel); //flexTree = sampleTree(tree, alignment, siteModel, rateModel); } else { flexTree = sampleTree(tree, alignment, siteModel, rateModel); } introduceGaps(flexTree, tree); return flexTree; } private void introduceGaps(FlexibleTree flexTree, Tree gapTree) { // I forget what this function was supposed to do. - Marc } public static final char GAP = '-'; boolean[] bit = null; private FlexibleTree sampleTree(Tree tree, PatternList alignment, GammaSiteRateModel siteModel, BranchRateModel rateModel) { FlexibleTree flexTree = new FlexibleTree(tree, true); flexTree.adoptTreeModelOrdering(); FlexibleTree finalTree = new FlexibleTree(tree); finalTree.adoptTreeModelOrdering(); TreeModel treeModel = new TreeModel(tree); // Turn off noisy logging by TreeLikelihood constructor Logger logger = Logger.getLogger("dr.evomodel"); boolean useParentHandlers = logger.getUseParentHandlers(); logger.setUseParentHandlers(false); // AncestralStateTreeLikelihood likelihood = new AncestralStateTreeLikelihood( // alignment, // treeModel, // siteModel, // rateModel, // false, true, // alignment.getDataType(), // TAG, // false); AncestralStateBeagleTreeLikelihood likelihood = new AncestralStateBeagleTreeLikelihood( alignment, treeModel, new HomogeneousBranchModel(siteModel.getSubstitutionModel()), siteModel, rateModel, null, false, PartialsRescalingScheme.DEFAULT, null, alignment.getDataType(), TAG, false, true ); // PatternList patternList, TreeModel treeModel, // BranchSiteModel branchSiteModel, // SiteRateModel siteRateModel, // BranchRateModel branchRateModel, // boolean useAmbiguities, // PartialsRescalingScheme scalingScheme, // Map<Set<String>, Parameter> partialsRestrictions, // final DataType dataType, // final String tag, // SubstitutionModel substModel, // boolean useMAP, // boolean returnML) { // PatternList patternList, TreeModel treeModel, // SiteModel siteModel, BranchRateModel branchRateModel, // boolean useAmbiguities, boolean storePartials, // final DataType dataType, // final String tag, // boolean forceRescaling, // boolean useMAP, // boolean returnML) { logger.setUseParentHandlers(useParentHandlers); // Sample internal nodes likelihood.makeDirty(); double logLikelihood = likelihood.getLogLikelihood(); System.out.println("The new and old Likelihood (this value should be roughly the same, debug?): " + logLikelihood + ", " + Double.parseDouble(tree.getAttribute(LIKELIHOOD).toString())); if(Double.parseDouble(tree.getAttribute(LIKELIHOOD).toString()) != logLikelihood) { /* Newly written check, not sure if this is correct. May need to round values at least */ //throw new RuntimeException("The values of likelihood are not identical"); } // System.err.printf("New logLikelihood = %4.1f\n", logLikelihood); flexTree.setAttribute(LIKELIHOOD, logLikelihood); TreeTrait ancestralStates = likelihood.getTreeTrait(TAG); for (int i = 0; i < treeModel.getNodeCount(); i++) { NodeRef node = treeModel.getNode(i); String sample = ancestralStates.getTraitString(treeModel, node); String oldSeq = (String) flexTree.getNodeAttribute(flexTree.getNode(i), SEQ_STRING); if (oldSeq != null) { char[] seq = (sample.substring(1, sample.length() - 1)).toCharArray(); int length = oldSeq.length(); //System.out.println("length " + length + "\t" + sample.length() + "\t" + sample + "\t" + seq.length + "\t" + oldSeq); for (int j = 0; j < length; j++) { if (oldSeq.charAt(j) == GAP) seq[j] = GAP; } String newSeq = new String(seq); // if( newSeq.contains("MMMMMMM") ) { // System.err.println("bad = "+newSeq); // System.exit(-1); finalTree.setNodeAttribute(finalTree.getNode(i), NEW_SEQ, newSeq); } // Taxon taxon = finalTree.getNodeTaxon(finalTree.getNode(i)); // System.err.println("node: "+(taxon == null ? "null" : taxon.getId())+" "+ // finalTree.getNodeAttribute(finalTree.getNode(i),NEW_SEQ)); } return finalTree; } private void setupAttributes(Tree tree) { for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); Iterator iter = tree.getNodeAttributeNames(node); if (iter != null) { while (iter.hasNext()) { String name = (String) iter.next(); if (!attributeNames.contains(name)) attributeNames.add(name); } } } } private void setupTreeAttributes(Tree tree) { Iterator<String> iter = tree.getAttributeNames(); if (iter != null) { while (iter.hasNext()) { String name = iter.next(); treeAttributeNames.add(name); } } } private void addTreeAttributes(Tree tree) { if (treeAttributeNames != null) { if (treeAttributeLists == null) { treeAttributeLists = new List[treeAttributeNames.size()]; for (int i = 0; i < treeAttributeNames.size(); i++) { treeAttributeLists[i] = new ArrayList(); } } for (int i = 0; i < treeAttributeNames.size(); i++) { String attributeName = treeAttributeNames.get(i); Object value = tree.getAttribute(attributeName); if (value != null) { treeAttributeLists[i].add(value); } } } } private Tree summarizeTrees(int burnin, CladeSystem cladeSystem, String inputFileName, boolean useSumCladeCredibility) throws IOException { Tree bestTree = null; double bestScore = Double.NEGATIVE_INFINITY; // System.out.println("Analyzing " + totalTreesUsed + " trees..."); // System.out.println("0 25 50 75 100"); int stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; int counter = 0; TreeImporter importer = new NexusImporter(new FileReader(inputFileName)); try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (counter >= burnin) { double score = scoreTree(tree, cladeSystem, useSumCladeCredibility); // System.out.println(score); if (score > bestScore) { bestTree = tree; bestScore = score; } } if (counter > 0 && counter % stepSize == 0) { // System.out.print("*"); // System.out.flush(); } counter++; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return null; } // System.out.println(); // System.out.println(); if (useSumCladeCredibility) { System.out.println("\tHighest Sum Clade Credibility: " + bestScore); } else { System.out.println("\tHighest Log Clade Credibility: " + bestScore); } return bestTree; } private double scoreTree(Tree tree, CladeSystem cladeSystem, boolean useSumCladeCredibility) { if (useSumCladeCredibility) { return cladeSystem.getSumCladeCredibility(tree, tree.getRoot(), null); } else { return cladeSystem.getLogCladeCredibility(tree, tree.getRoot(), null); } } private class CladeSystem { // Public stuff public CladeSystem() { } /** * adds all the clades in the tree */ public void add(Tree tree) { if (taxonList == null) { taxonList = tree; } // Recurse over the tree and add all the clades (or increment their // frequency if already present). The root clade is added too (for // annotation purposes). addClades(tree, tree.getRoot(), null); addTreeAttributes(tree); } public Map<BitSet, Clade> getCladeMap() { return cladeMap; } public Clade getClade(NodeRef node) { return null; } private void addClades(Tree tree, NodeRef node, BitSet bits) { BitSet bits2 = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits2.set(index); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); addClades(tree, node1, bits2); } } addClade(bits2, tree, node); if (bits != null) { bits.or(bits2); } } private void addClade(BitSet bits, Tree tree, NodeRef node) { Clade clade = cladeMap.get(bits); if (clade == null) { clade = new Clade(bits); cladeMap.put(bits, clade); } clade.setCount(clade.getCount() + 1); if (attributeNames != null) { if (clade.attributeLists == null) { clade.attributeLists = new List[attributeNames.size()]; for (int i = 0; i < attributeNames.size(); i++) { clade.attributeLists[i] = new ArrayList(); } } for (int i = 0; i < attributeNames.size(); i++) { String attributeName = attributeNames.get(i); Object value; if (attributeName.equals("height")) { value = tree.getNodeHeight(node); } else if (attributeName.equals("length")) { value = tree.getBranchLength(node); } else { value = tree.getNodeAttribute(node, attributeName); } if (value != null) { clade.attributeLists[i].add(value); } } } } public void calculateCladeCredibilities(int totalTreesUsed) { for (Clade clade : cladeMap.values()) { clade.setCredibility(((double) clade.getCount()) / totalTreesUsed); } } public double getSumCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double sum = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); sum += getSumCladeCredibility(tree, node1, bits2); } sum += getCladeCredibility(bits2); if (bits != null) { bits.or(bits2); } } return sum; } public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double logCladeCredibility = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); logCladeCredibility += getLogCladeCredibility(tree, node1, bits2); } logCladeCredibility += Math.log(getCladeCredibility(bits2)); if (bits != null) { bits.or(bits2); } } return logCladeCredibility; } private double getCladeCredibility(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade == null) { return 0.0; } return clade.getCredibility(); } public void annotateTree(MutableTree tree, NodeRef node, BitSet bits, int heightsOption) { BitSet bits2 = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits2.set(index); annotateNode(tree, node, bits2, true, heightsOption); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); annotateTree(tree, node1, bits2, heightsOption); } annotateNode(tree, node, bits2, false, heightsOption); } if (bits != null) { bits.or(bits2); } } private void annotateNode(MutableTree tree, NodeRef node, BitSet bits, boolean isTip, int heightsOption) { Clade clade = cladeMap.get(bits); if (clade == null) { throw new RuntimeException("Clade missing"); } // System.err.println("annotateNode new: "+bits.toString()+" size = "+attributeNames.size()); // for(String string : attributeNames) { // System.err.println(string); // System.exit(-1); boolean filter = false; if (!isTip) { double posterior = clade.getCredibility(); tree.setNodeAttribute(node, "posterior", posterior); if (posterior < posteriorLimit) { filter = true; } } for (int i = 0; i < attributeNames.size(); i++) { String attributeName = attributeNames.get(i); double[] values = new double[clade.attributeLists[i].size()]; HashMap<String, Integer> hashMap = new HashMap<String, Integer>(clade.attributeLists[i].size()); if (values.length > 0) { Object v = clade.attributeLists[i].get(0); boolean isHeight = attributeName.equals("height"); boolean isBoolean = v instanceof Boolean; boolean isDiscrete = v instanceof String; double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; for (int j = 0; j < clade.attributeLists[i].size(); j++) { if (isDiscrete) { String value = (String) clade.attributeLists[i].get(j); if (value.startsWith("\"")) { value = value.replaceAll("\"", ""); } if (attributeName.equals(NEW_SEQ)) { // Strip out gaps before storing value = value.replaceAll("-", ""); } if (hashMap.containsKey(value)) { int count = hashMap.get(value); hashMap.put(value, count + 1); } else { hashMap.put(value, 1); } } else if (isBoolean) { values[j] = (((Boolean) clade.attributeLists[i].get(j)) ? 1.0 : 0.0); } else { values[j] = ((Number) clade.attributeLists[i].get(j)).doubleValue(); if (values[j] < minValue) minValue = values[j]; if (values[j] > maxValue) maxValue = values[j]; } } if (isHeight) { if (heightsOption == MEAN_HEIGHTS) { double mean = DiscreteStatistics.mean(values); tree.setNodeHeight(node, mean); } else if (heightsOption == MEDIAN_HEIGHTS) { double median = DiscreteStatistics.median(values); tree.setNodeHeight(node, median); } else { // keep the existing height } } if (!filter) { if (!isDiscrete) annotateMeanAttribute(tree, node, attributeName, values); else annotateModeAttribute(tree, node, attributeName, hashMap); // if( tree.getNodeTaxon(node) != null && // tree.getNodeTaxon(node).getId().compareTo("Calanus") == 0) { // System.err.println("size = "+hashMap.keySet().size()); // System.err.println("count = "+hashMap.get(hashMap.keySet().toArray()[0])); // System.err.println(); if (!isBoolean && minValue < maxValue && !isDiscrete) { // Basically, if it is a boolean (0, 1) then we don't need the distribution information // Likewise if it doesn't vary. annotateMedianAttribute(tree, node, attributeName + "_median", values); annotateHPDAttribute(tree, node, attributeName + "_95%_HPD", 0.95, values); annotateRangeAttribute(tree, node, attributeName + "_range", values); } } } } } private void annotateMeanAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double mean = DiscreteStatistics.mean(values); tree.setNodeAttribute(node, label, mean); } private void annotateMedianAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double median = DiscreteStatistics.median(values); tree.setNodeAttribute(node, label, median); } public static final String fileName = "junk"; // public static final String execName = "/sw/bin/clustalw"; private int externalCalls = 0; private void annotateModeAttribute(MutableTree tree, NodeRef node, String label, HashMap<String, Integer> values) { if (label.equals(NEW_SEQ)) { String consensusSeq = null; double[] support = null; int numElements = values.keySet().size(); // System.err.println("size = "+numElements); if (numElements > 1) { // Essentially just finding the modal character try { PrintWriter pw = new PrintWriter(new PrintStream(new FileOutputStream(fileName))); int i = 0; int[] weight = new int[numElements]; // Iterator iter = values.keySet().iterator(); for (String key : values.keySet()) { int thisCount = values.get(key); weight[i] = thisCount; //TODO I THINK I FIXED IT?!?! pw.write(">" + i+"\n");// + " " + thisCount + "\n"); pw.write(key + "\n"); i++; } pw.close(); //Process p = Runtime.getRuntime().exec(kalignExecutable + " " + fileName + " -OUTPUT=NEXUS"); //Process p = Runtime.getRuntime().exec(kalignExecutable + " " + fileName + " -fmsf -o"+fileName + ".fasta"); // System.out.println("Command: " + kalignExecutable + " " + fileName + " -ffasta -o"+fileName + ".fasta"); // Process p = Runtime.getRuntime().exec(kalignExecutable + " " + fileName + " -ffasta -o"+fileName + ".fasta"); Process p = Runtime.getRuntime().exec(kalignExecutable + " " + fileName + " -ffasta -q -o"+fileName + ".fasta"); // ByteArrayOutputStream kalignOutput = new ByteArrayOutputStream(); // StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERR"); // StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), "OUT", kalignOutput); // errorGobbler.start(); // outputGobbler.start(); // int exitVal = p.waitFor(); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); { // String line; while ((/*line = */input.readLine()) != null) { // System.out.println(line); } } input.close(); externalCalls++; // System.err.println("clustal call #" + externalCalls); //NexusImporter importer = new NexusImporter(new FileReader(fileName + ".nxs")); // FastaImporter importer = new FastaImporter(new FileReader(new File(fileName + ".fasta")), Nucleotides.INSTANCE); FastaImporter importer = new FastaImporter(new FileReader(new File(fileName + ".fasta")), new GeneralDataType(new String[0]));//AminoAcids.INSTANCE); //new FastaImporter(new FileReader(), new AminoAcids.INSTANCE); Alignment alignment = importer.importAlignment(); // build index int[] index = new int[numElements]; for (int j = 0; j < numElements; j++) index[j] = alignment.getTaxonIndex("" + j); StringBuffer sb = new StringBuffer(); support = new double[alignment.getPatternCount()]; // System.err.println(new dr.math.matrixAlgebra.Vector(weight)); for (int j = 0; j < alignment.getPatternCount(); j++) { int[] pattern = alignment.getPattern(j); // support[j] = appendNextConsensusCharacter(alignment,j,sb); // System.err.println(new dr.math.matrixAlgebra.Vector(pattern)); int[] siteWeight = new int[30]; // + 2 to handle ambiguous and gap int maxWeight = -1; int totalWeight = 0; int maxChar = -1; for (int k = 0; k < pattern.length; k++) { int whichChar = pattern[k]; if (whichChar < 30) { int addWeight = weight[index[k]]; //System.out.println(k + "\t" + addWeight + "\t" + whichChar + "\t" + siteWeight[whichChar]); siteWeight[whichChar] += addWeight; totalWeight += addWeight; // if( k >= alignment.getDataType().getStateCount()+2 ) { // System.err.println("k = "+k); // System.err.println("pattern = "+new dr.math.matrixAlgebra.Vector(pattern)); if (siteWeight[whichChar] > maxWeight) { maxWeight = siteWeight[whichChar]; maxChar = whichChar; } } else { System.err.println("BUG"); System.err.println("k = " + k); System.err.println("whichChar = " + whichChar); System.err.println("pattern = " + new dr.math.matrixAlgebra.Vector(pattern)); } } sb.append(alignment.getDataType().getChar(maxChar)); support[j] = (double) maxWeight / (double) totalWeight; } // System.err.println("cSeq = " + sb.toString()); consensusSeq = sb.toString(); // System.exit(-1); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (Importer.ImportException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } } else { consensusSeq = (String) values.keySet().toArray()[0]; support = new double[consensusSeq.length()]; for (int i = 0; i < support.length; i++) support[i] = 1.0; } // Trim out gaps from consensus and support // ArrayList<Double> newSupport = new ArrayList<Double>(support.length); boolean noComma = true; StringBuffer newSupport = new StringBuffer("{"); StringBuffer newSeq = new StringBuffer(); if (consensusSeq.length() != support.length) { System.err.println("What happened here?"); System.exit(-1); } // Restripping all the sequences of gap characters since they may have been added in during clustal step for (int i = 0; i < support.length; i++) { if (consensusSeq.charAt(i) != GAP) { newSeq.append(consensusSeq.charAt(i)); if (noComma) noComma = false; else newSupport.append(","); newSupport.append(String.format("%1.3f", support[i])); } } newSupport.append("}"); tree.setNodeAttribute(node, label, newSeq); // String num = Str tree.setNodeAttribute(node, label + ".prob", newSupport); } else { String mode = null; int maxCount = 0; int totalCount = 0; for (String key : (String[]) values.keySet().toArray()) { int thisCount = values.get(key); if (thisCount == maxCount) mode = mode.concat("+" + key); else if (thisCount > maxCount) { mode = key; maxCount = thisCount; } totalCount += thisCount; } double freq = (double) maxCount / (double) totalCount; tree.setNodeAttribute(node, label, mode); tree.setNodeAttribute(node, label + ".prob", freq); } } // private double appendNextConsensusCharacter(Alignment alignment, int j, StringBuffer sb, int[] weight) { // int[] pattern = alignment.getPattern(j); // int[] siteWeight = new int[alignment.getDataType().getStateCount()]; // int maxWeight = -1; // int totalWeight = 0; // int maxChar = -1; // for (int k = 0; k < pattern.length; k++) { // int whichChar = pattern[k]; // if (whichChar < alignment.getDataType().getStateCount()) { // int addWeight = weight[index[k]]; // siteWeight[whichChar] += addWeight; // totalWeight += addWeight; // if (siteWeight[k] > maxWeight) { // maxWeight = siteWeight[k]; // maxChar = k; // sb.append(alignment.getDataType().getChar(maxChar)); // return (double) maxWeight / (double) totalWeight; private void annotateRangeAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double min = DiscreteStatistics.min(values); double max = DiscreteStatistics.max(values); tree.setNodeAttribute(node, label, new Object[]{min, max}); } private void annotateHPDAttribute(MutableTree tree, NodeRef node, String label, double hpd, double[] values) { int[] indices = new int[values.length]; HeapSort.sort(values, indices); double minRange = Double.MAX_VALUE; int hpdIndex = 0; int diff = (int) Math.round(hpd * (double) values.length); for (int i = 0; i <= (values.length - diff); i++) { double minValue = values[indices[i]]; double maxValue = values[indices[i + diff - 1]]; double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } double lower = values[indices[hpdIndex]]; double upper = values[indices[hpdIndex + diff - 1]]; tree.setNodeAttribute(node, label, new Object[]{lower, upper}); } class Clade { public Clade(BitSet bits) { this.bits = bits; count = 0; credibility = 0.0; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getCredibility() { return credibility; } public void setCredibility(double credibility) { this.credibility = credibility; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Clade clade = (Clade) o; return !(bits != null ? !bits.equals(clade.bits) : clade.bits != null); } public int hashCode() { return (bits != null ? bits.hashCode() : 0); } int count; double credibility; BitSet bits; List[] attributeLists = null; } // Private stuff TaxonList taxonList = null; Map<BitSet, Clade> cladeMap = new HashMap<BitSet, Clade>(); } int totalTrees = 0; int totalTreesUsed = 0; double posteriorLimit = 0.0; String kalignExecutable = null; List<String> attributeNames = new ArrayList<String>(); List<String> treeAttributeNames = new ArrayList<String>(); List[] treeAttributeLists = null; TaxonList taxa = null; public static void printTitle() { System.out.println(); centreLine("Ancestral Sequence Annotator " + "v0.1" + ", " + "2008", 60); // version.getVersionString() + ", " + version.getDateString(), 60); System.out.println(); centreLine("by", 60); System.out.println(); centreLine("Marc A. Suchard, Wai Lok Sibon Li", 60); System.out.println(); centreLine("Departments of Biomathematics,", 60); centreLine("Biostatistics and Human Genetics", 60); centreLine("UCLA", 60); centreLine("msuchard@ucla.edu", 60); System.out.println(); System.out.println(); System.out.println("NB: I stole a substantial portion of this code from Andrew Rambaut."); System.out.println(" Please also give him due credit."); System.out.println(); } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { System.out.print(" "); } System.out.println(line); } public static void printUsage(Arguments arguments) { arguments.printUsage("ancestralsequenceannotator", "<input-file-name> <output-file-name>"); System.out.println(); System.out.println(" Example: ancestralsequenceannotator test.trees out.txt"); System.out.println(); } //Main method public static void main(String[] args) throws IOException { String targetTreeFileName = null; String inputFileName = null; String outputFileName = null; printTitle(); Arguments arguments = new Arguments( new Arguments.Option[]{ //new Arguments.StringOption("target", new String[] { "maxclade", "maxtree" }, false, "an option of 'maxclade' or 'maxtree'"), new Arguments.StringOption("heights", new String[]{"keep", "median", "mean"}, false, "an option of 'keep', 'median' or 'mean'"), new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"), new Arguments.StringOption("beastInput", new String[]{"true", "false"}, false, "If the input is taken from BEAST rather than BAli-Phy"), new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annotated"), new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"), new Arguments.Option("help", "option to print this message"), new Arguments.StringOption("kalign", "full_path_to_kalign", "specifies full path to the kalign executable file") }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { System.out.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption("help")) { printUsage(arguments); System.exit(0); } int heights = KEEP_HEIGHTS; if (arguments.hasOption("heights")) { String value = arguments.getStringOption("heights"); if (value.equalsIgnoreCase("mean")) { heights = MEAN_HEIGHTS; } else if (value.equalsIgnoreCase("median")) { heights = MEDIAN_HEIGHTS; } } int burnin = -1; if (arguments.hasOption("burnin")) { burnin = arguments.getIntegerOption("burnin"); } double posteriorLimit = 0.0; if (arguments.hasOption("limit")) { posteriorLimit = arguments.getRealOption("limit"); } boolean beastInput = false; if(arguments.hasOption("beastInput") && arguments.getStringOption("beastInput").equals("true")) { SEQ_STRING = "states"; } int target = MAX_CLADE_CREDIBILITY; if (arguments.hasOption("target")) { target = USER_TARGET_TREE; targetTreeFileName = arguments.getStringOption("target"); } // String kalignExecutable = "/usr/local/bin/clustalw"; String kalignExecutable = "/usr/local/bin/kalign"; if (arguments.hasOption("kalign")) { kalignExecutable = arguments.getStringOption("kalign"); } String[] args2 = arguments.getLeftoverArguments(); if (args2.length > 2) { System.err.println("Unknown option: " + args2[2]); System.err.println(); printUsage(arguments); System.exit(1); } if (args2.length == 2) { targetTreeFileName = null; inputFileName = args2[0]; outputFileName = args2[1]; } else { if (inputFileName == null) { // No input file name was given so throw up a dialog box... inputFileName = Utils.getLoadFileName("AncestralSequenceAnnotator " + version.getVersionString() + " - Select input file file to analyse"); } if (outputFileName == null) { outputFileName = Utils.getSaveFileName("AncestralSequenceAnnotator " + version.getVersionString() + " - Select output file"); } } if(inputFileName == null || outputFileName == null) { System.err.println("Missing input or output file name"); printUsage(arguments); System.exit(1); } new AncestralSequenceAnnotator(burnin, heights, posteriorLimit, target, targetTreeFileName, inputFileName, outputFileName, kalignExecutable); System.exit(0); } }
package dr.inference.trace; import dr.util.FileHelpers; import dr.util.TabularData; import dr.xml.AttributeRule; import dr.xml.XMLObject; import dr.xml.XMLParseException; import dr.xml.XMLSyntaxRule; import java.io.File; import java.io.IOException; public class LogFileTraceExporter extends TabularData { private final LogFileTraces analysis; private final String[] rows = {"mean", "median", "hpdLower", "hpdUpper", "ESS"}; TraceDistribution[] distributions; public LogFileTraceExporter(File file, int burnin) throws TraceException, IOException { analysis = new LogFileTraces(file.getCanonicalPath(), file); analysis.loadTraces(); if (burnin >= 0) { analysis.setBurnIn(burnin); } distributions = new TraceDistribution[nColumns()]; } public int nColumns() { return analysis.getTraceCount(); } public String columnName(int nColumn) { return analysis.getTraceName(nColumn); } public int nRows() { return rows.length; // analysis.getStateCount(); } public Object data(int nRow, int nColumn) { if (distributions[nColumn] == null) { analysis.analyseTrace(nColumn); distributions[nColumn] = analysis.getDistributionStatistics(nColumn); } TraceDistribution distribution = distributions[nColumn]; switch (nRow) { case 0: { return distribution.getMean(); } case 1: { return distribution.getMedian(); } case 2: { return distribution.getLowerHPD(); } case 3: { return distribution.getUpperHPD(); } case 4: { return distribution.getESS(); } } return null; // return analysis.getStateValue(nColumn, nRow); } public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { private static final String FILENAME = "fileName"; private static final String BURN_IN = "burnIn"; public String getParserName() { return "logFileTrace"; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final File file = FileHelpers.getFile(xo.getStringAttribute(FILENAME)); int burnIn = xo.getAttribute(BURN_IN, -1); try { return new LogFileTraceExporter(file, burnIn); } catch (Exception e) { throw new XMLParseException(e.getMessage()); } }
package edu.nyu.cs.omnidroid.core; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import edu.nyu.cs.omnidroid.R; import edu.nyu.cs.omnidroid.util.AGParser; import edu.nyu.cs.omnidroid.util.OmLogger; import edu.nyu.cs.omnidroid.util.StringMap; import edu.nyu.cs.omnidroid.util.UGParser; import android.R.string; import android.app.Activity; import android.content.ComponentName; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.widget.Toast; public class DummyActivity extends Activity { private String uri; Intent intent; // Activity a; String filterdata = null; String filtertype = null; String uridata = null; String actionname = null; String actionapp = null; String intentAction = null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); this.intent = getIntent(); if (intent.getAction().contains("SMS_RECEIVED")) { String id = null; this.uri = "content://sms/inbox"; intentAction = "SMS_RECEIVED"; StringBuilder sb = new StringBuilder(uri); sb.append("/"); sb.append(getLastId(uri)); this.uri = sb.toString(); } else if(intent.getAction().contains("PHONE_STATE")) {} else { intentAction = intent.getAction(); this.uri = getURI(intent); } matchEventName(intentAction); this.finish(); } public String getURI(Intent intent1) { /* * bundle=intent.getExtras(); Set<String> keys = bundle.keySet(); */ Bundle b = intent1.getExtras(); Object c = b.get("uri"); String uri = c.toString(); return uri; } public void matchEventName(String intentAction) { UGParser ug = new UGParser(getApplicationContext()); ArrayList<HashMap<String, String>> recs = ug.readbyEventName(intentAction); // ArrayList<HashMap<String, String>> UCRecords = ug.readRecords(); Iterator<HashMap<String, String>> i = recs.iterator(); while (i.hasNext()) { HashMap<String, String> HM1 = i.next(); // Configure the Intent Filter with the Events if Instance in enabled if (HM1.get("EnableInstance").equalsIgnoreCase("True")) { filtertype = HM1.get(ug.KEY_FilterType); filterdata = HM1.get(ug.KEY_FilterData); actionname = HM1.get("ActionName"); actionapp = HM1.get(ug.KEY_ActionApp); // added by Pradeep to populate Omniu CP at runtime uridata = HM1.get("ActionData"); // uridata = "SENDER PHONE NUMBER"; if (!uridata.contains("content://") && !uridata.equals("")) { uridata = fillURIData(uri, uridata);// Call fillURIData if ActionData contains fields like // s_ph_no etc. and not the actual URI. } // boolean val=checkFilter(uri,filtertype,filterdata); getCols(uri, filtertype, filterdata, actionapp); } } } // Added by Pradeep private String fillURIData(String uri2, String uridata2) { int cnt = 1; Uri uri_ret = null; String str_uri = uri2; String[] temp = null; temp = str_uri.split("/"); String num = temp[temp.length - 1]; String final_uri = str_uri.substring(0, str_uri.length() - num.length() - 1); int new_id = Integer.parseInt(num); if(actionname.equalsIgnoreCase("SMS_RECEIVED")) new_id = new_id-1; Cursor cur = managedQuery(Uri.parse(final_uri), null, null, null, null); if (cur.moveToFirst()) { do { int id = Integer.parseInt(cur.getString(cur.getColumnIndex("_id"))); if (new_id == id) { AGParser ag = new AGParser(getApplicationContext()); ArrayList<StringMap> cm = ag.readContentMap(actionapp); Iterator<StringMap> i = cm.iterator(); StringMap sm = new StringMap(); while (i.hasNext()) { sm = (StringMap) i.next(); if (sm.get(1).equalsIgnoreCase(uridata2)) uridata2 = sm.getKey(); } String aData = cur.getString(cur.getColumnIndex(uridata2)); String[] projection = { "i_name", "a_data" }; ContentValues values = new ContentValues(); values.put("i_name", "tempcnt");// using temp to store the instance data. values.put("a_data", "1"); Cursor cur1 = getContentResolver().query( Uri.parse("content://edu.nyu.cs.omnidroid.core.maincp/CP"), projection, "i_name='tempcnt'", null, null); if (cur1.getCount() == 0) uri_ret = getContentResolver().insert( Uri.parse("content://edu.nyu.cs.omnidroid.core.maincp/CP"), values); else { cur1.moveToFirst(); cnt = (Integer.parseInt(cur1.getString(cur1.getColumnIndex("a_data"))) + 1) % 3; getContentResolver().delete(Uri.parse("content://edu.nyu.cs.omnidroid.core.maincp/CP"), "i_name='tempcnt'", null); values.clear(); values.put("i_name", "tempcnt");// using temp to store the instance data. values.put("a_data", cnt); uri_ret = getContentResolver().insert( Uri.parse("content://edu.nyu.cs.omnidroid.core.maincp/CP"), values); } String tempstr = "temp" + cnt; values.clear(); values.put("i_name", tempstr);// using temp to store the instance data. values.put("a_data", aData); cur1 = getContentResolver().query( Uri.parse("content://edu.nyu.cs.omnidroid.core.maincp/CP"), projection, "i_name='" + tempstr + "'", null, null); // Checking to see if the temp is populated if (cur1.getCount() == 0) uri_ret = getContentResolver().insert( Uri.parse("content://edu.nyu.cs.omnidroid.core.maincp/CP"), values); else { getContentResolver().delete(Uri.parse("content://edu.nyu.cs.omnidroid.core.maincp/CP"), "i_name='temp'", null); uri_ret = getContentResolver().insert( Uri.parse("content://edu.nyu.cs.omnidroid.core.maincp/CP"), values); } } } while (cur.moveToNext()); } return uri_ret.toString(); } public boolean checkFilter(String uri, String filtertype1, String filterdata1) { String str_uri = uri; String[] temp = null; temp = str_uri.split("/"); String num = temp[temp.length - 1]; String final_uri = str_uri.substring(0, str_uri.length() - num.length() - 1); int new_id = Integer.parseInt(num); if(actionname.equalsIgnoreCase("SMS_RECEIVED")) new_id = new_id-1; Cursor cur = managedQuery(Uri.parse(final_uri), null, null, null, null); if (cur.moveToPosition(new_id)) { if (filterdata1.equalsIgnoreCase(cur.getString(cur.getColumnIndex(filtertype1)))) { Toast.makeText(getApplicationContext(), cur.getString(cur.getColumnIndex(filtertype1)), Toast.LENGTH_LONG).show(); } } String action = cur.getColumnName(cur.getColumnIndex(CP.ACTION_DATA)); return true; } public void sendIntent(String actiondata1) { Intent send_intent = new Intent(); send_intent.setAction(actionname); send_intent.putExtra("uri", uridata); // sendBroadcast(send_intent); // PackageManager pm = this.getPackageManager(); // try { // PackageInfo pi = pm.getPackageInfo(actiondata1, 0); AGParser ag = new AGParser(getApplicationContext()); String pkgname = ag.readPkgName(actiondata1); String listener = ag.readListenerClass(actiondata1); if (!pkgname.equalsIgnoreCase("")) { ComponentName comp = new ComponentName(pkgname, listener); send_intent.setComponent(comp); } // send_intent.setClass(this.getApplicationContext(), pi.getClass()); // startActivity(send_intent); try{ sendBroadcast(send_intent); }catch(Exception e){ e.toString();} Toast.makeText(getApplicationContext(), "Sent!", Toast.LENGTH_SHORT).show(); // } catch (NameNotFoundException e) { // TODO Auto-generated catch block // OmLogger.write(getApplicationContext(), actiondata1 + "not installed"); // e.printStackTrace(); } public void getCols(String uri, String filtertype1, String filterdata1, String actiondata1) { String[] cols = null; String str_uri = uri; String[] temp = null; temp = str_uri.split("/"); String num = temp[temp.length - 1]; String final_uri = str_uri.substring(0, str_uri.length() - num.length() - 1); int new_id = Integer.parseInt(num); if(actionname.equalsIgnoreCase("SMS_RECEIVED")) new_id = new_id-1; int flag = 0; Cursor cur = managedQuery(Uri.parse(final_uri), null, null, null, null); if (cur.moveToFirst()) { do { int id = Integer.parseInt(cur.getString(cur.getColumnIndex("_id"))); String ft = cur.getString(cur.getColumnIndex(filtertype1)); if (new_id == id) { if (filterdata1.equalsIgnoreCase(ft)) { { if(final_uri.contains("sms")) { Toast.makeText( getApplicationContext(), cur.getString(cur.getColumnIndex(filtertype1)) + ":" + cur.getString(cur.getColumnIndex("body")), Toast.LENGTH_LONG).show(); sendIntent(actiondata1); } else { try{ Toast.makeText( getApplicationContext(), cur.getString(cur.getColumnIndex("s_name")) + ":" + cur.getString(cur.getColumnIndex(filtertype1)), Toast.LENGTH_LONG).show(); sendIntent(actiondata1); }catch(Exception e){OmLogger.write(getApplicationContext(), "Unable to execute action");} } } //sendIntent(actiondata1); flag = 1; } } } while (cur.moveToNext()); if (flag == 0) { Toast.makeText(getApplicationContext(), cur.getString(cur.getColumnIndex(filtertype1)) + " does not exist", Toast.LENGTH_LONG) .show(); } } } public String getLastId(String smsuri) { String id = null; String lastids = null; Cursor c = managedQuery(Uri.parse(smsuri), null, null, null, null); if (c.moveToFirst()) { id = c.getString(c.getColumnIndex("_id")); int lastid = Integer.parseInt(id) - 1; lastids = Integer.toString(lastid); } return id; } }
package foam.nanos.auth; import foam.core.ContextAwareSupport; import foam.core.X; import foam.dao.*; import foam.mlang.MLang; import foam.nanos.NanoService; import foam.util.LRULinkedHashMap; import javax.naming.AuthenticationException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.*; import java.util.regex.Pattern; public class UserAndGroupAuthService extends ContextAwareSupport implements AuthService, NanoService { public static final Pattern emailPattern = Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\" + "\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\" + "\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\" + "n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\" + "031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[" + "^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(" + "?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?" + "[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*" + "\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\" + "[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[" + "\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@," + ";:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;" + ":\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:" + "\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] " + "\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]" + "))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\" + "n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]" + ")+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?" + ":(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[" + "\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[" + "\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\" + "r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\" + "t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\]" + "(?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\" + "[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\" + "[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[" + " \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031" + "]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\" + "\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:" + "\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[" + " \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*" + "\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\"." + "\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\"." + "\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?" + ":\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n" + ")?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\." + "|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*" + "(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\" + "Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\" + "n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()" + "<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()" + "<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"" + "(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] " + "\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]" + "))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n" + ")?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]" + ")+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?" + ":(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:" + "\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\" + "]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)" + "?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ " + "\\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*" + "\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\"" + ".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\"" + ".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?" + ":(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\" + "n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\" + "\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\" + "\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\" + "\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:" + "(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:" + "\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]" + "|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)" + "?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+" + "|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r" + "\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@" + ",;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@" + ",;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)" + "(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:" + "(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\" + "\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(" + "?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?" + "=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ " + "\\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:" + "\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:" + "\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:" + "\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-" + "\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[" + "([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\" + "t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(" + "?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\" + "n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\" + "t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:" + "\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:" + "[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"" + "()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t" + "])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:" + "(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\" + "\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;" + ":\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\" + "\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:" + "(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ " + "\\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?" + ":(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\" + "000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(" + "?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(" + "?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[" + " \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\" + "r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\" + "\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\" + "[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)" + "?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?" + "=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\" + "t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)"); protected static final ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() { @Override protected StringBuilder initialValue() { return new StringBuilder(); } @Override public StringBuilder get() { StringBuilder b = super.get(); b.setLength(0); return b; } }; protected DAO userDAO_; protected DAO groupDAO_; protected Map challengeMap; public static final String HASH_METHOD = "SHA-512"; @Override public void start() { userDAO_ = (DAO) getX().get("localUserDAO"); groupDAO_ = (DAO) getX().get("groupDAO"); challengeMap = new LRULinkedHashMap<Long, Challenge>(20000); } /** * A challenge is generated from the userID provided * This is saved in a LinkedHashMap with ttl of 5 */ public String generateChallenge(long userId) throws AuthenticationException { if ( userId < 1 ) { throw new AuthenticationException("Invalid User Id"); } if ( userDAO_.find(userId) == null ) { throw new AuthenticationException("User not found"); } String generatedChallenge = UUID.randomUUID() + String.valueOf(userId); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, 5); challengeMap.put(userId, new Challenge(generatedChallenge, calendar.getTime())); return generatedChallenge; } /** * Checks the LinkedHashMap to see if the the challenge supplied is correct * and the ttl is still valid * * How often should we purge this map for challenges that have expired? */ public X challengedLogin(long userId, String challenge) throws AuthenticationException { if ( userId < 1 || "".equals(challenge) ) { throw new AuthenticationException("Invalid Parameters"); } Challenge c = (Challenge) challengeMap.get(userId); if ( c == null ) throw new AuthenticationException("Invalid userId"); if ( ! c.getChallenge().equals(challenge) ) { throw new AuthenticationException("Invalid Challenge"); } if ( new Date().after(c.getTtl()) ) { challengeMap.remove(userId); throw new AuthenticationException("Challenge expired"); } User user = (User) userDAO_.find(userId); if ( user == null ) throw new AuthenticationException("User not found"); challengeMap.remove(userId); return this.getX().put("user", user); } /** * Login a user by the id provided, validate the password * and return the user in the context. */ public X login(long userId, String password) throws AuthenticationException { if ( userId < 1 || "".equals(password) ) { throw new AuthenticationException("Invalid Parameters"); } User user = (User) userDAO_.find(userId); if ( user == null ) { throw new AuthenticationException("User not found."); } String hashedPassword; String storedPassword; String salt; try { String[] split = user.getPassword().split(":"); salt = split[1]; storedPassword = split[0]; hashedPassword = hashPassword(password, salt); } catch (Throwable e) { throw new AuthenticationException("Invalid Password"); } if ( ! hashedPassword.equals(storedPassword) ) { throw new AuthenticationException("Invalid Password"); } return getX().put("user", user); } public X loginByEmail(String email, String password) throws AuthenticationException { if ( "".equals(email) || "".equals(password) ) { throw new AuthenticationException("Invalid Parameters"); } Sink sink = new ListSink(); sink = userDAO_.where(MLang.EQ(User.EMAIL, email)).limit(1).select(sink); List data = ((ListSink) sink).getData(); if ( data == null || data.size() != 1 ) { throw new AuthenticationException("User not found"); } User user = (User) data.get(0); String salt; String hashedPassword; String storedPassword; try { String[] split = user.getPassword().split(":"); salt = split[1]; storedPassword = split[0]; hashedPassword = hashPassword(password, salt); } catch (Throwable t) { throw new AuthenticationException("Invalid password"); } if ( ! hashedPassword.equals(storedPassword) ) { throw new AuthenticationException("Invalid password"); } return getX().put("user", user); } public Boolean check(foam.core.X x, java.security.Permission permission) { if ( x == null || permission == null ) return false; User user = (User) x.get("user"); if ( user == null ) return false; Group group = (Group) user.getGroup(); if ( group == null ) return false; if ( userDAO_.find_(x, user.getId()) == null ) { return false; } return group.implies(permission); } /** * Given a context with a user, validate the password to be updated * and return a context with the updated user information */ public X updatePassword(foam.core.X x, String oldPassword, String newPassword) throws AuthenticationException { if ( x == null || "".equals(oldPassword) || "".equals(newPassword) ) { throw new AuthenticationException("Invalid Parameters"); } User user = (User) userDAO_.find_(x, ((User) x.get("user")).getId()); if ( user == null ) { throw new AuthenticationException("User not found"); } String password = user.getPassword(); String storedPassword = password.split(":")[0]; String oldSalt = password.split(":")[1]; String hashedOldPassword; String hashedNewPasswordOldSalt; String hashedNewPassword; String newSalt = generateRandomSalt(); try { hashedOldPassword = hashPassword(oldPassword, oldSalt); hashedNewPasswordOldSalt = hashPassword(newPassword, oldSalt); hashedNewPassword = hashPassword(newPassword, newSalt); } catch (NoSuchAlgorithmException e) { throw new AuthenticationException("Invalid Password"); } if ( ! hashedOldPassword.equals(storedPassword) ) { throw new AuthenticationException("Invalid Password"); } if ( hashedOldPassword.equals(hashedNewPasswordOldSalt) ) { throw new AuthenticationException("New Password must be different"); } user.setPassword(hashedNewPassword + ":" + newSalt); userDAO_.put(user); return this.getX().put("user", user); } /** * Used to validate properties of a user. This will be called on registration of users * Will mainly be used as a veto method. * Users should have id, email, first name, last name, password for registration */ public void validateUser(User user) throws AuthenticationException { if ( user == null ) { throw new AuthenticationException("Invalid User"); } if ( "".equals(user.getEmail()) ) { throw new AuthenticationException("Email is required for creating a user"); } if ( ! emailPattern.matcher(user.getEmail()).matches() ) { throw new AuthenticationException("Email format is invalid"); } if ( "".equals(user.getFirstName()) ) { throw new AuthenticationException("First Name is required for creating a user"); } if ( "".equals(user.getLastName()) ) { throw new AuthenticationException("Last Name is required for creating a user"); } if ( "".equals(user.getPassword()) ) { throw new AuthenticationException("Password is required for creating a user"); } if ( ! validatePassword(user.getPassword()) ) { throw new AuthenticationException("Password needs to minimum 8 characters, contain at least one uppercase, one lowercase and a number"); } } public static String hashPassword(String password, String salt) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(HASH_METHOD); messageDigest.update(salt.getBytes()); byte[] hashedBytes = messageDigest.digest(password.getBytes()); StringBuilder hashedPasswordBuilder = new StringBuilder(); for( byte b : hashedBytes ) { hashedPasswordBuilder.append(String.format("%02x", b & 0xFF)); } return hashedPasswordBuilder.toString(); } public static String generateRandomSalt() { SecureRandom secureRandom = new SecureRandom(); byte bytes[] = new byte[20]; secureRandom.nextBytes(bytes); StringBuilder saltBuilder = sb.get(); for ( byte b : bytes ) { saltBuilder.append(String.format("%02x", b & 0xFF)); } return saltBuilder.toString(); } //Min 8 characters, at least one uppercase, one lowercase, one number public static boolean validatePassword(String password) { Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$"); return pattern.matcher(password).matches(); } /** * Just return a null user for now. Not sure how to handle the cleanup * of the current context */ public void logout(X x) {} }
package FlightScheduler; // INPUT.JAVA // Input reader for Lab 4b airport and flight data // To read all the information necessary for this lab: // (1) Create an object (say, "input") of type Input. // (2) Call input.readAirports(<airportFileName>) // (3) Call input.readFlights(<flightFileName>) // Note that you *must* do (3) after (2). // If all goes well, you will then have access to // * input.airports -- an array of Airport objects // * input.flights -- an array of Flight objects // * input.airportMap -- a HashMap mapping airport codes to the // corresponding Airport objects import java.util.*; class Input { // Airport information class Airport { public String name; // name of airport (3-letter code) public int offset; // offset of local time from GMT (in minutes) public int id; // convenient integer identifier } // Flight information // NB: all times are GMT, in minutes since midnight class Flight { public String name; // flight name public Airport startAirport, endAirport; // flight termini public int startTime, endTime; // departure and arrival times } // array of all airports read from input public Airport airports[]; // array of all flights read from input public Flight flights[]; // mapping from airport codes (strings) to Airport objects public HashMap<String,Airport> airportMap; // constructor public Input() { airportMap = new HashMap<String,Airport>(); } // readAirports() // Read the airport file public void readAirports(String filename) { FileParser fp = new FileParser(filename); // hold the airports as they are read ArrayList<Airport> aplist = new ArrayList<Airport>(); while (!fp.isEof()) { Airport ap = new Airport(); ap.name = fp.readWord(); ap.offset = (fp.readInt() / 100) * 60; if (!fp.isEof()) { // crete mapping from names to objects airportMap.put(ap.name, ap); aplist.add(ap); } } airports = new Airport [aplist.size()]; aplist.toArray(airports); } // readFlights() // read the flight file public void readFlights(String filename) { FileParser fp = new FileParser(filename); // hold the flights as they are read ArrayList<Flight> fllist = new ArrayList<Flight>(); // read the flights and store their times in GMT while (!fp.isEof()) { Flight fl = new Flight(); String airline; int flightno; airline = fp.readWord(); flightno = fp.readInt(); fl.name = airline + "-" + flightno; if (fp.isEof()) break; String code; int tm; String ampm; code = fp.readWord(); fl.startAirport = airportMap.get(code); tm = fp.readInt(); ampm = fp.readWord(); fl.startTime = toTime(tm, ampm, fl.startAirport.offset); code = fp.readWord(); fl.endAirport = airportMap.get(code); tm = fp.readInt(); ampm = fp.readWord(); fl.endTime = toTime(tm, ampm, fl.endAirport.offset); fllist.add(fl); } flights = new Flight [fllist.size()]; fllist.toArray(flights); } // toTime() // convert raw time value and AM/PM in local time, to minutes // since midnight in GMT, using supplied offset from GMT. int toTime(int timeRaw, String ampm, int offset) { int hour = (timeRaw / 100) % 12; int minute = timeRaw % 100; boolean isPM = (ampm.charAt(0) == 'P'); int minutes = hour * 60 + minute; if (isPM) minutes += 12 * 60; int finalTime = (minutes - offset + 24 * 60) % (24 * 60); return finalTime; } }
package gov.nih.nci.cananolab.ui.core; import gov.nih.nci.cananolab.exception.CaNanoLabException; import gov.nih.nci.cananolab.service.common.LookupService; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import gov.nih.nci.cananolab.util.ClassUtils; import gov.nih.nci.cananolab.util.StringUtils; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.apache.struts.upload.FormFile; /** * This class sets up information required for all forms. * * @author pansu, cais * */ public class InitSetup { private InitSetup() { } public static InitSetup getInstance() { return new InitSetup(); } /** * Returns a map between an object name and its display name * * @param appContext * @return * @throws CaNanoLabException */ public Map<String, String> getClassNameToDisplayNameLookup( ServletContext appContext) throws CaNanoLabException { Map<String, String> lookup = null; if (appContext.getAttribute("displayNameLookup") == null) { lookup = LookupService.findSingleAttributeLookupMap("displayName"); appContext.setAttribute("displayNameLookup", lookup); } else { lookup = new HashMap<String, String>( (HashMap<? extends String, String>) (appContext .getAttribute("displayNameLookup"))); } return lookup; } /** * Returns a map between a display name and its corresponding object name * * @param appContext * @return * @throws CaNanoLabException */ public Map<String, String> getDisplayNameToClassNameLookup( ServletContext appContext) throws Exception { Map<String, String> lookup = null; if (appContext.getAttribute("displayNameReverseLookup") == null) { Map<String, String> displayLookup = LookupService .findSingleAttributeLookupMap("displayName"); lookup = new HashMap<String, String>(); for (Map.Entry entry : displayLookup.entrySet()) { lookup.put(entry.getValue().toString(), entry.getKey() .toString()); } appContext.setAttribute("displayNameReverseLookup", lookup); } else { lookup = new HashMap<String, String>( (HashMap<? extends String, String>) (appContext .getAttribute("displayNameReverseLookup"))); } return lookup; } /** * Returns a map between a display name and its corresponding full class * name * * @param appContext * @return * @throws CaNanoLabException */ public Map<String, String> getDisplayNameToFullClassNameLookup( ServletContext appContext) throws Exception { Map<String, String> lookup = null; if (appContext.getAttribute("displayNameReverseLookup") == null) { Map<String, String> displayLookup = LookupService .findSingleAttributeLookupMap("displayName"); lookup = new HashMap<String, String>(); for (Map.Entry entry : displayLookup.entrySet()) { String className = entry.getKey().toString(); String fullClassName = ClassUtils.getFullClass(className) .getCanonicalName(); lookup.put(entry.getValue().toString(), fullClassName); } appContext.setAttribute("displayNameReverseLookup", lookup); } else { lookup = new HashMap<String, String>( (HashMap<? extends String, String>) (appContext .getAttribute("displayNameReverseLookup"))); } return lookup; } public String getDisplayName(String objectName, ServletContext appContext) throws CaNanoLabException { Map<String, String> lookup = getClassNameToDisplayNameLookup(appContext); if (lookup.get(objectName) != null) { return lookup.get(objectName); } else { return ""; } } public String getObjectName(String displayName, ServletContext appContext) throws Exception { Map<String, String> lookup = getDisplayNameToClassNameLookup(appContext); if (lookup.get(displayName) != null) { return lookup.get(displayName); } else { return ""; } } /** * Retrieve lookup attribute and other attribute for lookup name from the * database and store in the application context * * @param appContext * @param contextAttribute * @param lookupName * @param lookupAttribute * @return * @throws CaNanoLabException */ public SortedSet<String> getServletContextDefaultLookupTypes( ServletContext appContext, String contextAttribute, String lookupName, String lookupAttribute) throws CaNanoLabException { SortedSet<String> types = null; if (appContext.getAttribute(contextAttribute) == null) { types = LookupService.findLookupValues(lookupName, lookupAttribute); appContext.setAttribute(contextAttribute, types); return types; } else { types = new TreeSet<String>( (SortedSet<? extends String>) appContext .getAttribute(contextAttribute)); } return types; } /** * Retrieve lookup attribute and other attribute for lookup name from the * database and store in the session * * @param request * @param sessionAttribute * @param lookupName * @param lookupAttribute * @param otherTypeAttribute * @aparam updateSession * @return * @throws CaNanoLabException */ public SortedSet<String> getDefaultAndOtherLookupTypes( HttpServletRequest request, String sessionAttribute, String lookupName, String lookupAttribute, String otherTypeAttribute, boolean updateSession) throws CaNanoLabException { SortedSet<String> types = null; if (updateSession) { types = LookupService.getDefaultAndOtherLookupTypes(lookupName, lookupAttribute, otherTypeAttribute); request.getSession().setAttribute(sessionAttribute, types); } else { types = new TreeSet<String>((SortedSet<? extends String>) (request .getSession().getAttribute(sessionAttribute))); } return types; } public List<String> getDefaultFunctionTypes(ServletContext appContext) throws Exception { if (appContext.getAttribute("defaultFunctionTypes") == null) { List<String> functionTypes = new ArrayList<String>(); List<String> functionClassNames = ClassUtils .getChildClassNames("gov.nih.nci.cananolab.domain.particle.samplecomposition.Function"); for (String name : functionClassNames) { if (!name.contains("Other")) { String displayName = InitSetup.getInstance() .getDisplayName(ClassUtils.getShortClassName(name), appContext); functionTypes.add(displayName); } } appContext.setAttribute("defaultFunctionTypes", functionTypes); return functionTypes; } else { return new ArrayList<String>((List<? extends String>) appContext .getAttribute("defaultFunctionTypes")); } } /** * Retrieve lookup attribute and other attribute for lookup name based on * reflection and store in the application context * * @param appContext * @param contextAttribute * @param lookupName * @param fullParentClassName * @return * @throws Exception */ public SortedSet<String> getServletContextDefaultTypesByReflection( ServletContext appContext, String contextAttribute, String fullParentClassName) throws Exception { if (appContext.getAttribute(contextAttribute) == null) { SortedSet<String> types = new TreeSet<String>(); List<String> classNames = ClassUtils .getChildClassNames(fullParentClassName); for (String name : classNames) { if (!name.contains("Other")) { String displayName = InitSetup.getInstance() .getDisplayName(ClassUtils.getShortClassName(name), appContext); types.add(displayName); } } appContext.setAttribute(contextAttribute, types); return types; } else { return new TreeSet<String>((SortedSet<? extends String>) appContext .getAttribute(contextAttribute)); } } public String getFileUriFromFormFile(FormFile file, String folderType, String particleName, String submitType) { if (file != null && file.getFileName().length() > 0) { String prefix = folderType; if (particleName != null && submitType != null && folderType.equals(CaNanoLabConstants.FOLDER_PARTICLE)) { prefix += "/" + particleName + "/"; prefix += StringUtils .getOneWordLowerCaseFirstLetter(submitType); } String timestamp = StringUtils.convertDateToString(new Date(), "yyyyMMdd_HH-mm-ss-SSS"); return prefix + "/" + timestamp + "_" + file.getFileName(); } else { return null; } } }
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; public class PeerController implements Runnable { /** * * Miguel Velez * April 16, 2015 * * This class is the peer that we use to send and receive requests. * * Class variables: * * AtomicBoolean done * Check if we are done processing packets * * IncomingPacketQueue incomingPacketsFromCommunityQueue * Queue with packets from the community * * IncomingPacketQueue incomingPacketsFromUIQueue * Queue with packets from the UI * * DatagramReceiver receiveFromUI * Receiver for the UI * * OutgoingPacketQueue outgoingPacketsQueue * Queue for sending out packets to the UI or the community * * DatagramReceiver receiveFromCommunity * Receiver for the community * * ResourceManager resourceManager * Manager for this peer's resources * * RequestManager requestManager * Manager for this peer's requests * * DatagramSender sender * Sender for the ui or the community * * * Constructors: * * public PeerController(PortNumberPeerCommunity communityPort, PortNumberPeerUI uiPort) * create a peer controller * * * Methods: * * public void run() * Process packets from the UI and community * * private void processCommandFromCommunity() * Process packet from the community * * private void processCommandFromUI() * Process packets from the UI * * public Thread startAsThread() * Start this class as a thread * * public void setDoneFlag(boolean flag) * Setter for the done flag * * public boolean isStopped() * Check if the peer has stopped processing packets * * * * Modification History: * May 3, 2015 * Original version * * May 8, 2015 * Implemented receiving from the UI * * May 8, 2015 * Process requests from the UI * */ private AtomicBoolean done; private IncomingPacketQueue incomingPacketsFromCommunityQueue; private IncomingPacketQueue incomingPacketsFromUIQueue; private DatagramReceiver receiveFromUI; private OutgoingPacketQueue outgoingPacketsQueue; private DatagramReceiver receiveFromCommunity; // private RequestManager requestManager; // private ResourceManager resourceManager; private DatagramSender sender; private InetSocketAddress uiControllerAddress; // TODO have to check what parameter we need to get public PeerController(PortNumberPeerCommunity communityPort, PortNumberPeerUI uiPort, InetSocketAddress uiControllerAddress) { // TODO what is packet size try { this.done = new AtomicBoolean(false); this.incomingPacketsFromUIQueue = new IncomingPacketQueue(); this.receiveFromUI = new DatagramReceiver(new DatagramSocket(uiPort.get()), this.incomingPacketsFromUIQueue, 512); this.incomingPacketsFromCommunityQueue = new IncomingPacketQueue(); this.receiveFromCommunity = new DatagramReceiver(new DatagramSocket(communityPort.get()), this.incomingPacketsFromCommunityQueue, 512); this.outgoingPacketsQueue = new OutgoingPacketQueue(); this.sender = new DatagramSender(new DatagramSocket(), this.outgoingPacketsQueue, 512); this.uiControllerAddress = uiControllerAddress; } catch (SocketException se) { se.printStackTrace(); } } @Override public void run() { // Start listening for messages from the UI this.receiveFromUI.startAsThread(); // Start listening for messages from the Community this.receiveFromCommunity.startAsThread(); // Start sending packets from the outgoing queue this.sender.startAsThread(); while(!this.isStopped()) { try { // Check UI if(this.incomingPacketsFromUIQueue.peek() != null) { this.processCommandFromUI(); } // Sleep Thread.sleep(50); // Check Community if(this.incomingPacketsFromCommunityQueue.peek() != null) { this.processCommandFromCommunity(); } // Sleep Thread.sleep(50); // Generate a new ID ID.generateID(); // Sleep Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } // Stop all threads this.receiveFromUI.stop(); this.sender.stop(); this.receiveFromCommunity.stop(); } private void processCommandFromCommunity() { // Process a command from the community // Dequeue the packet from the community DatagramPacket communityPacket = this.incomingPacketsFromCommunityQueue.deQueue(); // Create a UDP message UDPMessage message = new UDPMessage(communityPacket); // Pass the message to my peers GossipPartners.getInstance().send(message); // Check if the ID2 matches one of our responses if(RequestManager.getInstance().getRequest(message.getID2()) != null) { // TODO test RequestFromUIControllerToFindResources responseRequest = (RequestFromUIControllerToFindResources) RequestManager.getInstance().getRequest(message.getID2()); responseRequest.updateRequest(message); } // Check if the ID2 matches one of our resources else if(ResourceManager.getInstance().getResourceFromID(message.getID2()) != null) { // TODO what happens here } // Check if the text criteria matches something we have else if(ResourceManager.getInstance().getResourcesThatMatch(new String(message.getMessage())) != null) { // TODO what happens here } } private void processCommandFromUI() { // Process a command from the UI // Dequeue the packet from the UI DatagramPacket packet = this.incomingPacketsFromUIQueue.deQueue(); // System.out.println("We got: " + new String(packet.getData())); // Set the request to lower case String request = new String(packet.getData()).toLowerCase(); // Check if it is a find request if(request.contains("find")) { // Get an ID for the find request ID id = ID.idFactory(); // create a find request RequestFromUIControllerToFindResources findRequest = new RequestFromUIControllerToFindResources(id, this.uiControllerAddress, this.outgoingPacketsQueue); // Save it in our request manager RequestManager.getInstance().insertRequest(findRequest); // System.out.println(this.requestManager.getRequest(id)); // Create a UDP message with format RequestID, random ID, TTL, text UDPMessage findMessage = new UDPMessage(id, ID.idFactory(), new TimeToLive(new Random().nextInt(100) + 1), "frogs"); GossipPartners.getInstance().send(findMessage); } // Check if it is a get request else if(request.contains("get")) { // TODO call send message in gossip partners by passing a UDP message } // The UI send an invalid command, send error back else { System.out.println("UIController, you sent a bad request to the PeerController"); // String message = "UIController, you sent a bad request to the PeerController"; // byte[] buffer = new byte[message.getBytes().length]; // // Create a packet to send the error message // DatagramPacket errorPacket = new DatagramPacket(buffer, buffer.length); // // Set the address // errorPacket.setAddress(this.uiControllerAddress.getAddress());; // // Set the listening port of the UI // errorPacket.setPort(this.uiControllerAddress.getPort()); // // Set the data // errorPacket.setData(message.getBytes()); // // Enqueue the packet in the outgoing queue // outgoingPacketsQueue.enQueue(errorPacket); } } public Thread startAsThread() { // Start this class a a thread Thread thread; thread = new Thread(this); // Execute the run method thread.start(); return thread; } public void setDoneFlag(boolean flag) { // Setter for the done flag this.done.set(flag); } public boolean isStopped() { // Check iff the peer is done processing packets return this.done.get(); } }
package cc.blynk.server; import cc.blynk.common.utils.Config; import cc.blynk.common.utils.ParseUtil; import cc.blynk.server.auth.UserRegistry; import cc.blynk.server.group.SessionsHolder; import cc.blynk.server.handlers.logging.LoggingHandler; import cc.blynk.server.utils.FileManager; import cc.blynk.server.utils.JsonParser; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Server implements Runnable { private static final Logger log = LogManager.getLogger(Server.class); private int port; private UserRegistry userRegistry; private FileManager fileManager; private SessionsHolder sessionsHolder; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; public Server(int port) { JsonParser.init(); this.port = port; this.fileManager = new FileManager(); this.sessionsHolder = new SessionsHolder(); log.debug("Reading user DB."); this.userRegistry = new UserRegistry(fileManager); log.debug("Reading user DB finished."); } public static void main(String[] args) throws Exception { // create Options object Options options = new Options(); options.addOption("port", true, "Server port."); CommandLine cmd = new BasicParser().parse(options, args); String portString = cmd.getOptionValue("port", String.valueOf(Config.DEFAULT_PORT)); int port = ParseUtil.parsePortString(portString); log.info("Using port : {}", port); new Thread(new Server(port)).start(); } @Override public void run() { this.bossGroup = new NioEventLoopGroup(1); this.workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) //.handler(new LoggingHandler(LogLevel.INFO)) .handler(new LoggingHandler()) .childHandler(new ServerHandlersInitializer(fileManager, userRegistry, sessionsHolder)); ChannelFuture channelFuture = b.bind(port).sync(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { log.error(e); } finally { stop(); } } public void stop() { log.info("Shutting down..."); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); log.info("Done!"); } }
package game.item; import java.util.HashMap; import engine.image.Images; import game.block.Blocks; import game.item.armor.ItemBelt; import game.item.armor.ItemChest; import game.item.armor.ItemHelm; import game.item.block.ItemBlockOven; import game.item.tool.ItemAxe; import game.item.tool.ItemPickaxe; import game.item.tool.ItemSword; import game.item.tool.ItemTool; import game.item.tool.ItemTool.EnumMaterial; import game.item.tool.ItemTool.EnumTools; public class Items { private static HashMap<String, Item> registeredItems = new HashMap<String, Item>(); public static Item getItemFromUIN(String uin){ if(registeredItems.containsKey(uin)) return registeredItems.get(uin); else System.out.println("[ERROR] The item " + uin + " wasn't recognized."); return null; } public static Item stick = new Item("stick", "Stick").setTexture(Images.loadImage("/items/resources/stick.png")); public static Item iron = new Item("iron", "Chunk of Iron").setTexture(Images.loadImage("/items/resources/iron.png")).setCookable(); public static Item stone = new Item("stone", "Stone").setTexture(Images.loadImage("/items/resources/stone.png")); public static Item ingot = new Item("ingot", "Iron Ingot").setTexture(Images.loadImage("/items/resources/ingot.png")); public static Item grease = new Item("grease", "Grease").setTexture(Images.loadImage("/items/resources/grease.png")); public static Item leather = new Item("leather", "Skin").setTexture(Images.loadImage("/items/resources/skin.png")); public static Item leather_fine = new Item("leather_fine", "Leather").setTexture(Images.loadImage("/items/resources/leather.png")); public static Item leather_strap = new Item("strap","Leather Strap").setTexture(Images.loadImage("/items/manufactured/leather_strap.png")); public static Item woodChip = new Item("woodchip","Wood Chips").setTexture(Images.loadImage("/items/resources/wood_chip.png")).setFuel().setFuelTimer(800); public static Item refinedStone = new Item("refinedstone","Smooth Stone").setTexture(Images.loadImage("/items/resources/stone_refined.png")); public static Item gem_blue = new Item("bluegem", "Blue Gem").setTexture(Images.loadImage("/items/resources/gem_blue.png")); public static Item plate_iron = new Item("plate_iron", "Iron Plate").setTexture(Images.loadImage("/items/manufactured/plate_iron.png")); public static Item plate_wood = new Item("plate_wood", "Wooden Plate").setTexture(Images.loadImage("/items/manufactured/plate_wood.png")); public static Item plate_leather = new Item("plate_leather", "Leather Plate").setTexture(Images.loadImage("/items/manufactured/plate_leather.png")); public static Item gunpowder = new Item("gunpowder", "GunPowder").setTexture(Images.loadImage("/items/resources/gunpowder.png")); public static Item whetstone = new ItemWhetstone("whetstone","WhetStone").setTexture(Images.loadImage("/items/manufactured/whetstone.png")); public static Item ovenBase = new ItemOvenbase("ovenbase", "Oven Base").setTexture(Images.loadImage("/items/manufactured/oven_base.png")); public static Item handle_small = new Item("handle_small","Small Handle").setTexture(Images.loadImage("/items/tools/handle_sword.png")); public static Item handle_soft = new Item("handle_soft","Modest Handle").setTexture(Images.loadImage("/items/tools/handle_soft.png")); public static Item handle_hard = new Item("handle_hard","Greater Handle").setTexture(Images.loadImage("/items/tools/handle_hard.png")); public static ItemFood meat_pig_raw = (ItemFood) new ItemFood("pig_raw", "Raw Pig Meat", 0.5F).setTexture(Images.loadImage("/items/food/meat_pig.png")).setCookable(); public static ItemFood meat_pig = (ItemFood)new ItemFood("pig_cooked","Pig Meat", 1f).setTexture(Images.loadImage("/items/food/meat_pig_cooked.png")); public static ItemFood meat_fish_raw = (ItemFood) new ItemFood("fish_raw", "Raw Fish", 0.5f).setTexture(Images.loadImage("/items/food/meat_fish_raw.png")).setCookable(); public static ItemFood meat_fish = (ItemFood) new ItemFood("fish_cooked", "Fish Filet", 1f).setTexture(Images.loadImage("/items/food/meat_fish_cooked.png")); public static ItemPouch pouch = (ItemPouch) new ItemPouch("pouch","Leather Pouch").setTexture(Images.loadImage("/items/manufactured/pouch.png")); public static ItemBlockOven oven = (ItemBlockOven) new ItemBlockOven(Blocks.OVEN, "Oven").setTexture(Images.loadImage("/blocks/oven.png")); public static ItemTool wood_pickaxe = (ItemTool) new ItemPickaxe("pickaxe", "Wooden Pickaxe", EnumMaterial.WOOD).setBaseAttack(2).setEffectiveness(EnumTools.PICKAXE).setEffectiveDamage(2).setStackDamage(16).setTexture(Images.loadImage("/items/tools/wood_pickaxe.png")); public static ItemTool stone_pickaxe= (ItemTool) new ItemPickaxe("stone_pickaxe", "Smooth Pickaxe", EnumMaterial.STONE).setBaseAttack(2).setEffectiveness(EnumTools.PICKAXE).setEffectiveDamage(2).setStackDamage(16).setTexture(Images.loadImage("/items/tools/smooth_pickaxe.png")); public static ItemTool iron_pickaxe = (ItemTool) new ItemPickaxe("iron_pickaxe", "Iron Pickaxe", EnumMaterial.IRON).setBaseAttack(2).setEffectiveness(EnumTools.PICKAXE).setEffectiveDamage(2).setStackDamage(32).setTexture(Images.loadImage("/items/tools/iron_pickaxe.png")); public static ItemTool wood_sword = (ItemTool) new ItemSword("sword", "Wooden Sword", EnumMaterial.WOOD).setBaseAttack(3).setEffectiveness(EnumTools.SWORD).setEffectiveDamage(2).setStackDamage(32).setTexture(Images.loadImage("/items/tools/wood_sword.png")); public static ItemTool stone_sword = (ItemTool) new ItemSword("stone_sword", "Smooth Sword", EnumMaterial.STONE).setBaseAttack(3).setEffectiveness(EnumTools.SWORD).setEffectiveDamage(2).setStackDamage(48).setTexture(Images.loadImage("/items/tools/smooth_sword.png")); public static ItemTool iron_sword = (ItemTool) new ItemSword("iron_sword", "Iron Sword", EnumMaterial.IRON).setBaseAttack(3).setEffectiveness(EnumTools.SWORD).setEffectiveDamage(2).setStackDamage(64).setTexture(Images.loadImage("/items/tools/iron_sword.png")); public static ItemTool wood_axe = (ItemTool) new ItemAxe("axe", "Wooden Axe", EnumMaterial.WOOD).setBaseAttack(2).setEffectiveness(EnumTools.AXE).setEffectiveDamage(2).setStackDamage(32).setTexture(Images.loadImage("/items/tools/wood_axe.png")); public static ItemTool stone_axe = (ItemTool) new ItemAxe("stone_axe", "Smooth Axe", EnumMaterial.STONE).setBaseAttack(2).setEffectiveness(EnumTools.AXE).setEffectiveDamage(2).setStackDamage(32).setTexture(Images.loadImage("/items/tools/smooth_axe.png")); public static ItemTool iron_axe = (ItemTool) new ItemAxe("iron_axe", "Iron Axe", EnumMaterial.IRON).setBaseAttack(2).setEffectiveness(EnumTools.AXE).setEffectiveDamage(2).setStackDamage(48).setTexture(Images.loadImage("/items/tools/iron_axe.png")); public static ItemLantern lantern = (ItemLantern) new ItemLantern("lantern", "Lantern").setTexture(Images.loadImage("/items/lantern.png")); public static ItemBelt belt = (ItemBelt) new ItemBelt("belt","Belt", "belt").setInventorySlots(5).setTexture(Images.loadImage("/items/manufactured/belt.png")); public static ItemBelt belt_s = (ItemBelt) new ItemBelt("belt_s", "Belt", "belt").setInventorySlots(10).setTexture(Images.loadImage("/items/manufactured/belt_small.png")); public static ItemBelt belt_m = (ItemBelt) new ItemBelt("belt_m", "Belt", "belt").setInventorySlots(15).setTexture(Images.loadImage("/items/manufactured/belt_med.png")); public static ItemBelt belt_l = (ItemBelt) new ItemBelt("belt_l", "Belt", "belt").setInventorySlots(20).setTexture(Images.loadImage("/items/manufactured/belt_large.png")); public static ItemHelm helm_wood = (ItemHelm) new ItemHelm("helm_wood","Wooden Helm").setDamageReduction(0.1f).setStackDamage(25).setTexture(Images.loadImage("/items/manufactured/armor/helm_wood.png")); public static ItemHelm helm_iron = (ItemHelm) new ItemHelm("helm_iron","Iron Helm").setDamageReduction(0.2f).setStackDamage(45).setTexture(Images.loadImage("/items/manufactured/armor/helm_iron.png")); public static ItemHelm stache = (ItemHelm) new ItemHelm("stache","WarfStache").setDamageReduction(0.12f).setStackDamage(75).setTexture(Images.loadImage("/items/manufactured/armor/stache.png")); public static ItemHelm sam_eye = (ItemHelm) new ItemHelm("septiceye","Sceptic Eye").setDamageReduction(0.12f).setStackDamage(75).setTexture(Images.loadImage("/items/manufactured/armor/septiceye.png")); public static ItemChest chest_wood = (ItemChest) new ItemChest("armor_wood", "Wooden ChestPlate").setDamageReduction(0.2f).setStackDamage(30).setTexture(Images.loadImage("/items/manufactured/armor/chest_wood.png")); public static ItemChest chest_iron = (ItemChest) new ItemChest("armor_iron", "Iron ChestPlate").setDamageReduction(0.5f).setStackDamage(50).setTexture(Images.loadImage("/items/manufactured/armor/chest_iron.png")); public static ItemBomb bomb = (ItemBomb) new ItemBomb("bomb", "Bomb", 2).setTexture(Images.loadImage("/items/bomb.png")); public static ItemBomb bomb_better = (ItemBomb) new ItemBomb("bomb_b", "Better Bomb", 4).setTexture(Images.loadImage("/items/bomb.png")); public static ItemBomb bomb_ultra = (ItemBomb) new ItemBomb("bomb_u", "Ultra Bomb", 8).setTexture(Images.loadImage("/items/bomb.png")); public static ItemGemHammer gem_hammer = (ItemGemHammer) new ItemGemHammer("gemhammer", "Gem Hammer").setTexture(Images.loadImage("/items/manufactured/gem_hammer.png")); public static void loadItems(){ registerItem(stick); registerItem(woodChip); registerItem(iron); registerItem(stone); registerItem(wood_pickaxe); registerItem(wood_sword); registerItem(wood_axe); registerItem(oven); registerItem(ingot); registerItem(meat_pig); registerItem(meat_pig_raw); registerItem(lantern); registerItem(grease); registerItem(belt); registerItem(belt_s); registerItem(belt_m); registerItem(belt_l); registerItem(leather); registerItem(pouch); registerItem(bomb); registerItem(bomb_better); registerItem(bomb_ultra); registerItem(meat_fish_raw); registerItem(meat_fish); registerItem(whetstone); registerItem(leather_fine); registerItem(handle_small); registerItem(handle_soft); registerItem(handle_hard); registerItem(refinedStone); registerItem(ovenBase); registerItem(stone_sword); registerItem(stone_axe); registerItem(stone_pickaxe); registerItem(iron_sword); registerItem(iron_axe); registerItem(iron_pickaxe); registerItem(leather_strap); registerItem(gem_blue); registerItem(gem_hammer); registerItem(plate_iron); registerItem(plate_leather); registerItem(plate_wood); registerItem(helm_iron); registerItem(helm_wood); registerItem(stache); registerItem(sam_eye); registerItem(chest_wood); registerItem(chest_iron); registerItem(gunpowder); } public static void registerItem(Item item){ registeredItems.put(item.getUIN(), item); } }
package parser; import java.io.Serializable; public class Options implements Cloneable, Serializable { private static final long serialVersionUID = 1L; public enum LearningMode { Basic, // 1st order arc factored model Standard, // 3rd order using similar features as TurboParser Full // full model with two additional 3rd order features and global features } public String trainFile = null; public String testFile = null; public String unimapFile = null; public String outFile = null; public boolean train = false; public boolean test = false; public String wordVectorFile = null; public String modelFile = "model.out"; public String format = "CONLL"; public int maxNumSent = -1; public int numPretrainIters = 1; public int maxNumIters = 10; public boolean initTensorWithPretrain = true; //public LearningMode learningMode = LearningMode.Basic; public LearningMode learningMode = LearningMode.Standard; public boolean projective = false; public boolean learnLabel = false; public boolean pruning = true; public double pruningCoeff = 0.1; public int labelLossType = 0; public int numHcThreads = 10; // hill climbing: number of threads public int numHcConverge = 300; // hill climbing: number of restarts to converge public boolean average = true; public double C = 0.01; public double gamma = 1, gammaLabel = 1; public int R = 50; // feature set public boolean useCS = true; // use consecutive siblings public boolean useGP = true; // use grandparent public boolean useHB = true; // use head bigram public boolean useGS = true; // use grand sibling public boolean useTS = true; // use tri-sibling public boolean useGGP = true; // use great-grandparent public boolean usePSC = true; // use parent-sibling-child public boolean useHO = true; // use global feature // CoNLL language specific info // used only in Full learning mode public enum PossibleLang { Arabic, Bulgarian, Chinese, Czech, Danish, Dutch, English08, German, Japanese, Portuguese, Slovene, Spanish, Swedish, Turkish, Unknown, } PossibleLang lang; final static String langString[] = {"arabic", "bulgarian", "chinese", "czech", "danish", "dutch", "english08", "german", "japanese", "portuguese", "slovene", "spanish", "swedish", "turkish"}; public Options() { } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } public void processArguments(String[] args) { for (String arg : args) { if (arg.equals("train")) { train = true; } else if (arg.equals("test")) { test = true; } else if (arg.startsWith("label")) { learnLabel = Boolean.parseBoolean(arg.split(":")[1]); } else if (arg.startsWith("proj")) { projective = Boolean.parseBoolean(arg.split(":")[1]); } else if (arg.startsWith("average:")) { average = Boolean.parseBoolean(arg.split(":")[1]); } else if (arg.startsWith("train-file:")) { trainFile = arg.split(":")[1]; } else if (arg.startsWith("test-file:")) { testFile = arg.split(":")[1]; } else if (arg.startsWith("unimap-file:")) { unimapFile = arg.split(":")[1]; } else if (arg.startsWith("output-file:")) { outFile = arg.split(":")[1]; } else if (arg.startsWith("model-file:")) { modelFile = arg.split(":")[1]; } else if (arg.startsWith("max-sent:")) { maxNumSent = Integer.parseInt(arg.split(":")[1]); } else if (arg.startsWith("C:")) { C = Double.parseDouble(arg.split(":")[1]); } else if (arg.startsWith("gamma:")) { gamma = Double.parseDouble(arg.split(":")[1]); //gammaLabel = gamma; } else if (arg.startsWith("R:")) { R = Integer.parseInt(arg.split(":")[1]); } else if (arg.startsWith("word-vector:")) { wordVectorFile = arg.split(":")[1]; } else if (arg.startsWith("iters:")) { maxNumIters = Integer.parseInt(arg.split(":")[1]); } else if (arg.startsWith("pre-iters:")) { numPretrainIters = Integer.parseInt(arg.split(":")[1]); } else if (arg.startsWith("pruning:")) { pruning = Boolean.parseBoolean(arg.split(":")[1]); } else if (arg.startsWith("thread:")) { numHcThreads = Integer.parseInt(arg.split(":")[1]); } else if (arg.startsWith("converge:")) { numHcConverge = Integer.parseInt(arg.split(":")[1]); } else if (arg.startsWith("model:")) { String str = arg.split(":")[1]; if (str.equals("basic")) learningMode = LearningMode.Basic; else if (str.equals("standard")) learningMode = LearningMode.Standard; else if (str.equals("full")) learningMode = LearningMode.Full; } } //gammaLabel = 1.0; switch (learningMode) { case Basic: useCS = false; useGP = false; useHB = false; useGS = false; useTS = false; useGGP = false; usePSC = false; useHO = false; break; case Standard: useGGP = false; usePSC = false; useHO = false; break; case Full: break; default: break; } lang = findLang(trainFile != null ? trainFile : testFile); } public void printOptions() { System.out.println(" System.out.println("train-file: " + trainFile); System.out.println("test-file: " + testFile); System.out.println("model-name: " + modelFile); System.out.println("output-file: " + outFile); System.out.println("train: " + train); System.out.println("test: " + test); System.out.println("iters: " + maxNumIters); System.out.println("label: " + learnLabel); System.out.println("max-sent: " + maxNumSent); System.out.println("C: " + C); System.out.println("label-loss-type: " + labelLossType); System.out.println("gamma: " + gamma + " " + gammaLabel); System.out.println("R: " + R); System.out.println("word-vector:" + wordVectorFile); System.out.println("projective: " + projective); System.out.println("pruning: " + pruning); System.out.println("converge iter: " + numHcConverge); System.out.println(); System.out.println("use consecutive siblings: " + useCS); System.out.println("use grandparent: " + useGP); System.out.println("use head bigram: " + useHB); System.out.println("use grand siblings: " + useGS); System.out.println("use tri-siblings: " + useTS); System.out.println("use great-grandparent: " + useGGP); System.out.println("use parent-sibling-child: " + usePSC); System.out.println("use high-order: " + useHO); System.out.println("model: " + learningMode.name()); System.out.println(" } PossibleLang findLang(String file) { for (PossibleLang lang : PossibleLang.values()) if (lang != PossibleLang.Unknown && file.indexOf(langString[lang.ordinal()]) != -1) { return lang; } System.out.println("Warning: unknow language"); return PossibleLang.Unknown; } }
package com.exedio.cope; import com.exedio.cope.testmodel.PointerItem; import com.exedio.cope.testmodel.PointerItem2; public class JoinOuterTest extends DatabaseLibTest { PointerItem leftJoined; PointerItem leftLonely; PointerItem2 rightJoined; PointerItem2 rightLonely; protected void setUp() throws Exception { super.setUp(); deleteOnTearDown(rightLonely = new PointerItem2("right")); deleteOnTearDown(rightJoined = new PointerItem2("joined")); deleteOnTearDown(leftJoined = new PointerItem("joined", rightJoined)); deleteOnTearDown(leftLonely = new PointerItem("left", rightJoined)); } public void testJoin() { { final Query query = new Query(PointerItem.TYPE, null); query.join(PointerItem2.TYPE, Cope.equal(PointerItem.code, PointerItem2.code)); assertContains(leftJoined, query.search()); } { final Query query = new Query(PointerItem.TYPE, null); query.joinOuterLeft(PointerItem2.TYPE, Cope.equal(PointerItem.code, PointerItem2.code)); assertContains(leftJoined, leftLonely, query.search()); } { final Query query = new Query(PointerItem.TYPE, null); query.joinOuterRight(PointerItem2.TYPE, Cope.equal(PointerItem.code, PointerItem2.code)); if(hsqldb) { try { query.search(); fail("should have throws RuntimeException"); } catch(RuntimeException e) { assertEquals("hsqldb not support right outer joins", e.getMessage()); } } else { assertContains(leftJoined, null, query.search()); } } } }
package VegansWay; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.World; import org.bukkit.entity.Bat; import org.bukkit.entity.CaveSpider; import org.bukkit.entity.Chicken; import org.bukkit.entity.Cow; import org.bukkit.entity.Creature; import org.bukkit.entity.Donkey; import org.bukkit.entity.Entity; import org.bukkit.entity.Horse; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Llama; import org.bukkit.entity.Mule; import org.bukkit.entity.Ocelot; import org.bukkit.entity.Parrot; import org.bukkit.entity.Pig; import org.bukkit.entity.Player; import org.bukkit.entity.Rabbit; import org.bukkit.entity.Sheep; import org.bukkit.entity.Spider; import org.bukkit.entity.Squid; import org.bukkit.entity.Villager; import org.bukkit.entity.Wolf; import org.bukkit.entity.Zombie; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.event.player.PlayerInteractAtEntityEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import org.bukkit.plugin.java.JavaPlugin; import org.mcstats.Metrics; /** * * @author Pronink */ public class Main extends JavaPlugin implements Listener { int state = 0; CatTaming catTaming; ItemRenaming itemRenaming; CraftingRecipes craftingRecipes; SpidersEnhanced spidersEnhanced; LovingPets lovingPets; FeedingPets feedingPets; @Override public void onEnable() { saveDefaultConfig(); // Nunca sobreescribe si ya existe algo Config.load(getConfig()); if (Config.CONFIG_MODULE_ITEMS_RENAMING) { itemRenaming = new ItemRenaming(); } if (Config.CONFIG_MODULE_CRAFTING_RECIPES) { craftingRecipes = new CraftingRecipes(); craftingRecipes.addAllCraftingRecipes(); } if (Config.CONFIG_MODULE_SPIDERS_ENHANCED) { spidersEnhanced = new SpidersEnhanced(); } if (Config.CONFIG_MODULE_HEALING_AND_TAMING) { catTaming = new CatTaming(); lovingPets = new LovingPets(); feedingPets = new FeedingPets(lovingPets); } // REGISTRAR EVENTOS, INICIAR EVENTOS TEMPORIZADOS, INICIAR CRAFTEOS Bukkit.getServer().getPluginManager().registerEvents(this, this); startTimedEvents(); // MOSTRAR VERSIONES getVersionInfo(); // Muestro el logo (si esta habilitado), la version y busco actualizaciones (hilo) // INICIO METRICS try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { // Failed to submit the stats :-( printC("Algo falló al iniciar Metrics"); } } private void startTimedEvents() { Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { @Override public void run() { state = ++state % 120; // EL CICLO DURA 60 SEGUNDOS if (state % 2 == 0) // CADA 1 SEGUNDOS { if (Config.CONFIG_MODULE_HEALING_AND_TAMING) { catTaming.testOcelotTaming(); lovingPets.testLovingPets(); } } } }, 20 * 1, 20 * 1 / 2); // Cada 1/2 segundos, empezando desde el segundo 1 } @Override public void onDisable() { } @EventHandler public void onItemSpawn(ItemSpawnEvent event) { if (Config.CONFIG_MODULE_ITEMS_RENAMING) { itemRenaming.modifyItemGround(event); } } @EventHandler public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { if (Config.CONFIG_MODULE_HEALING_AND_TAMING) { catTaming.testConvertToCat(event); lovingPets.testNewDogOrCatBaby(event.getDamager(), event.getEntity()); } if (Config.CONFIG_MODULE_SPIDERS_ENHANCED) { spidersEnhanced.testSpiderWebAttack(event); } Entity entity = event.getEntity(); World world = entity.getWorld(); if (entity instanceof LivingEntity) { Location location = ((LivingEntity)entity).getEyeLocation(); if(isFriendlyMob(entity)) { Thread t = new Thread(new Runnable() { @Override public void run() { Location nowLocation = ((LivingEntity)event.getEntity()).getEyeLocation(); world.spawnParticle(Particle.ITEM_CRACK, nowLocation, 50, 0.2f, 0.2f, 0.2f, 0.2f, new ItemStack(Material.RAW_BEEF)); for (int i = 0; i < 5*5; i++) { nowLocation = (((LivingEntity)event.getEntity()).getEyeLocation()).add(0, -0.4f, 0); world.spawnParticle(Particle.BLOCK_CRACK, nowLocation, 5, 0.2f, 0.2f, 0.2f, 0.001f, new MaterialData(Material.NETHER_WART_BLOCK)); if (event.getEntity().isDead()) { break; } try { Thread.sleep(200); } catch (InterruptedException ex) { } } } }); t.start(); } else { world.spawnParticle(Particle.BLOCK_CRACK, location, 5, 0.2f, 0.2f, 0.2f, 0.1f, new MaterialData(Material.SLIME_BLOCK)); } /*else if(entity instanceof Zombie) { world.spawnParticle(Particle.ITEM_CRACK, location.add(0, -0.5f, 0), 5, 0.2f, 0.5f, 0.2f, 0.1f, new ItemStack(Material.ROTTEN_FLESH)); world.spawnParticle(Particle.BLOCK_CRACK, location.add(0, -0.5f, 0), 5, 0.2f, 0.5f, 0.2f, 0.1f, new MaterialData(Material.SLIME_BLOCK)); } else if(entity instanceof Spider || entity instanceof CaveSpider) { world.spawnParticle(Particle.ITEM_CRACK, location, 5, 0.2f, 0.2f, 0.2f, 0.1f, new ItemStack(Material.SPIDER_EYE)); world.spawnParticle(Particle.BLOCK_CRACK, location, 5, 0.2f, 0.2f, 0.2f, 0.1f, new MaterialData(Material.SLIME_BLOCK)); }*/ } } private boolean isFriendlyMob(Entity e) { if(e instanceof Player || e instanceof Bat || e instanceof Chicken || e instanceof Cow || e instanceof Pig || e instanceof Rabbit || e instanceof Sheep || e instanceof Squid || e instanceof Villager || e instanceof Donkey || e instanceof Horse || e instanceof Llama || e instanceof Mule || e instanceof Ocelot || e instanceof Parrot || e instanceof Wolf || e instanceof Squid) { return true; } return false; } @EventHandler public void onEntityDeath(EntityDeathEvent event) { if (Config.CONFIG_MODULE_SPIDERS_ENHANCED) { spidersEnhanced.addSpiderDrops(event); } } @EventHandler public void onRightClick(PlayerInteractAtEntityEvent event) { if (Config.CONFIG_MODULE_HEALING_AND_TAMING) { feedingPets.testPetFeeding(event); } } private String getLogo() { StringBuilder asciiLogo = new StringBuilder(""); asciiLogo.append(ChatColor.GREEN).append("\n\n"); asciiLogo.append(" ynn \n"); asciiLogo.append(".s+` -/oyhdN/ \n"); asciiLogo.append(" oNo -mMmMMMMN` \n"); asciiLogo.append(" +Md` ds:dMMMMs \n"); asciiLogo.append(" oMm` .:NMMNh/ :+syhddhhysso+++++ `:+sssssyyyo/` \n"); asciiLogo.append(" hMd /N+. oNh+:-:oso/+ossyMMN- .+o `/yys/.` `-oms \n"); asciiLogo.append(" `NM+ /M/ sMo /.sM` yMN- `/dMd` `+hy/` s. \n"); asciiLogo.append(" +MN` :Mo .ymo/::+yy- sMM: .smdMd` :yd+` \n"); asciiLogo.append(" NMo.Nm -/ .:::. oMM:-ym++Mm`/dh: \n"); asciiLogo.append(" oMNdM: -syyds `oyyhy:y/ .oyyds/h- `sNhomN/ `NNs` /MMshN+ /MNomd-`+yyhd:yo /d/ /d/ \n"); asciiLogo.append(" `MMMm .dd: :h+`sN/ `MN+.hm: -Mm: :mh- .mm.-h+Mm -MMMNo` :MMMm/ oNo` mMo .hm: hN/ \n"); asciiLogo.append(" hMM+ NMs/--`:hMy :my.:mM+ `/Ns./yN/ `sNs+hM :M/-o/ `mMMy. .NMNo /Md -dd-:oNs` `Ny-/: \n"); asciiLogo.append(" /hh` /ydyso+::ydmMNho+-:yhs+hyo+hs` yhs+::y/+hhs/` /yy- sys` `shy+yhso+hysdNNho+- \n"); asciiLogo.append(" /+yMy` /+hMs` \n"); asciiLogo.append(" .o-hm: .o-hm- \n"); asciiLogo.append(" ysm+ ysm+ \n"); asciiLogo.append(" . `. \n"); return (asciiLogo.toString()); } private void getVersionInfo() { Thread t = new Thread(new Runnable() { @Override public void run() { String installedVersion = "v" + getDescription().getVersion(); String latestVersion = Util.getLatestVersionName(); String text = ""; if (Config.CONFIG_SHOWLOGO) { text = getLogo(); // Obtengo el logo } if (latestVersion.equals("")) // Si no hay conexion a github { printC(text); // Imprime el logo, si este ha sido activado antes } else if (installedVersion.equals(latestVersion)) // Si esta actualizado { printC(text + ChatColor.GREEN + "\nYou use the latest version of VegansWay: " + latestVersion); } else { printC(text + ChatColor.RED + "\nYou do not use the latest version of VegansWay:" + ChatColor.DARK_RED + "\n\tINSTALLED VERSION -> " + installedVersion + "\n\tLATEST VERSION -> " + latestVersion + ChatColor.RED + "\nDownload the latest version from: " + ChatColor.RESET + "https: } } }); t.start(); } private void printC(String string) { Bukkit.getConsoleSender().sendMessage(string); } }
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.SwingConstants; import java.awt.Font; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JTextArea; import java.awt.Color; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class WaitConnection extends JFrame { private static final long serialVersionUID = -8611725700060761275L; private JPanel contentPane; private int portNumber = 50000; public WaitConnection() { setResizable(false); setTitle("Connecting..."); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 455, 199); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel labelTitle = new JLabel("Waiting for synchronization"); labelTitle.setBackground(Color.WHITE); labelTitle.setFont(new Font("Tahoma", Font.PLAIN, 24)); labelTitle.setHorizontalAlignment(SwingConstants.CENTER); labelTitle.setBounds(10, 10, 414, 53); contentPane.add(labelTitle); JTextArea textareaDescription = new JTextArea(); textareaDescription.setWrapStyleWord(true); textareaDescription.setLineWrap(true); textareaDescription.setEditable(false); textareaDescription.setText("In the other pc, connect to the created hostednetwork and wait for the synchronization process."); textareaDescription.setBounds(20, 74, 404, 82); contentPane.add(textareaDescription); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { startWaitSocket(); } }); } private void startWaitSocket() { System.out.println("SERVERWAIT: waiting for an handshake"); try(ServerSocket serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); DataInputStream input = new DataInputStream(clientSocket.getInputStream())){ System.out.println("SERVERWAIT: connected to " + clientSocket.getInetAddress()); // check for input request type String line = reader.readLine(); if(line.equals("handshake")){ // send acceptation System.out.println("SERVER: Sending handshake"); writer.write("handshake"); writer.newLine(); writer.flush(); } else { System.out.println("faiulure..."); } } catch(IOException e){ e.printStackTrace(); System.exit(1); } } }
package weave.servlets; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import weave.utils.CSVParser; import weave.utils.ListUtils; import com.thoughtworks.paranamer.BytecodeReadingParanamer; import com.thoughtworks.paranamer.Paranamer; import flex.messaging.MessageException; import flex.messaging.io.SerializationContext; import flex.messaging.io.amf.ASObject; import flex.messaging.io.amf.Amf3Input; import flex.messaging.io.amf.Amf3Output; import flex.messaging.messages.ErrorMessage; /** * This class provides a servlet interface to a set of functions. * The functions may be invoked using URL parameters via HTTP GET or AMF3-serialized objects via HTTP POST. * Currently, the result of calling a function is given as an AMF3-serialized object. * * TODO: Provide optional JSON output. * * Not all objects will be supported automatically. * GenericServlet supports basic AMF3-serialized objects such as String,Object,Array. * * The following mappings work (ActionScript -> Java): * Array -> Object[], Object[][], String[], String[][], double[], double[][], List * Object -> Map<String,Object> * String -> String, int, Integer, boolean, Boolean * Boolean -> boolean, Boolean * Number -> double * Raw byte stream -> Java InputStream * * The following Java parameter types are supported: * boolean, Boolean * int, Integer * float, Float * double, Double * String, String[], String[][] * Object, Object[], Object[][] * double[], double[][] * Map<String,Object> * List * InputStream * * TODO: Add support for more common parameter types. * * @author skota * @author adufilie */ public class GenericServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * This is the name of the URL parameter corresponding to the method name. */ protected final String METHOD_NAME = "methodName"; protected final String METHOD_PARAMETERS = "methodParameters"; protected final String STREAM_PARAMETER_INDEX = "streamParameterIndex"; private Map<String, ExposedMethod> methodMap = new HashMap<String, ExposedMethod>(); //Key: methodName private Paranamer paranamer = new BytecodeReadingParanamer(); // this gets parameter names from Methods /** * This class contains a Method with its parameter names and class instance. */ private class ExposedMethod { public ExposedMethod(Object instance, Method method, String[] paramNames) { this.instance = instance; this.method = method; this.paramNames = paramNames; } public Object instance; public Method method; public String[] paramNames; } /** * Default constructor. * This initializes all public methods defined in a class extending GenericServlet. */ protected GenericServlet() { super(); initLocalMethods(); } /** * @param serviceObjects The objects to invoke methods on. */ protected GenericServlet(Object ...serviceObjects) { super(); initLocalMethods(); for (Object serviceObject : serviceObjects) initAllMethods(serviceObject); } /** * This function will expose all the public methods of a class as servlet methods. * @param serviceObject The object containing public methods to be exposed by the servlet. */ protected void initLocalMethods() { initAllMethods(this); } /** * This function will expose all the declared public methods of a class as servlet methods, * except methods that match those declared by GenericServlet or a superclass of GenericServlet. * @param serviceObject The object containing public methods to be exposed by the servlet. */ protected void initAllMethods(Object serviceObject) { Method[] genericServletMethods = GenericServlet.class.getMethods(); Method[] declaredMethods = serviceObject.getClass().getDeclaredMethods(); for (int i = declaredMethods.length - 1; i >= 0; i { Method declaredMethod = declaredMethods[i]; boolean shouldIgnore = false; for (Method genericServletMethod : genericServletMethods) { if (declaredMethod.getName().equals(genericServletMethod.getName()) && Arrays.equals(declaredMethod.getParameterTypes(), genericServletMethod.getParameterTypes()) ) { shouldIgnore = true; break; } } if (!shouldIgnore) initMethod(serviceObject, declaredMethod); } // for debugging printExposedMethods(); } /** * @param serviceObject The instance of an object to use in the servlet. * @param methodName The method to expose on serviceObject. */ synchronized protected void initMethod(Object serviceObject, Method method) { // only expose public methods if (!Modifier.isPublic(method.getModifiers())) return; String methodName = method.getName(); if (methodMap.containsKey(methodName)) { methodMap.put(methodName, null); System.err.println(String.format( "Method %s.%s will not be supported because there are multiple definitions.", this.getClass().getName(), methodName )); } else { String[] paramNames = null; paramNames = paranamer.lookupParameterNames(method, false); // returns null if not found methodMap.put(methodName, new ExposedMethod(serviceObject, method, paramNames)); } } protected void printExposedMethods() { String output = ""; List<String> methodNames = new Vector<String>(methodMap.keySet()); Collections.sort(methodNames); for (String methodName : methodNames) { ExposedMethod m = methodMap.get(methodName); if (m != null) output += String.format( "Exposed servlet method: %s.%s\n", m.instance.getClass().getName(), formatFunctionSignature( m.method.getName(), m.method.getParameterTypes(), m.paramNames ) ); else output += "Not exposed: "+methodName; } System.out.print(output); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { handleServletRequest(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { handleServletRequest(request, response); } protected class ServletRequestInfo { public ServletRequestInfo(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; } HttpServletRequest request; HttpServletResponse response; } /** * This maps a thread to the corresponding RequestInfo for the doGet() or doPost() call that thread is handling. */ private Map<Thread,ServletRequestInfo> servletRequestInfo = new HashMap<Thread,ServletRequestInfo>(); /** * This function retrieves the HttpServletResponse associated with the current thread's doGet() or doPost() call. * In a public function with a void return type, you can use the ServletOutputStream for full control over the output. */ protected ServletRequestInfo getServletRequestInfo() { synchronized (servletRequestInfo) { return servletRequestInfo.get(Thread.currentThread()); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private void handleServletRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { synchronized (servletRequestInfo) { servletRequestInfo.put(Thread.currentThread(), new ServletRequestInfo(request, response)); } if (request.getMethod().equals("GET")) { List<String> urlParamNames = Collections.list(request.getParameterNames()); // Read Method Name from URL String methodName = request.getParameter(METHOD_NAME); HashMap<String, String> params = new HashMap(); for (String paramName : urlParamNames) params.put(paramName, request.getParameter(paramName)); invokeMethod(methodName, params); } else if (request.getMethod().equals("POST")) { try { // this stream decompresses the post data InflaterInputStream inflaterInputStream = new InflaterInputStream(request.getInputStream()); // read the compressed AMF3 object Object obj = deseriaizeAmf3(inflaterInputStream); String methodName = (String) ((ASObject)obj).get(METHOD_NAME); Object methodParameters = ((ASObject)obj).get(METHOD_PARAMETERS); Number streamParameterIndex = (Number) ((ASObject)obj).get(STREAM_PARAMETER_INDEX); if (methodParameters instanceof Object[]) // Array of parameters { // if there is a stream index, int index = streamParameterIndex.intValue(); if (index >= 0) ((Object[])methodParameters)[index] = inflaterInputStream; invokeMethod(methodName, (Object[])methodParameters); } else // Map of parameters { invokeMethod(methodName, (Map)methodParameters); } } catch (Exception e) { e.printStackTrace(); sendError(response, e); } } else { throw new ServletException("HTTP Request method not supported: " + request.getMethod()); } } finally { synchronized (servletRequestInfo) { servletRequestInfo.remove(Thread.currentThread()); } } } @SuppressWarnings({ "unchecked", "rawtypes" }) private void invokeMethod(String methodName, Map params) throws IOException { if(!methodMap.containsKey(methodName) || methodMap.get(methodName) == null) { HttpServletResponse response = getServletRequestInfo().response; sendError(response, new IllegalArgumentException(String.format("Method \"%s\" not supported.", methodName))); return; } ExposedMethod exposedMethod = methodMap.get(methodName); String[] argNames = exposedMethod.paramNames; Class[] argTypes = exposedMethod.method.getParameterTypes(); Object[] argValues = new Object[argTypes.length]; Map extraParameters = null; // parameters that weren't mapped directly to method arguments // For each method parameter, get the corresponding url parameter value. if (argNames != null && params != null) { //TODO: check why params is null for (Object parameterName : params.keySet()) { Object parameterValue = params.get(parameterName); int index = ListUtils.findString((String)parameterName, argNames); if (index >= 0) { argValues[index] = parameterValue; } else if (!parameterName.equals(METHOD_NAME)) { if (extraParameters == null) extraParameters = new HashMap(); extraParameters.put(parameterName, parameterValue); } } } // support for a function having a single Map<String,String> parameter // see if we can find a Map arg. If so, set it to extraParameters if (argTypes != null) { for (int i = 0; i < argTypes.length; i++) { if (argTypes[i] == Map.class) { // avoid passing a null Map to the function if (extraParameters == null) extraParameters = new HashMap<String,String>(); argValues[i] = extraParameters; extraParameters = null; break; } } } if (extraParameters != null) { System.out.println("Received servlet request: " + methodName + Arrays.asList(argValues)); System.out.println("Unused parameters: "+extraParameters.entrySet()); } invokeMethod(methodName, argValues); } /** * @param methodName The name of the function to invoke. * @param methodParameters A list of input parameters for the method. Values will be cast to the appropriate types if necessary. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void invokeMethod(String methodName, Object[] methodParameters) throws IOException { HttpServletResponse response = getServletRequestInfo().response; // debug //System.out.println(methodName + Arrays.asList(methodParameters)); // get method by name ExposedMethod exposedMethod = methodMap.get(methodName); if (exposedMethod == null) { sendError(response, new IllegalArgumentException("Unknown method: "+methodName)); } // cast input values to appropriate types if necessary Class[] expectedArgTypes = exposedMethod.method.getParameterTypes(); if (expectedArgTypes.length == methodParameters.length) { for (int index = 0; index < methodParameters.length; index++) { Object value = methodParameters[index]; // if given value is a String, check if the function is expecting a different type if (value instanceof String) { if (expectedArgTypes[index] == int.class || expectedArgTypes[index] == Integer.class) { value = Integer.parseInt((String)value); } else if (expectedArgTypes[index] == boolean.class || expectedArgTypes[index] == Boolean.class) { value = ((String)(value)).equalsIgnoreCase("true"); } else if (expectedArgTypes[index] == String[].class || expectedArgTypes[index] == List.class) { String[][] table = CSVParser.defaultParser.parseCSV((String)value); if (table.length == 0) value = new String[0]; // empty else value = table[0]; // first row if (expectedArgTypes[index] == List.class) value = Arrays.asList((String[])value); } } else if (value != null) { // additional parameter type casting if (value instanceof Boolean && expectedArgTypes[index] == boolean.class) { value = (boolean)(Boolean)value; } else if (value.getClass() == Object[].class) { Object[] valueArray = (Object[])value; if (expectedArgTypes[index] == List.class) { value = ListUtils.copyArrayToList(valueArray, new Vector()); } else if (expectedArgTypes[index] == Object[][].class) { Object[][] valueMatrix = new Object[valueArray.length][]; for (int i = 0; i < valueArray.length; i++) { valueMatrix[i] = (Object[])valueArray[i]; } value = valueMatrix; } else if (expectedArgTypes[index] == String[][].class) { String[][] valueMatrix = new String[valueArray.length][]; for (int i = 0; i < valueArray.length; i++) { // cast Objects to Strings Object[] objectArray = (Object[])valueArray[i]; valueMatrix[i] = ListUtils.copyStringArray(objectArray, new String[objectArray.length]); } value = valueMatrix; } else if (expectedArgTypes[index] == String[].class) { value = ListUtils.copyStringArray(valueArray, new String[valueArray.length]); } else if (expectedArgTypes[index] == double[][].class) { double[][] valueMatrix = new double[valueArray.length][]; for (int i = 0; i < valueArray.length; i++) { // cast Objects to doubles Object[] objectArray = (Object[])valueArray[i]; valueMatrix[i] = ListUtils.copyDoubleArray(objectArray, new double[objectArray.length]); } value = valueMatrix; } else if (expectedArgTypes[index] == double[].class) { value = ListUtils.copyDoubleArray(valueArray, new double[valueArray.length]); } } } methodParameters[index] = value; } } // prepare to output the result of the method call ServletOutputStream servletOutputStream = response.getOutputStream(); // Invoke the method on the object with the arguments try { Object result = exposedMethod.method.invoke(exposedMethod.instance, methodParameters); if (exposedMethod.method.getReturnType() != void.class) seriaizeCompressedAmf3(result, servletOutputStream); } catch (InvocationTargetException e) { System.out.println(methodName + (List)Arrays.asList(methodParameters)); e.getCause().printStackTrace(); sendError(response, e.getCause()); } catch (IllegalArgumentException e) { String moreInfo = "Expected: " + formatFunctionSignature(methodName, expectedArgTypes, exposedMethod.paramNames) + "\n" + "Received: " + formatFunctionSignature(methodName, methodParameters, null); System.out.println(e.getMessage() + '\n' + moreInfo); sendError(response, e, moreInfo); } catch (Exception e) { System.out.println(methodName + (List)Arrays.asList(methodParameters)); e.printStackTrace(); sendError(response, e); } } /** * This function formats a Java function signature as a String. * @param methodName The name of the method. * @param paramValuesOrTypes A list of Class objects or arbitrary Objects to get the class names from. * @param paramNames The names of the parameters, may be null. * @return A readable Java function signature. */ private String formatFunctionSignature(String methodName, Object[] paramValuesOrTypes, String[] paramNames) { // don't use paramNames if the length doesn't match the paramValuesOrTypes length. if (paramNames != null && paramNames.length != paramValuesOrTypes.length) paramNames = null; List<String> names = new Vector<String>(paramValuesOrTypes.length); for (int i = 0; i < paramValuesOrTypes.length; i++) { Object valueOrType = paramValuesOrTypes[i]; String name = "null"; if (valueOrType instanceof Class) name = ((Class<?>)valueOrType).getName(); else if (valueOrType != null) name = valueOrType.getClass().getName(); // decode output of Class.getName() while (name.charAt(0) == '[') // array type { name = name.substring(1) + "[]"; // decode element type encoding String type = ""; switch (name.charAt(0)) { case 'Z': type = "boolean"; break; case 'B': type = "byte"; break; case 'C': type = "char"; break; case 'D': type = "double"; break; case 'F': type = "float"; break; case 'I': type = "int"; break; case 'J': type = "long"; break; case 'S': type = "short"; break; case 'L': // remove ';' name = name.replace(";", ""); break; default: continue; } // remove first char encoding name = type + name.substring(1); } // hide package names if (name.indexOf('.') >= 0) name = name.substring(name.lastIndexOf('.') + 1); if (paramNames != null) name += " " + paramNames[i]; names.add(name); } String result = names.toString(); return String.format("%s(%s)", methodName, result.substring(1, result.length() - 1)); } private void sendError(HttpServletResponse response, Throwable exception) throws IOException { sendError(response, exception, null); } private void sendError(HttpServletResponse response, Throwable exception, String moreInfo) throws IOException { //response.setHeader("Cache-Control", "no-cache"); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); String message = exception.getMessage(); if (moreInfo != null) message += "\n" + moreInfo; System.out.println("Serializing ErrorMessage: "+message); ServletOutputStream servletOutputStream = response.getOutputStream(); ErrorMessage errorMessage = new ErrorMessage(new MessageException(message)); errorMessage.faultCode = exception.getClass().getSimpleName(); seriaizeCompressedAmf3(errorMessage, servletOutputStream); } protected static SerializationContext getSerializationContext() { SerializationContext context = SerializationContext.getSerializationContext(); // set serialization context properties context.enableSmallMessages = true; context.instantiateTypes = true; context.supportRemoteClass = true; context.legacyCollection = false; context.legacyMap = false; context.legacyXMLDocument = false; context.legacyXMLNamespaces = false; context.legacyThrowable = false; context.legacyBigNumbers = false; context.restoreReferences = false; context.logPropertyErrors = false; context.ignorePropertyErrors = true; return context; } // Serialize a Java Object to AMF3 ByteArray protected void seriaizeCompressedAmf3(Object objToSerialize, ServletOutputStream servletOutputStream) { try { SerializationContext context = getSerializationContext(); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(servletOutputStream); Amf3Output amf3Output = new Amf3Output(context); amf3Output.setOutputStream(deflaterOutputStream); // compress amf3Output.writeObject(objToSerialize); amf3Output.flush(); deflaterOutputStream.close(); // this is necessary to finish the compression } catch (Exception e) { e.printStackTrace(); } } // De-serialize a ByteArray/AMF3/Flex object to a Java object protected Object deseriaizeAmf3(InputStream inputStream) throws ClassNotFoundException, IOException { Object deSerializedObj = null; SerializationContext context = getSerializationContext(); Amf3Input amf3Input = new Amf3Input(context); amf3Input.setInputStream(inputStream); // uncompress deSerializedObj = amf3Input.readObject(); //amf3Input.close(); return deSerializedObj; } }
public class algo3 { int n = 0; int sum; int[] tab = new int[n]; int[] sortTab; int counter = 0; int exAlgo(int A[], int N) { n = N; tab = A; sortTab = new int[n]; for (int num = 0; num < A.length; num++) if (checkExist(A[num]) == false) { sortTab[counter] = A[num]; counter++; } sumSortTab(); return sum; } private boolean checkExist(int num) { boolean status = false; for (int i = 0; i < sortTab.length; i++) { if (sortTab[i] == num) { status = true; break; } } return status; } private void sumSortTab() { for (int i = 0; i < sortTab.length; i++) sum += sortTab[i]; } }
package io.flutter.actions; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ComboBoxAction; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.run.daemon.ConnectedDevice; import io.flutter.run.daemon.FlutterDaemonService; import io.flutter.sdk.FlutterSdk; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class DeviceSelectorAction extends ComboBoxAction implements DumbAware { final private List<SelectDeviceAction> actions = new ArrayList<>(); private boolean isListening = false; @NotNull @Override protected DefaultActionGroup createPopupActionGroup(JComponent button) { final DefaultActionGroup group = new DefaultActionGroup(); updateActions(); if (actions.isEmpty()) { group.add(new NoDevicesAction()); } else { group.addAll(actions); } if (SystemInfo.isMac) { boolean simulatorOpen = false; for (SelectDeviceAction action : actions) { if (StringUtil.equals(action.device.platform(), "ios") && action.device.emulator()) { simulatorOpen = true; } } group.add(new Separator()); group.add(new OpenSimulatorAction(!simulatorOpen)); } return group; } @Override protected boolean shouldShowDisabledActions() { return true; } @Override public void update(AnActionEvent e) { // Suppress device actions in all but the toolbars. final String place = e.getPlace(); if (!Objects.equals(place, ActionPlaces.NAVIGATION_BAR_TOOLBAR) && !Objects.equals(place, ActionPlaces.MAIN_TOOLBAR)) { e.getPresentation().setVisible(false); return; } super.update(e); FlutterDaemonService service = FlutterDaemonService.getInstance(); if (service == null) { return; } if (!isListening) { isListening = true; service.addDeviceListener(device -> updateActions()); } ConnectedDevice selectedDevice = service.getSelectedDevice(); Presentation presentation = e.getPresentation(); for (SelectDeviceAction action : actions) { if (Objects.equals(action.device, selectedDevice)) { Presentation template = action.getTemplatePresentation(); presentation.setIcon(template.getIcon()); presentation.setText(template.getText()); presentation.setEnabled(true); return; } } presentation.setText(null); } private void updateActions() { actions.clear(); FlutterDaemonService service = FlutterDaemonService.getInstance(); if (service != null) { final Collection<ConnectedDevice> devices = service.getConnectedDevices(); actions.addAll(devices.stream().map(SelectDeviceAction::new).collect(Collectors.toList())); } } private static class NoDevicesAction extends AnAction implements TransparentUpdate { NoDevicesAction() { super("No devices", null, null); getTemplatePresentation().setEnabled(false); } @Override public void actionPerformed(AnActionEvent e) { // No-op } } private static class OpenSimulatorAction extends AnAction { final boolean enabled; OpenSimulatorAction(boolean enabled) { super("Open iOS Simulator"); this.enabled = enabled; } @Override public void update(AnActionEvent e) { e.getPresentation().setEnabled(enabled); } @Override public void actionPerformed(AnActionEvent event) { try { final GeneralCommandLine cmd = new GeneralCommandLine().withExePath("open").withParameters("-a", "Simulator.app"); final OSProcessHandler handler = new OSProcessHandler(cmd); handler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(final ProcessEvent event) { if (event.getExitCode() != 0) { Notifications.Bus.notify( new Notification(FlutterSdk.GROUP_DISPLAY_ID, "Error Opening Simulator", event.getText(), NotificationType.ERROR)); } } }); handler.startNotify(); } catch (ExecutionException e) { Notifications.Bus.notify( new Notification(FlutterSdk.GROUP_DISPLAY_ID, "Error Opening Simulator", FlutterBundle.message("flutter.command.exception", e.getMessage()), NotificationType.ERROR)); } } } private static class SelectDeviceAction extends AnAction { @NotNull private final ConnectedDevice device; SelectDeviceAction(@NotNull ConnectedDevice device) { super(device.deviceName(), null, FlutterIcons.Phone); this.device = device; } @Override public void actionPerformed(AnActionEvent e) { FlutterDaemonService service = FlutterDaemonService.getInstance(); if (service != null) { service.setSelectedDevice(device); } } } }
package io.github.katherinaxc.bioevosim; public class Program { public static void main(String[] args) { StdDraw.setPenRadius(0.05); StdDraw.setPenColor(StdDraw.BLUE); StdDraw.point(0.5, 0.5); StdDraw.setPenColor(StdDraw.MAGENTA); StdDraw.line(0.2, 0.2, 0.8, 0.2); } }
package com.skburgart.rwr.xml; import com.skburgart.rwr.vo.Player; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; /** * * @author Steven Burgart <skburgart@gmail.com> */ public class PlayerParser { public static Player parseXML(File profileXMLFile, File personXMLFile) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document profileXML = dBuilder.parse(profileXMLFile); Document personXML = dBuilder.parse(personXMLFile); Player player = new Player(); Element profile = (Element) profileXML.getElementsByTagName("profile").item(0); player.setUsername(profile.getAttribute("username")); player.setGame_version(Integer.parseInt(profile.getAttribute("game_version"))); player.setDigest(profile.getAttribute("digest")); Element profile_stats = (Element) profileXML.getElementsByTagName("stats").item(0); player.setTime_played(Double.parseDouble(profile_stats.getAttribute("time_played"))); player.setDeaths(Integer.parseInt(profile_stats.getAttribute("deaths"))); player.setKills(Integer.parseInt(profile_stats.getAttribute("kills"))); player.setPlayer_kills(Integer.parseInt(profile_stats.getAttribute("player_kills"))); player.setTeamkills(Integer.parseInt(profile_stats.getAttribute("teamkills"))); player.setLongest_kill_streak(Integer.parseInt(profile_stats.getAttribute("longest_kill_streak"))); player.setTargets_destroyed(Integer.parseInt(profile_stats.getAttribute("targets_destroyed"))); player.setVehicles_destroyed(Integer.parseInt(profile_stats.getAttribute("vehicles_destroyed"))); player.setSoldiers_healed(Integer.parseInt(profile_stats.getAttribute("soldiers_healed"))); player.setTime_played(Integer.parseInt(profile_stats.getAttribute("times_got_healed"))); Element person = (Element) personXML.getElementsByTagName("person").item(0); player.setMax_authority_reached(Double.parseDouble(person.getAttribute("max_authority_reached"))); player.setAuthority(Double.parseDouble(person.getAttribute("authority"))); player.setJob_points(Double.parseDouble(person.getAttribute("job_points"))); player.setFaction(Integer.parseInt(person.getAttribute("faction"))); player.setName(person.getAttribute("name")); player.setVehicles_destroyed(Integer.parseInt(person.getAttribute("version"))); player.setSoldier_group_id(Integer.parseInt(person.getAttribute("soldier_group_id"))); player.setBlock(person.getAttribute("block")); player.setSquad_size_setting(Integer.parseInt(person.getAttribute("squad_size_setting"))); player.setSquad_config_index(Integer.parseInt(person.getAttribute("squad_config_index"))); return player; } public static ArrayList<Player> parseDirectory(String dir) throws ParserConfigurationException, SAXException, IOException { ArrayList<Player> players = new ArrayList<>(); File[] files = new File(dir).listFiles(); for (File personFile : files) { if (personFile.getName().endsWith("person")) { String profileFileName = dir + personFile.getName().replace("person", "profile"); File profileFile = new File(profileFileName); players.add(parseXML(profileFile, personFile)); } } return players; } public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { String profileDir = "C:\\Users\\Steve\\Documents\\NetBeansProjects\\running-with-rifles-stats\\profiles\\"; SessionFactory factory = new Configuration().configure().buildSessionFactory(); Session session = factory.openSession(); session.beginTransaction(); ArrayList<Player> players = parseDirectory(profileDir); for (Player p : players) { session.save(p); } session.getTransaction().commit(); } }
package org.jaxen.expr; import java.util.Comparator; import java.util.Iterator; import org.jaxen.Navigator; import org.jaxen.UnsupportedAxisException; class NodeComparator implements Comparator { private Navigator navigator; NodeComparator(Navigator navigator) { this.navigator = navigator; } public int compare(Object o1, Object o2) { if (navigator == null) return 0; if (isNonChild(o1) && isNonChild(o2)) { try { return compare(navigator.getParentNode(o1), navigator.getParentNode(o2)); } catch (UnsupportedAxisException ex) { return 0; } } try { int depth1 = getDepth(o1); int depth2 = getDepth(o2); Object a1 = o1; Object a2 = o2; while (depth1 > depth2) { a1 = navigator.getParentNode(a1); depth1 } if (a1 == o2) return 1; while (depth2 > depth1) { a2 = navigator.getParentNode(a2); depth2 } if (a2 == o1) return -1; // a1 and a2 are now at same depth; and are not the same while (true) { Object p1 = navigator.getParentNode(a1); Object p2 = navigator.getParentNode(a2); if (p1 == p2) { return compareSiblings(a1, a2); } a1 = p1; a2 = p2; } } catch (UnsupportedAxisException ex) { return 0; // ???? should I throw an exception instead? } } private boolean isNonChild(Object o) { return navigator.isAttribute(o) || navigator.isNamespace(o); } private int compareSiblings(Object sib1, Object sib2) throws UnsupportedAxisException { Iterator following = navigator.getFollowingSiblingAxisIterator(sib1); while (following.hasNext()) { Object next = following.next(); if (next == sib2) return -1; } return 1; } private int getDepth(Object o) throws UnsupportedAxisException { int depth = 0; Object parent = o; while ((parent = navigator.getParentNode(parent)) != null) { depth++; } return depth; } }
// Clirr: compares two versions of a java library for binary compatibility // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sf.clirr.checks; import net.sf.clirr.event.ApiDifference; import net.sf.clirr.event.Severity; import net.sf.clirr.event.ScopeSelector; import net.sf.clirr.framework.AbstractDiffReporter; import net.sf.clirr.framework.ApiDiffDispatcher; import net.sf.clirr.framework.ClassChangeCheck; import net.sf.clirr.framework.CoIterator; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.generic.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Checks the methods of a class. * * @author lkuehne */ public class MethodSetCheck extends AbstractDiffReporter implements ClassChangeCheck { private ScopeSelector scopeSelector; /** {@inheritDoc} */ public MethodSetCheck(ApiDiffDispatcher dispatcher, ScopeSelector scopeSelector) { super(dispatcher); this.scopeSelector = scopeSelector; } public final boolean check(JavaClass compatBaseline, JavaClass currentVersion) { // Dont't report method problems when gender has changed, as // really the whole API is a pile of crap then - let GenderChange check // do it's job, and that's it if (compatBaseline.isInterface() ^ currentVersion.isInterface()) { return true; } // The main problem here is to figure out which old method corresponds to which new method. // Methods that are named differently are trated as unrelated // For Methods that differ only in their parameter list we build a similarity table, i.e. // for new method i and old method j we have number that charaterizes how similar // the method signatures are (0 means equal, higher number means more different) Map bNameToMethod = buildNameToMethodMap(compatBaseline); Map cNameToMethod = buildNameToMethodMap(currentVersion); CoIterator iter = new CoIterator(null, bNameToMethod.keySet(), cNameToMethod.keySet()); while (iter.hasNext()) { iter.next(); String baselineMethodName = (String) iter.getLeft(); String currentMethodName = (String) iter.getRight(); if (baselineMethodName == null) { // a new method name has been added in the new version List currentMethods = (List) cNameToMethod.get(currentMethodName); for (Iterator i = currentMethods.iterator(); i.hasNext();) { Method method = (Method) i.next(); reportMethodAdded(currentVersion, method); } } else if (currentMethodName == null) { // all methods with name x have been removed from the old version List baselineMethods = (List) bNameToMethod.get(baselineMethodName); for (Iterator i = baselineMethods.iterator(); i.hasNext();) { Method method = (Method) i.next(); reportMethodRemoved(compatBaseline, method, currentVersion); } } else { // assert baselineMethodName equals currentMethodName List baselineMethods = (List) bNameToMethod.get(baselineMethodName); List currentMethods = (List) cNameToMethod.get(currentMethodName); checkChangedMethods(compatBaseline, baselineMethodName, baselineMethods, currentMethods); } } return true; } private void checkChangedMethods( JavaClass compatBaseline, String methodName, List baselineMethods, List currentMethods) { while (baselineMethods.size() * currentMethods.size() > 0) { int[][] similarityTable = buildSimilarityTable(baselineMethods, currentMethods); int min = Integer.MAX_VALUE; int iMin = baselineMethods.size(); int jMin = currentMethods.size(); for (int i = 0; i < baselineMethods.size(); i++) { for (int j = 0; j < currentMethods.size(); j++) { final int tableEntry = similarityTable[i][j]; if (tableEntry < min) { min = tableEntry; iMin = i; jMin = j; } } } Method iMethod = (Method) baselineMethods.remove(iMin); Method jMethod = (Method) currentMethods.remove(jMin); check(compatBaseline, iMethod, jMethod); } } private int[][] buildSimilarityTable(List baselineMethods, List currentMethods) { int[][] similarityTable = new int[baselineMethods.size()][currentMethods.size()]; for (int i = 0; i < baselineMethods.size(); i++) { for (int j = 0; j < currentMethods.size(); j++) { final Method iMethod = (Method) baselineMethods.get(i); final Method jMethod = (Method) currentMethods.get(j); similarityTable[i][j] = distance(iMethod, jMethod); } } return similarityTable; } private int distance(Method m1, Method m2) { final Type[] m1Args = m1.getArgumentTypes(); final Type[] m2Args = m2.getArgumentTypes(); if (m1Args.length != m2Args.length) { return 1000 * Math.abs(m1Args.length - m2Args.length); } int retVal = 0; for (int i = 0; i < m1Args.length; i++) { if (!m1Args[i].toString().equals(m2Args[i].toString())) { retVal += 1; } } return retVal; } /** * Searches the class hierarchy for a method that has a certtain signature. * @param methodSignature the sig we're looking for * @param clazz class where search starts * @return class name of a superclass of clazz, might be null */ private String findSuperClassWithSignature(String methodSignature, JavaClass clazz) { final JavaClass[] superClasses = clazz.getSuperClasses(); for (int i = 0; i < superClasses.length; i++) { JavaClass superClass = superClasses[i]; final Method[] superMethods = superClass.getMethods(); for (int j = 0; j < superMethods.length; j++) { Method superMethod = superMethods[j]; final String superMethodSignature = getMethodId(superClass, superMethod); if (methodSignature.equals(superMethodSignature)) { return superClass.getClassName(); } } } return null; } /** * Searches the class hierarchy for a method that has a certtain signature. * @param methodSignature the sig we're looking for * @param clazz class where search starts * @return class name of a superinterface of clazz, might be null */ private String findSuperInterfaceWithSignature(String methodSignature, JavaClass clazz) { final JavaClass[] superClasses = clazz.getAllInterfaces(); for (int i = 0; i < superClasses.length; i++) { JavaClass superClass = superClasses[i]; final Method[] superMethods = superClass.getMethods(); for (int j = 0; j < superMethods.length; j++) { Method superMethod = superMethods[j]; final String superMethodSignature = getMethodId(superClass, superMethod); if (methodSignature.equals(superMethodSignature)) { return superClass.getClassName(); } } } return null; } /** * Report that a method has been removed from a class. * @param oldClass the class where the method was available * @param oldMethod the method that has been removed * @param currentClass the superclass where the method is now available, might be null */ private void reportMethodRemoved( JavaClass oldClass, Method oldMethod, JavaClass currentClass) { String methodSignature = getMethodId(oldClass, oldMethod); String superClassName = findSuperClassWithSignature(methodSignature, currentClass); String superInterfaceName = null; if (oldMethod.isAbstract()) { superInterfaceName = findSuperInterfaceWithSignature(methodSignature, currentClass); } if (superClassName != null) { fireDiff("Method '" + getMethodId(oldClass, oldMethod) + "' is now implemented in superclass " + superClassName, Severity.INFO, oldClass, oldMethod); } else if (superInterfaceName != null) { fireDiff("Abstract method '" + getMethodId(oldClass, oldMethod) + "' is now specified by implemented interface " + superInterfaceName, Severity.INFO, oldClass, oldMethod); } else { fireDiff("Method '" + getMethodId(oldClass, oldMethod) + "' has been removed", Severity.ERROR, oldClass, oldMethod); } } private void reportMethodAdded(JavaClass newClass, Method newMethod) { final Severity severity = !newClass.isInterface() && (newClass.isFinal() || !newMethod.isAbstract()) ? Severity.INFO : Severity.ERROR; fireDiff("Method '" + getMethodId(newClass, newMethod) + "' has been added", severity, newClass, newMethod); } /** * Builds a map from a method name to a List of methods. */ private Map buildNameToMethodMap(JavaClass clazz) { Method[] methods = clazz.getMethods(); Map retVal = new HashMap(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (!scopeSelector.isSelected(method)) { continue; } final String name = method.getName(); List set = (List) retVal.get(name); if (set == null) { set = new ArrayList(); retVal.put(name, set); } set.add(method); } return retVal; } private void check(JavaClass compatBaseline, Method baselineMethod, Method currentMethod) { checkParameterTypes(compatBaseline, baselineMethod, currentMethod); checkReturnType(compatBaseline, baselineMethod, currentMethod); checkDeclaredExceptions(compatBaseline, baselineMethod, currentMethod); checkDeprecated(compatBaseline, baselineMethod, currentMethod); } private void checkParameterTypes(JavaClass compatBaseline, Method baselineMethod, Method currentMethod) { Type[] bArgs = baselineMethod.getArgumentTypes(); Type[] cArgs = currentMethod.getArgumentTypes(); if (bArgs.length != cArgs.length) { fireDiff("In Method '" + getMethodId(compatBaseline, baselineMethod) + "' the number of arguments has changed", Severity.ERROR, compatBaseline, baselineMethod); return; } //System.out.println("baselineMethod = " + getMethodId(compatBaseline, baselineMethod)); for (int i = 0; i < bArgs.length; i++) { Type bArg = bArgs[i]; Type cArg = cArgs[i]; if (bArg.toString().equals(cArg.toString())) { continue; } // TODO: Check assignability... fireDiff("Parameter " + (i + 1) + " of '" + getMethodId(compatBaseline, baselineMethod) + "' has changed it's type to " + cArg, Severity.ERROR, compatBaseline, baselineMethod); } } private void checkReturnType(JavaClass compatBaseline, Method baselineMethod, Method currentMethod) { Type bReturnType = baselineMethod.getReturnType(); Type cReturnType = currentMethod.getReturnType(); // TODO: Check assignability... if (!bReturnType.toString().equals(cReturnType.toString())) { fireDiff("Return type of Method '" + getMethodId(compatBaseline, baselineMethod) + "' has been changed to " + cReturnType, Severity.ERROR, compatBaseline, baselineMethod); } } private void checkDeclaredExceptions( JavaClass compatBaseline, Method baselineMethod, Method currentMethod) { // TODO } private void checkDeprecated(JavaClass compatBaseline, Method baselineMethod, Method currentMethod) { boolean bIsDeprecated = isDeprecated(baselineMethod); boolean cIsDeprecated = isDeprecated(currentMethod); if (bIsDeprecated && !cIsDeprecated) { fireDiff( "Method '" + getMethodId(compatBaseline, baselineMethod) + "' is no longer deprecated", Severity.INFO, compatBaseline, baselineMethod); } else if (!bIsDeprecated && cIsDeprecated) { fireDiff( "Method '" + getMethodId(compatBaseline, baselineMethod) + "' has been deprecated", Severity.INFO, compatBaseline, baselineMethod); } } /** * Creates a human readable String that is similar to the method signature * and identifies the method within a class. * @param clazz the container of the method * @param method the method to identify. * @return a human readable id, for example "public void print(java.lang.String)" */ private String getMethodId(JavaClass clazz, Method method) { StringBuffer buf = new StringBuffer(); final String scopeDecl = ScopeSelector.getScopeDecl(method); if (scopeDecl.length() > 0) { buf.append(scopeDecl); buf.append(" "); } String name = method.getName(); if ("<init>".equals(name)) { final String className = clazz.getClassName(); int idx = className.lastIndexOf('.'); name = className.substring(idx + 1); } else { buf.append(method.getReturnType()); buf.append(' '); } buf.append(name); buf.append('('); appendHumanReadableArgTypeList(method, buf); buf.append(')'); return buf.toString(); } private void appendHumanReadableArgTypeList(Method method, StringBuffer buf) { Type[] argTypes = method.getArgumentTypes(); String argSeparator = ""; for (int i = 0; i < argTypes.length; i++) { buf.append(argSeparator); buf.append(argTypes[i].toString()); argSeparator = ", "; } } private void fireDiff(String report, Severity severity, JavaClass clazz, Method method) { final String className = clazz.getClassName(); final ApiDifference diff = new ApiDifference(report + " in " + className, severity, className, getMethodId(clazz, method), null); getApiDiffDispatcher().fireDiff(diff); } private boolean isDeprecated(Method method) { Attribute[] attrs = method.getAttributes(); for (int i = 0; i < attrs.length; ++i) { if (attrs[i] instanceof org.apache.bcel.classfile.Deprecated) { return true; } } return false; } }
package org.intermine.web; import java.util.List; import java.util.ArrayList; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * A template query, which consists of a PathQuery and its (templated) description string * @author Mark Woodbridge */ public class TemplateQuery { protected static final String PATTERN = "\\[(.*?)\\]"; protected String description, indexedDescription; protected PathQuery query; protected List nodes = new ArrayList(); /** * Constructor * @param description the description, containing references to paths in the query * @param query the query itself */ public TemplateQuery(String description, PathQuery query) { this.description = description; this.query = query; if (description != null) { int i = 1; StringBuffer sb = new StringBuffer(); Matcher m = Pattern.compile(PATTERN).matcher(description); while (m.find()) { nodes.add(query.getNodes().get(m.group(1))); m.appendReplacement(sb, "[" + (i++) + "]"); } m.appendTail(sb); indexedDescription = sb.toString(); } } /** * Get the description (eg. "For a given company [Company.name]") * @return the description */ public String getDescription() { return description; } /** * Get the query (eg. select c from Company as c where c.name = 'CompanyA') * @return the query */ public PathQuery getQuery() { return query; } /** * Get the nodes from the description, in order (eg. {Company.name}) * @return the nodes */ public List getNodes() { return nodes; } /** * Get the indexed description (eg. "For a given company [1]") * @return the indexed description */ public String getIndexedDescription() { return indexedDescription; } /** * Get the "clean" description (eg. "For a given company") * @return the clean description */ public String getCleanDescription() { return description.replaceAll(" " + PATTERN, ""); } }
package io.spacedog.examples; import java.net.URL; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.Sets; import com.google.common.io.Resources; import io.spacedog.client.SpaceClient; import io.spacedog.client.SpaceRequest; import io.spacedog.utils.DataPermission; import io.spacedog.utils.Json; import io.spacedog.utils.Schema; import io.spacedog.utils.SchemaSettings; import io.spacedog.utils.SchemaSettings.SchemaAcl; public class Joho extends SpaceClient { final static Backend JOHO2 = new Backend("joho2", "joho", "hi joho", "david@spacedog.io"); final static Backend JOHORECETTE = new Backend("johorecette", "johorecette", "hi johorecette", "david@spacedog.io"); private Backend backend; @Test public void updateJohoBackend() { backend = JOHO2; // SpaceRequest.configuration().target(SpaceTarget.production); // setSchemaSettings(); // setSchema(buildDiscussionSchema(), backend); // setSchema(buildMessageSchema(), backend); // setSchema(buildCustomUserSchema(), backend); // setSchema(buildThemesSchema(), backend); // setSchema(buildSitesSchema(), backend); // setSchema(buildSondageSchema(), backend); // createInstallationSchema(); // createThemes(); // createSites(); } void setSchemaSettings() { SchemaSettings settings = new SchemaSettings(); settings.add(buildDiscussionSchema()) .add(buildMessageSchema()) .add(buildCustomUserSchema()) .add(buildThemesSchema()) .add(buildSondageSchema()) .add(buildSitesSchema()); SchemaAcl schemaAcl = new SchemaAcl(); schemaAcl.put("user", Sets.newHashSet(DataPermission.create, DataPermission.read, DataPermission.update, DataPermission.delete)); schemaAcl.put("admin", Sets.newHashSet(DataPermission.search, DataPermission.update_all, DataPermission.delete_all)); settings.acl.put("installation", schemaAcl); SpaceClient.saveSettings(backend, settings); } void createInstallationSchema() { SpaceRequest.delete("/1/schema/installation").adminAuth(backend).go(200, 404); SpaceRequest.put("/1/schema/installation").adminAuth(backend).go(201); } void createThemes() { URL url = Resources.getResource("io/spacedog/examples/joho.themes.json"); JsonNode themes = Json.readNode(url); SpaceRequest.post("/1/data/themes").adminAuth(backend).body(themes).go(201); } void createSites() { URL url = Resources.getResource("io/spacedog/examples/joho.sites.json"); JsonNode sites = Json.readNode(url); SpaceRequest.post("/1/data/sites").adminAuth(backend).body(sites).go(201); } static Schema buildDiscussionSchema() { return Schema.builder("discussion") .acl("user", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .text("title").french() .text("description").french() .object("theme") .text("name").french() .text("description").french() .string("code") .close() .object("category") .text("name").french() .text("description").french() .string("code") .close() .object("author") .text("firstname").french() .text("lastname").french() .string("avatar") .string("job") .close() .object("lastMessage") .text("text").french() .object("author") .text("firstname").french() .text("lastname").french() .string("avatar") .string("job") .build(); } static Schema buildMessageSchema() { return Schema.builder("message") .acl("user", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .text("text").french() .string("discussionId") .object("author") .text("firstname").french() .text("lastname").french() .string("avatar") .string("job") .close() .object("category") .text("name").french() .text("description").french() .string("code") .close() .object("responses").array() .text("text").french() .object("author") .text("firstname").french() .text("lastname").french() .string("avatar") .string("job") .close() .close() .build(); } static Schema buildCustomUserSchema() { return Schema.builder("user") .id("username") .acl("user", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("username") .string("email") .text("firstname").french() .text("lastname").french() .enumm("job") .enumm("service") .string("mobile") .string("fixed") .string("avatar") .object("site") .text("name").french() .string("address1") .string("address2") .string("town") .string("zipcode") .geopoint("where") .string("code") .close() .build(); } static Schema buildThemesSchema() { return Schema.builder("themes") .acl("user", DataPermission.search) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .object("themes").array() .text("name").french() .text("description").french() .string("code") .object("categories").array() .text("name").french() .text("description").french() .string("code") .close() .build(); } static Schema buildSitesSchema() { return Schema.builder("sites") .acl("user", DataPermission.search) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .object("sites").array() .text("name").french() .string("address1") .string("address2") .string("town") .string("zipcode") .geopoint("where") .string("code") .build(); } static Schema buildSondageSchema() { return Schema.builder("sondage") .acl("user", DataPermission.search, DataPermission.update_all) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .text("question").french() .string("status") .object("choices").array() .text("title").french() .object("answers").array() .string("userId").array() .close() .close() .build(); } }
package org.xblackcat.sjpu.settings; import javassist.ClassClassPath; import javassist.ClassPool; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xblackcat.sjpu.settings.ann.SettingsSource; import org.xblackcat.sjpu.settings.config.*; import org.xblackcat.sjpu.settings.util.IValueGetter; import org.xblackcat.sjpu.settings.util.LoadUtils; import org.xblackcat.sjpu.settings.util.MapWrapper; import org.xblackcat.sjpu.util.function.SupplierEx; import org.xblackcat.sjpu.util.thread.CustomNameThreadFactory; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.*; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * 14.04.2014 15:22 * * @author xBlackCat */ public final class Config { private final static PoolHolder POOL_HOLDER = new PoolHolder(); private static final SettingsWatchingDaemon WATCHING_DAEMON; private static final Executor notifyExecutor; private static final UnsupportedOperationException EXCEPTION; private static final IValueGetter JVM_VALUES_GETTER = new IValueGetter() { @Override public String get(String key) { return System.getProperties().getProperty(key); } @Override public Set<String> keySet() { return System.getProperties().stringPropertyNames(); } }; private static final IValueGetter ENV_VALUES_GETTER = LoadUtils.wrap(System.getenv()); private static final List<IValueGetter> DEFAULT_SUBSTITUTION = Arrays.asList( JVM_VALUES_GETTER, ENV_VALUES_GETTER ); static { SettingsWatchingDaemon daemon = null; UnsupportedOperationException ex = null; try { daemon = new SettingsWatchingDaemon(); final Thread thread = new Thread(daemon, "Settings Watching Daemon"); thread.setDaemon(true); thread.start(); } catch (IOException e) { throw new IOError(e); } catch (UnsupportedOperationException e) { ex = e; } EXCEPTION = ex; WATCHING_DAEMON = daemon; notifyExecutor = new ThreadPoolExecutor( 0, 15, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new CustomNameThreadFactory("notify-thread", "SettingsNotifier") ); } private static void postNotify(Runnable event) { notifyExecutor.execute(() -> { try { event.run(); } catch (Throwable e) { SettingsWatchingDaemon.log.error("Failed to process notify", e); } }); } private Config() { } /** * Initializes specified class with default values if any. A {@linkplain org.xblackcat.sjpu.settings.SettingsException} will be thrown * if the specified interface has methods without {@linkplain org.xblackcat.sjpu.settings.ann.DefaultValue} annotation */ public static final IConfig Defaults = new DefaultConfig(POOL_HOLDER.pool, Collections.emptyMap(), DEFAULT_SUBSTITUTION); /** * Builds a config reader from .properties file specified by {@linkplain java.io.File File} object. * * @param file .properties file. * @return config reader */ public static IConfig use(File file) { if (file == null) { throw new NullPointerException("File can't be null"); } return use(() -> LoadUtils.getInputStream(file)); } /** * Builds a config reader from .properties file specified by {@linkplain Path Path} object. * * @param file .properties file. * @return config reader */ public static IConfig use(Path file) { if (file == null) { throw new NullPointerException("File can't be null"); } return use(() -> LoadUtils.getInputStream(file)); } /** * Builds a config reader from .properties file specified by url. * * @param url url to .properties file. * @return config reader */ public static IConfig use(URL url) { if (url == null) { throw new NullPointerException("Url should be set"); } return use(url::openStream); } /** * Builds a config reader from .properties file located in class path resources. * * @param resourceName resource name. * @return config reader */ public static IConfig use(String resourceName) { return use(() -> LoadUtils.buildInputStreamProvider(resourceName)); } /** * Builds a config reader from .properties file located in class path resources. * * @param inputStreamSupplier input stream provider with all the * @return config reader */ public static IConfig use(SupplierEx<InputStream, IOException> inputStreamSupplier) { return new InputStreamConfig(POOL_HOLDER.pool, Collections.emptyMap(), DEFAULT_SUBSTITUTION, inputStreamSupplier); } public static IConfig useEnv() { return new APermanentConfig(POOL_HOLDER.pool, Collections.emptyMap(), DEFAULT_SUBSTITUTION) { @Override protected IValueGetter loadProperties() { return ENV_VALUES_GETTER; } }; } public static IConfig useJvm() { return new APermanentConfig(POOL_HOLDER.pool, Collections.emptyMap(), DEFAULT_SUBSTITUTION) { @Override protected IValueGetter loadProperties() { return JVM_VALUES_GETTER; } }; } public static IConfig anyOf(IConfig... sources) { return new MultiSourceConfig(POOL_HOLDER.pool, Collections.emptyMap(), DEFAULT_SUBSTITUTION, sources); } /** * Builds a config reader from .properties file which location is specified by annotations in the given class. * * @param clazz class annotated with {@linkplain org.xblackcat.sjpu.settings.ann.SettingsSource @SettingsSource} annotation. * @return config reader * @throws org.xblackcat.sjpu.settings.SettingsException if interface methods are not annotated or interface is not annotated with * {@linkplain org.xblackcat.sjpu.settings.ann.SettingsSource @SettingsSource} */ public static IConfig use(Class<?> clazz) throws SettingsException { return use(extractSource(clazz)); } /** * Loads settings for specified interface. A default location of resource file is used. Default location is specified * by {@linkplain org.xblackcat.sjpu.settings.ann.SettingsSource @SettingsSource} annotation. * <p> * If specified class marked with {@linkplain org.xblackcat.sjpu.settings.ann.Optional} annotation a <code>null</code> value will be * returned in case when required resource is not exists. * * @param clazz target interface class for holding settings. * @param <T> target interface for holding settings. * @return initialized implementation of the specified interface class. * @throws org.xblackcat.sjpu.settings.SettingsException if interface methods are not annotated or interface is not annotated with * {@linkplain org.xblackcat.sjpu.settings.ann.SettingsSource @SettingsSource} */ public static <T> T get(Class<T> clazz) throws SettingsException { return use(clazz).get(clazz); } public static IMutableConfig track(Class<?> clazz) throws SettingsException, IOException, UnsupportedOperationException { return track(extractSource(clazz), clazz.getClassLoader()); } public static IMutableConfig track(String resourceName) throws IOException, UnsupportedOperationException { return track(resourceName, Config.class.getClassLoader()); } public static IMutableConfig track(String resourceName, ClassLoader classLoader) throws IOException, UnsupportedOperationException { try { final URL resource = classLoader.getResource(resourceName); if (resource == null) { throw new FileNotFoundException("Resource " + resourceName + " is not found in class path"); } if (!"file".equals(resource.getProtocol())) { throw new IOException("Only resources as local files could be tracked."); } final Path path = Paths.get(resource.toURI()); return track(path); } catch (URISyntaxException e) { throw new IOException("Failed to get URI for the resource " + resourceName, e); } } public static IMutableConfig track(Path file) throws IOException, UnsupportedOperationException { if (file == null) { throw new NullPointerException("File can't be null"); } if (EXCEPTION != null) { throw EXCEPTION; } return WATCHING_DAEMON.watch(file, Collections.emptyMap(), DEFAULT_SUBSTITUTION); } public static IMutableConfig track(File file) throws IOException, UnsupportedOperationException { if (file == null) { throw new NullPointerException("File can't be null"); } return track(file.toPath()); } public static Builder with(APrefixHandler prefixHandler) { return new Builder().with(prefixHandler); } public static Builder substitute(IConfig substitution) throws SettingsException { return new Builder().substitute(substitution); } public static Builder substitute(IConfig substitution, String prefixName) { return new Builder().substitute(substitution, prefixName); } private static String extractSource(Class<?> clazz) throws SettingsException { final SettingsSource sourceAnn = clazz.getAnnotation(SettingsSource.class); if (sourceAnn == null) { throw new SettingsException( "No default source is specified for " + clazz.getName() + ". Should be specified with @" + SettingsSource.class + " annotation" ); } return sourceAnn.value(); } private static final class PoolHolder { private final ClassPool pool; private final ClassLoader classLoader = new ClassLoader(Config.class.getClassLoader()) { }; private PoolHolder() { pool = new ClassPool(true) { @Override public ClassLoader getClassLoader() { return classLoader; } }; pool.appendClassPath(new ClassClassPath(IConfig.class)); } } private final static class SettingsWatchingDaemon implements Runnable { private static final Log log = LogFactory.getLog(SettingsWatchingDaemon.class); private final WatchService watchService = FileSystems.getDefault().newWatchService(); private final Map<Path, MutableConfig> trackedFiles = new WeakHashMap<>(); private final Map<WatchKey, List<MutableConfig>> trackers = new WeakHashMap<>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private IMutableConfig watch( Path file, Map<String, APrefixHandler> prefixHandler, List<IValueGetter> subtitution ) throws IOException { lock.writeLock().lock(); try { MutableConfig config = trackedFiles.get(file); if (config != null) { return config; } MutableConfig newConfig = new MutableConfig(POOL_HOLDER.pool, prefixHandler, subtitution, file, Config::postNotify); final WatchKey watchKey = file.getParent().register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE ); trackers.computeIfAbsent(watchKey, k -> new ArrayList<>()).add(newConfig); trackedFiles.put(file, newConfig); return newConfig; } finally { lock.writeLock().unlock(); } } private SettingsWatchingDaemon() throws IOException { } @Override public void run() { for (; ; ) { final WatchKey key; try { key = watchService.take(); } catch (InterruptedException e) { return; } if (!key.isValid()) { lock.writeLock().lock(); try { trackers.remove(key); } finally { lock.writeLock().unlock(); } continue; } final List<MutableConfig> configs; lock.readLock().lock(); try { configs = trackers.get(key); } finally { lock.readLock().unlock(); } if (configs != null) { Set<Path> paths = new HashSet<>(); for (WatchEvent<?> event: key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } Path filename = getContext(event); paths.add(filename); } for (MutableConfig c: configs) { c.checkPaths(paths); } } key.reset(); } } @SuppressWarnings("unchecked") private static <T> T getContext(WatchEvent<?> event) { return ((WatchEvent<T>) event).context(); } } public static class Builder { private final Map<String, APrefixHandler> prefixHandlers = new HashMap<>(); private final List<IValueGetter> substitutions = new ArrayList<>(); public Builder with(APrefixHandler prefixHandler) { prefixHandlers.put(prefixHandler.getPrefix(), prefixHandler); return this; } public Builder substitute(IConfig substitution) { return substitute(substitution, ""); } public Builder substitute(Map<String, String> substitution) { if (substitution == null) { throw new NullPointerException("Substitution map is null"); } if (!substitution.isEmpty()) { substitutions.add(new MapWrapper(new HashMap<>(substitution))); } return this; } public Builder substitute(IConfig substitution, String prefixName) { if (!(substitution instanceof AConfig)) { throw new IllegalArgumentException("Unsupported config for substitution"); } substitutions.add(IValueGetter.withPrefix(((AConfig) substitution).getValueGetter(), prefixName)); return this; } /** * Builds a config reader from .properties file specified by {@linkplain java.io.File File} object. * * @param file .properties file. * @return config reader */ public IConfig use(File file) { if (file == null) { throw new NullPointerException("File can't be null"); } return use(() -> LoadUtils.getInputStream(file)); } public IConfig defaults() { return new DefaultConfig(POOL_HOLDER.pool, prefixHandlers, substitutions); } /** * Builds a config reader from .properties file specified by {@linkplain Path Path} object. * * @param file .properties file. * @return config reader */ public IConfig use(Path file) { if (file == null) { throw new NullPointerException("File can't be null"); } return use(() -> LoadUtils.getInputStream(file)); } /** * Builds a config reader from .properties file specified by url. * * @param url url to .properties file. * @return config reader */ public IConfig use(URL url) { if (url == null) { throw new NullPointerException("Url should be set"); } return use(url::openStream); } /** * Builds a config reader from .properties file located in class path resources. * * @param resourceName resource name. * @return config reader */ public IConfig use(String resourceName) { return use(() -> LoadUtils.buildInputStreamProvider(resourceName)); } /** * Builds a config reader from .properties file located in class path resources. * * @param inputStreamSupplier input stream provider with all the * @return config reader */ public IConfig use(SupplierEx<InputStream, IOException> inputStreamSupplier) { return new InputStreamConfig(POOL_HOLDER.pool, prefixHandlers, substitutions, inputStreamSupplier); } public IConfig useEnv() { return new APermanentConfig(POOL_HOLDER.pool, prefixHandlers, substitutions) { @Override protected IValueGetter loadProperties() { return ENV_VALUES_GETTER; } }; } public IConfig useJvm() { return new APermanentConfig(POOL_HOLDER.pool, prefixHandlers, substitutions) { @Override protected IValueGetter loadProperties() { return JVM_VALUES_GETTER; } }; } public IConfig anyOf(IConfig... sources) { return new MultiSourceConfig(POOL_HOLDER.pool, prefixHandlers, substitutions, sources); } /** * Builds a config reader from .properties file which location is specified by annotations in the given class. * * @param clazz class annotated with {@linkplain org.xblackcat.sjpu.settings.ann.SettingsSource @SettingsSource} annotation. * @return config reader * @throws org.xblackcat.sjpu.settings.SettingsException if interface methods are not annotated or interface is not annotated with * {@linkplain org.xblackcat.sjpu.settings.ann.SettingsSource @SettingsSource} */ public IConfig use(Class<?> clazz) throws SettingsException { return use(extractSource(clazz)); } /** * Loads settings for specified interface. A default location of resource file is used. Default location is specified * by {@linkplain org.xblackcat.sjpu.settings.ann.SettingsSource @SettingsSource} annotation. * <p> * If specified class marked with {@linkplain org.xblackcat.sjpu.settings.ann.Optional} annotation a <code>null</code> value will be * returned in case when required resource is not exists. * * @param clazz target interface class for holding settings. * @param <T> target interface for holding settings. * @return initialized implementation of the specified interface class. * @throws org.xblackcat.sjpu.settings.SettingsException if interface methods are not annotated or interface is not annotated with * {@linkplain org.xblackcat.sjpu.settings.ann.SettingsSource @SettingsSource} */ public <T> T get(Class<T> clazz) throws SettingsException { return use(clazz).get(clazz); } public IMutableConfig track(Class<?> clazz) throws SettingsException, IOException, UnsupportedOperationException { return track(extractSource(clazz), clazz.getClassLoader()); } public IMutableConfig track(String resourceName) throws IOException, UnsupportedOperationException { return track(resourceName, Config.class.getClassLoader()); } public IMutableConfig track(String resourceName, ClassLoader classLoader) throws IOException, UnsupportedOperationException { try { final URL resource = classLoader.getResource(resourceName); if (resource == null) { throw new FileNotFoundException("Resource " + resourceName + " is not found in class path"); } if (!"file".equals(resource.getProtocol())) { throw new IOException("Only resources as local files could be tracked."); } final Path path = Paths.get(resource.toURI()); return track(path); } catch (URISyntaxException e) { throw new IOException("Failed to get URI for the resource " + resourceName, e); } } public IMutableConfig track(Path file) throws IOException, UnsupportedOperationException { if (file == null) { throw new NullPointerException("File can't be null"); } if (EXCEPTION != null) { throw EXCEPTION; } return WATCHING_DAEMON.watch(file, prefixHandlers, substitutions); } public IMutableConfig track(File file) throws IOException, UnsupportedOperationException { if (file == null) { throw new NullPointerException("File can't be null"); } return track(file.toPath()); } } }
package jmetest.renderer.loader; import com.jme.app.SimpleGame; import com.jme.scene.model.XMLparser.JmeBinaryReader; import com.jme.scene.model.XMLparser.BinaryToXML; import com.jme.scene.model.XMLparser.Converters.MaxToJme; import com.jme.scene.Node; import com.jme.scene.shape.Box; import com.jme.math.Vector3f; import com.jme.math.Quaternion; import com.jme.bounding.BoundingSphere; import com.jme.renderer.ColorRGBA; import java.io.*; import java.net.URL; public class TestMaxJmeWrite extends SimpleGame{ public static void main(String[] args) { TestMaxJmeWrite app=new TestMaxJmeWrite(); app.setDialogBehaviour(SimpleGame.FIRSTRUN_OR_NOCONFIGFILE_SHOW_PROPS_DIALOG); app.start(); } Node globalLoad=null; protected void simpleInitGame() { MaxToJme C1=new MaxToJme(); try { ByteArrayOutputStream BO=new ByteArrayOutputStream(); URL maxFile=TestMaxJmeWrite.class.getClassLoader().getResource("jmetest/data/model/cubeColoured.3DS"); // URL maxFile = new File("3dsmodels/sphere.3ds").toURI().toURL(); // URL maxFile = new File("3dsmodels/cube.3ds").toURI().toURL(); // URL maxFile = new File("3dsmodels/face.3ds").toURI().toURL(); // URL maxFile = new File("3dsmodels/europe.3ds").toURI().toURL(); // URL maxFile = new File("3dsmodels/cow.3ds").toURI().toURL(); // URL maxFile = new File("3dsmodels/tank.3ds").toURI().toURL(); // URL maxFile = new File("3dsmodels/simpmovement.3DS").toURI().toURL(); C1.convert(new BufferedInputStream(maxFile.openStream()),BO); JmeBinaryReader jbr=new JmeBinaryReader(); BinaryToXML btx=new BinaryToXML(); StringWriter SW=new StringWriter(); btx.sendBinarytoXML(new ByteArrayInputStream(BO.toByteArray()),SW); System.out.println(SW); // jbr.setProperty("texurl",new File("3dsmodels").toURI().toURL()); Node r=jbr.loadBinaryFormat(new ByteArrayInputStream(BO.toByteArray())); r.setLocalScale(.1f); rootNode.attachChild(r); // drawAxis(); } catch (IOException e) { System.out.println("Damn exceptions:"+e); } } private void drawAxis() { Box Xaxis=new Box("axisX",new Vector3f(5,0,0),5f,.1f,.1f); Xaxis.setModelBound(new BoundingSphere()); Xaxis.updateModelBound(); Xaxis.setSolidColor(ColorRGBA.blue); Box Yaxis=new Box("axisY",new Vector3f(0,5,0),.1f,5f,.1f); Yaxis.setModelBound(new BoundingSphere()); Yaxis.updateModelBound(); Yaxis.setSolidColor(ColorRGBA.red); Box Zaxis=new Box("axisZ",new Vector3f(0,0,5),.1f,.1f,5f); Zaxis.setSolidColor(ColorRGBA.green); Zaxis.setModelBound(new BoundingSphere()); Zaxis.updateModelBound(); rootNode.attachChild(Xaxis); rootNode.attachChild(Yaxis); rootNode.attachChild(Zaxis); } }
// PythonModuleTracker.java package ed.lang.python; import org.python.core.*; import java.util.*; import java.io.*; import ed.appserver.*; import ed.util.*; /** * Replacement class for sys.modules. Can flush outdated modules, and * prevents untrusted code from getting access to Java * packages/classes. */ public class PythonModuleTracker extends PyStringMap { static final boolean DEBUG = Boolean.getBoolean( "DEBUG.PYTHONMODULETRACKER" ); boolean _flushing = false; PythonModuleTracker( PyStringMap old ){ super(); update( new PyObject[]{ old }, new String[0] ); } public PyObject __finditem__( String key ){ return handleReturn( super.__finditem__( key ) ); } public PyObject __finditem__( PyObject key ){ return handleReturn( super.__finditem__( key ) ); } PyObject handleReturn( PyObject obj ){ Python.checkSafeImport( obj ); if( ! ( obj instanceof PyModule ) ) return obj; // if module is outdated PyModule module = (PyModule)obj; return module; } public PyObject get( PyObject key ){ return get( key , Py.None ); } public PyObject get( PyObject key , PyObject missing ){ return handleReturn( super.get( key , missing ) ); } public PyStringMap copy(){ return new PythonModuleTracker( this ); } public PyList keys(){ PyList k = new PyList(); PyList keys = super.keys(); int len = keys.__len__(); for( int i = 0; i < len; i++ ){ PyObject key = keys.pyget( i ); PyObject val = super.get( key ); if( Python.isSafeImport( val ) ) k.append(key); } return k; } public PyList items(){ PyList l = new PyList(); PyList keys = keys(); int len = keys.__len__(); for( int i = 0; i < len ; i++){ PyObject key = keys.pyget(i); PyObject val = super.get(key); PyTuple t = new PyTuple(key, val); l.append(t); } return l; } public PyList values(){ PyList v = new PyList(); PyList values = super.values(); int len = values.__len__(); for( int i = 0; i < len; ++i){ PyObject val = values.pyget(i); if( Python.isSafeImport( val ) ) v.append(val); } return v; } // FIXME: clumsy -- actually implement? public PyObject iterkeys(){ return keys().__iter__(); } public PyObject itervalues(){ return values().__iter__(); } public PyObject iteritems(){ return items().__iter__(); } public PyObject pop( PyObject key ){ return pop( key , Py.None ); } public PyObject pop( PyObject key , PyObject value ){ PyObject m = super.__finditem__( key ); // Don't pop unless safe if( Python.isSafeImport( m ) ) return handleReturn( super.pop( key , value ) ); Python.checkSafeImport( m ); // raises exception return null; } public void __setitem__( String key , PyObject value ){ super.__setitem__( key , value ); handleSet( value ); } public void __setitem__( PyObject key , PyObject value ){ super.__setitem__( key , value ); handleSet( value ); } void handleSet( PyObject obj ){ // Thought I could get the __file__ and check timestamp, but at this // point in time, the module doesn't have a __file__ } public static boolean needsRefresh( String filename ){ // Src for file File pyFile = new File( filename ); String clsPath = filename.replace( ".py" , "$py.class" ); // Compiled class file -- might not exist File clsFile = new File( clsPath ); if( ! pyFile.exists() ){ if( DEBUG ) System.out.println("File was deleted: " + pyFile); return true; } if( clsFile.exists() && pyFile.lastModified() > clsFile.lastModified() ){ if( DEBUG ) System.out.println("Newer " + pyFile + " " + clsFile); return true; } return false; } /** * @return the flushed files */ public Set<File> flushOld(){ boolean shouldFlush = false; Set<String> newer = new HashSet<String>(); Set<File> files = new HashSet<File>(); // Go through each module in sys.modules and see if the file is newer for( Object o : keys() ){ if( ! (o instanceof String) ){ throw new RuntimeException( "not a string in the keys " + o.getClass() ); } String s = (String)o; PyObject obj = super.__finditem__( s ); if( ! ( obj instanceof PyModule ) ) continue; // User madness? PyModule mod = (PyModule)obj; // File the module was loaded from. PyObject __file__ = mod.__dict__.__finditem__( "__file__" ); if( __file__ == null || !( __file__ instanceof PyString ) ){ // User could have overridden it, in which case, can't do much continue; } if( __file__.toString().equals( SiteSystemState.VIRTUAL_MODULE ) ){ // FIXME: might have to somehow refresh these someday continue; } if( needsRefresh( __file__.toString() ) ){ newer.add( s ); for( Object o2 : keys() ){ if( ! (o2 instanceof String) ){ throw new RuntimeException( "got a non-string key " + o.getClass() ); // can't happen } String s2 = (String)o2; if( s2.startsWith( s + "." ) ) // "child" of flushed module newer.add( s2 ); } } } Set<String> flushed = new HashSet<String>(); Set<String> toAdd = new HashSet<String>(); toAdd.addAll( newer ); while( ! toAdd.isEmpty() ){ // FIXME -- guess I should use a queue or something String o = toAdd.iterator().next(); flushed.add( o ); toAdd.remove( o ); PyObject obj = super.__finditem__( o ); if( obj == null ){ // Not really a module -- someone probably stuck a filename in // our rdeps. files.add( new File( o ) ); continue; } if( ! ( obj instanceof PyModule ) ){ // user madness? // FIXME: go in files? continue; } PyModule mod = (PyModule)obj; PyObject __file__ = obj.__findattr__( "__file__" ); if( __file__ != null ) files.add( new File( __file__.toString() ) ); if( DEBUG ) System.out.println("Flushing " + o); __delitem__( o ); // Get the set of modules that imported module o Set<String> rdeps = _reverseDeps.get( o ); _reverseDeps.remove( o ); if( rdeps == null ){ if( DEBUG ) System.out.println("Nothing imported " + o ); continue; } for( String s : rdeps ){ if( DEBUG ) System.out.println("module "+ s + " imported " + o ); toAdd.add( s ); } } return files; } // Stores relationships of "module Y was imported by modules X1, X2, X3.." Map<String, Set<String> > _reverseDeps = new HashMap<String, Set<String> >(); Map<String, Set<String> > _forwardDeps = new HashMap<String, Set<String> >(); public void addDependency( String moduleS , String importerS ){ Set<String> rdeps = _reverseDeps.get( moduleS ); if( rdeps == null ){ rdeps = new HashSet<String>(); _reverseDeps.put( moduleS , rdeps ); } if( DEBUG ) System.out.println( "Module "+ moduleS + " was imported by module " + importerS ); rdeps.add( importerS ); Set<String> fdeps = _forwardDeps.get( importerS ); if( fdeps == null ){ fdeps = new HashSet<String>(); _forwardDeps.put( importerS , fdeps ); } fdeps.add( moduleS ); } public void addRecursive( String name , AppContext ac ){ addRecursive( name , ac , new IdentitySet()); } public void addRecursive( String name , AppContext ac , IdentitySet seen ){ if( seen.contains( name ) ) return; seen.add( name ); PyObject mod = __finditem__( name ); if( DEBUG ) System.out.println("Adding init dependency for " + name + " " + mod); if( mod != null ){ PyObject __file__ = mod.__findattr__( "__file__" ); if( __file__ != null ){ File file = new File( __file__.toString() ); ac.addInitDependency( file ); } else { // builtin module; for dependency purposes, it doesn't matter, // because how could a builtin module import user code? } } else { // This is OK because a JXP doesn't have a module, but imported // other modules. if( DEBUG ) System.out.println("Skipping -- no module by that name."); } Set<String> fdeps = _forwardDeps.get( name ); if( DEBUG ){ System.out.println( name + " imported " + fdeps ); } if( fdeps == null ) return; // didn't import any modules for( String s : fdeps ){ addRecursive( s, ac , seen ); } } }
package OpenTechnology; import OpenTechnology.proxy.CommonProxy; import OpenTechnology.utils.PointerList; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; 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 org.apache.logging.log4j.Logger; @Mod(modid= OpenTechnology.MODID, name= OpenTechnology.MODID, version= OpenTechnology.VERSION) public class OpenTechnology { public final static String MODID = "OpenTechnology"; public final static String VERSION = "0.3.13a"; public static Logger logger; public static CreativeTab tab = new CreativeTab(); @Mod.Instance public static OpenTechnology instance; @SidedProxy(clientSide = "OpenTechnology.proxy.ClientProxy", serverSide = "OpenTechnology.proxy.ServerProxy") public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent e) { logger = e.getModLog(); Config.init(e.getSuggestedConfigurationFile()); proxy.preInit(e); } @EventHandler public void init(FMLInitializationEvent e) { proxy.init(e); PointerList.timer.schedule(PointerList.task, 1000, 1000); } @EventHandler public void postInit(FMLPostInitializationEvent e) { proxy.postInit(e); } }
package allout58.util.SiteUtils; import java.net.MalformedURLException; import java.net.URL; public class Utils { public static final String chromeUA = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; public static final String[] blockedExtensions = new String[] { ".pdf", ".json", ".jpg", ".jpeg", ".gif", ".png", ".doc", ".docx", ".ppt", ".pptx", ".zip" }; public static String absoluteURL(String referer, String link) throws MalformedURLException { String newlink = link.replace(" ", "%20"); String base = referer.substring(0, referer.lastIndexOf("/") + 1); URL url = new URL(new URL(referer), newlink); return url.toExternalForm(); } public static String stripCssStates(String inputStyle) { if (!inputStyle.contains(":")) return inputStyle; String output = inputStyle; while (output.indexOf(":") > 0) { int indexCol = output.indexOf(":"); int indexSpace = output.indexOf(" ", indexCol); int indexComma = output.indexOf(",", indexCol); int indexArrow = output.indexOf(">", indexCol); if (indexSpace > 0) output = output.replace(output.substring(indexCol, indexSpace), ""); else if (indexComma > 0) output = output.replace(output.substring(indexCol, indexComma), ""); else if (indexArrow > 0) output = output.replace(output.substring(indexCol, indexArrow), ""); else output = output.substring(0, indexCol); } return output; } }
package bulkscandownloader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.nio.file.Paths; import java.rmi.Remote; import java.rmi.RemoteException; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.Response; import javax.xml.rpc.ServiceException; import javax.xml.soap.SOAPException; import org.apache.axis.types.URI; import org.apache.axis.types.URI.MalformedURIException; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import iris.*; import iris.containers.ArrayDictionary; public class Downloader { private static final Logger logger = LogManager.getLogger(Downloader.class); private Configuration config; private Authentication authClient; private ContentDownloadService downloadService; public Downloader(Configuration config) throws ServiceException { this.authClient = new Authentication(config.getFrontSessionURL()); this.downloadService = authClient.getDownloadService(config.getDownloadServiceURL()); this.config = config; } public void run() throws InterruptedException { while (true) { logger.info("Starting fetch iteration."); oneIteration(); logger.info("Ending fetch iteration, sleeping 10 minutes now."); Thread.sleep(600000); // 10 minutes } } public void oneIteration() { for (User user : config.getUsers()) { if (!user.isActive()) continue; QueryDownloadableContentRequest downloadRequest = new QueryDownloadableContentRequest( user.isAllEnvelopeSides(), user.isContentScans(), user.isEnvelopeImages(), null); // MailboxID, can be left at null to grab all mailboxes try { authClient.signIn(user.getUsername(), user.getPassword()); downloadItemsForUser(user, downloadRequest); } catch (Exception e) { logger.warn("Unable to sign in user: " + user.getUsername()); logger.warn(e); // If we can't sign in, proceed to next user } } } private void downloadItemsForUser(User user, QueryDownloadableContentRequest downloadRequest) { QueryDownloadableContentResponse qdcr = null; int totalJobCompletedCount = 0; while (qdcr == null || sumOfLengthsOfLists(qdcr.getQueryResult()) < qdcr.getItemCount()) { try { qdcr = requestDownloadDance(user, downloadRequest); } catch (Exception e) { logger.warn("Unable to create a download request for user: " + user.getUsername()); logger.warn("Proceeding to next user."); break; // We can't make a download request for this user } if (qdcr.getItemCount() == 0) logger.info("No items to download for user: " + user.getUsername()); ArrayDictionary[] scannedContentDictionary = qdcr.getQueryResult(); int currentListCompletedCount = 0; for (ArrayDictionary kvPair : scannedContentDictionary) { DownloadableContent[] scannedContentList = kvPair.getValue(); Enclosure firstEnclosure = null; for (DownloadableContent sc : scannedContentList) { try { processItem(user, sc, qdcr.getItemCount() - (currentListCompletedCount + 1)); ++currentListCompletedCount; ++totalJobCompletedCount; if (sc.getClass() == ScannedContent.class) { acknowledgeDownload(sc); } else if (firstEnclosure == null && sc.getClass() == Enclosure.class) { firstEnclosure = (Enclosure) sc; } } catch (IOException e) { // Just log this error as we want to be able to continue with the other // users and items even if this fails. logger.error("Unable save item to disk:"); logger.error(e); } } if (firstEnclosure != null) { acknowledgeDownload(firstEnclosure); } if (scannedContentList.length > 0) { processPostDownloadAction(scannedContentList[0]); } } if (totalJobCompletedCount > 0) logger.info("Completed downloading for user: " + user.getUsername()); } } /* * This dance happens because a series of item downloads may take so long that the authentication * session will time out in the middle of the process so it needs to be renewed before the next * item can be downloaded. */ private QueryDownloadableContentResponse requestDownloadDance(User user, QueryDownloadableContentRequest downloadRequest) throws Exception { QueryDownloadableContentResponse qdcr; try { qdcr = downloadService.queryDownloadableContent(downloadRequest); } catch (AuthFault e) { // retry once in case session expired authClient.signIn(user.getUsername(), user.getPassword()); qdcr = downloadService.queryDownloadableContent(downloadRequest); } return qdcr; } private void processPostDownloadAction(DownloadableContent content) { try { if (content.getItemStatus() == PItemStatus.Active && (content.getOperation() == null || content.getExtractStatus() == ExtractStatus.Canceled || content.getExtractStatus() == ExtractStatus.Completed )) { switch (config.getPostDownloadAction()) { case 0: //Noop break; case 1: // Recycle RecycleDownloadedItemRequest recycleRequest = new RecycleDownloadedItemRequest( true, // Keep Scans content.getMailboxID(), new VItemID[]{content.getVItemID()} ); downloadService.recycleDownloadedItem(recycleRequest); break; case 2: // Shred ShredDownloadedItemRequest shredRequest = new ShredDownloadedItemRequest( true, // Keep Scans content.getMailboxID(), new VItemID[]{content.getVItemID()} ); downloadService.shredDownloadedItem(shredRequest); break; default: logger.error("Post Download Action not properly defined. Doing nothing."); } } } catch (RemoteException e) { logger.error("Unable to contact download service for post download action, no action will be taken."); logger.error(e); } } private AcknowledgeDownloadResponse acknowledgeDownload(DownloadableContent sc) { if (BulkScanDownloader.DEBUG_BUILD) // Don't acknowledge for debug builds, we want to be able to re-run things return null; AcknowledgeDownloadResponse response; try { response = downloadService.acknowledgeDownload(new AcknowledgeDownloadRequest(sc)); } catch (RemoteException e) { logger.error("Unable to contact download service for download acknowledgement, item will be downloaded again next time."); logger.error(e); response = null; } return response; } private void processItem(User user, DownloadableContent itemToSave, int itemsRemaining) throws IOException { String fileName = getFileName(user, itemToSave); logger.info("File processing started: " + fileName); saveScannedContent(itemToSave, fileName); logger.info("File processing completed: " + fileName); logger.info("Items remaining: " + itemsRemaining); } private void saveScannedContent(DownloadableContent contentToRetrieve, String fileName) throws IOException { File file = new File(fileName); file.getParentFile().mkdirs(); file.createNewFile(); InputStream inputStream = fetchScannedContent(contentToRetrieve); OutputStream outputStream = new FileOutputStream(file); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } private InputStream fetchScannedContent(DownloadableContent contentToRetrieve) throws RemoteException { FetchDownloadableContentRequest fetchRequest = new FetchDownloadableContentRequest(contentToRetrieve); URI url = downloadService.fetchDownloadableContent(fetchRequest).getUrl(); logger.info("Starting fetch of: " + url.toString()); Cookie cookie = new Cookie("AuthFront", authClient.getSession().getSessionID(), "/", url.getHost()); Response dataResponse = this.authClient.client.target(url.toString()).request().cookie(cookie).get(); return dataResponse.readEntity(InputStream.class); } private String getFileName(User user, DownloadableContent itemToSave) { String dir = config.getRootDir(); if (config.isUseFolders()) dir = Paths.get(dir, user.getUsername(), itemToSave.getFolderName()).toString(); Enclosure enclosureToSave = itemToSave.getClass() == Enclosure.class ? (Enclosure) itemToSave : null; String fileName = String.format("%s%s.%s", itemToSave.getLicensePlate().getID(), enclosureToSave != null ? "-" + enclosureToSave.getSide().toString() : "", itemToSave.getContentType() == FileStoreContentType.JPEG ? "JPG" : itemToSave.getContentType().toString() ); return Paths.get(dir, fileName).toString(); } private Integer sumOfLengthsOfLists( ArrayDictionary[] queryResult) { int sum = 0; for (ArrayDictionary content : queryResult) sum += content.getValue().length; return sum; } }
package com.austinv11.etf.util; import com.austinv11.etf.ETFConfig; import com.austinv11.etf.common.TermTypes; import com.austinv11.etf.erlang.ErlangMap; import com.austinv11.etf.parsing.ETFParser; import com.austinv11.etf.writing.ETFWriter; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * This represents a mapper which will handle object serialization/deserialization. */ public class Mapper { private ETFConfig config; private static sun.misc.Unsafe UNSAFE; static { try { Field theUnsafe = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); UNSAFE = (sun.misc.Unsafe) theUnsafe.get(null); } catch (Throwable e) { UNSAFE = null; //Unsafe unavailable } } public Mapper(ETFConfig config) { this.config = config; } private List<PropertyManager> findProperties(Object instance, Class clazz) { List<PropertyManager> properties = new ArrayList<>(); for (Field field : clazz.getFields()) { if (!Modifier.isTransient(field.getModifiers())) { properties.add(new PropertyManager(instance, field)); } } return properties; } private <T> T createInstance(Class<T> clazz) { if (UNSAFE != null) { //Unsafe available, use it to instantiate the class try { return (T) UNSAFE.allocateInstance(clazz); } catch (InstantiationException e) {} } //Fallback to reflection try { return clazz.getConstructor().newInstance(); } catch (Exception e) { throw new ETFException(e); } } public <T> byte[] writeToMap(T obj) { ETFWriter writer = config.createWriter(); Map<String, Object> properties = findProperties(obj, obj.getClass()) .stream().collect(Collectors.toMap(PropertyManager::getName, PropertyManager::getValue)); return writer.writeMap(properties).toBytes(); } public <T> byte[] write(T obj) { ETFWriter writer = config.createWriter(); findProperties(obj, obj.getClass()).forEach(writer::write); return writer.toBytes(); } public <T> T read(ErlangMap data, Class<T> clazz) { T instance = createInstance(clazz); List<PropertyManager> properties = findProperties(instance, clazz); for (PropertyManager property : properties) { if (data.containsKey(property.getName())) { property.setValue(data.get(property.getName())); } } return instance; } public <T> T read(byte[] data, Class<T> clazz) { ETFParser parser = config.createParser(data); T instance = createInstance(clazz); List<PropertyManager> properties = findProperties(instance, clazz); if (parser.peek() == TermTypes.MAP_EXT) { ErlangMap map = parser.nextMap(); if (Map.class.isAssignableFrom(clazz)) { //User wants a map so lets give it to them return (T) map; } else { return read(map, clazz); } } else { for (PropertyManager property : properties) { if (parser.isFinished()) break; property.setValue(parser.next()); } return instance; } } public interface IPropertyAccessor { Object get(); } public interface IPropertyMutator { void set(Object o); } public static class FieldAccessorAndMutator implements IPropertyAccessor, IPropertyMutator { private final Object object; private final Field field; public FieldAccessorAndMutator(Object object, Field field) { this.object = object; this.field = field; this.field.setAccessible(true); } @Override public Object get() { try { return field.get(object); } catch (IllegalAccessException e) { throw new ETFException(e); } } @Override public void set(Object o) { try { field.set(object, o); } catch (IllegalAccessException e) { throw new ETFException(e); } } } public static class MethodAccessorAndMutator implements IPropertyAccessor, IPropertyMutator { private final Object object; private final Method method; public MethodAccessorAndMutator(Object object, Method method) { this.object = object; this.method = method; this.method.setAccessible(true); } @Override public Object get() { try { return method.invoke(object); } catch (IllegalAccessException | InvocationTargetException e) { throw new ETFException(e); } } @Override public void set(Object o) { try { method.invoke(object, o); } catch (IllegalAccessException | InvocationTargetException e) { throw new ETFException(e); } } } public static class NOPAccessorAndMutator implements IPropertyAccessor, IPropertyMutator { public static final NOPAccessorAndMutator INSTANCE = new NOPAccessorAndMutator(); @Override public Object get() { return null; } @Override public void set(Object o) {} } public static class PropertyManager { private final Object instance; private final IPropertyMutator mutator; private final IPropertyAccessor accessor; private final String name; private static String capitalize(String s) { return s.substring(0, 1).toUpperCase() + (s.length() > 1 ? s.substring(1) : ""); } public PropertyManager(Object instance, Field field) { this.instance = instance; field.setAccessible(true); IPropertyAccessor accessor = null; boolean isFinal = Modifier.isFinal(field.getModifiers()); IPropertyMutator mutator = isFinal ? NOPAccessorAndMutator.INSTANCE : null; for (Method m : instance.getClass().getMethods()) { if (mutator != null && accessor != null) break; m.setAccessible(true); if (m.getName().equals(String.format("get%s", capitalize(field.getName())))) { accessor = new MethodAccessorAndMutator(instance, m); continue; } else if (!isFinal && m.getName().equals(String.format("set%s", capitalize(field.getName()))) && m.getParameterCount() == 1 && m.getParameterTypes()[0].equals(field.getType())) { mutator = new MethodAccessorAndMutator(instance, m); continue; } else if (m.getDeclaredAnnotation(GetterMethod.class) != null) { if (m.getDeclaredAnnotation(GetterMethod.class).value().equals(field.getName())) { accessor = new MethodAccessorAndMutator(instance, m); continue; } } else if (!isFinal && m.getDeclaredAnnotation(SetterMethod.class) != null && m.getParameterCount() == 1 && m.getParameterTypes()[0].equals(field.getType())) { if (m.getDeclaredAnnotation(SetterMethod.class).value().equals(field.getName())) { mutator = new MethodAccessorAndMutator(instance, m); continue; } } } if (accessor == null) accessor = new FieldAccessorAndMutator(instance, field); if (mutator == null) mutator = new FieldAccessorAndMutator(instance, field); this.accessor = accessor; this.mutator = mutator; this.name = field.getName(); } public void setValue(Object value) { mutator.set(value); } public Object getValue() { return accessor.get(); } public String getName() { return name; } } }
package com.ezardlabs.lostsector; import com.ezardlabs.dethsquare.Animator; import com.ezardlabs.dethsquare.Collider; import com.ezardlabs.dethsquare.GameObject; import com.ezardlabs.dethsquare.LevelManager; import com.ezardlabs.dethsquare.Renderer; import com.ezardlabs.dethsquare.Rigidbody; import com.ezardlabs.dethsquare.TextureAtlas; import com.ezardlabs.dethsquare.multiplayer.NetworkAnimator; import com.ezardlabs.dethsquare.multiplayer.NetworkRenderer; import com.ezardlabs.dethsquare.multiplayer.NetworkTransform; import com.ezardlabs.dethsquare.prefabs.PrefabManager; import com.ezardlabs.dethsquare.util.BaseGame; import com.ezardlabs.lostsector.levels.ExploreLevel; import com.ezardlabs.lostsector.levels.MainMenuLevel; import com.ezardlabs.lostsector.levels.MultiplayerLevel; import com.ezardlabs.lostsector.levels.MultiplayerLobbyLevel; import com.ezardlabs.lostsector.levels.ProceduralLevel; import com.ezardlabs.lostsector.levels.SurvivalLevel; import com.ezardlabs.lostsector.objects.Player; import com.ezardlabs.lostsector.objects.environment.Door; import com.ezardlabs.lostsector.objects.environment.LaserDoor; import com.ezardlabs.lostsector.objects.environment.Locker; import com.ezardlabs.lostsector.objects.hud.HUD; import com.ezardlabs.lostsector.objects.projectiles.LankaBeam; import com.ezardlabs.lostsector.objects.warframes.Frost; public class Game extends BaseGame { public static GameObject[] players; public enum DamageType { NORMAL, SLASH, COLD, KUBROW } @Override public void create() { LevelManager.registerLevel("explore", new ExploreLevel()); LevelManager.registerLevel("survival", new SurvivalLevel()); LevelManager.registerLevel("procedural", new ProceduralLevel()); LevelManager.registerLevel("multiplayer_lobby", new MultiplayerLobbyLevel()); LevelManager.registerLevel("multiplayer", new MultiplayerLevel()); LevelManager.registerLevel("main_menu", new MainMenuLevel()); registerPlayerPrefabs(); registerProjectilePrefabs(); registerDoorPrefabs(); registerLockerPrefabs(); LevelManager.loadLevel("main_menu"); } private void registerPlayerPrefabs() { PrefabManager.addPrefab("player", () -> new GameObject("Player", "player", new Player(), new HUD(), new Renderer(), new Animator(), new Frost(), new Collider(200, 200), new Rigidbody(), new NetworkTransform(), new NetworkRenderer(), new NetworkAnimator()), () -> new GameObject("Other Player", "player", new Renderer(), new Animator(), new Frost(), new Collider(200, 200), new NetworkTransform(), new NetworkRenderer(), new NetworkAnimator())); } private void registerProjectilePrefabs() { PrefabManager.addPrefab("lanka_beam", () -> new GameObject("Lanka Beam", new Renderer("images/blue.png", 0, 0), new LankaBeam(500), new NetworkTransform(), new NetworkRenderer()), () -> new GameObject("Lanka Beam", new Renderer("images/blue.png", 0, 0), new NetworkTransform(), new NetworkRenderer())); } private void registerDoorPrefabs() { PrefabManager.addPrefab("door", () -> new GameObject("Door", new Door( new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")), new Renderer(), new Animator(), new Collider(100, 500, true), new NetworkAnimator()), () -> new GameObject("Door", new Door( new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")), new Renderer(), new Animator(), new NetworkAnimator())); PrefabManager.addPrefab("laser_door", () -> new GameObject("Laser Door", new LaserDoor( new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")), new Renderer(), new Animator(), new Collider(100, 500, true), new NetworkAnimator()), () -> new GameObject("Laser Door", new LaserDoor( new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")), new Renderer(), new Animator(), new NetworkAnimator())); } private void registerLockerPrefabs() { PrefabManager.addPrefab("locker_locked", () -> new GameObject("Locker", true, new Renderer(), new Locker(true, new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")))); PrefabManager.addPrefab("locker_unlocked", () -> new GameObject("Locker", true, new Renderer(), new Locker(false, new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")), new Collider(100, 200, true), new Animator(), new NetworkAnimator()), () -> new GameObject("Locker", true, new Renderer(), new Locker(false, new TextureAtlas("images/environment/atlas.png", "images/environment/atlas.txt")), new Animator(), new NetworkAnimator())); } }
package com.fishercoder.solutions; /** * 59. Spiral Matrix II * * Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] */ public class _59 { public static class Solution1 { public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; if (n == 0) { return matrix; } int value = 1; int top = 0; int bottom = n - 1; int left = 0; int right = n - 1; while (left <= right && top <= bottom) { for (int j = left; j <= right; j++) { matrix[top][j] = value++; } top++; for (int i = top; i <= bottom; i++) { matrix[i][right] = value++; } right for (int j = right; j >= left; j matrix[bottom][j] = value++; } bottom for (int i = bottom; i >= top; i matrix[i][left] = value++; } left++; } return matrix; } } }
package com.fishercoder.solutions; import java.util.Stack; public class _84 { public static class Solution1 { public int largestRectangleArea(int[] heights) { int len = heights.length; Stack<Integer> s = new Stack<>(); int maxArea = 0; for (int i = 0; i <= len; i++) { int h = (i == len ? 0 : heights[i]); if (s.isEmpty() || h >= heights[s.peek()]) { s.push(i); } else { int tp = s.pop(); maxArea = Math.max(maxArea, heights[tp] * (s.isEmpty() ? i : i - 1 - s.peek())); i } } return maxArea; } } }
package com.gpii.jsonld; import com.google.gson.Gson; import com.gpii.ontology.OntologyManager; import com.gpii.ontology.UPREFS; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.InfModel; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.reasoner.rulesys.GenericRuleReasoner; import com.hp.hpl.jena.reasoner.rulesys.Rule; import java.io.*; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; /** * * @author nkak * @author Claudia Loitsch */ public class JsonLDManager { //input public String currentNPSet; public String currentDeviceManagerPayload; //static input files //public String semanticsSolutionsFilePath; //public String explodePrefTermsFilePath; public String mappingRulesFilePath; //temp preprocessing output files public String preprocessingTempfilePath_defaultInput; public String postprocessingTempfilePath_Output; public Gson gson; private static JsonLDManager instance = null; private JsonLDManager() { File f = new File(System.getProperty("user.dir") + "/../webapps/CLOUD4All_RBMM_Restful_WS/WEB-INF/testData/rules/basicAlignment.rules"); if(f.exists()) //deployment mode { //static input files //semanticsSolutionsFilePath = System.getProperty("user.dir") + "/../webapps/CLOUD4All_RBMM_Restful_WS/WEB-INF/semantics/semanticsSolutions.jsonld"; //explodePrefTermsFilePath = System.getProperty("user.dir") + "/../webapps/CLOUD4All_RBMM_Restful_WS/WEB-INF/semantics/explodePreferenceTerms.jsonld"; /** * TODO find a new location, not in folder test data; split ontology alingment rules from matching rules */ mappingRulesFilePath = System.getProperty("user.dir") + "/../webapps/CLOUD4All_RBMM_Restful_WS/WEB-INF/testData/rules/basicAlignment.rules"; // temp preprocessing output files preprocessingTempfilePath_defaultInput = System.getProperty("user.dir") + "/../webapps/CLOUD4All_RBMM_Restful_WS/WEB-INF/TEMP/preprocessingDefaultInput.jsonld"; postprocessingTempfilePath_Output = System.getProperty("user.dir") + "/src/main/webapp/WEB-INF/TEMP/postprocessingOutput.json"; } else //Jetty integration tests { //static input files //semanticsSolutionsFilePath = System.getProperty("user.dir") + "/src/main/webapp/WEB-INF/semantics/semanticsSolutions.jsonld"; //explodePrefTermsFilePath = System.getProperty("user.dir") + "/src/main/webapp/WEB-INF/semantics/explodePreferenceTerms.jsonld"; mappingRulesFilePath = System.getProperty("user.dir") + "/src/main/webapp/WEB-INF/testData/rules/basicAlignment.rules"; //temp preprocessing output files preprocessingTempfilePath_defaultInput = System.getProperty("user.dir") + "/src/main/webapp/WEB-INF/TEMP/preprocessingDefaultInput.jsonld"; postprocessingTempfilePath_Output = System.getProperty("user.dir") + "/src/main/webapp/WEB-INF/TEMP/postprocessingOutput.json"; } currentNPSet = ""; currentDeviceManagerPayload = ""; gson = new Gson(); } public static JsonLDManager getInstance() { if(instance == null) instance = new JsonLDManager(); return instance; } public void runJSONLDTests() { // preprocessing(); // populate all default JSONLDInput to a model OntologyManager.getInstance().populateJSONLDInput(preprocessingTempfilePath_defaultInput); // infer configuration Model imodel = inferConfiguration(OntologyManager._dmodel, mappingRulesFilePath); // create MM output createMMoutput(imodel); } public Model inferConfiguration(Model model, String ruleFile) { File f = new File(ruleFile); if (f.exists()) { List<Rule> rules = Rule.rulesFromURL("file:" + mappingRulesFilePath); GenericRuleReasoner r = new GenericRuleReasoner(rules); InfModel infModel = ModelFactory.createInfModel(r, model); infModel.prepare(); Model deducedModel = infModel.getDeductionsModel(); model.add(deducedModel); } return model; } public void createMMoutput(Model model){ runQuery(" select DISTINCT (str(?c) as ?contextID) (str(?an) as ?appName) (str(?aa) as ?appActive) (str(?si) as ?setID) (str(?sv) as ?setValue) where{ ?if rdf:type c4a:InferredConfiguration. ?if c4a:id ?c. ?if c4a:refersTo ?app. ?app c4a:name ?an. ?app c4a:isActive ?aa. ?app c4a:settings ?set. ?set c4a:id ?si. ?set c4a:value ?sv. } ORDER BY DESC(?c)", model); //add the query string } private void runQuery(String queryRequest, Model model){ StringBuffer queryStr = new StringBuffer(); // Establish Prefixes //Set default Name space first queryStr.append("PREFIX rdfs" + ": <" + "http://www.w3.org/2000/01/rdf-schema queryStr.append("PREFIX rdf" + ": <" + "http://www.w3.org/1999/02/22-rdf-syntax-ns queryStr.append("PREFIX c4a" + ": <" + "http://rbmm.org/schemas/cloud4all/0.1/" + "> "); //Now add query queryStr.append(queryRequest); Query query = QueryFactory.create(queryStr.toString()); QueryExecution qexec = QueryExecutionFactory.create(query, model); try { ResultSet response = qexec.execSelect(); // JSON Object spec the MM output JSONObject mmOut = new JSONObject(); JSONObject infConfig = new JSONObject(); JSONObject contextSet; JSONObject appSet; JSONObject solution; JSONObject settings; mmOut.put("inferredConfiguration", infConfig); while(response.hasNext()){ QuerySolution soln = response.nextSolution(); System.out.println("out: "+ soln.toString()); RDFNode contextID = soln.get("?contextID"); RDFNode appName = soln.get("?appName"); RDFNode appActive = soln.get("?appActive"); RDFNode setId = soln.get("?setID"); RDFNode setValue = soln.get("?setValue"); infConfig = mmOut.getJSONObject("inferredConfiguration"); if(infConfig.has(contextID.toString())){ contextSet = infConfig.getJSONObject(contextID.toString()); }else { appSet = new JSONObject(); infConfig.put(contextID.toString(), appSet); contextSet = infConfig.getJSONObject(contextID.toString()); } if(contextSet.has("applications")){ appSet = contextSet.getJSONObject("applications"); }else { appSet = new JSONObject(); contextSet.put("applications", appSet); appSet = contextSet.getJSONObject("applications"); } if(appSet.has(appName.toString())){ solution = appSet.getJSONObject(appName.toString()); }else{ solution = new JSONObject(); appSet.put(appName.toString(), solution); solution = appSet.getJSONObject(appName.toString()); } if(!solution.has("active")){ solution.put("active", appActive.toString()); } if(solution.has("settings")){ settings = solution.getJSONObject("settings"); settings.put(setId.toString(), setValue.toString()); }else { settings = new JSONObject(); settings.put(setId.toString(), setValue.toString()); solution.put("settings", settings); } } byte dataToWrite[] = mmOut.toString().getBytes(StandardCharsets.US_ASCII); writeFile(postprocessingTempfilePath_Output, dataToWrite); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { qexec.close();} } private void preprocessing() {} /** * TODO create a class for help functions * @param path where to write the file * @param dataToWrite // data to write in the file */ private void writeFile(String path, byte[] dataToWrite){ FileOutputStream out = null; try { out = new FileOutputStream(path); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { out.write(dataToWrite); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.qiniu.qbox.auth; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.json.JSONException; import org.json.JSONStringer; import com.qiniu.qbox.Config; public final class GetPolicy { public long expiry; public String scope; public GetPolicy(long expiry, String scope) throws Exception { if (expiry <= 0) { expiry = 3600; // set to default value, an hour } if (scope == null || scope.trim().length() == 0) { scope = "*/*"; // set to default. } this.expiry = System.currentTimeMillis() / 1000 + expiry; this.scope = scope; } private String generateSignature() throws JSONException { String jsonScope = new JSONStringer().object().key("S") .value(this.scope).key("E").value(this.expiry).endObject() .toString(); return Client.urlsafeEncode(jsonScope); } private byte[] makeHmac(String signature) throws Exception { Mac mac = Mac.getInstance("HmacSHA1"); byte[] secretKey = Config.SECRET_KEY.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "HmacSHA1"); mac.init(secretKeySpec); mac.update(signature.getBytes()); return mac.doFinal(); } public String token() throws Exception { String signature = generateSignature(); String checksum = Client.urlsafeEncodeString(makeHmac(signature)); return Config.ACCESS_KEY + ":" + checksum + ":" + signature; } }
// samskivert library - useful routines for java programs package com.samskivert.util; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import static com.samskivert.Log.log; /** * Runnable related utility methods. */ public class Runnables { /** A runnable that does nothing. Useful for use as the default value for optional callbacks. */ public static Runnable NOOP = new Runnable() { public void run () { // noop! } }; public static Runnable asRunnable (Object instance, String methodName) { Class<?> clazz = instance.getClass(); Method method = findMethod(clazz, methodName); if (Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException( clazz.getName() + "." + methodName + "() must not be static"); } return new MethodRunner(method, instance); } public static Runnable asRunnable (Class<?> clazz, String methodName) { Method method = findMethod(clazz, methodName); if (!Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException( clazz.getName() + "." + methodName + "() must be static"); } return new MethodRunner(method, null); } protected static Method findMethod (Class<?> clazz, String methodName) { for (Method method : clazz.getDeclaredMethods()) { if (method.getName().equals(methodName) && method.getParameterTypes().length == 0) { method.setAccessible(true); // isAccessible() check is too slow return method; } } throw new IllegalArgumentException(clazz.getName() + "." + methodName + "() not found"); } protected static class MethodRunner implements Runnable { public MethodRunner (Method method, Object instance) { _method = method; _instance = instance; } public void run () { try { _method.invoke(_instance); } catch (IllegalAccessException iae) { log.warning("Failed to invoke " + _method.getName() + ": " + iae); } catch (InvocationTargetException ite) { log.warning("Invocation of " + _method.getName() + " failed", ite); } } protected Method _method; protected Object _instance; } protected Runnables () { // no constructy } }
package com.systemjx.ems; import static com.systemjx.ems.SharedResource.logException; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import com.systemj.ipc.GenericSignalSender; public class OutputSignal extends GenericSignalSender { private static final int PACKET_SIZE = 5; private String ip; private int port; private int actuatorId; private int groupId; private int nodeId; private boolean fsent = true; private int preVal = Integer.MAX_VALUE; private static Map<Thread, Map<String, Socket>> socketMap = new HashMap<>(); private String urn; @SuppressWarnings({ "rawtypes" }) @Override public void configure(Hashtable t) throws RuntimeException { this.ip = (String) t.get("IP"); this.port = Integer.parseInt((String) t.get("Port")); this.actuatorId = Integer.parseInt((String) t.get("Actuator"), 16); this.groupId = Integer.parseInt((String) t.get("Group"), 16); this.nodeId = Integer.parseInt((String) t.get("Node"), 16); this.urn = ip + ":" + port; socketMap.putIfAbsent(Thread.currentThread(), new HashMap<>()); } public Map<String, Socket> getSockets(){ return socketMap.get(Thread.currentThread()); } protected byte[] buildPacket(byte v) { ByteBuffer b = ByteBuffer.allocate(PACKET_SIZE + 3); b.putShort((short)0xAABB); b.put((byte)PACKET_SIZE); b.putShort((short)(groupId << 8 | nodeId)); b.put((byte)0xA0); // Packet type -- fixed b.put((byte)actuatorId); b.put(v); b.position(0); byte[] bb = new byte[PACKET_SIZE + 3]; b.get(bb); return bb; } @Override public boolean setup(Object[] b) { Socket s = getSockets().get(urn); if (s == null || !s.isConnected() || s.isClosed()) { s = new Socket(); try { s.connect(new InetSocketAddress(ip, port), 50); s.setSoTimeout(50); getSockets().put(urn, s); } catch (SocketTimeoutException e) { return false; } catch (IOException e){ logException(e); return false; } } super.buffer = b; return true; } private void sendPacket(byte[] b) { Socket s = getSockets().get(urn); try { DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.write(b); } catch (IOException e) { try { s.close(); getSockets().remove(urn); } catch (IOException e1) { logException(e1); } } } @Override public void run() { int val; try { val = (int) super.buffer[1]; } catch (NullPointerException e) { val = 1; } if(fsent || val != preVal) { byte[] b = buildPacket((byte) val); sendPacket(b); fsent = false; preVal = val; } } @Override public void arun() { if (!fsent) { if(setup(super.buffer)){ byte[] b = buildPacket((byte) 0); sendPacket(b); fsent = true; } } } @Override public void cleanUp() { synchronized (Thread.currentThread()) { socketMap.get(Thread.currentThread()).forEach((k, v) -> { try { v.close(); } catch (IOException e) { logException(e); } }); } } }
package common.base.utils; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Picture; import android.os.Build; import android.util.DisplayMetrics; import android.view.Display; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.WindowManager; import android.webkit.WebView; import android.widget.ScrollView; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; public class ScreenUtils { private static Context sContext; private static int windowWidth; private static int windowHeight; private static float density; private static int statusBarHeight = 10; private static DisplayMetrics displayMetrics; private static int navigationBarHeight = 10; public static void init(Context context) { sContext = context.getApplicationContext(); if (sContext == null) { sContext = context; } if (sContext == null) { return; } WindowManager windowManager = (WindowManager) sContext.getSystemService(Context.WINDOW_SERVICE); if (windowManager == null) { return; } displayMetrics = new DisplayMetrics(); Display defDisplay = windowManager.getDefaultDisplay(); if (defDisplay == null) { return; } if (Build.VERSION.SDK_INT >= 17) {//android4.0 defDisplay.getRealMetrics(displayMetrics); } else { boolean useDefResolve = true; Class c; try { c = Class.forName("android.view.Display"); Method method = c.getMethod("getRealMetrics", DisplayMetrics.class); method.invoke(defDisplay, displayMetrics); useDefResolve = false; } catch (Exception e) { e.printStackTrace(); } if (useDefResolve) { defDisplay.getMetrics(displayMetrics); } } //note here :, //note here : Activity() //getScreenCurWidth(boolean needLandscapeScreenWidth) windowWidth = displayMetrics.widthPixels; windowHeight = displayMetrics.heightPixels; density = displayMetrics.density; int displayWidth = defDisplay.getWidth(); int displayHeight = defDisplay.getHeight(); int swdp = context.getResources().getConfiguration().smallestScreenWidthDp; CommonLog.sysErr("ScreenUtils: " + displayMetrics + " display width :" + displayWidth + " display height :" + displayHeight + " swdp = " + swdp ); boolean isLandscape = windowWidth > windowHeight; if (isLandscape) { navigationBarHeight = windowWidth - displayWidth; } else { navigationBarHeight = windowHeight - displayHeight; } } // public static int getScreenWidth() { // return windowWidth; // public static int getScreenHeight() { // return windowHeight; public static int getScreenCurWidth(boolean needLandscapeScreenWidth) { if (needLandscapeScreenWidth) { return Math.max(windowWidth, windowHeight); } return Math.min(windowWidth, windowHeight); } public static int getScreenCurHeight(boolean needLandscapeScreenHeight) { if (needLandscapeScreenHeight) { return Math.min(windowHeight, windowWidth); } return Math.max(windowHeight, windowWidth); } public static int getStatusBarHeight() { if (statusBarHeight == 10 && sContext != null) { int result = 0; Resources res = sContext.getResources(); int resourceId = res.getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = res.getDimensionPixelSize(resourceId); } if (result > 0) { statusBarHeight = result; } } return statusBarHeight; } /** * () * ????? * @return */ public static int getNavigationBarHeight(){ // if (navigationBarHeight == 10 && sContext != null) { // int result = 0; // Resources res = sContext.getResources(); // int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android"); // if (resourceId > 0) { // result = res.getDimensionPixelSize(resourceId); // if (result > 0) { // navigationBarHeight = result; return navigationBarHeight; } /** * * @param activity * @return */ @SuppressLint("NewApi") public static boolean checkDeviceHasNavigationBar(Context activity) { //(,)navigation bar boolean hasMenuKey = ViewConfiguration.get(activity) .hasPermanentMenuKey(); boolean hasBackKey = KeyCharacterMap .deviceHasKey(KeyEvent.KEYCODE_BACK); if (!hasMenuKey && !hasBackKey) { return true; } return false; } public static int dp2px(float dpValue) { // final float scale = sContext.getResources().getDisplayMetrics().density; return (int) (dpValue * density + 0.5f); } public static int px2dp(float pxValue) { // final float scale = sContext.getResources().getDisplayMetrics().density; return (int) (pxValue / density + 0.5f); } public static int sp2px(float spValue) { if (sContext == null) { return (int) spValue; } float fontScale = sContext.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } //webviewwebviewapi private static Bitmap captureWebView(WebView webView) { Picture snapShot = webView.capturePicture(); if (snapShot == null) { return null; } Bitmap bmp = Bitmap.createBitmap(snapShot.getWidth(), snapShot.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); snapShot.draw(canvas); return bmp; } /** * scrollview * **/ public static Bitmap getScrollViewBitmap(ScrollView scrollView) { int h = 0; Bitmap bitmap; for (int i = 0; i < scrollView.getChildCount(); i++) { h += scrollView.getChildAt(i).getHeight(); } // bitmap bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(bitmap); scrollView.draw(canvas); return bitmap; } public static Bitmap captureViewSnapShot(View theView,String savedPath) { if (theView != null) { theView.setDrawingCacheEnabled(true); // theView.buildDrawingCache(true); theView.buildDrawingCache(); Bitmap bitmap = null; bitmap = Bitmap.createBitmap(theView.getDrawingCache(false)); FileOutputStream fos = null; if (bitmap != null && savedPath != null) { try { File snapShotFile = new File(savedPath); fos = new FileOutputStream(snapShotFile); bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } bitmap.recycle(); return null; } return bitmap; } return null; } public static Bitmap captureView(View notRootView) { View theView = notRootView; if (theView != null) { theView.setDrawingCacheEnabled(true); theView.buildDrawingCache(); Bitmap bitmap = Bitmap.createBitmap(theView.getDrawingCache()); return bitmap; } return null; } /** * Google I/O App for Android * @param context * @return True False */ public static boolean isPadDevice(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } public static String screenOrientationDesc(int curScreenOr) { String oriDesc = curScreenOr + ""; switch (curScreenOr) { case ActivityInfo.SCREEN_ORIENTATION_BEHIND: oriDesc = "BEHIND"; break; case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT: oriDesc = ""; break; case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE: oriDesc = ""; break; case ActivityInfo.SCREEN_ORIENTATION_USER: oriDesc = ""; break; case ActivityInfo.SCREEN_ORIENTATION_SENSOR: oriDesc = ""; break; case ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED: oriDesc = ""; break; } return oriDesc; } public static String getDevInfos() { return " windowWidth:" + windowWidth + " windowHeight:" + windowHeight + " density:" + density; } public static String getDisplayMetricsDesc() { DisplayMetrics curDisplayMetrics = null; Resources res = null; int swdp = 0; if (sContext != null) { res = sContext.getResources(); } if (res != null) { curDisplayMetrics = res.getDisplayMetrics(); swdp = res.getConfiguration().smallestScreenWidthDp; } StringBuilder sb = new StringBuilder(); sb.append(":").append(curDisplayMetrics) .append(" --> :").append(displayMetrics) .append(" dpi:").append(swdp) ; return sb.toString(); } public static int[] getCurScreenWidthHeight(Context context) { int resultWidth = 0; int resultHeight = 0; WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (windowManager != null) { Display display = windowManager.getDefaultDisplay(); if (display != null) { int w = display.getWidth(); int h = display.getHeight(); CommonLog.sysErr("ScreenUtils: w = " + w + " h = " + h); boolean isLandscape = w > h; resultWidth = getScreenCurWidth(isLandscape); resultHeight = getScreenCurHeight(isLandscape); } } return new int[]{resultWidth,resultHeight}; } }
package de.ailis.xadrian.data; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import de.ailis.xadrian.asciitable.Table; import de.ailis.xadrian.asciitable.TableCell; import de.ailis.xadrian.asciitable.TableCell.Align; import de.ailis.xadrian.data.factories.FactoryFactory; import de.ailis.xadrian.data.factories.GameFactory; import de.ailis.xadrian.data.factories.RaceFactory; import de.ailis.xadrian.data.factories.SectorFactory; import de.ailis.xadrian.data.factories.SunFactory; import de.ailis.xadrian.data.factories.WareFactory; import de.ailis.xadrian.dialogs.SetYieldsDialog; import de.ailis.xadrian.exceptions.TemplateCodeException; import de.ailis.xadrian.interfaces.GameProvider; import de.ailis.xadrian.support.Config; import de.ailis.xadrian.support.DynaByteInputStream; import de.ailis.xadrian.support.DynaByteOutputStream; import de.ailis.xadrian.support.I18N; import de.ailis.xadrian.support.ModalDialog.Result; import de.ailis.xadrian.support.MultiCollection; /** * A complex * * @author Klaus Reimer (k@ailis.de) */ public class Complex implements Serializable, GameProvider { /** Serial version UID */ private static final long serialVersionUID = 2128684141345704703L; /** The logger */ private static final Log log = LogFactory.getLog(Complex.class); /** The single price of a complex construction kit */ public static final int KIT_PRICE = 259696; /** The volume of a complex construction kit */ public static final int KIT_VOLUME = 4250; /** The complex counter for the complex name generator */ private static int complexCounter = 0; /** The game this complex belongs to. */ private final Game game; /** The complex name */ private String name; /** The factories in this complex */ private final List<ComplexFactory> factories; /** Automatically added factories in this complex */ private final List<ComplexFactory> autoFactories; /** The sun power in percent */ private Sun suns; /** The sector where this complex is build */ private Sector sector = null; /** If base complex should be calculated or not */ private boolean addBaseComplex = false; /** Custom buy/sell prices in this complex */ private final Map<Ware, Integer> customPrices; /** If complex setup should be displayed */ private boolean showingComplexSetup = true; /** If production statistics should be displayed */ private boolean showingProductionStats = false; /** If storage capacities should be displayed */ private boolean showingStorageCapacities = false; /** If shopping list should be displayed */ private boolean showingShoppingList = false; /** The built factories */ private final Map<String, Integer> builtFactories; /** The number of built kits */ private int builtKits; /** The cached shopping list */ private ShoppingList shoppingList; /** * Constructor * * @param game * The game this complex belongs to. */ public Complex(final Game game) { this(game, createComplexName()); } /** * Constructor * * @param game * The game this complex belongs to. * @param name * The complex name */ public Complex(final Game game, final String name) { this.game = game; this.suns = game.getSunFactory().getDefaultSun(); this.name = name; this.factories = new ArrayList<ComplexFactory>(); this.autoFactories = new ArrayList<ComplexFactory>(); this.customPrices = new HashMap<Ware, Integer>(); this.builtFactories = new HashMap<String, Integer>(); } /** * Returns a new name for a complex. * * @return A new complex name */ private static String createComplexName() { complexCounter++; return I18N.getString("complex.nameTemplate", complexCounter); } /** * Returns the name. * * @return The name */ public String getName() { return this.name; } /** * Sets the complex name. * * @param name * The complex name to set */ public void setName(final String name) { this.name = name; } /** * Returns the total number of factories in the complex * * @return The total number of factories in the complex */ public int getTotalQuantity() { int quantity = 0; for (final ComplexFactory factory: this.factories) quantity += factory.getQuantity(); for (final ComplexFactory factory: this.autoFactories) quantity += factory.getQuantity(); return quantity; } /** * Returns the total complex price. * * @return The total complex price */ public long getTotalPrice() { long price = 0; for (final ComplexFactory complexFactory: this.factories) price += ((long) complexFactory.getQuantity()) * complexFactory.getFactory().getPrice(); for (final ComplexFactory complexFactory: this.autoFactories) price += ((long) complexFactory.getQuantity()) * complexFactory.getFactory().getPrice(); return price + getTotalKitPrice(); } /** * A immutable copy of the factories in this complex. * * @return The factories in this complex */ public List<ComplexFactory> getFactories() { return Collections.unmodifiableList(this.factories); } /** * A immutable copy of the automatically added factories in this complex. * * @return The automatically added factories in this complex */ public List<ComplexFactory> getAutoFactories() { return Collections.unmodifiableList(this.autoFactories); } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return new HashCodeBuilder().append(this.name).append(this.factories) .append(this.autoFactories).hashCode(); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj.getClass() != getClass()) return false; final Complex other = (Complex) obj; return new EqualsBuilder().append(this.name, other.name).append( this.factories, other.factories).append(this.suns, other.suns) .append(this.sector, other.sector).isEquals(); } /** * Removes the factory with the given index. * * @param index * The factory index */ public void removeFactory(final int index) { this.factories.remove(index); calculateBaseComplex(); updateShoppingList(); } /** * Disables the factory with the given index. * * @param index * The factory index */ public void disableFactory(final int index) { this.factories.get(index).disable(); calculateBaseComplex(); } /** * Disables the factory with the given index. * * @param index * The factory index */ public void enableFactory(final int index) { this.factories.get(index).enable(); calculateBaseComplex(); } /** * Accepts the automatically added factory with the given index. * * @param index * The factory index */ public void acceptFactory(final int index) { addFactory(this.autoFactories.get(index)); calculateBaseComplex(); } /** * Returns the quantity of the factory with the given index. * * @param index * The factory index * @return The quantity */ public int getQuantity(final int index) { return this.factories.get(index).getQuantity(); } /** * Increases the quantity of the factory with the given index. * * @param index * The factory index * @return True if quantity was changed, false if not. */ public boolean increaseQuantity(final int index) { if (this.factories.get(index).increaseQuantity()) { calculateBaseComplex(); updateShoppingList(); return true; } return false; } /** * Decreases the quantity of the factory with the given index. * * @param index * The factory index * @return True if quantity was changed, false if not. */ public boolean decreaseQuantity(final int index) { if (this.factories.get(index).decreaseQuantity()) { calculateBaseComplex(); updateShoppingList(); return true; } return false; } /** * Sets the quantity of the factory with the given index to the specified * quantity. * * @param index * The factory index * @param quantity * The quantity to set */ public void setQuantity(final int index, final int quantity) { final ComplexFactory factory = this.factories.get(index); if (factory.getQuantity() != quantity) { factory.setQuantity(quantity); calculateBaseComplex(); updateShoppingList(); } } /** * Returns the yield of the factory with the given index. * * @param index * The factory index * @return The yield */ public List<Integer> getYields(final int index) { return this.factories.get(index).getYields(); } /** * Sets the yields of the factory with the given index. * * @param index * The factory index * @param yields * The yields to set */ public void setYields(final int index, final List<Integer> yields) { final ComplexFactory factory = this.factories.get(index); factory.setYields(yields); calculateBaseComplex(); updateShoppingList(); } /** * Returns the factory type of factory with the given index. * * @param index * The factory index * @return The factory */ public Factory getFactory(final int index) { return this.factories.get(index).getFactory(); } /** * Sets the suns in percent. * * @param suns * The suns in percent to set */ public void setSuns(final Sun suns) { this.suns = suns; calculateBaseComplex(); } /** * Returns the suns in percent. * * @return The suns in percent */ public Sun getSuns() { if (this.sector != null) return this.sector.getSuns(); return this.suns; } /** * Adds a factory to the complex. * * @param factory * The factory to add */ public void addFactory(final Factory factory) { if (factory.isMine()) { final SetYieldsDialog dialog = new SetYieldsDialog(factory); dialog.setYields(null); dialog.setSector(getSector()); if (dialog.open() == Result.OK) { setSector(dialog.getSector()); addFactory(new ComplexFactory(this.game, factory, dialog.getYields())); calculateBaseComplex(); updateShoppingList(); } } else { addFactory(new ComplexFactory(this.game, factory, 1, 0)); calculateBaseComplex(); updateShoppingList(); } } /** * Adds the specified factory/factories to the complex. * * @param complexFactory * The factory/factories to add */ private void addFactory(final ComplexFactory complexFactory) { if (!complexFactory.getFactory().isMine()) { for (final ComplexFactory current: this.factories) { if (current.getFactory().equals(complexFactory.getFactory()) && current.getYield() == complexFactory.getYield()) { current.addQuantity(complexFactory.getQuantity()); return; } } } this.factories.add(complexFactory); Collections.sort(this.factories); updateShoppingList(); } /** * Converts the complex into XML and returns it. * * @return The complex as XML */ public Document toXML() { final Document document = DocumentHelper.createDocument(); final Element root = document.addElement("complex"); root.addAttribute("version", "4"); root.addAttribute("game", this.game.getId()); root.addAttribute("suns", Integer.toString(getSuns().getPercent())); if (this.sector != null) root.addAttribute("sector", this.sector.getId()); root.addAttribute("addBaseComplex", Boolean .toString(this.addBaseComplex)); root.addAttribute("showingProductionStats", Boolean .toString(this.showingProductionStats)); root.addAttribute("showingShoppingList", Boolean .toString(this.showingShoppingList)); root.addAttribute("showingStorageCapacities", Boolean .toString(this.showingStorageCapacities)); root.addAttribute("showingComplexSetup", Boolean .toString(this.showingComplexSetup)); if (!this.factories.isEmpty()) { final Element factoriesE = root.addElement("complexFactories"); for (final ComplexFactory factory: this.factories) { final Element factoryE = factoriesE .addElement("complexFactory"); factoryE.addAttribute("factory", factory.getFactory().getId()); factoryE.addAttribute("disabled", Boolean.toString(factory .isDisabled())); if (factory.getFactory().isMine()) { final Element yieldsE = factoryE.addElement("yields"); for (final Integer yield: factory.getYields()) { final Element yieldE = yieldsE.addElement("yield"); yieldE.setText(Integer.toString(yield)); } } else { factoryE.addAttribute("quantity", Integer.toString(factory .getQuantity())); } } } if (!this.customPrices.isEmpty()) { final Element waresE = root.addElement("complexWares"); for (final Map.Entry<Ware, Integer> entry: this.customPrices .entrySet()) { final Ware ware = entry.getKey(); final int price = entry.getValue(); final Element wareE = waresE.addElement("complexWare"); wareE.addAttribute("ware", ware.getId()); wareE .addAttribute("use", Boolean.valueOf(price > 0) .toString()); wareE.addAttribute("price", Integer.toString(Math.abs(price))); } } final Element shoppingListE = root.addElement("built"); shoppingListE.addAttribute("kits", Integer.toString(this.builtKits)); for (final Entry<String, Integer> entry: this.builtFactories .entrySet()) { final String id = entry.getKey(); final int quantity = entry.getValue(); final Element factoryE = shoppingListE.addElement("factory"); factoryE.addAttribute("id", id); factoryE.addAttribute("quantity", Integer.toString(quantity)); } return document; } /** * Loads a complex from the specified XML document and returns it. * * @param document * The XML document * @return The complex * @throws DocumentException * If XML file could not be read */ public static Complex fromXML(final Document document) throws DocumentException { final Element root = document.getRootElement(); // Check the version final String versionStr = root.attributeValue("version"); int version = 1; if (versionStr != null) version = Integer.parseInt(versionStr); if (version > 4) throw new DocumentException( I18N.getString("error.fileFormatTooNew")); // Determine the game for this complex. String gameId = "x3tc"; if (version == 4) gameId = root.attributeValue("game"); final Game game = GameFactory.getInstance().getGame(gameId); final Complex complex = new Complex(game); final FactoryFactory factoryFactory = game.getFactoryFactory(); final SectorFactory sectorFactory = game.getSectorFactory(); final WareFactory wareFactory = game.getWareFactory(); final SunFactory sunsFactory = game.getSunFactory(); complex.setSuns(sunsFactory.getSun(Integer.parseInt(root .attributeValue("suns")))); complex.setSector(sectorFactory .getSector(root.attributeValue("sector"))); complex.setAddBaseComplex(Boolean.parseBoolean(root.attributeValue( "addBaseComplex", "false"))); complex.showingProductionStats = Boolean.parseBoolean(root .attributeValue("showingProductionStats", "false")); complex.showingShoppingList = Boolean.parseBoolean(root.attributeValue( "showingShoppingList", "false")); complex.showingStorageCapacities = Boolean.parseBoolean(root .attributeValue("showingStorageCapacities", "false")); complex.showingComplexSetup = Boolean.parseBoolean(root.attributeValue( "showingComplexSetup", "true")); // Get the factories parent element (In older version this was the root // node) Element factoriesE = root.element("complexFactories"); if (factoriesE == null) factoriesE = root; // Read the complex factories for (final Object item: factoriesE.elements("complexFactory")) { final Element element = (Element) item; final Factory factory = factoryFactory.getFactory(element .attributeValue("factory")); final ComplexFactory complexFactory; final Element yieldsE = element.element("yields"); if (yieldsE == null) { final int yield = Integer.parseInt(element.attributeValue("yield", "0")); final int quantity = Integer.parseInt(element .attributeValue("quantity")); complexFactory = new ComplexFactory(game, factory, quantity, yield); } else { final List<Integer> yields = new ArrayList<Integer>(); for (final Object yieldItem: yieldsE.elements("yield")) { final Element yieldE = (Element) yieldItem; yields.add(Integer.parseInt(yieldE.getText())); } complexFactory = new ComplexFactory(game, factory, yields); } if (Boolean.parseBoolean(element .attributeValue("disabled", "false"))) complexFactory.disable(); complex.addFactory(complexFactory); } // Read the complex wares final Element waresE = root.element("complexWares"); if (waresE != null) { complex.customPrices.clear(); for (final Object item: waresE.elements("complexWare")) { final Element element = (Element) item; final Ware ware = wareFactory.getWare(element .attributeValue("ware")); final boolean use = Boolean.parseBoolean(element .attributeValue("use")); final int price = Integer.parseInt(element .attributeValue("price")); complex.customPrices.put(ware, use ? price : -price); } } final Element builtE = root.element("built"); if (builtE != null) { complex.builtKits = Integer.parseInt(builtE.attributeValue("kits", "0")); for (final Object item: builtE.elements("factory")) { final Element element = (Element) item; final String id = element.attributeValue("id"); final int quantity = Integer.parseInt(element .attributeValue("quantity")); complex.builtFactories.put(id, quantity); } } complex.calculateBaseComplex(); return complex; } /** * Returns all factories (Manually and automatically added ones): * * @return All factories */ @SuppressWarnings("unchecked") private Collection<ComplexFactory> getAllFactories() { return new MultiCollection<ComplexFactory>(this.factories, this.autoFactories); } /** * Returns the number of disabled factories. * * @return The number of disabled factories. */ private int getDisabledFactrories() { int disabled = 0; for (final ComplexFactory factory: this.factories) if (factory.isDisabled()) disabled += 1; return disabled; } /** * Returns the products this complex produces in one hour. * * @return The products per hour. */ public Collection<Product> getProductsPerHour() { final Map<String, Product> products = new HashMap<String, Product>(); for (final ComplexFactory factory: getAllFactories()) { final Product product = factory.getProductPerHour(getSuns()); final Ware ware = product.getWare(); final Product mapProduct = products.get(ware.getId()); if (mapProduct == null) products.put(ware.getId(), product); else products.put(ware.getId(), new Product(ware, mapProduct .getQuantity() + product.getQuantity())); } return products.values(); } /** * Returns the resources this complex needs in one hour. * * @return The needed resources per hour. */ public Collection<Product> getResourcesPerHour() { final Map<String, Product> resources = new HashMap<String, Product>(); for (final ComplexFactory factory: getAllFactories()) { for (final Product resource: factory .getResourcesPerHour(getSuns())) { final Ware ware = resource.getWare(); final Product mapResource = resources.get(ware.getId()); if (mapResource == null) resources.put(ware.getId(), resource); else resources.put(ware.getId(), new Product(ware, mapResource .getQuantity() + resource.getQuantity())); } } return resources.values(); } /** * Returns the list of complex wares (Produced and needed). * * @return The list of complex wares */ public Collection<ComplexWare> getWares() { final Map<String, ComplexWare> wares = new HashMap<String, ComplexWare>(); // Add the products for (final Product product: getProductsPerHour()) { final Ware ware = product.getWare(); final String wareId = ware.getId(); wares.put(wareId, new ComplexWare(ware, product.getQuantity(), 0, getWarePrice(ware))); } // Add the resources for (final Product resource: getResourcesPerHour()) { final Ware ware = resource.getWare(); final String wareId = ware.getId(); ComplexWare complexWare = wares.get(wareId); if (complexWare == null) complexWare = new ComplexWare(ware, 0, resource.getQuantity(), getWarePrice(ware)); else complexWare = new ComplexWare(ware, complexWare.getProduced(), resource.getQuantity(), getWarePrice(ware)); wares.put(wareId, complexWare); } final List<ComplexWare> result = new ArrayList<ComplexWare>(wares .values()); Collections.sort(result); return result; } /** * Returns the profit of this complex. * * @return The profit */ public double getProfit() { double profit; profit = 0; for (final ComplexWare complexWare: getWares()) { profit += complexWare.getProfit(); } return profit; } /** * Returns the number of needed complex construction kits in this complex. * * @return The number of needed complex construction kits. */ public int getKitQuantity() { return Math.max(0, getTotalQuantity() - 1); } /** * Returns the price of a single complex construction kit. * * @return The price of a single complex construction kit */ public int getKitPrice() { return KIT_PRICE; } /** * Returns the total price of all needed complex construction kits. * * @return The total price of all needed complex construction kits */ public int getTotalKitPrice() { return getKitQuantity() * getKitPrice(); } /** * Calculates and adds the factories needed to keep the factories of this * complex running stable. */ private void calculateBaseComplex() { final FactoryFactory factoryFactory = this.game.getFactoryFactory(); final RaceFactory raceFactory = this.game.getRaceFactory(); final Ware crystals = this.game.getWareFactory().getWare("crystals"); final Config config = Config.getInstance(); long currentPrice; long price; final List<ComplexFactory> backup = new ArrayList<ComplexFactory>(); // First of all remove all automatically added factories this.autoFactories.clear(); updateShoppingList(); if (!this.addBaseComplex) return; // First of all we build a base complex without specific crystal fab // race and remember the price while (true) if (!addBaseComplex(null)) break; currentPrice = getTotalPrice(); // Now cycle over all races and check if the complex gets cheaper if // the crystal fabs are bought from them for (final Race race: raceFactory.getRaces()) { // If race is ignored then don't use it if (config.isRaceIgnored(race)) continue; // If race has no crystal fabs then don't use it if (!factoryFactory.hasFactories(race, crystals)) continue; // Backup current automatically added factories, clear the // calculated factories and then calculate the complex again with // a specific "crystal race" backup.addAll(this.autoFactories); this.autoFactories.clear(); while (true) if (!addBaseComplex(race)) break; // Check if new price is cheaper then the old one. If cheaper // then the new complex is used (and checked against the next // available race). If not cheaper then the old complex is restored price = getTotalPrice(); if (price < currentPrice) { currentPrice = price; } else { this.autoFactories.clear(); this.autoFactories.addAll(backup); } backup.clear(); } updateShoppingList(); } /** * Updates the base complex. */ public void updateBaseComplex() { calculateBaseComplex(); } /** * Updates the shopping list. */ public void updateShoppingList() { this.shoppingList = null; this.builtKits = Math.max(0, Math.min(this.builtKits, getTotalQuantity() - 1)); for (final Map.Entry<String, Integer> entry: this.builtFactories .entrySet()) { final String id = entry.getKey(); final int max = getMaxFactories(id); final int quantity = Math.min(entry.getValue(), max); this.builtFactories.put(id, quantity); } this.shoppingList = null; } /** * Searches for the first unfulfilled resource need (which is not a mineral) * and adds the necessary factories for this. If a need was found (and * fixed) then this method returns true. If all needs are already fulfilled * then it returns false. * * @param crystalRace * Optional race from which crystal fabs should be bought. If * null then the cheapest fab is searched. * @return True if a need was found and fixed, false if everything is * finished */ private boolean addBaseComplex(final Race crystalRace) { for (final ComplexWare ware: getWares()) { // We are not going to add mines if (ware.getWare().getId().equals("siliconWafers")) continue; if (ware.getWare().getId().equals("ore")) continue; // If the current ware has missing units then add the necessary // factories for this ware and then restart the adding of factories if (ware.getMissing() > 0) { final Race race = ware.getWare().getId().equals("crystals") ? crystalRace : null; if (!addBaseComplexForWare(ware, race)) continue; return true; } } return false; } /** * Adds the factories needed to fulfill the need of the specified complex * ware. * * @param complexWare * The complex ware for which factories must be added * @param race * The race from which factories should be bought. If null then * the cheapest factory is used. * @return True if a new factories were added, false if this was not * possible */ private boolean addBaseComplexForWare(final ComplexWare complexWare, final Race race) { final Ware ware = complexWare.getWare(); final FactoryFactory factoryFactory = this.game.getFactoryFactory(); // Remove all automatically added factories which produces the // specified ware and calculate the real need which must be // fulfilled. double need = complexWare.getMissing(); final double oldNeed = need; for (final ComplexFactory complexFactory: new ArrayList<ComplexFactory>( this.autoFactories)) { if (complexFactory.getFactory().getProduct().getWare().equals(ware)) { need += complexFactory.getProductPerHour(getSuns()) .getQuantity(); this.autoFactories.remove(complexFactory); } } // Determine the available factory sizes final SortedSet<FactorySize> sizesSet = factoryFactory.getFactorySizes(ware, race); final FactorySize[] sizes = sizesSet.toArray(new FactorySize[sizesSet.size()]); // Abort if no factories were found if (sizes.length == 0) return false; // Get the cheapest factories for the sizes final Map<FactorySize, Factory> factories = new HashMap<FactorySize, Factory>(); for (final FactorySize size: sizes) { if (race == null) factories.put(size, factoryFactory.getCheapestFactory(ware, size)); else factories .put(size, factoryFactory.getFactory(ware, size, race)); } // Get the smallest possible production quantity final double minProduction = factories.get(sizes[0]).getProductPerHour( getSuns(), 0).getQuantity(); // Iterate the available sizes (from largest to smallest) and add // the factories producing an adequate number of products for (int i = sizes.length - 1; i >= 0; i { final FactorySize size = sizes[i]; final Factory factory = factories.get(size); final double product = factory.getProductPerHour(getSuns(), 0) .getQuantity(); // Calculate the number of factories of the current size needed log.debug("Need " + need + " units of " + ware + ". Considering " + factory + " which produces " + product + " units"); final int quantity = (int) Math.floor((need + minProduction - 0.1) / product); // Add the number of factories and decrease the need if (quantity > 0) { log.debug("Adding " + quantity + "x " + factory); this.autoFactories .add(new ComplexFactory(this.game, factory, quantity, 0)); need -= quantity * product; } else log.debug("Not adding any " + factory); } if (Math.abs(need - oldNeed) < .0000001) { log.debug("Unable to calculate best matching factory. Aborting"); return false; } return true; } /** * Toggles the addition of automatically calculated base complex. */ public void toggleAddBaseComplex() { this.addBaseComplex = !this.addBaseComplex; calculateBaseComplex(); } /** * Enables or disabled base complex addition. * * @param addBaseComplex * True if base complex should be added, false if not */ public void setAddBaseComplex(final boolean addBaseComplex) { this.addBaseComplex = addBaseComplex; } /** * Checks whether a base complex was added or not. * * @return True if a base complex was added. False if not. */ public boolean isAddBaseComplex() { return this.addBaseComplex; } /** * Returns the storage capacities. * * @return The storage capacities. */ public Collection<Capacity> getCapacities() { final Map<String, Capacity> capacities = new HashMap<String, Capacity>(); for (final ComplexFactory factory: getAllFactories()) { for (final Capacity capacity: factory.getCapacities()) { final Ware ware = capacity.getWare(); final Capacity mapCapacity = capacities.get(ware.getId()); if (mapCapacity == null) capacities.put(ware.getId(), capacity); else capacities.put(ware.getId(), new Capacity(ware, mapCapacity .getQuantity() + capacity.getQuantity())); } } final List<Capacity> result = new ArrayList<Capacity>(capacities .values()); Collections.sort(result); return result; } /** * Returns the total storage capacity * * @return The total storage capacity; */ public long getTotalCapacity() { long total = 0; for (final Capacity capacity: getCapacities()) total += capacity.getQuantity(); return total; } /** * Returns the total storage volume * * @return The total storage volume; */ public long getTotalStorageVolume() { long total = 0; for (final Capacity capacity: getCapacities()) total += capacity.getVolume(); return total; } /** * Sets the sector in which to build this complex * * @param sector * The sector to set */ public void setSector(final Sector sector) { if ((sector != null && !sector.equals(this.sector)) || (sector == null && this.sector != null)) { this.sector = sector; calculateBaseComplex(); updateShoppingList(); } } /** * Returns the sector in which this complex is build. * * @return The sector */ public Sector getSector() { return this.sector; } /** * Returns the factory shopping list. * * @return The factory shopping list */ public ShoppingList getShoppingList() { // Return cached shopping list if present if (this.shoppingList != null) return this.shoppingList; final ShoppingList list = new ShoppingList(this.sector == null ? null : this.sector.getNearestKitSellingSector(), this.builtKits); for (final ComplexFactory factory: this.factories) { list.addItem(new ShoppingListItem(factory.getFactory(), factory .getQuantity(), this.sector == null ? null : factory .getFactory().getNearestManufacturer(this.sector), getFactoriesBuilt(factory.getFactory()))); } for (final ComplexFactory factory: this.autoFactories) { list.addItem(new ShoppingListItem(factory.getFactory(), factory .getQuantity(), this.sector == null ? null : factory .getFactory().getNearestManufacturer(this.sector), getFactoriesBuilt(factory.getFactory()))); } this.shoppingList = list; return list; } /** * Returns the price for the specified ware. If the price has a custom price * then this one is returned. If not then the standard average price of the * ware is returned. * * @param ware * The ware * @return The price */ public int getWarePrice(final Ware ware) { final Integer price = this.customPrices.get(ware); if (price == null) return ware.getAvgPrice(); if (price < 0) return 0; return price; } /** * Returns the map with custom prices. * * @return The map with custom prices */ public Map<Ware, Integer> getCustomPrices() { return Collections.unmodifiableMap(this.customPrices); } /** * Sets a new map with custom prices. * * @param customPrices * The new map with custom prices */ public void setCustomPrices(final Map<Ware, Integer> customPrices) { this.customPrices.clear(); this.customPrices.putAll(customPrices); } /** * Checks if complex setup should be displayed. * * @return True if complex setup should be displayed, false if not */ public boolean isShowingComplexSetup() { return this.showingComplexSetup; } /** * Toggles the display of the complex setup. */ public void toggleShowingComplexSetup() { this.showingComplexSetup = !this.showingComplexSetup; } /** * Checks if production stats should be displayed. * * @return True if production stats should be displayed, false if not */ public boolean isShowingProductionStats() { return this.showingProductionStats; } /** * Toggles the display of production statistics. */ public void toggleShowingProductionStats() { this.showingProductionStats = !this.showingProductionStats; } /** * Checks if storage capacities should be displayed. * * @return True if storage capacities should be displayed, false if not */ public boolean isShowingStorageCapacities() { return this.showingStorageCapacities; } /** * Toggles the display of storage capacities. */ public void toggleShowingStorageCapacities() { this.showingStorageCapacities = !this.showingStorageCapacities; } /** * Checks if the shopping list should be displayed. * * @return True if the shopping list should be displayed, false if not */ public boolean isShowingShoppingList() { return this.showingShoppingList; } /** * Toggles the display of the shopping list. */ public void toggleShowingShoppingList() { this.showingShoppingList = !this.showingShoppingList; } /** * Returns the maximum number of factories in the shopping list for the * specified factory id. * * @param id * The id of the factory * @return The number of factories in the shopping list */ private int getMaxFactories(final String id) { final ShoppingList list = getShoppingList(); for (final ShoppingListItem item: list.getItems()) { if (item.getFactory().getId().equals(id)) return item.getQuantity(); } return 0; } /** * Builds a factory with the specified id * * @param id * The id of the factory to build */ public void buildFactory(final String id) { Integer oldCount = this.builtFactories.get(id); if (oldCount == null) oldCount = 0; if (oldCount == getMaxFactories(id)) return; this.builtFactories.put(id, oldCount + 1); updateShoppingList(); } /** * Destroys a factory with the specified id. * * @param id * The id of the factory to destroy */ public void destroyFactory(final String id) { final Integer oldCount = this.builtFactories.get(id); if (oldCount == null) return; if (oldCount == 0) return; this.builtFactories.put(id, oldCount - 1); updateShoppingList(); } /** * Build a kit. */ public void buildKit() { if (this.builtKits >= getTotalQuantity() - 1) return; this.builtKits++; updateShoppingList(); } /** * Destroys a kit. */ public void destroyKit() { if (this.builtKits == 0) return; this.builtKits updateShoppingList(); } /** * Returns the number of built factories of the specified type. * * @param factory * The factory type * @return The number of built factores of the specified type */ private int getFactoriesBuilt(final Factory factory) { final Integer count = this.builtFactories.get(factory.getId()); return count == null ? 0 : count; } /** * @see de.ailis.xadrian.interfaces.GameProvider#getGame() */ @Override public Game getGame() { return this.game; } /** * Checks if the complex uses the specified ware as product or resource. * * @param ware * The ware to check. * @return True if ware is used, false if not. */ public boolean usesWare(final Ware ware) { for (final ComplexFactory complexFactory: getAllFactories()) { final Factory factory = complexFactory.getFactory(); if (factory.getProduct().getWare().equals(ware)) return true; for (final Product product: factory.getResources()) if (product.getWare().equals(ware)) return true; } return false; } /** * Checks if the complex is empty. * * @return True when the complex is empty, false if not. */ public boolean isEmpty() { return this.factories.isEmpty(); } /** * Creates a complex from the specified template code. * * @param templateCode * The template code * @return The complex. */ public static Complex fromTemplateCode(final String templateCode) { try { // Decode base 64 final byte[] data = DatatypeConverter.parseBase64Binary(templateCode); final InputStream stream = new DynaByteInputStream(new ByteArrayInputStream(data)); // Read complex settings final int settings = stream.read(); final boolean hasSector = (settings & 1) == 1; final int gameNid = (settings >> 1) & 7; final Game game = GameFactory.getInstance().getGame(gameNid); final Complex complex = new Complex(game); // Read sector coordinates or sun power if (hasSector) { final int x = stream.read(); final int y = stream.read(); complex.setSector(game.getSectorFactory().getSector(x, y)); } else { final int percent = stream.read(); complex.setSuns(game.getSunFactory().getSun(percent)); } int factoryId; while ((factoryId = stream.read()) != 0) { final Factory factory = game.getFactoryFactory().getFactory(factoryId); if (factory.isMine()) { final List<Integer> yields = new ArrayList<Integer>(); int yield; while ((yield = stream.read()) != 0) yields.add(yield - 1); complex .addFactory(new ComplexFactory(game, factory, yields)); } else { final int quantity = stream.read(); complex.addFactory(new ComplexFactory(game, factory, quantity, 0)); } } return complex; } catch (final IOException e) { throw new TemplateCodeException(e.toString(), e); } } /** * Returns the template code. * * @return The template code. */ public String getTemplateCode() { try { final ByteArrayOutputStream arrayStream = new ByteArrayOutputStream(); final OutputStream stream = new DynaByteOutputStream(arrayStream); // Write the template settings bit mask. int settings = this.sector == null ? 0 : 1; settings |= this.game.getNid() << 1; stream.write(settings); // Write the sector coordinates if (this.sector != null) { stream.write(this.sector.getX()); stream.write(this.sector.getY()); } // Or else write the sun power else { stream.write(this.suns.getPercent()); } // Write the factories for (final ComplexFactory complexFactory: getAllFactories()) { final Factory factory = complexFactory.getFactory(); stream.write(factory.getNid()); if (factory.isMine()) { for (final int yield: complexFactory.getYields()) stream.write(yield + 1); stream.write(0); } else stream.write(complexFactory.getQuantity()); } // Write end marker stream.write(0); stream.close(); // Get byte array from stream final byte[] data = arrayStream.toByteArray(); // Return base 64 encoded bytes return DatatypeConverter.printBase64Binary(data); } catch (final IOException e) { throw new TemplateCodeException(e.toString(), e); } } /** * Checks if this complex has mines. * * @return True if complex has mines, false if not. */ public boolean hasMines() { for (final ComplexFactory factory: this.factories) if (factory.getFactory().isMine()) return true; return false; } /** * Returns the complex data as ASCII. * * @return The complex data as ASCII. */ public String getASCII() { final StringWriter writer = new StringWriter(); final PrintWriter out = new PrintWriter(writer); // Print the game name. out.print(I18N.getString("complex.game")); out.print(": "); out.println(getGame().getName()); // Print the sector name if chosen final Sector sector = getSector(); if (sector != null) { out.print(I18N.getString("complex.sector")); out.print(": "); out.println(sector.getName()); } // Print the sun power out.print(I18N.getString("complex.suns")); out.print(": "); out.println(getSuns().toString()); // Print the template code out.print(I18N.getString("complex.templateCode")); out.print(": "); out.println(getTemplateCode()); // Print empty line out.println(); final boolean hasMines = hasMines(); final Collection<ComplexFactory> complexFactories = getAllFactories(); final Table table = new Table(complexFactories.size() + 1 - getDisabledFactrories(), hasMines ? 4 : 3); // Add table headers table.setCell(0, 0, new TableCell(I18N.getString("complex.factory"))); table.setCell(0, 1, new TableCell(I18N.getString("complex.race"))); table.setCell(0, 2, new TableCell(I18N.getString("complex.quantity"), Align.RIGHT)); if (hasMines) table.setCell(0, 3, new TableCell(I18N.getString("complex.yield"), Align.RIGHT)); table.addSeparator(0); // Add the factories int row = 1; for (final ComplexFactory complexFactory: complexFactories) { if (complexFactory.isDisabled()) continue; final Factory factory = complexFactory.getFactory(); table.setCell(row, 0, new TableCell(factory.getName())); table.setCell(row, 1, new TableCell(factory.getRace().getName())); table.setCell(row, 2, new TableCell("" + complexFactory.getQuantity(), Align.RIGHT)); if (hasMines && factory.isMine()) { table.setCell(row, 3, new TableCell( (complexFactory.isHomogenousYield() ? "" : "~") + complexFactory.getYield(), Align.RIGHT)); } row += 1; } // Print complex table out.print(table.toString()); // Print empty line out.println(); // Print total complex price out.print(I18N.getString("complex.totalPrice")); out.print(": "); out.print(new DecimalFormat().format(getTotalPrice())); out.println(" Cr"); // Print total complex price out.print(I18N.getString("complex.profitPerHour")); out.print(": "); out.print(new DecimalFormat().format(Math.round(getProfit()))); out.println(" Cr"); return writer.toString(); } }
package de.bwaldvogel.liblinear; import static de.bwaldvogel.liblinear.Linear.atof; import static de.bwaldvogel.liblinear.Linear.atoi; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.StringTokenizer; public class Train { public static void main(String[] args) throws IOException, InvalidInputDataException { new Train().run(args); } private double bias = 1; private boolean cross_validation = false; private String inputFilename; private String modelFilename; private int nr_fold; private Parameter param = null; private Problem prob = null; private void do_cross_validation() { double total_error = 0; double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0; double[] target = new double[prob.l]; long start, stop; start = System.currentTimeMillis(); Linear.crossValidation(prob, param, nr_fold, target); stop = System.currentTimeMillis(); System.out.println("time: " + (stop - start) + " ms"); if (param.solverType.isSupportVectorRegression()) { for (int i = 0; i < prob.l; i++) { double y = prob.y[i]; double v = target[i]; total_error += (v - y) * (v - y); sumv += v; sumy += y; sumvv += v * v; sumyy += y * y; sumvy += v * y; } System.out.printf("Cross Validation Mean squared error = %g%n", total_error / prob.l); System.out.printf("Cross Validation Squared correlation coefficient = %g%n", ((prob.l * sumvy - sumv * sumy) * (prob.l * sumvy - sumv * sumy)) / ((prob.l * sumvv - sumv * sumv) * (prob.l * sumyy - sumy * sumy))); } else { int total_correct = 0; for (int i = 0; i < prob.l; i++) if (target[i] == prob.y[i]) ++total_correct; System.out.printf("correct: %d%n", total_correct); System.out.printf("Cross Validation Accuracy = %g%%%n", 100.0 * total_correct / prob.l); } } private void exit_with_help() { System.out.printf("Usage: train [options] training_set_file [model_file]%n" + "options:%n" + "-s type : set type of solver (default 1)%n" + " 0 -- L2-regularized logistic regression (primal)%n" + " 1 -- L2-regularized L2-loss support vector classification (dual)%n" + " 2 -- L2-regularized L2-loss support vector classification (primal)%n" + " 3 -- L2-regularized L1-loss support vector classification (dual)%n" + " 4 -- multi-class support vector classification by Crammer and Singer%n" + " 5 -- L1-regularized L2-loss support vector classification%n" + " 6 -- L1-regularized logistic regression%n" + " 7 -- L2-regularized logistic regression (dual)%n" + " 11 -- L2-regularized L2-loss epsilon support vector regression (primal)%n" + " 12 -- L2-regularized L2-loss epsilon support vector regression (dual)%n" + " 13 -- L2-regularized L1-loss epsilon support vector regression (dual)%n" + "-c cost : set the parameter C (default 1)%n" + "-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)%n" + "-e epsilon : set tolerance of termination criterion%n" + " -s 0 and 2%n" + " |f'(w)|_2 <= eps*min(pos,neg)/l*|f'(w0)|_2,%n" + " where f is the primal function and pos/neg are # of%n" + " positive/negative data (default 0.01)%n" + " -s 11%n" + " |f'(w)|_2 <= eps*|f'(w0)|_2 (default 0.001)%n" + " -s 1, 3, 4 and 7%n" + " Dual maximal violation <= eps; similar to libsvm (default 0.1)%n" + " -s 5 and 6%n" + " |f'(w)|_1 <= eps*min(pos,neg)/l*|f'(w0)|_1,%n" + " where f is the primal function (default 0.01)%n" + " -s 12 and 13\n" + " |f'(alpha)|_1 <= eps |f'(alpha0)|,\n" + " where f is the dual function (default 0.1)\n" + "-B bias : if bias >= 0, instance x becomes [x; bias]; if < 0, no bias term added (default -1)%n" + "-wi weight: weights adjust the parameter C of different classes (see README for details)%n" + "-v n: n-fold cross validation mode%n" + "-q : quiet mode (no outputs)%n"); System.exit(1); } Problem getProblem() { return prob; } double getBias() { return bias; } Parameter getParameter() { return param; } void parse_command_line(String argv[]) { int i; // eps: see setting below param = new Parameter(SolverType.L2R_L2LOSS_SVC_DUAL, 1, Double.POSITIVE_INFINITY, 0.1); // default values bias = -1; cross_validation = false; // parse options for (i = 0; i < argv.length; i++) { if (argv[i].charAt(0) != '-') break; if (++i >= argv.length) exit_with_help(); switch (argv[i - 1].charAt(1)) { case 's': param.solverType = SolverType.getById(atoi(argv[i])); break; case 'c': param.setC(atof(argv[i])); break; case 'p': param.setP(atof(argv[i])); break; case 'e': param.setEps(atof(argv[i])); break; case 'B': bias = atof(argv[i]); break; case 'w': int weightLabel = atoi(argv[i - 1].substring(2)); double weight = atof(argv[i]); param.weightLabel = addToArray(param.weightLabel, weightLabel); param.weight = addToArray(param.weight, weight); break; case 'v': cross_validation = true; nr_fold = atoi(argv[i]); if (nr_fold < 2) { System.err.println("n-fold cross validation: n must >= 2"); exit_with_help(); } break; case 'q': i Linear.disableDebugOutput(); break; default: System.err.println("unknown option"); exit_with_help(); } } // determine filenames if (i >= argv.length) exit_with_help(); inputFilename = argv[i]; if (i < argv.length - 1) modelFilename = argv[i + 1]; else { int p = argv[i].lastIndexOf('/'); ++p; // whew... modelFilename = argv[i].substring(p) + ".model"; } if (param.eps == Double.POSITIVE_INFINITY) { switch (param.solverType) { case L2R_LR: case L2R_L2LOSS_SVC: param.setEps(0.01); break; case L2R_L2LOSS_SVR: param.setEps(0.001); break; case L2R_L2LOSS_SVC_DUAL: case L2R_L1LOSS_SVC_DUAL: case MCSVM_CS: case L2R_LR_DUAL: param.setEps(0.1); break; case L1R_L2LOSS_SVC: case L1R_LR: param.setEps(0.01); break; case L2R_L1LOSS_SVR_DUAL: case L2R_L2LOSS_SVR_DUAL: param.setEps(0.1); break; default: throw new IllegalStateException("unknown solver type: " + param.solverType); } } } /** * reads a problem from LibSVM format * @param file the SVM file * @throws IOException obviously in case of any I/O exception ;) * @throws InvalidInputDataException if the input file is not correctly formatted */ public static Problem readProblem(File file, double bias) throws IOException, InvalidInputDataException { BufferedReader fp = new BufferedReader(new FileReader(file)); List<Double> vy = new ArrayList<Double>(); List<Feature[]> vx = new ArrayList<Feature[]>(); int max_index = 0; int lineNr = 0; try { while (true) { String line = fp.readLine(); if (line == null) break; lineNr++; StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:"); String token; try { token = st.nextToken(); } catch (NoSuchElementException e) { throw new InvalidInputDataException("empty line", file, lineNr, e); } try { vy.add(atof(token)); } catch (NumberFormatException e) { throw new InvalidInputDataException("invalid label: " + token, file, lineNr, e); } int m = st.countTokens() / 2; Feature[] x; if (bias >= 0) { x = new Feature[m + 1]; } else { x = new Feature[m]; } int indexBefore = 0; for (int j = 0; j < m; j++) { token = st.nextToken(); int index; try { index = atoi(token); } catch (NumberFormatException e) { throw new InvalidInputDataException("invalid index: " + token, file, lineNr, e); } // assert that indices are valid and sorted if (index < 0) throw new InvalidInputDataException("invalid index: " + index, file, lineNr); if (index <= indexBefore) throw new InvalidInputDataException("indices must be sorted in ascending order", file, lineNr); indexBefore = index; token = st.nextToken(); try { double value = atof(token); x[j] = new FeatureNode(index, value); } catch (NumberFormatException e) { throw new InvalidInputDataException("invalid value: " + token, file, lineNr); } } if (m > 0) { max_index = Math.max(max_index, x[m - 1].getIndex()); } vx.add(x); } return constructProblem(vy, vx, max_index, bias); } finally { fp.close(); } } void readProblem(String filename) throws IOException, InvalidInputDataException { prob = Train.readProblem(new File(filename), bias); } private static int[] addToArray(int[] array, int newElement) { int length = array != null ? array.length : 0; int[] newArray = new int[length + 1]; if (array != null && length > 0) { System.arraycopy(array, 0, newArray, 0, length); } newArray[length] = newElement; return newArray; } private static double[] addToArray(double[] array, double newElement) { int length = array != null ? array.length : 0; double[] newArray = new double[length + 1]; if (array != null && length > 0) { System.arraycopy(array, 0, newArray, 0, length); } newArray[length] = newElement; return newArray; } private static Problem constructProblem(List<Double> vy, List<Feature[]> vx, int max_index, double bias) { Problem prob = new Problem(); prob.bias = bias; prob.l = vy.size(); prob.n = max_index; if (bias >= 0) { prob.n++; } prob.x = new Feature[prob.l][]; for (int i = 0; i < prob.l; i++) { prob.x[i] = vx.get(i); if (bias >= 0) { assert prob.x[i][prob.x[i].length - 1] == null; prob.x[i][prob.x[i].length - 1] = new FeatureNode(max_index + 1, bias); } } prob.y = new double[prob.l]; for (int i = 0; i < prob.l; i++) prob.y[i] = vy.get(i).doubleValue(); return prob; } private void run(String[] args) throws IOException, InvalidInputDataException { parse_command_line(args); readProblem(inputFilename); if (cross_validation) do_cross_validation(); else { Model model = Linear.train(prob, param); Linear.saveModel(new File(modelFilename), model); } } }
package iH4v3n0N4m3.game.e3d; import iH4v3n0N4m3.ui.swing.Panel; public abstract class Object3D extends Panel{ public abstract void render3D(Vertex3D v,Camera c); }
package im.actor.crypto; import im.actor.crypto.primitives.util.ByteStrings; /** * Actor's MTProto V2 keys */ public class ActorProtoKey { private byte[] clientMacKey; private byte[] serverMacKey; private byte[] clientKey; private byte[] serverKey; private byte[] clientMacRussianKey; private byte[] serverMacRussianKey; private byte[] clientRussianKey; private byte[] serverRussianKey; public ActorProtoKey(byte[] masterKey) { int offset = 0; clientMacKey = ByteStrings.substring(masterKey, (offset++) * 32, 32); serverMacKey = ByteStrings.substring(masterKey, (offset++) * 32, 32); clientKey = ByteStrings.substring(masterKey, (offset++) * 32, 32); serverKey = ByteStrings.substring(masterKey, (offset++) * 32, 32); // Moving to russian part offset = 128; clientMacRussianKey = ByteStrings.substring(masterKey, (offset++) * 32, 32); serverMacRussianKey = ByteStrings.substring(masterKey, (offset++) * 32, 32); clientRussianKey = ByteStrings.substring(masterKey, (offset++) * 32, 32); serverRussianKey = ByteStrings.substring(masterKey, (offset++) * 32, 32); } public byte[] getClientMacKey() { return clientMacKey; } public byte[] getServerMacKey() { return serverMacKey; } public byte[] getClientKey() { return clientKey; } public byte[] getServerKey() { return serverKey; } public byte[] getClientMacRussianKey() { return clientMacRussianKey; } public byte[] getServerMacRussianKey() { return serverMacRussianKey; } public byte[] getClientRussianKey() { return clientRussianKey; } public byte[] getServerRussianKey() { return serverRussianKey; } }
package info.faceland.loot; import info.faceland.api.FacePlugin; import info.faceland.facecore.shade.command.CommandHandler; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryConfiguration; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryYamlConfiguration; import info.faceland.facecore.shade.nun.ivory.config.settings.IvorySettings; import info.faceland.loot.api.groups.ItemGroup; import info.faceland.loot.api.items.CustomItem; import info.faceland.loot.api.items.CustomItemBuilder; import info.faceland.loot.api.items.ItemBuilder; import info.faceland.loot.api.managers.CustomItemManager; import info.faceland.loot.api.managers.ItemGroupManager; import info.faceland.loot.api.managers.NameManager; import info.faceland.loot.api.managers.SocketGemManager; import info.faceland.loot.api.managers.TierManager; import info.faceland.loot.api.sockets.SocketGem; import info.faceland.loot.api.sockets.SocketGemBuilder; import info.faceland.loot.api.sockets.effects.SocketEffect; import info.faceland.loot.api.tier.Tier; import info.faceland.loot.api.tier.TierBuilder; import info.faceland.loot.commands.LootCommand; import info.faceland.loot.groups.LootItemGroup; import info.faceland.loot.io.SmartTextFile; import info.faceland.loot.items.LootCustomItemBuilder; import info.faceland.loot.items.LootItemBuilder; import info.faceland.loot.managers.LootCustomItemManager; import info.faceland.loot.managers.LootItemGroupManager; import info.faceland.loot.managers.LootNameManager; import info.faceland.loot.managers.LootSocketGemManager; import info.faceland.loot.managers.LootTierManager; import info.faceland.loot.sockets.LootSocketGemBuilder; import info.faceland.loot.sockets.effects.LootSocketPotionEffect; import info.faceland.loot.tier.LootTierBuilder; import info.faceland.loot.utils.converters.StringConverter; import info.faceland.utils.TextUtils; import net.nunnerycode.java.libraries.cannonball.DebugPrinter; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.event.HandlerList; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; public final class LootPlugin extends FacePlugin { private DebugPrinter debugPrinter; private VersionedIvoryYamlConfiguration itemsYAML; private VersionedIvoryYamlConfiguration tierYAML; private VersionedIvoryYamlConfiguration corestatsYAML; private VersionedIvoryYamlConfiguration customItemsYAML; private VersionedIvoryYamlConfiguration socketGemsYAML; private VersionedIvoryYamlConfiguration languageYAML; private VersionedIvoryYamlConfiguration configYAML; private IvorySettings settings; private ItemGroupManager itemGroupManager; private TierManager tierManager; private NameManager nameManager; private CustomItemManager customItemManager; private SocketGemManager socketGemManager; @Override public void preEnable() { debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log"); itemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "items.yml"), getResource("items.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (itemsYAML.update()) { getLogger().info("Updating items.yml"); debug("Updating items.yml"); } tierYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "tier.yml"), getResource("tier.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (tierYAML.update()) { getLogger().info("Updating tier.yml"); debug("Updating tier.yml"); } corestatsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "corestats.yml"), getResource("corestats.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (corestatsYAML.update()) { getLogger().info("Updating corestats.yml"); debug("Updating corestats.yml"); } customItemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "customItems.yml"), getResource("customItems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (customItemsYAML.update()) { getLogger().info("Updating customItems.yml"); debug("Updating customItems.yml"); } socketGemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "socketGems.yml"), getResource("socketGems.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (socketGemsYAML.update()) { getLogger().info("Updating socketGems.yml"); debug("Updating socketGems.yml"); } languageYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "language.yml"), getResource("language.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (languageYAML.update()) { getLogger().info("Updating language.yml"); debug("Updating language.yml"); } configYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "config.yml"), getResource("config.yml"), VersionedIvoryConfiguration.VersionUpdateType .BACKUP_AND_UPDATE); if (configYAML.update()) { getLogger().info("Updating config.yml"); debug("Updating config.yml"); } settings = IvorySettings.loadFromFiles(corestatsYAML, languageYAML, configYAML); itemGroupManager = new LootItemGroupManager(); tierManager = new LootTierManager(); nameManager = new LootNameManager(); customItemManager = new LootCustomItemManager(); socketGemManager = new LootSocketGemManager(); } @Override public void enable() { loadItemGroups(); loadTiers(); loadNames(); loadCustomItems(); loadSocketGems(); } private void loadSocketGems() { for (SocketGem sg : getSocketGemManager().getSocketGems()) { getSocketGemManager().removeSocketGem(sg.getName()); } Set<SocketGem> gems = new HashSet<>(); List<String> loadedSocketGems = new ArrayList<>(); for (String key : socketGemsYAML.getKeys(false)) { if (!socketGemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = socketGemsYAML.getConfigurationSection(key); SocketGemBuilder builder = getNewSocketGemBuilder(key); builder.withPrefix(cs.getString("prefix")); builder.withSuffix(cs.getString("suffix")); builder.withLore(cs.getStringList("lore")); builder.withWeight(cs.getDouble("weight")); List<SocketEffect> effects = new ArrayList<>(); for (String eff : cs.getStringList("effects")) { effects.add(LootSocketPotionEffect.parseString(eff)); } builder.withSocketEffects(effects); SocketGem gem = builder.build(); gems.add(gem); loadedSocketGems.add(gem.getName()); } for (SocketGem sg : gems) { getSocketGemManager().addSocketGem(sg); } debug("Loaded socket gems: " + loadedSocketGems.toString()); } @Override public void postEnable() { CommandHandler handler = new CommandHandler(this); handler.registerCommands(new LootCommand(this)); //Bukkit.getPluginManager().registerEvents(new LoginListener(this), this); debug("v" + getDescription().getVersion() + " enabled"); } @Override public void preDisable() { HandlerList.unregisterAll(this); } @Override public void disable() { } @Override public void postDisable() { socketGemManager = null; customItemManager = null; nameManager = null; tierManager = null; itemGroupManager = null; settings = null; configYAML = null; languageYAML = null; customItemsYAML = null; corestatsYAML = null; tierYAML = null; itemsYAML = null; debugPrinter = null; } public void debug(String... messages) { debug(Level.INFO, messages); } public void debug(Level level, String... messages) { if (debugPrinter != null) { debugPrinter.debug(level, messages); } } private void loadCustomItems() { for (CustomItem ci : getCustomItemManager().getCustomItems()) { getCustomItemManager().removeCustomItem(ci.getName()); } Set<CustomItem> customItems = new HashSet<>(); List<String> loaded = new ArrayList<>(); for (String key : customItemsYAML.getKeys(false)) { if (!customItemsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = customItemsYAML.getConfigurationSection(key); CustomItemBuilder builder = getNewCustomItemBuilder(key); builder.withMaterial(StringConverter.toMaterial(cs.getString("material"))); builder.withDisplayName(cs.getString("display-name")); builder.withLore(cs.getStringList("lore")); CustomItem ci = builder.build(); customItems.add(ci); loaded.add(ci.getName()); } for (CustomItem ci : customItems) { getCustomItemManager().addCustomItem(ci); } debug("Loaded custom items: " + loaded.toString()); } private void loadNames() { for (String s : getNameManager().getPrefixes()) { getNameManager().removePrefix(s); } for (String s : getNameManager().getSuffixes()) { getNameManager().removeSuffix(s); } File prefixFile = new File(getDataFolder(), "prefix.txt"); File suffixFile = new File(getDataFolder(), "suffix.txt"); SmartTextFile.writeToFile(getResource("prefix.txt"), prefixFile, true); SmartTextFile.writeToFile(getResource("suffix.txt"), suffixFile, true); SmartTextFile smartPrefixFile = new SmartTextFile(prefixFile); SmartTextFile smartSuffixFile = new SmartTextFile(suffixFile); for (String s : smartPrefixFile.read()) { getNameManager().addPrefix(s); } for (String s : smartSuffixFile.read()) { getNameManager().addSuffix(s); } debug("Loaded prefixes: " + getNameManager().getPrefixes().size(), "Loaded suffixes: " + getNameManager() .getSuffixes().size()); } private void loadItemGroups() { for (ItemGroup ig : getItemGroupManager().getItemGroups()) { getItemGroupManager().removeItemGroup(ig.getName()); } Set<ItemGroup> itemGroups = new HashSet<>(); List<String> loadedItemGroups = new ArrayList<>(); for (String key : itemsYAML.getKeys(false)) { if (!itemsYAML.isList(key)) { continue; } List<String> list = itemsYAML.getStringList(key); ItemGroup ig = new LootItemGroup(key, false); for (String s : list) { Material m = StringConverter.toMaterial(s); if (m == Material.AIR) { continue; } ig.addMaterial(m); } itemGroups.add(ig); loadedItemGroups.add(key); } for (ItemGroup ig : itemGroups) { getItemGroupManager().addItemGroup(ig); } debug("Loaded item groups: " + loadedItemGroups.toString()); } private void loadTiers() { for (Tier t : getTierManager().getLoadedTiers()) { getTierManager().removeTier(t.getName()); } Set<Tier> tiers = new HashSet<>(); List<String> loadedTiers = new ArrayList<>(); for (String key : tierYAML.getKeys(false)) { if (!tierYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = tierYAML.getConfigurationSection(key); TierBuilder builder = getNewTierBuilder(key); builder.withDisplayName(cs.getString("display-name")); builder.withDisplayColor(TextUtils.convertTag(cs.getString("display-color"))); builder.withIdentificationColor(TextUtils.convertTag(cs.getString("identification-color"))); builder.withSpawnWeight(cs.getDouble("spawn-weight")); builder.withIdentifyWeight(cs.getDouble("identify-weight")); builder.withDistanceWeight(cs.getDouble("distance-weight")); builder.withMinimumSockets(cs.getInt("minimum-sockets")); builder.withMaximumSockets(cs.getInt("maximum-sockets")); builder.withMinimumBonusLore(cs.getInt("minimum-bonus-lore")); builder.withMaximumBonusLore(cs.getInt("maximum-bonus-lore")); builder.withBaseLore(cs.getStringList("base-lore")); builder.withBonusLore(cs.getStringList("bonus-lore")); List<String> sl = cs.getStringList("item-groups"); Set<ItemGroup> itemGroups = new HashSet<>(); for (String s : sl) { ItemGroup ig; if (s.startsWith("-")) { ig = getItemGroupManager().getItemGroup(s.substring(1)); if (ig == null) { continue; } ig = ig.getInverse(); } else { ig = getItemGroupManager().getItemGroup(s); if (ig == null) { continue; } } itemGroups.add(ig.getInverse()); } builder.withItemGroups(itemGroups); builder.withMinimumDurability(cs.getDouble("minimum-durability")); builder.withMaximumDurability(cs.getDouble("maximum-durability")); Tier t = builder.build(); loadedTiers.add(t.getName()); tiers.add(t); } for (Tier t : tiers) { getTierManager().addTier(t); } debug("Loaded tiers: " + loadedTiers.toString()); } public TierBuilder getNewTierBuilder(String name) { return new LootTierBuilder(name); } public ItemBuilder getNewItemBuilder() { return new LootItemBuilder(this); } public CustomItemBuilder getNewCustomItemBuilder(String name) { return new LootCustomItemBuilder(name); } public SocketGemBuilder getNewSocketGemBuilder(String name) { return new LootSocketGemBuilder(name); } public TierManager getTierManager() { return tierManager; } public ItemGroupManager getItemGroupManager() { return itemGroupManager; } public NameManager getNameManager() { return nameManager; } public IvorySettings getSettings() { return settings; } public CustomItemManager getCustomItemManager() { return customItemManager; } public SocketGemManager getSocketGemManager() { return socketGemManager; } }
package io.luna.game.model.mobile; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import io.luna.LunaContext; import io.luna.game.model.EntityType; import io.luna.game.model.Position; import io.luna.game.model.def.NpcCombatDefinition; import io.luna.game.model.def.NpcDefinition; import io.luna.game.model.mobile.update.UpdateFlagHolder.UpdateFlag; import java.util.Objects; public final class Npc extends MobileEntity { /** * The identifier for this {@code Npc}. */ private final int id; /** * The definition instance for this {@code Npc}. */ private NpcDefinition definition; /** * The combat definition instance for this {@code Npc}. */ private NpcCombatDefinition combatDefinition; /** * The identifier for the transformation {@code Npc}. */ private int transformId = -1; /** * The current health value of this {@code Npc}. */ private int currentHp; /** * Creates a new {@link Npc}. * * @param context The context to be managed in. * @param id The identifier for this {@code Npc}. * @param position The position of this {@code Npc}. */ public Npc(LunaContext context, int id, Position position) { super(context); this.id = id; definition = NpcDefinition.DEFINITIONS[id]; combatDefinition = NpcCombatDefinition.getDefinition(id); currentHp = combatDefinition.getHitpoints(); ImmutableList<Integer> skills = combatDefinition.getSkills(); Skill attack = skill(Skill.ATTACK); Skill strength = skill(Skill.STRENGTH); Skill defence = skill(Skill.DEFENCE); Skill ranged = skill(Skill.RANGED); Skill magic = skill(Skill.MAGIC); attack.setLevel(skills.get(NpcCombatDefinition.ATTACK)); strength.setLevel(skills.get(NpcCombatDefinition.STRENGTH)); defence.setLevel(skills.get(NpcCombatDefinition.DEFENCE)); ranged.setLevel(skills.get(NpcCombatDefinition.RANGED)); magic.setLevel(skills.get(NpcCombatDefinition.MAGIC)); setPosition(position); } @Override public int hashCode() { return Objects.hash(getIndex()); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("id", id).add("name", definition.getName()).toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Npc) { Npc other = (Npc) obj; return getIndex() == other.getIndex(); } return false; } @Override public int size() { return definition.getSize(); } @Override public EntityType type() { return EntityType.NPC; } @Override public void reset() { transformId = -1; } /** * Transforms this {@code Npc} into another {@code Npc}. * * @param id The identifier of the {@code Npc} to transform into. */ public void transform(int id) { transformId = id; definition = NpcDefinition.DEFINITIONS[id]; updateFlags.flag(UpdateFlag.TRANSFORM); } /** * @return The definition instance for this {@code Npc}. */ public NpcDefinition getDefinition() { return definition; } /** * @return The definition instance for this {@code Npc}. */ public NpcCombatDefinition getCombatDefinition() { return combatDefinition; } /** * @return The identifier for this {@link Npc}. */ public int getId() { return id; } /** * @return The identifier for the transformation {@code Npc}. */ public int getTransformId() { return transformId; } /** * @return The current health value of this {@code Npc}. */ public int getCurrentHp() { return currentHp; } /** * Sets the current health value of this {@code Npc}. */ public void setCurrentHp(int currentHp) { this.currentHp = currentHp; } }
package joshie.harvest.crops; import joshie.harvest.api.crops.Crop; import joshie.harvest.crops.block.BlockHFCrops.CropType; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class CropData { private Crop crop = Crop.NULL_CROP; //The Crop Type of this plant private int stage; //The stage it is currently at private int daysWithoutWater; //The number of days this crop has gone without water public CropData setCrop(Crop crop, int stage) { this.crop = crop; this.stage = stage; return this; } //Returns false if the crop was withered public boolean newDay(World world, BlockPos pos) { //Stage 1, Check how long the plant has been without water, If it's more than 2 days kill it if (crop == null || (crop.requiresWater() && daysWithoutWater > 2) || !crop.getGrowthHandler().canGrow(world, pos, crop)) { return false; } else { //Stage 2: Now that we know, it has been watered, Update it's stage //If we aren't ticking randomly, Then increase the stage if (!HFCrops.ALWAYS_GROW) { if (daysWithoutWater == 0 || !crop.requiresWater()) { grow(world, pos); } } } //Stage 6, Reset the water counter and fertilising daysWithoutWater++; return true; } public void grow(World world, BlockPos pos) { //Increase the stage of this crop if (stage < crop.getStages()) { stage++; } //If the crop has become double add in the new block if (crop.isDouble(stage)) { world.setBlockState(pos.up(), HFCrops.CROPS.getStateFromEnum(CropType.FRESH_DOUBLE), 2); } //If the crop grows a block to the side if (crop.growsToSide() != null) { if (stage == crop.getStages()) { if (!attemptToGrowToSide(world, pos)) { stage--; //If we failed to grow, decrease the growth stage } } } } @SuppressWarnings("deprecation") private boolean attemptToGrowToSide(World world, BlockPos pos) { if (world.isAirBlock(pos.add(1, 0, 0))) { //If it's air, then let's grow some shit return world.setBlockState(pos.add(1, 0, 0), crop.growsToSide().getStateFromMeta(0), 2); //0 = x- } else if (world.isAirBlock(pos.add(0, 0, -1))) { return world.setBlockState(pos.add(0, 0, -1), crop.growsToSide().getStateFromMeta(1), 2); //1 = z+ } else if (world.isAirBlock(pos.add(0, 0, 1))) { return world.setBlockState(pos.add(0, 0, 1), crop.growsToSide().getStateFromMeta(2), 2); //2 = z- } else if (world.isAirBlock(pos.add(-1, 0, 0))) { return world.setBlockState(pos.add(-1, 0, 0), crop.growsToSide().getStateFromMeta(2), 2); //3 = x- } return false; } public ResourceLocation getResource() { return crop.getRegistryName(); } public int getStage() { return stage < 1 ? 1: stage; } @Nonnull public Crop getCrop() { return crop; } public ItemStack harvest(@Nullable EntityPlayer player, boolean doHarvest) { if (crop == null) return null; if (stage >= crop.getStages()) { if (doHarvest) { if (crop.getRegrowStage() > 0) { stage = crop.getRegrowStage(); } } return crop.getHarvested(); } else return null; } public void setHydrated() { daysWithoutWater = 0; } public void readFromNBT(NBTTagCompound nbt) { if (nbt.hasKey("CropResource")) { crop = Crop.REGISTRY.getValue(new ResourceLocation(nbt.getString("CropResource"))); stage = nbt.getByte("CurrentStage"); daysWithoutWater = nbt.getShort("DaysWithoutWater"); } if (crop == null) crop = Crop.NULL_CROP; } public NBTTagCompound writeToNBT(NBTTagCompound nbt) { if (crop != null) { nbt.setString("CropResource", crop.getRegistryName().toString()); nbt.setByte("CurrentStage", (byte) stage); nbt.setShort("DaysWithoutWater", (short) daysWithoutWater); } return nbt; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CropData other = (CropData) obj; if (crop == null) { if (other.crop != null) return false; } else if (!crop.equals(other.crop)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((crop == null) ? 0 : crop.hashCode()); return result; } }
package kr.ac.ajou.dsd.kda.model; import java.util.Arrays; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import org.hibernate.validator.constraints.NotBlank; @Entity public class Meal { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") @Column( columnDefinition = "BINARY(16)", length = 16 ) private UUID id; @NotBlank(message = "koreanName must not be blank!") private String koreanName; @NotBlank(message = "englishName must not be blank!") private String englishName; @NotBlank(message = "transliteratedName must not be blank!") private String transliteratedName; private String description = ""; private String[] ingredients = new String[]{""}; private String[] category = new String[]{""}; private String photoUrl = ""; @Embedded private Rating rating = new Rating(); private int viewNum = 0; private int spicyGrade = 0; protected Meal(){ } public Meal(String koreanName, String englishName, String transliteratedName) { this(koreanName, englishName, transliteratedName, "", new String[]{""}, new String[]{""}, new Rating(), 0, 0); } public Meal(String koreanName, String englishName, String transliteratedName, String description, String[] ingredients, String[] category, Rating rating, int viewNum, int spicyGrade) { super(); this.koreanName = koreanName; this.englishName = englishName; this.transliteratedName = transliteratedName; } public UUID getId() { return id; } private void setId(UUID id) { this.id = id; } public String getKoreanName() { return koreanName; } public void setKoreanName(String koreanName) { this.koreanName = koreanName; } public String getEnglishName() { return englishName; } public void setEnglishName(String englishName) { this.englishName = englishName; } public String getTransliteratedName() { return transliteratedName; } public void setTransliteratedName(String transliteratedName) { this.transliteratedName = transliteratedName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String[] getIngredients() { return ingredients; } public void setIngredients(String[] ingredients) { this.ingredients = ingredients; } public String[] getCategory() { return category; } public void setCategory(String[] category) { this.category = category; } public Rating getRating() { return rating; } public void setRating(Rating rating) { this.rating = rating; } public int getViewNum() { return viewNum; } public void setViewNum(int viewNum) { this.viewNum = viewNum; } public int getSpicyGrade() { return spicyGrade; } public void setSpicyGrade(int spicyGrade) { this.spicyGrade = spicyGrade; } public String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(category); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((photoUrl == null) ? 0 : photoUrl.hashCode()); result = prime * result + ((englishName == null) ? 0 : englishName.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + Arrays.hashCode(ingredients); result = prime * result + ((koreanName == null) ? 0 : koreanName.hashCode()); result = prime * result + ((rating == null) ? 0 : rating.hashCode()); result = prime * result + spicyGrade; result = prime * result + ((transliteratedName == null) ? 0 : transliteratedName.hashCode()); result = prime * result + viewNum; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Meal other = (Meal) obj; if (!Arrays.equals(category, other.category)) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (photoUrl == null) { if (other.photoUrl != null) return false; } else if (!photoUrl.equals(other.photoUrl)) return false; if (englishName == null) { if (other.englishName != null) return false; } else if (!englishName.equals(other.englishName)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (!Arrays.equals(ingredients, other.ingredients)) return false; if (koreanName == null) { if (other.koreanName != null) return false; } else if (!koreanName.equals(other.koreanName)) return false; if (rating == null) { if (other.rating != null) return false; } else if (!rating.equals(other.rating)) return false; if (spicyGrade != other.spicyGrade) return false; if (transliteratedName == null) { if (other.transliteratedName != null) return false; } else if (!transliteratedName.equals(other.transliteratedName)) return false; if (viewNum != other.viewNum) return false; return true; } }
package mcjty.immcraft; import mcjty.immcraft.blocks.ModBlocks; import mcjty.immcraft.config.ConfigSetup; import mcjty.immcraft.events.ClientForgeEventHandlers; import mcjty.immcraft.events.ForgeEventHandlers; import mcjty.immcraft.input.InputHandler; import mcjty.immcraft.input.KeyBindings; import mcjty.immcraft.items.ModItems; import mcjty.immcraft.network.PacketHandler; import mcjty.immcraft.worldgen.WorldGen; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraftforge.client.model.obj.OBJLoader; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import org.apache.logging.log4j.Logger; @Mod(modid = ImmersiveCraft.MODID, name = ImmersiveCraft.MODNAME, dependencies = "required-after:Forge@[11.15.0.1684,)", useMetadata = true) public class ImmersiveCraft { public static final String MODID = "immcraft"; public static final String MODNAME = "ImmersiveCraft"; @SidedProxy public static CommonProxy proxy; @Mod.Instance public static ImmersiveCraft instance; public static CreativeTabs creativeTab; public static Logger logger; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event){ logger = event.getModLog(); creativeTab = new CreativeTabs("immcraft") { @Override public Item getTabIconItem() { return Items.apple; } }; proxy.preInit(event); } @Mod.EventHandler public void init(FMLInitializationEvent e) { proxy.init(e); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent e) { proxy.postInit(e); } public static class CommonProxy { public void preInit(FMLPreInitializationEvent e) { PacketHandler.registerMessages("immcraft"); ConfigSetup.preInit(e); ModBlocks.init(); ModItems.init(); WorldGen.init(); } public void init(FMLInitializationEvent e) { MinecraftForge.EVENT_BUS.register(new ForgeEventHandlers()); ModBlocks.initCrafting(); ModItems.initCrafting(); } public void postInit(FMLPostInitializationEvent e) { ConfigSetup.postInit(); } } public static class ClientProxy extends CommonProxy { @Override public void preInit(FMLPreInitializationEvent e) { super.preInit(e); MinecraftForge.EVENT_BUS.register(new ClientForgeEventHandlers()); OBJLoader.instance.addDomain(MODID); ModBlocks.initModels(); ModItems.initModels(); } @Override public void init(FMLInitializationEvent e) { super.init(e); FMLCommonHandler.instance().bus().register(new InputHandler()); KeyBindings.init(); // ModBlocks.initItemModels(); } } public static class ServerProxy extends CommonProxy { } }
package me.dreamteam.tardis; public class HowToPlay { /* DEPRECATED CLASS - NO LONGER IN USE AND WILL BE REMOVED IN CONSEQUENT UPDATES */ }
package me.dzhmud.euler; /** * Common interface for solutions. * * @author dzhmud */ public interface EulerSolution { java.lang.String getAnswer(); class SolutionNotFoundException extends RuntimeException { public SolutionNotFoundException() { } public SolutionNotFoundException(String message) { super(message); } } }
package net.glowstone; import net.glowstone.entity.GlowPlayer; import net.glowstone.net.message.play.game.WorldBorderMessage; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.WorldBorder; public class GlowWorldBorder implements WorldBorder { private final World world; private double size; private double futureSize; private double step; private Location center; private double damageBuffer; private double damagePerBlock; private int warningTime; private int warningDistance; private long time; private long lastWorldTick; /** * Initializes a new {@link WorldBorder} for the given world. * * @param world the world to initialize a new {@link WorldBorder} for. */ public GlowWorldBorder(World world) { this.world = world; lastWorldTick = world.getFullTime(); size = 60000000; time = 0; futureSize = size; step = 0; center = new Location(world, 0, 0, 0); damageBuffer = 5; damagePerBlock = 0.2; warningTime = 15; warningDistance = 5; } /** * Creates a {@link WorldBorderMessage} containing information to initialize the world border on * the client-side. * * @return a new {@link WorldBorderMessage} for this world border. */ public WorldBorderMessage createMessage() { return new WorldBorderMessage( WorldBorderMessage.Action.INITIALIZE, center.getX(), center.getZ(), size, futureSize, time * 1000, 29999984, warningTime, warningDistance); } /** * Pulses the world border for each tick. * * <p>Attempts to call this method more than once per tick will be ignored. */ public void pulse() { if (lastWorldTick >= world.getFullTime()) { // The pulse method is being called more than once per tick; abort. return; } lastWorldTick = world.getFullTime(); if (step != 0) { size += step; if (Math.abs(size - futureSize) < 1) { // completed size = futureSize; time = 0; step = 0; } } } @Override public void reset() { setSize(60000000); time = 0; futureSize = size; step = 0; setCenter(new Location(world, 0, 0, 0)); setDamageBuffer(5); setDamageAmount(0.2); setWarningTime(15); setWarningDistance(5); } @Override public double getSize() { return size; } @Override public void setSize(double size) { this.size = size; this.futureSize = size; broadcast(new WorldBorderMessage(WorldBorderMessage.Action.SET_SIZE, size)); } @Override public void setSize(double size, long seconds) { if (seconds <= 0) { setSize(size); return; } long ticks = seconds * 20; step = (size - this.size) / (double) ticks; futureSize = size; time = seconds; broadcast(new WorldBorderMessage( WorldBorderMessage.Action.LERP_SIZE, this.size, futureSize, time * 1000)); } @Override public Location getCenter() { return center; } @Override public void setCenter(Location location) { center = location.clone(); broadcast(new WorldBorderMessage( WorldBorderMessage.Action.SET_CENTER, center.getX(), center.getZ())); } @Override public void setCenter(double x, double z) { setCenter(new Location(world, x, 0, z)); } @Override public double getDamageBuffer() { return damageBuffer; } @Override public void setDamageBuffer(double blocks) { this.damageBuffer = blocks; } @Override public double getDamageAmount() { return damagePerBlock; } @Override public void setDamageAmount(double damage) { this.damagePerBlock = damage; } @Override public int getWarningTime() { return warningTime; } @Override public void setWarningTime(int seconds) { this.warningTime = seconds; broadcast(new WorldBorderMessage(WorldBorderMessage.Action.SET_WARNING_TIME, seconds)); } @Override public int getWarningDistance() { return warningDistance; } @Override public void setWarningDistance(int distance) { this.warningDistance = distance; broadcast(new WorldBorderMessage(WorldBorderMessage.Action.SET_WARNING_BLOCKS, distance)); } @Override public boolean isInside(Location location) { Location max = center.clone().add(size / 2, 0, size / 2); Location min = center.clone().subtract(size / 2, 0, size / 2); return location.getX() <= max.getX() && location.getZ() <= max.getZ() && location.getX() >= min.getX() && location.getZ() >= min.getZ(); } /** * The target side length the world border is being resized to, in blocks. * * @return the target side length the world border is being resized to. */ public double getSizeLerpTarget() { return futureSize; } /** * The delay in ticks until the world border's sides should reach the target length. * * @return the delay until the world border's sides should reach the target length. */ public long getSizeLerpTime() { return time; } private void broadcast(WorldBorderMessage message) { world.getPlayers().forEach(player -> ((GlowPlayer) player).getSession().send(message)); } }
package net.glowstone; import lombok.Getter; import lombok.Setter; import net.glowstone.entity.GlowPlayer; import net.glowstone.net.message.play.game.WorldBorderMessage; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.WorldBorder; public class GlowWorldBorder implements WorldBorder { private final World world; @Getter private double size; /** * The target side length the world border is being resized to, in blocks. * * @return the target side length the world border is being resized to. */ @Getter private double sizeLerpTarget; private double step; @Getter private Location center; @Getter @Setter private double damageBuffer; @Getter @Setter private double damageAmount; @Getter private int warningTime; @Getter private int warningDistance; /** * The delay in ticks until the world border's sides should reach the target length. * * @return the delay until the world border's sides should reach the target length. */ @Getter private long sizeLerpTime; private long lastWorldTick; /** * Initializes a new {@link WorldBorder} for the given world. * * @param world the world to initialize a new {@link WorldBorder} for. */ public GlowWorldBorder(World world) { this.world = world; lastWorldTick = world.getFullTime(); size = 60000000; sizeLerpTime = 0; sizeLerpTarget = size; step = 0; center = new Location(world, 0, 0, 0); damageBuffer = 5; damageAmount = 0.2; warningTime = 15; warningDistance = 5; } /** * Creates a {@link WorldBorderMessage} containing information to initialize the world border on * the client-side. * * @return a new {@link WorldBorderMessage} for this world border. */ public WorldBorderMessage createMessage() { return new WorldBorderMessage( WorldBorderMessage.Action.INITIALIZE, center.getX(), center.getZ(), size, sizeLerpTarget, sizeLerpTime * 1000, 29999984, warningTime, warningDistance); } /** * Pulses the world border for each tick. * * <p>Attempts to call this method more than once per tick will be ignored. */ public void pulse() { if (lastWorldTick >= world.getFullTime()) { // The pulse method is being called more than once per tick; abort. return; } lastWorldTick = world.getFullTime(); if (step != 0) { size += step; if (Math.abs(size - sizeLerpTarget) < 1) { // completed size = sizeLerpTarget; sizeLerpTime = 0; step = 0; } } } @Override public void reset() { setSize(60000000); sizeLerpTime = 0; sizeLerpTarget = size; step = 0; setCenter(new Location(world, 0, 0, 0)); setDamageBuffer(5); setDamageAmount(0.2); setWarningTime(15); setWarningDistance(5); } @Override public void setSize(double size) { this.size = size; this.sizeLerpTarget = size; broadcast(new WorldBorderMessage(WorldBorderMessage.Action.SET_SIZE, size)); } @Override public void setSize(double size, long seconds) { if (seconds <= 0) { setSize(size); return; } long ticks = seconds * 20; step = (size - this.size) / (double) ticks; sizeLerpTarget = size; sizeLerpTime = seconds; broadcast(new WorldBorderMessage(WorldBorderMessage.Action.LERP_SIZE, this.size, sizeLerpTarget, sizeLerpTime * 1000)); } @Override public void setCenter(Location location) { center = location.clone(); broadcast(new WorldBorderMessage( WorldBorderMessage.Action.SET_CENTER, center.getX(), center.getZ())); } @Override public void setCenter(double x, double z) { setCenter(new Location(world, x, 0, z)); } @Override public void setWarningTime(int seconds) { this.warningTime = seconds; broadcast(new WorldBorderMessage(WorldBorderMessage.Action.SET_WARNING_TIME, seconds)); } @Override public void setWarningDistance(int distance) { this.warningDistance = distance; broadcast(new WorldBorderMessage(WorldBorderMessage.Action.SET_WARNING_BLOCKS, distance)); } @Override public boolean isInside(Location location) { Location max = center.clone().add(size / 2, 0, size / 2); Location min = center.clone().subtract(size / 2, 0, size / 2); return location.getX() <= max.getX() && location.getZ() <= max.getZ() && location.getX() >= min.getX() && location.getZ() >= min.getZ(); } private void broadcast(WorldBorderMessage message) { world.getPlayers().forEach(player -> ((GlowPlayer) player).getSession().send(message)); } }
package nl.peterbloem.motive.exec; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.nodes.DGraph; import org.nodes.DiskDGraph; import org.nodes.Graph; import org.nodes.compression.Functions; import org.nodes.data.Data; import org.nodes.data.GML; import org.nodes.data.RDF; import nl.peterbloem.kit.Global; public class Run { @Option( name="--type", usage="Selects the type of experiment, one of: synth (synthetic graph experiment), full (motif extraction with all null models), fast (skip the DS model), preload (load a large graph into a db file), class (classification experiment).") private static String type = "fast"; @Option( name="--preload.out", usage="Output file.") private static File outFile = new File("./graph.db"); @Option( name="--samples", usage="Number of samples to take.") private static int samples = 1000000; @Option( name="--minsize", usage="Minimum motif size in nodes (inclusive).") private static int minSize = 3; @Option( name="--maxsize", usage="Maximum motif size in nodes (inclusive).") private static int maxSize = 6; @Option( name="--maxmotifs", usage="Maximum number of motifs to test.") private static int maxMotifs = 100; @Option(name="--file", usage="Input file: a graph in edge-list encoding (2 tab separated integers per line). Multiple edges and self-loops are ignored. If type is class, this should be an RDF file.") private static File file; @Option(name="--class.table", usage="TSV file containing the classification experiment.") private static File classTSV; @Option(name="--filetype", usage="Filetype: edgelist, gml or graph (ie. a file created with \"--type preload\")") private static String filetype = "edgelist"; @Option(name="--undirected", usage="If the input should be interpeted as undirected (only for edgelist files).") private static boolean undirected = false; @Option(name="--threads", usage="Number of threads to run simultaneaously. Default is the number of cores available. In full mode, there will always be at least 2 concurrent threads, even if this value is 1.") private static int threads = Global.numThreads(); @Option( name="--fast.graphloop", usage="Loop over the graph instead of the instances when computing the score. A little faster when there are many instances, but a lot slower when there are few.") private static boolean graphLoop = false; @Option( name="--fast.disk", usage="Use the disk to store the graph. Slower, but uses very little memory. Supports graphs up to billions of links (disk space permitting).") private static boolean useDisk = false; @Option( name="--full.depth", usage="The search depth for the DS model.") private static int dsDepth = 3; @Option( name="--full.mix", usage="What proportion of available cores to use for motif computation (with the rest used for sampling). Changing this parameter won't affect the end result, but it might lead to better utilitzation of the available cores. If 1.0, the motif scores are computed one by one, sequentially, and the free cores are used to sample for the DS model. If 0.0, the motif scores are computed in parallel, and sampling is done single-threaded.") private static double mix = 0.4; @Option(name="--help", usage="Print usage information.", aliases={"-h"}, help=true) private static boolean help = false; @Option( name="--synth.repeats", usage="How often the synth experiment should be repeated.") private static int synthRepeats = 10; @Option( name="--synth.n", usage="Number of nodes in the sampled graph.") private static int synthN = 5000; @Option( name="--synth.m", usage="Number of links in the sampled graph.") private static int synthM = 10000; @Option( name="--synth.instances", usage="Number of motif instances to inject. Should be a list of comma-separated ints (no spaces).") private static String synthNumInstances = "0,10,100"; @Option( name="--synth.maxdegree", usage="Maximum degree for an instance node.") private static int synthMaxDegree = 5; @Option( name="--class.prob", usage="Fanmod probability of expanding a search tree node (1.0 enumerates all subgraphs, lower means a smaller sample, and lower runtime)") private static double classProb = 0.5; @Option( name="--class.hubs", usage="Number of hubs to remove from the data (the more hubs removed, the smaller the instances become.") private static int classHubs = 0; @Option( name="--class.fanmodSamples", usage="Number of samples from the null model in the FANMOD experiment.") private static int classFMSamples = 1000; @Option( name="--class.motiveSamples", usage="Number of subgraphs to sample in the motive experiment.") private static int classMotiveSamples = 1000000; @Option( name="--class.depth", usage="Depth to which to extract the instances.") private static int classDepth = 2; @Option( name="--class.mixingTime", usage="Mixing time for the curveball sampling algorithm (ie. the number of steps taken in the markov chain for each sample).") private static int classMixingTime = 10000; @Option( name="--class.numInstances", usage="The number of instances to use (samples from the total available)") private static int classNumInstances = 100; /** * Main executable function * @param args */ public static void main(String[] args) { Run run = new Run(); // * Parse the command-line arguments CmdLineParser parser = new CmdLineParser(run); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("java -jar motive.jar [options...]"); parser.printUsage(System.err); System.exit(1); } if(help) { parser.printUsage(System.out); System.exit(0); } Global.setNumThreads(threads); Global.log().info("Using " + Global.numThreads() + " concurrent threads"); if ("class".equals(type.toLowerCase())) { ClassExperiment exp = new ClassExperiment(); try { exp.graph = RDF.readSimple(file); } catch (IOException e) { throw new RuntimeException("Could not read RDF input file.", e); } try { exp.map = ClassExperiment.tsv(classTSV); } catch (IOException e) { throw new RuntimeException("Could not read TSV classification file.", e); } exp.prob = classProb; exp.hubsToRemove = classHubs; exp.samples = classFMSamples; exp.motiveSamples = classMotiveSamples; exp.instanceDepth = classDepth; exp.mixingTime = classMixingTime; exp.numInstances = classNumInstances; try { exp.main(args); } catch (IOException e) { throw new RuntimeException(e); } } else if ("preload".equals(type.toLowerCase())) { try { File tmpDir = new File("./tmp/"); tmpDir.mkdir(); DiskDGraph graph = DiskDGraph.fromFile(file, tmpDir, outFile); graph.close(); for(File file : tmpDir.listFiles()) file.delete(); tmpDir.delete(); } catch(IOException e) { throw new RuntimeException("Something went wrong reading or writing files.", e); } } else if ("synth".equals(type.toLowerCase())) { Global.log().info("Experiment type: synthetic"); Synthetic synth = new Synthetic(); // * Set the parameters synth.runs = synthRepeats; synth.n = synthN; synth.m = synthM; synth.maxDegree = synthMaxDegree; List<Integer> numInstances = new ArrayList<Integer>(); try{ for(String elem : synthNumInstances.split(",")) { numInstances.add(Integer.parseInt(elem)); } } catch(RuntimeException e) { throw new RuntimeException("Failed to parse num instances argument: " + synthNumInstances + " (does it contain spaces, or non-integers?)." , e); } synth.numsInstances = numInstances; // * Run the experiment Global.log().info("Starting experiment."); Functions.tic(); try { synth.main(); } catch(IOException e) { throw new RuntimeException("Encountered a problem when writing the results to disk.", e); } Global.log().info("Experiment finished. Time taken: "+(Functions.toc())+" seconds."); } else if ("fast".equals(type.toLowerCase())) { Global.log().info("Experiment type: fast"); if(undirected) throw new IllegalArgumentException("fast experiment is currently only implemented for directed graphs (please make a ticket on the github page if you need this feature for undirected graphs)."); DGraph<String> data; try { if("edgelist".equals(filetype.toLowerCase().trim())) { data = useDisk ? DiskDGraph.fromFile(file, new File("./tmp/")) : Data.edgeListDirectedUnlabeledSimple(file); } else if ("gml".equals(filetype.toLowerCase().trim())) { if(!useDisk) throw new IllegalArgumentException("GML is not supported with mode fast.disk"); Graph<String> graph = GML.read(file); if(! (graph instanceof DGraph<?>)) throw new IllegalArgumentException("Input file seems to describe an undirected graph. This is not (yet) supported for the fast mode."); data = (DGraph<String>) graph; } else if("db".equals(filetype.toLowerCase().trim())) { data = DiskDGraph.fromDB(file); } else { throw new IllegalArgumentException("File type ("+filetype+") not recognized."); } } catch (IOException e) { throw new IllegalArgumentException("There was a problem reading the input file ("+file+").", e); } CompareLarge large = new CompareLarge(); large.dataName = file.getName(); large.data = data; large.motifMinSize = minSize; large.motifMaxSize = maxSize; large.maxMotifs = maxMotifs; large.motifSamples = samples; large.graphLoop = graphLoop; Global.log().info("Starting experiment."); Functions.tic(); try { large.main(); } catch(IOException e) { throw new RuntimeException("Encountered a problem when writing the results to disk.", e); } Global.log().info("Experiment finished. Time taken: "+(Functions.toc())+" seconds."); if(useDisk) { File dir = new File("./tmp/"); for(File file : dir.listFiles()) file.delete(); dir.delete(); } } else if ("full".equals(type.toLowerCase())) { Global.log().info("Experiment type: full"); Graph<String> data; try { if("edgelist".equals(filetype.trim().toLowerCase())) { if(undirected) data = Data.edgeListUndirectedUnlabeled(file, true); // TODO: read as simple graph (like directed) else data = Data.edgeListDirectedUnlabeledSimple(file); } else if ("edgelist".equals(filetype.trim().toLowerCase())) { data = GML.read(file); } else { throw new IllegalArgumentException("File type ("+filetype+") not recognized."); } } catch (IOException e) { throw new IllegalArgumentException("There was a problem reading the input file ("+file+")."); } Compare full = new Compare(); full.dataName = file.getName(); full.data = data; full.motifMinSize = minSize; full.motifMaxSize = maxSize; full.maxMotifs = maxMotifs; full.motifSamples = samples; full.betaSearchDepth = dsDepth; full.mix = mix; Global.log().info("Starting experiment."); Functions.tic(); try { full.main(); } catch(IOException e) { throw new RuntimeException("Encountered a problem when writing the results to disk.", e); } Global.log().info("Experiment finished. Time taken: "+(Functions.toc())+" seconds."); } else { Global.log().severe("Experiment type " + type + " not recognized. Exiting."); System.err.println("java -jar motive.jar [options...]"); parser.printUsage(System.err); System.exit(-1); } } }
package org.cactoos.io; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import org.cactoos.Input; import org.cactoos.text.BytesAsText; import org.cactoos.text.UncheckedText; import org.w3c.dom.ls.LSInput; // @checkstyle AbbreviationAsWordInNameCheck (10 lines) /** * Input as LSInput. * * <p>There is no thread-safety guarantee. * * @author Yegor Bugayenko (yegor256@gmail.com) * @version $Id$ * @since 0.6 */ public final class InputAsLSInput implements LSInput { /** * The input. */ private final Input input; /** * PublicID. */ private final String pid; /** * SystemID. */ private final String sid; /** * Base. */ private final String base; /** * Ctor. * @param inpt Input */ public InputAsLSInput(final Input inpt) { this(inpt, "#public", "#system", "#base"); } // @checkstyle ParameterNumberCheck (10 lines) /** * Ctor. * @param inpt Input * @param pubid PublicID * @param sysid SystemID * @param bse Base */ public InputAsLSInput(final Input inpt, final String pubid, final String sysid, final String bse) { this.input = inpt; this.pid = pubid; this.sid = sysid; this.base = bse; } @Override public Reader getCharacterStream() { return new InputStreamReader( this.getByteStream(), StandardCharsets.UTF_8 ); } @Override public void setCharacterStream(final Reader stream) { throw new UnsupportedOperationException( "#setCharacterStream() is not supported" ); } @Override public InputStream getByteStream() { return new UncheckedInput(this.input).stream(); } @Override public void setByteStream(final InputStream stream) { throw new UnsupportedOperationException( "#setByteStream() is not supported" ); } @Override public String getStringData() { return new UncheckedText( new BytesAsText(new InputAsBytes(this.input)) ).asString(); } @Override public void setStringData(final String data) { throw new UnsupportedOperationException( "#setStringData() is not supported" ); } @Override public String getSystemId() { return this.sid; } @Override public void setSystemId(final String sysid) { throw new UnsupportedOperationException( "#setSystemId() is not supported" ); } @Override public String getPublicId() { return this.pid; } @Override public void setPublicId(final String pubid) { throw new UnsupportedOperationException( "#setPublicId() is not supported" ); } @Override public String getBaseURI() { return this.base; } @Override public void setBaseURI(final String uri) { throw new UnsupportedOperationException( "#setBaseURI() is not supported" ); } @Override public String getEncoding() { return StandardCharsets.UTF_8.displayName(); } @Override public void setEncoding(final String encoding) { throw new UnsupportedOperationException( "#setEncoding() is not supported" ); } @Override @SuppressWarnings("PMD.BooleanGetMethodName") public boolean getCertifiedText() { return true; } @Override public void setCertifiedText(final boolean text) { throw new UnsupportedOperationException( "#setCertifiedText() is not supported" ); } }
package org.dita.dost.ant; import static org.dita.dost.util.Constants.*; import static org.apache.commons.io.FileUtils.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.DITAOTAntLogger; import org.dita.dost.util.FileUtils; import org.dita.dost.util.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * This class is for converting charset and escaping * entities in html help component files. * * @version 1.0 2010-09-30 * * @author Zhang Di Hua */ public final class ConvertLang extends Task { private static final String ATTRIBUTE_FORMAT_VALUE_WINDOWS = "windows"; private static final String ATTRIBUTE_FORMAT_VALUE_HTML = "html"; private static final String tag1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; private static final String tag2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>[OPTIONS]"; private static final String tag3 = "&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;"; private static final String CODEPAGE_ISO_8859_1 = "iso-8859-1"; private static final String CODEPAGE_ISO_8859_2 = "iso-8859-2"; private static final String CODEPAGE_ISO_8859_7 = "iso-8859-7"; private static final String CODEPAGE_1250 = "windows-1250"; private static final String CODEPAGE_1252 = "windows-1252"; private static final String CODEPAGE_1253 = "windows-1253"; private String basedir; private String outputdir; private String message; private String langcode; //charset map(e.g html = iso-8859-1) private final Map<String, String>charsetMap = new HashMap<>(); //lang map(e.g ar- = 0x0c01 Arabic (EGYPT)) private final Map<String, String>langMap = new HashMap<>(); //entity map(e.g 38 = &amp;) private final Map<String, String>entityMap = new HashMap<>(); //Exceptions that should not generate entities private Set<Integer> entityExceptionSet; //Charset currently stored in exception list private String exceptionCharset; private DITAOTLogger logger; /** * Executes the Ant task. */ @Override public void execute(){ logger = new DITAOTAntLogger(getProject()); logger.info(message); //ensure outdir is absolute if (!new File(outputdir).isAbsolute()) { outputdir = new File(basedir, outputdir).getAbsolutePath(); } //initialize language map createLangMap(); //initialize entity map createEntityMap(); //Initialize entitye exceptions entityExceptionSet = new HashSet<>(128); //initialize charset map createCharsetMap(); //change charset of html files convertHtmlCharset(); //update entity and lang code updateAllEntitiesAndLangs(); } private void createLangMap() { final Properties entities = new Properties(); InputStream in = null; try { in = getClass().getClassLoader().getResourceAsStream("org/dita/dost/util/languages.properties"); entities.load(in); } catch (final IOException e) { throw new RuntimeException("Failed to read language property file: " + e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (final IOException e) {} } } for (final Entry<Object, Object> e: entities.entrySet()) { langMap.put((String) e.getKey(), (String) e.getValue()); } } private void createEntityMap(){ final Properties entities = new Properties(); InputStream in = null; try { in = getClass().getClassLoader().getResourceAsStream("org/dita/dost/util/entities.properties"); entities.load(in); } catch (final IOException e) { throw new RuntimeException("Failed to read entities property file: " + e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (final IOException e) {} } } for (final Entry<Object, Object> e: entities.entrySet()) { entityMap.put((String) e.getKey(), (String) e.getValue()); } } private void createCharsetMap() { InputStream in = null; try { in = getClass().getClassLoader().getResourceAsStream("org/dita/dost/util/codepages.xml"); final DocumentBuilder builder = XMLUtils.getDocumentBuilder(); final Document doc = builder.parse(in); final Element root = doc.getDocumentElement(); final NodeList childNodes = root.getChildNodes(); //search the node with langcode for(int i = 0; i< childNodes.getLength(); i++){ final Node node = childNodes.item(i); //only for element node if(node.getNodeType() == Node.ELEMENT_NODE){ final Element e = (Element)node; final String lang = e.getAttribute(ATTRIBUTE_NAME_LANG); //node found if(langcode.equalsIgnoreCase(lang)|| lang.startsWith(langcode)){ //store the value into a map //charsetMap = new HashMap<String, String>(); //iterate child nodes skip the 1st one final NodeList subChild = e.getChildNodes(); for(int j = 0; j< subChild.getLength(); j++){ final Node subNode = subChild.item(j); if(subNode.getNodeType() == Node.ELEMENT_NODE){ final Element elem = (Element)subNode; final String format = elem.getAttribute(ATTRIBUTE_NAME_FORMAT); final String charset = elem.getAttribute(ATTRIBUTE_NAME_CHARSET); //store charset into map charsetMap.put(format, charset); } } break; } } } //no matched charset is found set default value en-us if(charsetMap.size() == 0){ charsetMap.put(ATTRIBUTE_FORMAT_VALUE_HTML, "iso-8859-1"); charsetMap.put(ATTRIBUTE_FORMAT_VALUE_WINDOWS, "windows-1252"); } } catch (final Exception e) { throw new RuntimeException("Failed to read charset configuration file: " + e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (final IOException e) {} } } } private String replaceXmlTag(final String source,final String tag){ final int startPos = source.indexOf(tag); final int endPos = startPos + tag.length(); return source.substring(0, startPos) + source.substring(endPos); } private void convertHtmlCharset() { final File outputDir = new File(outputdir); final File[] files = outputDir.listFiles(); if (files != null) { for (final File file : files) { //Recursive method convertCharset(file); } } } //Recursive method private void convertCharset(final File inputFile){ if(inputFile.isDirectory()){ final File[] files = inputFile.listFiles(); if (files != null) { for (final File file : files) { convertCharset(file); } } }else if(FileUtils.isHTMLFile(inputFile.getName())|| FileUtils.isHHCFile(inputFile.getName())|| FileUtils.isHHKFile(inputFile.getName())){ final String fileName = inputFile.getAbsolutePath(); final File outputFile = new File(fileName + FILE_EXTENSION_TEMP); log("Processing " + fileName, Project.MSG_INFO); BufferedReader reader = null; Writer writer = null; try { //prepare for the input and output final FileInputStream inputStream = new FileInputStream(inputFile); final InputStreamReader streamReader = new InputStreamReader(inputStream, UTF8); reader = new BufferedReader(streamReader); final FileOutputStream outputStream = new FileOutputStream(outputFile); final OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, UTF8); writer = new BufferedWriter(streamWriter); String value = reader.readLine(); while(value != null){ //meta tag contains charset found if(value.contains("<meta http-equiv") && value.contains("charset")){ final int insertPoint = value.indexOf("charset=") + "charset=".length(); final String subString = value.substring(0, insertPoint); final int remainIndex = value.indexOf(UTF8) + UTF8.length(); final String remainString = value.substring(remainIndex); //change the charset final String newValue = (FileUtils.isHHCFile(inputFile.getName()) || FileUtils.isHHKFile(inputFile.getName()) ? subString + charsetMap.get(ATTRIBUTE_FORMAT_VALUE_WINDOWS) + remainString : subString + charsetMap.get(ATTRIBUTE_FORMAT_VALUE_HTML) + remainString); //write into the output file writer.write(newValue); //add line break writer.write(LINE_SEPARATOR); }else{ if(value.contains(tag1)){ value = replaceXmlTag(value,tag1); }else if(value.contains(tag2)){ value = replaceXmlTag(value,tag2); }else if(value.contains(tag3)){ value = replaceXmlTag(value,tag3); } //other values writer.write(value); writer.write(LINE_SEPARATOR); } value = reader.readLine(); } } catch (final FileNotFoundException e) { logger.error(e.getMessage(), e) ; } catch (final UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (final IOException e) { logger.error(e.getMessage(), e) ; } finally { if (reader != null) { try { reader.close(); } catch (final IOException e) { logger.error("Failed to close input stream: " + e.getMessage()); } } if (writer != null) { try { writer.close(); } catch (final IOException e) { logger.error("Failed to close output stream: " + e.getMessage()); } } } try { deleteQuietly(inputFile); moveFile(outputFile, inputFile); } catch (final Exception e) { logger.error("Failed to replace " + inputFile + ": " + e.getMessage()); } } } private void updateAllEntitiesAndLangs() { final File outputDir = new File(outputdir); final File[] files = outputDir.listFiles(); if (files != null) { for (final File file : files) { //Recursive method updateEntityAndLang(file); } } } //Recursive method private void updateEntityAndLang(final File inputFile) { //directory case if(inputFile.isDirectory()){ final File[] files = inputFile.listFiles(); if (files != null) { for (final File file : files) { updateEntityAndLang(file); } } } //html file case else if(FileUtils.isHTMLFile(inputFile.getName())){ //do converting work convertEntityAndCharset(inputFile, ATTRIBUTE_FORMAT_VALUE_HTML); } //hhp/hhc/hhk file case else if(FileUtils.isHHPFile(inputFile.getName()) || FileUtils.isHHCFile(inputFile.getName()) || FileUtils.isHHKFile(inputFile.getName())){ //do converting work convertEntityAndCharset(inputFile, ATTRIBUTE_FORMAT_VALUE_WINDOWS); //update language setting of hhp file final String fileName = inputFile.getAbsolutePath(); final File outputFile = new File(fileName + FILE_EXTENSION_TEMP); //get new charset final String charset = charsetMap.get(ATTRIBUTE_FORMAT_VALUE_WINDOWS); BufferedReader reader = null; BufferedWriter writer = null; try { //prepare for the input and output final FileInputStream inputStream = new FileInputStream(inputFile); final InputStreamReader streamReader = new InputStreamReader(inputStream, charset); //wrapped into reader reader = new BufferedReader(streamReader); final FileOutputStream outputStream = new FileOutputStream(outputFile); //convert charset final OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, charset); //wrapped into writer writer = new BufferedWriter(streamWriter); String value = reader.readLine(); while(value != null){ if(value.contains(tag1)){ value = replaceXmlTag(value,tag1); }else if(value.contains(tag2)){ value = replaceXmlTag(value,tag2); }else if(value.contains(tag3)){ value = replaceXmlTag(value,tag3); } //meta tag contains charset found if(value.contains("Language=")){ String newValue = langMap.get(langcode); if (newValue == null) { newValue = langMap.get(langcode.split("-")[0]); } if (newValue != null) { writer.write("Language=" + newValue); writer.write(LINE_SEPARATOR); } else { throw new IllegalArgumentException("Unsupported language code '" + langcode + "', unable to map to a Locale ID."); } }else{ //other values writer.write(value); writer.write(LINE_SEPARATOR); } value = reader.readLine(); } } catch (final FileNotFoundException e) { logger.error(e.getMessage(), e) ; } catch (final UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (final IOException e) { logger.error(e.getMessage(), e) ; } finally { if (reader != null) { try { reader.close(); } catch (final IOException e) { logger.error("Failed to close input stream: " + e.getMessage()); } } if (writer != null) { try { writer.close(); } catch (final IOException e) { logger.error("Failed to close output stream: " + e.getMessage()); } } } try { deleteQuietly(inputFile); moveFile(outputFile, inputFile); } catch (final Exception e) { logger.error("Failed to replace " + inputFile + ": " + e.getMessage()); } } } private void updateExceptionCharacters(final String charset) { if (exceptionCharset != null && exceptionCharset.equals(charset)) { return; } exceptionCharset = charset; if (!entityExceptionSet.isEmpty()) { entityExceptionSet.clear(); } if (charset.equals(CODEPAGE_ISO_8859_2) || charset.equals(CODEPAGE_1250) || charset.equals(CODEPAGE_ISO_8859_1) || charset.equals(CODEPAGE_1252)) { entityExceptionSet.add(193); entityExceptionSet.add(225);//A-acute entityExceptionSet.add(194); entityExceptionSet.add(226);//A-circumflex entityExceptionSet.add(196); entityExceptionSet.add(228);//A-umlaut entityExceptionSet.add(199); entityExceptionSet.add(231);//C-cedilla entityExceptionSet.add(201); entityExceptionSet.add(233);//E-acute entityExceptionSet.add(203); entityExceptionSet.add(235);//E-umlaut entityExceptionSet.add(205); entityExceptionSet.add(237);//I-acute entityExceptionSet.add(206); entityExceptionSet.add(238);//I-circumflex entityExceptionSet.add(211); entityExceptionSet.add(243);//O-acute entityExceptionSet.add(212); entityExceptionSet.add(244);//O-circumflex entityExceptionSet.add(214); entityExceptionSet.add(246);//O-umlaut entityExceptionSet.add(218); entityExceptionSet.add(250);//U-acute entityExceptionSet.add(220); entityExceptionSet.add(252);//U-umlaut entityExceptionSet.add(221); entityExceptionSet.add(253);//Y-acute entityExceptionSet.add(223); //Szlig entityExceptionSet.add(215); //&times; } if (charset.equals(CODEPAGE_ISO_8859_1) || charset.equals(CODEPAGE_1252)) { entityExceptionSet.add(192); entityExceptionSet.add(224);//A-grave entityExceptionSet.add(195); entityExceptionSet.add(227);//A-tilde entityExceptionSet.add(197); entityExceptionSet.add(229);//A-ring entityExceptionSet.add(198); entityExceptionSet.add(230);//AElig entityExceptionSet.add(200); entityExceptionSet.add(232);//E-grave entityExceptionSet.add(202); entityExceptionSet.add(234);//E-circumflex entityExceptionSet.add(204); entityExceptionSet.add(236);//I-grave entityExceptionSet.add(207); entityExceptionSet.add(239);//I-uml entityExceptionSet.add(208); entityExceptionSet.add(240);//ETH entityExceptionSet.add(209); entityExceptionSet.add(241);//N-tilde entityExceptionSet.add(210); entityExceptionSet.add(242);//O-grave entityExceptionSet.add(213); entityExceptionSet.add(245);//O-tilde entityExceptionSet.add(216); entityExceptionSet.add(248);//O-slash entityExceptionSet.add(217); entityExceptionSet.add(249);//U-grave entityExceptionSet.add(219); entityExceptionSet.add(251);//O-circumflex entityExceptionSet.add(222); entityExceptionSet.add(254);//Thorn entityExceptionSet.add(255);//y-umlaut } else if (charset.equals(CODEPAGE_ISO_8859_2) || charset.equals(CODEPAGE_1250)) { entityExceptionSet.add(352); entityExceptionSet.add(353);//S-caron } else if (charset.equals(CODEPAGE_ISO_8859_7) || charset.equals(CODEPAGE_1253)) { entityExceptionSet.add(913); entityExceptionSet.add(945);//Alpha entityExceptionSet.add(914); entityExceptionSet.add(946); entityExceptionSet.add(915); entityExceptionSet.add(947); entityExceptionSet.add(916); entityExceptionSet.add(948); entityExceptionSet.add(917); entityExceptionSet.add(949); entityExceptionSet.add(918); entityExceptionSet.add(950); entityExceptionSet.add(919); entityExceptionSet.add(951); entityExceptionSet.add(920); entityExceptionSet.add(952); entityExceptionSet.add(921); entityExceptionSet.add(953); entityExceptionSet.add(922); entityExceptionSet.add(954); entityExceptionSet.add(923); entityExceptionSet.add(955); entityExceptionSet.add(924); entityExceptionSet.add(956); entityExceptionSet.add(925); entityExceptionSet.add(957); entityExceptionSet.add(926); entityExceptionSet.add(958); entityExceptionSet.add(927); entityExceptionSet.add(959); entityExceptionSet.add(928); entityExceptionSet.add(960); entityExceptionSet.add(929); entityExceptionSet.add(961); entityExceptionSet.add(930); entityExceptionSet.add(962); entityExceptionSet.add(931); entityExceptionSet.add(963); entityExceptionSet.add(932); entityExceptionSet.add(964); entityExceptionSet.add(933); entityExceptionSet.add(965); entityExceptionSet.add(934); entityExceptionSet.add(966); entityExceptionSet.add(935); entityExceptionSet.add(967); entityExceptionSet.add(936); entityExceptionSet.add(968); entityExceptionSet.add(937); entityExceptionSet.add(969);//Omega } } private void convertEntityAndCharset(final File inputFile, final String format) { final String fileName = inputFile.getAbsolutePath(); final File outputFile = new File(fileName + FILE_EXTENSION_TEMP); BufferedReader reader = null; BufferedWriter writer = null; try { //prepare for the input and output final FileInputStream inputStream = new FileInputStream(inputFile); final InputStreamReader streamReader = new InputStreamReader(inputStream, UTF8); //wrapped into reader reader = new BufferedReader(streamReader); final FileOutputStream outputStream = new FileOutputStream(outputFile); //get new charset final String charset = charsetMap.get(format); //convert charset final OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, charset); //wrapped into writer writer = new BufferedWriter(streamWriter); updateExceptionCharacters(charset); //read a character int charCode = reader.read(); while(charCode != -1){ final String key = String.valueOf(charCode); //Is an entity char if (entityMap.containsKey(key) && !entityExceptionSet.contains(charCode)) { //get related entity final String value = entityMap.get(key); //write entity into output file writer.write(value); } else { //normal process writer.write(charCode); } charCode = reader.read(); } } catch (final IOException e) { logger.error(e.getMessage(), e) ; } finally { if (reader != null) { try { reader.close(); } catch (final IOException e) { logger.error("Failed to close input stream: " + e.getMessage()); } } if (writer != null) { try { writer.close(); } catch (final IOException e) { logger.error("Failed to close output stream: " + e.getMessage()); } } } try { deleteQuietly(inputFile); moveFile(outputFile, inputFile); } catch (final Exception e) { logger.error("Failed to replace " + inputFile + ": " + e.getMessage()); } } public void setBasedir(final String basedir) { this.basedir = basedir; } public void setLangcode(final String langcode) { this.langcode = langcode; } public void setMessage(final String message) { this.message = message; } public void setOutputdir(final String outputdir) { this.outputdir = outputdir; } }
package org.javacs; import com.google.common.collect.ImmutableList; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import org.eclipse.lsp4j.*; import org.eclipse.lsp4j.services.LanguageClient; import org.eclipse.lsp4j.services.LanguageServer; import org.eclipse.lsp4j.services.TextDocumentService; import org.eclipse.lsp4j.services.WorkspaceService; class JavaLanguageServer implements LanguageServer { private static final Logger LOG = Logger.getLogger("main"); Path workspaceRoot; LanguageClient client; JavaCompilerService compiler; final JavaTextDocumentService textDocuments = new JavaTextDocumentService(this); final JavaWorkspaceService workspace = new JavaWorkspaceService(this); private static DiagnosticSeverity severity(javax.tools.Diagnostic.Kind kind) { switch (kind) { case ERROR: return DiagnosticSeverity.Error; case WARNING: case MANDATORY_WARNING: return DiagnosticSeverity.Warning; case NOTE: case OTHER: default: return DiagnosticSeverity.Information; } } private static Position position(String content, long offset) { int line = 0, column = 0; for (int i = 0; i < offset; i++) { if (content.charAt(i) == '\n') { line++; column = 0; } else column++; } return new Position(line, column); } void publishDiagnostics(Collection<URI> files, List<Diagnostic<? extends JavaFileObject>> javaDiagnostics) { for (URI f : files) { List<org.eclipse.lsp4j.Diagnostic> ds = new ArrayList<>(); for (Diagnostic<? extends JavaFileObject> j : javaDiagnostics) { URI uri = j.getSource().toUri(); if (uri.equals(f)) { String content = textDocuments.contents(uri).content; Position start = position(content, j.getStartPosition()), end = position(content, j.getEndPosition()); DiagnosticSeverity sev = severity(j.getKind()); org.eclipse.lsp4j.Diagnostic d = new org.eclipse.lsp4j.Diagnostic(); d.setSeverity(sev); d.setRange(new Range(start, end)); d.setCode(j.getCode()); d.setMessage(j.getMessage(null)); ds.add(d); } } client.publishDiagnostics(new PublishDiagnosticsParams(f.toString(), ds)); } } void lint(Collection<URI> uris) { LOG.info("Lint " + uris.stream().map(uri -> uri.toString()).collect(Collectors.joining(", "))); List<Path> paths = uris.stream().map(uri -> Paths.get(uri)).collect(Collectors.toList()); publishDiagnostics(uris, compiler.lint(paths)); } private JavaCompilerService createCompiler() { Objects.requireNonNull(workspaceRoot, "Can't create compiler because workspaceRoot has not been initialized"); InferConfig infer = new InferConfig(workspaceRoot); return new JavaCompilerService( InferSourcePath.sourcePath(workspaceRoot), infer.classPath(), infer.buildDocPath()); } @Override public CompletableFuture<InitializeResult> initialize(InitializeParams params) { this.workspaceRoot = Paths.get(URI.create(params.getRootUri())); this.compiler = createCompiler(); InitializeResult result = new InitializeResult(); ServerCapabilities c = new ServerCapabilities(); c.setTextDocumentSync(TextDocumentSyncKind.Incremental); c.setDefinitionProvider(true); c.setCompletionProvider(new CompletionOptions(true, ImmutableList.of("."))); c.setHoverProvider(true); c.setWorkspaceSymbolProvider(true); c.setReferencesProvider(true); c.setDocumentSymbolProvider(true); c.setSignatureHelpProvider(new SignatureHelpOptions(ImmutableList.of("(", ","))); c.setDocumentFormattingProvider(true); result.setCapabilities(c); return CompletableFuture.completedFuture(result); } @Override public CompletableFuture<Object> shutdown() { return CompletableFuture.completedFuture(null); } @Override public void exit() {} @Override public TextDocumentService getTextDocumentService() { return textDocuments; } @Override public WorkspaceService getWorkspaceService() { return workspace; } void installClient(LanguageClient client) { this.client = client; } }
package org.jsapar; import org.jsapar.compose.bean.*; import org.jsapar.convert.AbstractConverter; import org.jsapar.convert.ConvertTask; import org.jsapar.parse.bean.BeanMap; import org.jsapar.parse.text.TextParseConfig; import org.jsapar.parse.text.TextParseTask; import org.jsapar.schema.Schema; import java.beans.IntrospectionException; import java.io.IOException; import java.io.Reader; /** * Converts text input to Java bean objects. You can choose to use the standard behavior or you may customize assigning * of bean properties. The default behavior is to use the schema names where the line type name needs to match the class * name of the class to create and the cell names needs to match bean property names. Any sub-objects needs to be of a * class that provides a default constructor. By supplying a {@link BeanMap} instance to the constructor you can map * different line and cell names to property names. {@link BeanMap} instance can be created form an xml input by using * the {@link BeanMap#ofXml(Reader)} method. * * See {@link AbstractConverter} for details about error handling and manipulating data. * @see AbstractConverter */ public class Text2BeanConverter<T> extends AbstractConverter { private final Schema parseSchema; private BeanFactory<T> beanFactory; private BeanComposeConfig composeConfig = new BeanComposeConfig(); private TextParseConfig parseConfig = new TextParseConfig(); /** * Creates a converter with supplied composer schema. * @param parseSchema The schema to use while reading the text input. * @param beanMap The bean map to use to map schema names to bean properties. By supplying a {@link BeanMap} instance to the constructor you can map * different line and cell names to property names. {@link BeanMap} instance can be created form an xml input by using * the {@link BeanMap#ofXml(Reader)} method. */ public Text2BeanConverter(Schema parseSchema, BeanMap beanMap) { this.parseSchema = parseSchema; this.beanFactory = new BeanFactoryByMap<>(beanMap); } /** * The default behavior is to use the schema names where the line type name needs to match the class * name of the class to create and the cell names needs to match bean property names. * @param parseSchema The schema to use while reading the text input. * @throws IntrospectionException If a referenced property * @throws ClassNotFoundException If a class d */ public Text2BeanConverter(Schema parseSchema) throws IntrospectionException, ClassNotFoundException { this(parseSchema, BeanMap.ofSchema(parseSchema)); } /** * Assigns a different bean factory. The bean factory is responsible for creating beans and assigning bean values. You may implement your own or use any of the existing: * <ul> * <li>{@link BeanFactoryByMap} - Default for this class. Uses input schema with optional {@link BeanMap} to map properties.</li> * <li>{@link BeanFactoryDefault} - Default if no schema is present. Uses cell names to guess the property names.</li> * </ul> * @param beanFactory The bean factory to use. */ public void setBeanFactory(BeanFactory<T> beanFactory) { this.beanFactory = beanFactory; } /** * Executes the actual convert. Will produce a callback to supplied eventListener for each bean that is parsed. * @param reader The reader to read the text from. * @param eventListener The callback interface which will receive a callback for each bean that is successfully parsed. * @return Number of converted beans. * @throws IOException In case of io error. */ public long convert(Reader reader, BeanEventListener<T> eventListener) throws IOException { BeanComposer<T> composer = new BeanComposer<>(composeConfig, beanFactory); ConvertTask convertTask = new ConvertTask(new TextParseTask(this.parseSchema, reader, parseConfig), composer); composer.setComposedEventListener(eventListener); if (beanFactory != null) composer.setBeanFactory(beanFactory); return execute(convertTask); } public void setComposeConfig(BeanComposeConfig composeConfig) { this.composeConfig = composeConfig; } public BeanComposeConfig getComposeConfig() { return composeConfig; } public TextParseConfig getParseConfig() { return parseConfig; } public void setParseConfig(TextParseConfig parseConfig) { this.parseConfig = parseConfig; } }
package org.kohsuke.youdebug; import com.sun.jdi.connect.IllegalConnectorArgumentsException; import com.sun.tools.attach.AgentInitializationException; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.AttachNotSupportedException; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; /** * Entry point. */ public class YouDebug { @Option(name="-pid",usage="Attaches to the local process of the given PID") public int pid = -1; @Option(name="-socket",usage="Attaches to the target process by a socket",metaVar="[HOST:]PORT") public String remote = null; // @Option(name="-force") // public boolean force = false; @Argument public File script; public int debugLevel=0; @Option(name="-debug",usage="Increase the debug output level. Specify multiple times to get more detailed logging") public void setDebugLevel(boolean b) { debugLevel++; } public static void main(String[] args) throws Exception { // locate tools.jar first String home = System.getProperty("java.home"); File toolsJar = new File(new File(home), "../lib/tools.jar"); if (!toolsJar.exists()) { toolsJar = new File(new File(home), "../Classes/classes.jar"); if (!toolsJar.exists()) { System.err.println("This tool requires a JDK, but you are running Java from "+home); System.exit(1); } } // shove tools.jar into the classpath ClassLoader cl = ClassLoader.getSystemClassLoader(); Method m = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); m.setAccessible(true); m.invoke(cl,toolsJar.toURL()); YouDebug main = new YouDebug(); CmdLineParser p = new CmdLineParser(main); try { p.parseArgument(args); System.exit(main.run()); } catch (CmdLineException e) { System.out.println(e.getMessage()); System.out.println("Usage: java -jar youdebug.jar [options...] [script file]"); p.printUsage(System.out); System.exit(1); } } public int run() throws CmdLineException, IOException, IllegalConnectorArgumentsException, InterruptedException, AgentInitializationException, AgentLoadException, AttachNotSupportedException { if (debugLevel>0) { ConsoleHandler h = new ConsoleHandler(); h.setLevel(Level.ALL); Logger logger = Logger.getLogger("org.kohsuke.youdebug"); Level lv; switch (debugLevel) { case 1: lv = Level.FINE; break; case 2: lv = Level.FINER; break; default: lv = Level.FINEST; break; } logger.setLevel(lv); logger.addHandler(h); } VM vm = null; if (pid>=0) { vm = VMFactory.connectLocal(pid); // try { // } catch (IOException e) { // VirtualMachine avm = VirtualMachine.attach(String.valueOf(pid)); // ServerSocket ss = new ServerSocket(); // int port =ss.getLocalPort(); // ss.close(); // System.out.println("Trying x"); // avm.loadAgentLibrary("jdwp","transport=dt_socket,server=y,suspend=n,address=9999"); // avm.detach(); // remote = "127.0.0.1:"+port; } if (remote!=null) { String[] tokens = remote.split(":"); if (tokens.length==1) tokens = new String[]{"localhost",tokens[0]}; if (tokens.length!=2) throw new CmdLineException("Invalid argument to the -socket option: "+remote); vm = VMFactory.connectRemote(tokens[0],Integer.valueOf(tokens[1])); } if (vm==null) throw new CmdLineException("Neither -pid nor -socket option was specified"); vm.execute(script!=null ? script : null); return 0; } }
package org.lightmare.rest; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.model.Resource; import org.lightmare.cache.RestContainer; import org.lightmare.rest.providers.JacksonFXmlFeature; import org.lightmare.rest.providers.ObjectMapperProvider; import org.lightmare.rest.providers.ResourceBuilder; import org.lightmare.rest.providers.RestReloader; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Dynamically manage REST resources, implementation of {@link ResourceConfig} * class to add and remove {@link Resource}'s and reload at runtime * * @author Levan Tsinadze * @since 0.0.50-SNAPSHOT */ public class RestConfig extends ResourceConfig { // Collection of resources before registration private Set<Resource> preResources; // Reloader instance (implementation of ContainerLifecycleListener class) private RestReloader reloader = RestReloader.get(); private static final Lock LOCK = new ReentrantLock(); public RestConfig(boolean changeCache) { super(); RestConfig config = RestContainer.getRestConfig(); register(ObjectMapperProvider.class); register(JacksonFXmlFeature.class); ObjectUtils.lock(LOCK); try { if (reloader == null) { reloader = new RestReloader(); } this.registerInstances(reloader); if (ObjectUtils.notNull(config)) { // Adds resources to pre-resources from existing cached // configuration this.addPreResources(config); Map<String, Object> properties = config.getProperties(); if (CollectionUtils.valid(properties)) { addProperties(properties); } } if (changeCache) { RestContainer.setRestConfig(this); } } finally { ObjectUtils.unlock(LOCK); } } public RestConfig() { this(Boolean.TRUE); } /** * Caches this instance of {@link RestConfig} in {@link RestContainer} cache */ public void cache() { RestConfig config = RestContainer.getRestConfig(); if (ObjectUtils.notEquals(this, config)) { RestContainer.setRestConfig(this); } } /** * Clears deployed REST {@link Resource}s for deploy ervices */ private void clearResources() { Set<Resource> resources = getResources(); if (CollectionUtils.valid(resources)) { getResources().clear(); } } /** * Registers {@link Resource}s from passed {@link RestConfig} as * {@link RestConfig#preResources} cache * * @param oldConfig */ public void registerAll(RestConfig oldConfig) { clearResources(); Set<Resource> newResources; newResources = new HashSet<Resource>(); if (ObjectUtils.notNull(oldConfig)) { Set<Resource> olds = oldConfig.getResources(); if (CollectionUtils.valid(olds)) { newResources.addAll(olds); } } registerResources(newResources); } public void addPreResource(Resource resource) { if (this.preResources == null || this.preResources.isEmpty()) { this.preResources = new HashSet<Resource>(); } this.preResources.add(resource); } public void addPreResources(Collection<Resource> preResources) { if (CollectionUtils.valid(preResources)) { if (this.preResources == null || this.preResources.isEmpty()) { this.preResources = new HashSet<Resource>(); } this.preResources.addAll(preResources); } } public void addPreResources(RestConfig oldConfig) { if (ObjectUtils.notNull(oldConfig)) { addPreResources(oldConfig.getResources()); addPreResources(oldConfig.preResources); } } private void removePreResource(Resource resource) { if (CollectionUtils.valid(preResources)) { preResources.remove(resource); } } /** * Caches {@link Resource} created from passed {@link Class} for further * registration * * @param resourceClass * @param oldConfig * @throws IOException */ public void registerClass(Class<?> resourceClass, RestConfig oldConfig) throws IOException { Resource.Builder builder = Resource.builder(resourceClass); Resource preResource = builder.build(); Resource resource = ResourceBuilder.rebuildResource(preResource); addPreResource(resource); } /** * Removes {@link Resource} created from passed {@link Class} from * pre-resources cache * * @param resourceClass */ public void unregister(Class<?> resourceClass) { Resource resource = RestContainer.getResource(resourceClass); removePreResource(resource); } /** * Registers all cached {@link org.glassfish.jersey.server.model.Resource} * instances */ public void registerPreResources() { if (CollectionUtils.valid(preResources)) { RestContainer.putResources(preResources); registerResources(preResources); } } }