@Nullable
  public static PsiElement invokeCreateCompilerPass(
      @NotNull PhpClass bundleClass, @Nullable Editor editor) {
    String className =
        Messages.showInputDialog(
            "Class name for CompilerPass (no namespace needed): ",
            "New File",
            Symfony2Icons.SYMFONY);
    if (StringUtils.isBlank(className)) {
      return null;
    }

    if (!PhpNameUtil.isValidClassName(className)) {
      Messages.showMessageDialog(
          bundleClass.getProject(), "Invalid class name", "Error", Symfony2Icons.SYMFONY);
    }

    try {
      return PhpBundleFileFactory.createCompilerPass(bundleClass, className);
    } catch (Exception e) {
      if (editor != null) {
        HintManager.getInstance().showErrorHint(editor, "Error:" + e.getMessage());
      } else {
        JOptionPane.showMessageDialog(null, "Error:" + e.getMessage());
      }
    }

    return null;
  }
  /** Sets current LAF. The method doesn't update component hierarchy. */
  @Override
  public void setCurrentLookAndFeel(UIManager.LookAndFeelInfo lookAndFeelInfo) {
    if (findLaf(lookAndFeelInfo.getClassName()) == null) {
      LOG.error("unknown LookAndFeel : " + lookAndFeelInfo);
      return;
    }
    // Set L&F
    if (IdeaLookAndFeelInfo.CLASS_NAME.equals(
        lookAndFeelInfo.getClassName())) { // that is IDEA default LAF
      IdeaLaf laf = new IdeaLaf();
      MetalLookAndFeel.setCurrentTheme(new IdeaBlueMetalTheme());
      try {
        UIManager.setLookAndFeel(laf);
      } catch (Exception e) {
        Messages.showMessageDialog(
            IdeBundle.message(
                "error.cannot.set.look.and.feel", lookAndFeelInfo.getName(), e.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return;
      }
    } else if (DarculaLookAndFeelInfo.CLASS_NAME.equals(lookAndFeelInfo.getClassName())) {
      DarculaLaf laf = new DarculaLaf();
      try {
        UIManager.setLookAndFeel(laf);
        JBColor.setDark(true);
        IconLoader.setUseDarkIcons(true);
      } catch (Exception e) {
        Messages.showMessageDialog(
            IdeBundle.message(
                "error.cannot.set.look.and.feel", lookAndFeelInfo.getName(), e.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return;
      }
    } else { // non default LAF
      try {
        LookAndFeel laf =
            ((LookAndFeel) Class.forName(lookAndFeelInfo.getClassName()).newInstance());
        if (laf instanceof MetalLookAndFeel) {
          MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
        }
        UIManager.setLookAndFeel(laf);
      } catch (Exception e) {
        Messages.showMessageDialog(
            IdeBundle.message(
                "error.cannot.set.look.and.feel", lookAndFeelInfo.getName(), e.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return;
      }
    }
    myCurrentLaf =
        ObjectUtils.chooseNotNull(findLaf(lookAndFeelInfo.getClassName()), lookAndFeelInfo);

    checkLookAndFeel(lookAndFeelInfo, false);
  }
Exemple #3
0
  public static Object loadFrame(
      JopSession session, String className, String instance, boolean scrollbar)
      throws ClassNotFoundException {

    if (className.indexOf(".pwg") != -1) {
      GrowFrame frame =
          new GrowFrame(
              className, session.getGdh(), instance, new GrowFrameCb(session), session.getRoot());
      frame.validate();
      frame.setVisible(true);
    } else {
      Object frame;
      if (instance == null) instance = "";

      JopLog.log(
          "JopSpider.loadFrame: Loading frame \"" + className + "\" instance \"" + instance + "\"");
      try {
        Class clazz = Class.forName(className);
        try {
          Class argTypeList[] =
              new Class[] {session.getClass(), instance.getClass(), boolean.class};
          Object argList[] = new Object[] {session, instance, new Boolean(scrollbar)};
          System.out.println("JopSpider.loadFrame getConstructor");
          Constructor constructor = clazz.getConstructor(argTypeList);

          try {
            frame = constructor.newInstance(argList);
          } catch (Exception e) {
            System.out.println(
                "Class instanciation error: "
                    + className
                    + " "
                    + e.getMessage()
                    + " "
                    + constructor);
            return null;
          }
          // frame = clazz.newInstance();
          JopLog.log("JopSpider.loadFrame openFrame");
          openFrame(frame);
          return frame;
        } catch (NoSuchMethodException e) {
          System.out.println("NoSuchMethodException: Unable to get frame constructor " + className);
        } catch (Exception e) {
          System.out.println(
              "Exception: Unable to get frame class " + className + " " + e.getMessage());
        }
      } catch (ClassNotFoundException e) {
        System.out.println("Class not found: " + className);
        throw new ClassNotFoundException();
      }
      return null;
    }
    return null;
  }
Exemple #4
0
  public MainFrame() {
    super("P2 Auto Update and Automatic Build Test");

    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
      System.out.println("Error loading System Look and Feel: " + e.getMessage());
      try {
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
      } catch (Exception ex) {
        System.out.println("Error loading CrossPlatform Look and Feel: " + e.getMessage());
      }
    }

    LabelOne one = new LabelOne();
    LabelTwo two = new LabelTwo();
    LabelThree three = new LabelThree();
    LabelFour four = new LabelFour();

    JPanel mainPanel = new JPanel();
    GroupLayout layout = new GroupLayout(mainPanel);
    mainPanel.setLayout(layout);

    layout.setAutoCreateContainerGaps(true);
    layout.setAutoCreateGaps(true);

    layout.setHorizontalGroup(
        layout
            .createParallelGroup()
            .addComponent(one)
            .addComponent(two)
            .addComponent(three)
            .addComponent(four));

    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addComponent(one)
            .addComponent(two)
            .addComponent(three)
            .addComponent(four));

    this.addWindowListener(this);

    this.add(mainPanel);
    this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    this.pack();
    this.setVisible(true);
  }
Exemple #5
0
  protected void flushSerialBuffer() throws RunnerException, SerialException {
    // Cleanup the serial buffer
    try {
      Serial serialPort = new Serial();
      byte[] readBuffer;
      while (serialPort.available() > 0) {
        readBuffer = serialPort.readBytes();
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
        }
      }

      serialPort.setDTR(false);
      serialPort.setRTS(false);

      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
      }

      serialPort.setDTR(true);
      serialPort.setRTS(true);

      serialPort.dispose();
    } catch (SerialNotFoundException e) {
      throw e;
    } catch (Exception e) {
      e.printStackTrace();
      throw new RunnerException(e.getMessage());
    }
  }
  @Override
  public synchronized void run() {
    try {
      for (int i = 0; i < NUM_PIPES; i++) {
        while (Thread.currentThread() == reader[i]) {
          try {
            this.wait(100);
          } catch (InterruptedException ie) {
          }
          if (pin[i].available() != 0) {
            String input = this.readLine(pin[i]);
            appendMsg(htmlize(input));
            if (textArea.getDocument().getLength() > 0) {
              textArea.setCaretPosition(textArea.getDocument().getLength() - 1);
            }
          }
          if (quit) {
            return;
          }
        }
      }

    } catch (Exception e) {
      Debug.error(me + "Console reports an internal error:\n%s", e.getMessage());
    }
  }
Exemple #7
0
  public static void main(String[] args) {
    String propertyFile;
    // create the command line parser
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption(
        "f",
        "file",
        true,
        "A property file containing values to override auto-detected field values (optional)");

    CommandLine line;
    Properties properties = new Properties();
    try {

      line = parser.parse(options, args);

      if (line.hasOption('f')) {
        propertyFile = line.getOptionValue('f');
        properties.load(new FileReader(propertyFile));
      }

    } catch (Exception e) {
      log.error(e.getMessage() + "\n Start aborted!");
      System.exit(1);
    }

    WSNGui gui = new WSNGui(properties);
    gui.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    gui.frame.setVisible(true);
  }
Exemple #8
0
  @Override
  public void run() {

    try {
      if (Fecs.getApplicationContext() == null) return;

      Long currentTime = System.currentTimeMillis();
      double deltaTime = (currentTime - lastUpdateTime) * 0.001;

      if (getEngineState() == STATE_START) { // last bit is 1 = started
        int s = getCircumstanceState() - 1; // 0 is null state(error)
        if (s >= CircumstanceType.values().length || s < 0)
          throw new Exception("unstable state value with " + String.valueOf(s));
        Circumstance.get(CircumstanceType.values()[s])
            .setParameter("currentTime", currentTime)
            .setParameter("deltaTime", deltaTime)
            .trigger();
        for (Cabin cabin : cabins.values()) updateCabin(cabin, deltaTime);
      }

      lastUpdateTime = currentTime;

      draw();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    } finally {
      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
      }
      SwingUtilities.invokeLater(this);
    }
  }
  void onDelete() {
    TreePath path = m_tree.getSelectionPath();
    if (path != null) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();

      Object[] options = {"Yes", "No"};
      int choise =
          JOptionPane.showOptionDialog(
              pohaci.gumunda.cgui.GumundaMainFrame.getMainFrame(),
              "Are you sure deleting this " + node + " ?",
              "Confirm",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              options,
              options[1]);

      if (choise == JOptionPane.YES_OPTION) {
        try {
          deleteNodeParent(node);
        } catch (Exception ex) {
          JOptionPane.showMessageDialog(
              this, ex.getMessage(), "Warning", JOptionPane.WARNING_MESSAGE);
        }
      }
    }
  }
Exemple #10
0
  private void applyMark() {
    try {
      final String channelName = applyMarkLChannelNameTextField.getText();
      final String description = applyMarkDescrTextField.getText();
      final String link = applyMarkLinkTextField.getText();
      final String title = applyMarkTitleTextField.getText();
      final double lon = Double.parseDouble(applyMarkLonTextField.getText());
      final double lat = Double.parseDouble(applyMarkLatTextField.getText());
      final JSONObject applyMarkResult =
          Geo2TagService.applyMark(
              authToken,
              channelName,
              description,
              StringUtils.isEmpty(link) ? "unknown" : link,
              lat,
              lon,
              new Date(),
              title);
      applyMarkStatusBar.setText(
          applyMarkResult.optString(Geo2TagConstants.Params.STATUS_DESCRIPTION));

    } catch (final Exception e) {
      applyMarkStatusBar.setText("Error: " + e.getMessage());
      System.out.println("Error: " + e);
      e.printStackTrace();
    }
  }
Exemple #11
0
  @Override
  public void actionPerformed(ActionEvent event) {
    // Rearrange the data structures.
    String[] s_param_names = new String[param_names.length];
    String[] s_return_types = new String[return_types.length];

    for (int i = 0; i < param_names.length; i++) s_param_names[i] = param_names[i].getText();

    for (int i = 0; i < return_types.length; i++) s_return_types[i] = return_types[i].getText();

    String method_name = this.gui_method_name.getText();
    String method_return_type = this.gui_method_return_type.getText();

    Operation method_target = this.target;
    RefactoringUndoManager.saveFile();

    if (change_method_signature(
        method_target, method_name, method_return_type, s_param_names, s_return_types)) {

      // Get rid of the dialog box.

      try {
        boolean status = (new CheckConstraints()).validateUML();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(
            this, ex.getMessage() + "\n\n" + "Going to revert back to the original state.");
        RefactoringUndoManager.reloadbackUp();
      }

      this.dispose();
    } else {
      JOptionPane.showMessageDialog(
          null, "Invalid input!", "Input validator", JOptionPane.INFORMATION_MESSAGE);
    }
  }
  // Fees update method
  private void updateFeesData(long id) {
    String columns[] = {"Course", "Fees Payed", "Total fees", "Installments"};
    try {
      Database db = new Database();

      panel_7.removeAll();

      feestablemodel = new MyTableModel(db.getFeeData(id), columns);

      feestable = new JTable(feestablemodel);
      feestable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      feestable.getSelectionModel().addListSelectionListener(this);

      feesscrollpane = new JScrollPane(feestable);
      panel_7.add(feesscrollpane);

      // change fees payed label
      feespayedlabel.setText("Fees Payed");
      feesduelabel.setText("Fees Due");
      totalfeeslabel.setText("Total Fees");

      panel_7.revalidate();
    } catch (Exception e) {
      JOptionPane.showMessageDialog(this, e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
    }
  }
Exemple #13
0
  /**
   * 向服务器发送命令行,给服务器端处理
   *
   * @param lines 命令行
   */
  public static void clientSend(String[] lines) {
    if (lines != null && lines.length <= 0) {
      return;
    }
    Socket socket = null;
    PrintWriter writer = null;
    try {
      socket = new Socket("localhost", port);

      writer =
          new PrintWriter(
              new BufferedWriter(
                  new OutputStreamWriter(
                      socket.getOutputStream(), EncodeConstants.ENCODING_UTF_8)));
      for (int i = 0; i < lines.length; i++) {
        writer.println(lines[i]);
      }

      writer.flush();
    } catch (Exception e) {
      FRContext.getLogger().error(e.getMessage(), e);
    } finally {
      try {
        writer.close();
        socket.close();
      } catch (IOException e) {
        FRContext.getLogger().error(e.getMessage(), e);
      }
    }
  }
Exemple #14
0
  public boolean modifierVideo(
      String oldTitre,
      String titre,
      int annee,
      int eval,
      boolean type,
      String comments,
      String categories) {
    ArrayList<String> arrayCategories = liste.obtenirCles();
    Video video;
    try {
      video = new Video(titre, annee, eval, type);
    } catch (Exception ex) {
      this.messageErreur(ex.getMessage());
      return false;
    }

    video.setCommentaires(comments);

    Video oldVideo = obtenirVideo(oldTitre);

    int indexOfVideo;

    boolean confirmation = false;

    for (String categorie : arrayCategories) {
      indexOfVideo = liste.obtenirIndex(categorie, oldVideo);
      if (indexOfVideo >= 0) {
        confirmation = liste.modifier(categorie, video, indexOfVideo);
      }
    }
    modeModification();
    return confirmation;
  }
Exemple #15
0
  // Big bunch of AJOUTS
  public boolean ajouterVideo(
      String titre, int annee, boolean type, int eval, String comments, String categories) {
    try {
      // Creer un objet video avec TITRE ANNEE TYPE EVAL COMMENTS
      Video video = new Video(titre, annee, eval, type);
      video.setCommentaires(comments);

      String[] arrayCategories = categories.split(System.getProperty("line.separator"));

      boolean confirmation = false;

      // Ajouter cette video dans toutes les categories
      for (String categorie : arrayCategories) {
        confirmation = liste.ajouter(categorie, video);
      }
      if (confirmation) {
        JOptionPane.showMessageDialog(fenetre, video.getTitre() + " ajouté à la liste!");
        return true;
      } else {
        JOptionPane.showMessageDialog(
            fenetre, video.getTitre() + " n'a pas été ajouté à la liste!");
        return false;
      }
    } catch (Exception ex) {
      this.messageErreur(ex.getMessage());
      return false;
    }
  }
 public void excluir(Oriundo oriundo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   String sqlExcluir = "DELETE FROM oriundo WHERE codigo=?";
   try {
     ps = con.prepareStatement(sqlExcluir);
     ps.setInt(1, oriundo.getCodigo());
     ps.executeUpdate();
     JOptionPane.showMessageDialog(
         null, "Ecluido Com Sucesso: ", "Mensagem do Sistema - Excluir", 1);
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Excluir", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
 }
  private void updateEditorView() {
    editorPane.setText("");
    numParameters = 0;
    try {
      java.util.List elements = editableTemplate.getPrintfElements();
      for (Iterator it = elements.iterator(); it.hasNext(); ) {
        PrintfUtil.PrintfElement el = (PrintfUtil.PrintfElement) it.next();
        if (el.getFormat().equals(PrintfUtil.PrintfElement.FORMAT_NONE)) {
          appendText(el.getElement(), PLAIN_ATTR);
        } else {
          insertParameter(
              (ConfigParamDescr) paramKeys.get(el.getElement()),
              el.getFormat(),
              editorPane.getDocument().getLength());
        }
      }
    } catch (Exception ex) {
      JOptionPane.showMessageDialog(
          this,
          "Invalid Format: " + ex.getMessage(),
          "Invalid Printf Format",
          JOptionPane.ERROR_MESSAGE);

      selectedPane = 1;
      printfTabPane.setSelectedIndex(selectedPane);
      updatePane(selectedPane);
    }
  }
  /**
   * Tests out the panel from the command line.
   *
   * @param args ignored.
   */
  public static void main(String[] args) {

    try {
      final JFrame jf = new JFrame("Generator Property Iterator");
      jf.getContentPane().setLayout(new BorderLayout());
      GeneratorPropertyIteratorPanel gp = new GeneratorPropertyIteratorPanel();
      jf.getContentPane().add(gp, BorderLayout.CENTER);
      jf.addWindowListener(
          new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              jf.dispose();
              System.exit(0);
            }
          });
      jf.pack();
      jf.setVisible(true);
      System.err.println("Short nap");
      Thread.currentThread().sleep(3000);
      System.err.println("Done");
      gp.setExperiment(new Experiment());
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println(ex.getMessage());
    }
  }
 /**
  * This is hack. AWT doesn't allow to create KeyStroke with specified key code and key char
  * simultaneously. Therefore we are using reflection.
  */
 private static KeyStroke getKeyStrokeWithoutMouseModifiers(KeyStroke originalKeyStroke) {
   int modifier =
       originalKeyStroke.getModifiers()
           & ~InputEvent.BUTTON1_DOWN_MASK
           & ~InputEvent.BUTTON1_MASK
           & ~InputEvent.BUTTON2_DOWN_MASK
           & ~InputEvent.BUTTON2_MASK
           & ~InputEvent.BUTTON3_DOWN_MASK
           & ~InputEvent.BUTTON3_MASK;
   try {
     Method[] methods = AWTKeyStroke.class.getDeclaredMethods();
     Method getCachedStrokeMethod = null;
     for (Method method : methods) {
       if (GET_CACHED_STROKE_METHOD_NAME.equals(method.getName())) {
         getCachedStrokeMethod = method;
         getCachedStrokeMethod.setAccessible(true);
         break;
       }
     }
     if (getCachedStrokeMethod == null) {
       throw new IllegalStateException("not found method with name getCachedStrokeMethod");
     }
     Object[] getCachedStrokeMethodArgs =
         new Object[] {
           originalKeyStroke.getKeyChar(),
           originalKeyStroke.getKeyCode(),
           modifier,
           originalKeyStroke.isOnKeyRelease()
         };
     return (KeyStroke) getCachedStrokeMethod.invoke(originalKeyStroke, getCachedStrokeMethodArgs);
   } catch (Exception exc) {
     throw new IllegalStateException(exc.getMessage());
   }
 }
  public void initContent(VirtualABoxStatistics statistics) {

    /* Fill the label summary value */
    String message = "";
    try {
      int count = statistics.getTotalTriples();
      message = String.format("%s %s", count, (count == 1 ? "triple" : "triples"));
    } catch (Exception e) {
      message = String.format("%s. Please try again!", e.getMessage());
      errorShown = true;
    }
    lblSummaryValue.setText(message);

    /* Fill the triples summary table */
    final HashMap<String, HashMap<String, Integer>> data = statistics.getStatistics();
    for (String datasourceName : data.keySet()) {

      HashMap<String, Integer> mappingStat = data.get(datasourceName);

      final int row = mappingStat.size();
      final int col = 2;
      final String[] columnNames = {"Mapping ID", "Number of Triples"};

      Object[][] rowData = new Object[row][col];

      int index = 0;
      for (String mappingId : mappingStat.keySet()) {
        rowData[index][0] = mappingId;
        rowData[index][1] = mappingStat.get(mappingId);
        index++;
      }
      JTable tblTriplesCount = createStatisticTable(rowData, columnNames);
      tabDataSources.add(datasourceName, new JScrollPane(tblTriplesCount));
    }
  }
  // initialize data hash table servers
  // read server addresses from file and initialize the servers
  private void initServers() {

    try {
      java.net.URL path = ClassLoader.getSystemResource(clientSettingFile);
      FileReader fr = new FileReader(path.getFile());
      BufferedReader br = new BufferedReader(fr);
      try {
        String[] portMap = br.readLine().split(",");
        mServerCount = portMap.length;
        mPortMap = new int[mServerCount];
        for (int i = 0; i < mServerCount; i++) {
          mPortMap[i] = Integer.parseInt(portMap[i]);
        }
      } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
      }
    } catch (FileNotFoundException e2) {
      e2.printStackTrace();
      System.exit(-1);
    }

    mDhtServerArray = new IDistributedHashTable[mServerCount];
    for (int i = 0; i < mServerCount; i++) {
      try {
        mDhtServerArray[i] =
            (IDistributedHashTable)
                Naming.lookup("rmi://localhost:" + mPortMap[i] + "/DistributedHashTable");
        appendOutput("server: " + (i + 1) + " is connected");
      } catch (Exception e) {
        appendOutput("initServers: " + (i + 1) + " " + e.getMessage());
      }
    }
  }
Exemple #22
0
 @Override
 public boolean importData(JComponent comp, Transferable t) {
   DataFlavor htmlFlavor = DataFlavor.stringFlavor;
   if (canImport(comp, t.getTransferDataFlavors())) {
     try {
       String transferString = (String) t.getTransferData(htmlFlavor);
       EditorPane targetTextPane = (EditorPane) comp;
       for (Map.Entry<String, String> entry : _copiedImgs.entrySet()) {
         String imgName = entry.getKey();
         String imgPath = entry.getValue();
         File destFile = targetTextPane.copyFileToBundle(imgPath);
         String newName = destFile.getName();
         if (!newName.equals(imgName)) {
           String ptnImgName = "\"" + imgName + "\"";
           newName = "\"" + newName + "\"";
           transferString = transferString.replaceAll(ptnImgName, newName);
           Debug.info(ptnImgName + " exists. Rename it to " + newName);
         }
       }
       targetTextPane.insertString(transferString);
     } catch (Exception e) {
       Debug.error(me + "importData: Problem pasting text\n%s", e.getMessage());
     }
     return true;
   }
   return false;
 }
Exemple #23
0
  private ClientDatabase getConfigDatabase() {
    try {
      Path configDir = databaseFile.toAbsolutePath().getParent();
      if (!Files.isDirectory(configDir)) {
        Files.createDirectory(configDir);
      }
      connection = DriverManager.getConnection(getSqliteConnectionString());

      try {
        try (Statement statement = connection.createStatement()) {
          statement.execute("PRAGMA FOREIGN_KEYS = ON");
        }
        ClientDatabase clientDatabase = new ChatClientDatabase(connection);
        clientDatabase.migrate();

        return clientDatabase;
      } catch (Exception e) {
        try {
          connection.close();
        } catch (Exception ignored) {
        }
        throw e;
      }

    } catch (Exception e) {
      throw new IllegalStateException(
          "failed to initialize or migrate config database:" + e.getMessage(), e);
    }
  }
  private void initComponents() {
    // Message - JLabel
    lblMessage =
        new JLabel(
            String.format(
                "An unexpected error has occurred: %s",
                e == null ? "Unexpected exception" : e.getMessage()));
    lblMessage.setIcon(icon);
    lblMessage.setPreferredSize(new Dimension(360, 40));
    lblMessage.setBorder(BorderFactory.createLineBorder(Color.red));

    // txtTrace - ExceptionTracePane
    txtTrace = new ExceptionTracePane();
    txtTrace.setBackground(new Color(92, 0, 0));
    txtTrace.setException(e);

    // srlTrace - JScrollPane
    JPanel traceWrapper = new JPanel(new BorderLayout());
    traceWrapper.add(txtTrace, BorderLayout.CENTER);
    srlTrace = new JScrollPane(traceWrapper);
    srlTrace.setPreferredSize(new Dimension(360, 200));
    srlTrace.setVisible(false);

    // btnDetails - JButton
    btnDetails = new JButton(new DetailsButtonAction());
    btnDetails.setPreferredSize(new Dimension(100, 40));

    // btnClose - JButton
    btnClose = new JButton(new CloseButtonAction());
    btnClose.setDefaultCapable(true);
    btnClose.setPreferredSize(new Dimension(100, 40));
  }
  public void actionPerformed(ActionEvent evt) {
    Object src = evt.getSource();

    try {
      if (src == propDialog) {
        propDialog_actionPerformed(evt);
      } else {
        pdu = new BlockPdu(context);
        if (src == setButton) {
          pdu.setPduType(BlockPdu.SET);
          pdu.addOid(toid.getText(), new AsnOctets(tvalue.getText()));
        } else if (src == getButton) {
          pdu.setPduType(BlockPdu.GET);
          pdu.addOid(toid.getText());
        } else if (src == getNextButton) {
          pdu.setPduType(BlockPdu.GETNEXT);
          pdu.addOid(toid.getText());
        }
        sendRequest(pdu);
      }
    } catch (Exception exc) {
      exc.printStackTrace();
      lmessage.setText("Exception: " + exc.getMessage());
      lmessage.setBackground(Color.red);
    }
  }
Exemple #26
0
  public void run() {
    try {
      AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
      AudioFormat format = ais.getFormat();
      //    System.out.println("Format: " + format);
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
      SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
      source.open(format);
      source.start();
      int read = 0;
      byte[] audioData = new byte[16384];
      while (read > -1) {
        read = ais.read(audioData, 0, audioData.length);
        if (read >= 0) {
          source.write(audioData, 0, read);
        }
      }
      donePlaying = true;

      source.drain();
      source.close();
    } catch (Exception exc) {
      System.out.println("error: " + exc.getMessage());
      exc.printStackTrace();
    }
  }
Exemple #27
0
 /**
  * 动作
  *
  * @param e 事件
  */
 public void actionPerformed(ActionEvent e) {
   DesignerEnvManager envManager = DesignerEnvManager.getEnvManager();
   Env selectedEnv = envManager.getEnv(this.getName());
   try {
     if (selectedEnv instanceof RemoteEnv && !((RemoteEnv) selectedEnv).testServerConnection()) {
       JOptionPane.showMessageDialog(
           DesignerContext.getDesignerFrame(),
           Inter.getLocText(new String[] {"M-SwitchWorkspace", "Failed"}));
       return;
     }
     String remoteVersion = selectedEnv.getDesignerVersion();
     if (StringUtils.isBlank(remoteVersion)
         || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) {
       String infor = Inter.getLocText("Server-version-tip");
       String moreInfo = Inter.getLocText("Server-version-tip-moreInfo");
       FRLogger.getLogger().log(Level.WARNING, infor);
       new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show();
       return;
     }
     SignIn.signIn(selectedEnv);
     LicUtils.resetBytes();
     HistoryTemplateListPane.getInstance().getCurrentEditingTemplate().refreshToolArea();
     fireDSChanged();
   } catch (Exception em) {
     FRContext.getLogger().error(em.getMessage(), em);
     JOptionPane.showMessageDialog(
         DesignerContext.getDesignerFrame(),
         Inter.getLocText(new String[] {"M-SwitchWorkspace", "Failed"}));
     TemplatePane.getInstance().editItems();
   }
 }
 /**
  * A helper method to save changes
  *
  * @param fileAdaptor
  * @param curatorFrame
  * @return true for saving the changes, while false for an unsuccessful saving. An unsuccessful
  *     saving might result from cancelling or throwing an exception.
  */
 private boolean saveChanges(XMLFileAdaptor fileAdaptor) {
   // Make sure everything is changed
   if (fileAdaptor.isDirty()) {
     int reply =
         JOptionPane.showConfirmDialog(
             this,
             "You have to save changes first before doing synchronization.\n"
                 + "Do you want to save changes and then do synchronization?",
             "Save Changes?",
             JOptionPane.OK_CANCEL_OPTION);
     if (reply == JOptionPane.CANCEL_OPTION) return false;
     try {
       fileAdaptor.save();
       return true;
     } catch (Exception e) {
       JOptionPane.showMessageDialog(
           this,
           "Cannot save changes:" + e.getMessage(),
           "Error in Saving",
           JOptionPane.ERROR_MESSAGE);
       System.err.println("SynchronizationDialog.saveChanges(): " + e);
       e.printStackTrace();
       return false;
     }
   }
   return true;
 }
Exemple #29
0
 private static Clip getClip(String wavFile) {
   String soundName = "sound\\" + wavFile + ".wav";
   InputStream sound = null;
   Clip clip = null;
   try {
     sound = new FileInputStream(soundName);
   } catch (FileNotFoundException ex) {
     sound = ClassLoader.getSystemResourceAsStream(soundName);
     if (sound == null) {
       System.out.println("Cant open file " + soundName);
       return null;
     }
   }
   try {
     AudioInputStream audioIn = AudioSystem.getAudioInputStream(sound);
     clip = AudioSystem.getClip();
     clip.open(audioIn);
   } catch (Exception ex) {
     System.out.println("Error in sound " + wavFile);
     System.out.println(ex.getMessage());
     if (clip != null) {
       clip.close();
       return null;
     }
     try {
       sound.close();
     } catch (IOException e) {
     }
   }
   return clip;
 }
Exemple #30
0
 private void insertString(int pos, String str) {
   Document doc = getDocument();
   try {
     doc.insertString(pos, str, null);
   } catch (Exception e) {
     Debug.error(me + "insertString: Problem while trying to insert at pos\n%s", e.getMessage());
   }
 }