Exemplo n.º 1
0
  private void getPokemon() {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);
      try (Statement s = con.createStatement()) {
        ResultSet rs;

        s.executeQuery("SELECT `name` FROM `pokemon`");
        rs = s.getResultSet();
        this.pokemon.clear();
        while (rs.next()) {
          this.pokemon.add(rs.getString("name"));
        }
        rs.close();
        s.close();
      }
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
  protected Collection<KnowledgePackage> compileResources(
      Map<Resource, ResourceType> resources, boolean enablePropertySpecificFacts) {
    KnowledgeBuilderConfiguration conf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();

    if (enablePropertySpecificFacts) {
      conf.setOption(PropertySpecificOption.ALLOWED);
    } else {
      conf.setOption(PropertySpecificOption.DISABLED);
    }

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(conf);
    for (Map.Entry<Resource, ResourceType> entry : resources.entrySet()) {
      kbuilder.add(entry.getKey(), entry.getValue());
      if (kbuilder.hasErrors()) {
        Logger.getLogger(Case1.class.getName())
            .log(Level.SEVERE, "Compilation Errors in {0}", entry.getKey());
        Iterator<KnowledgeBuilderError> iterator = kbuilder.getErrors().iterator();
        while (iterator.hasNext()) {
          KnowledgeBuilderError knowledgeBuilderError = iterator.next();
          Logger.getLogger(Case1.class.getName())
              .log(Level.SEVERE, knowledgeBuilderError.getMessage());
          System.out.println(knowledgeBuilderError.getMessage());
        }
        throw new IllegalStateException("Compilation Errors");
      }
    }
    return kbuilder.getKnowledgePackages();
  }
Exemplo n.º 3
0
  /** @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) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    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(FrameLoading.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(FrameLoading.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(FrameLoading.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(FrameLoading.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    }
    // </editor-fold>

    /* Create and display the form */

  }
Exemplo n.º 4
0
  public Connection getConnection(String database) {
    try {

      try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();

      } catch (InstantiationException ex) {
        Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
        Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
      }
      try {

        String _DBURL = "";
        if (database.equalsIgnoreCase("zabbix")) {
          _DBURL = this.ZabbixDBURL;
        } else if ("pulsar".equalsIgnoreCase(database)) {
          _DBURL = this.PulsarDBURL;
        } else {
          _DBURL = this.BrokerDBURL;
        }
        this.connection = DriverManager.getConnection(_DBURL);

        return this.connection;

      } catch (SQLException ex) {

        Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
      }

    } catch (ClassNotFoundException ex) {
      Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return this.connection;
  }
Exemplo n.º 5
0
  private String getData(String url, String data) throws WasabiNetClientException {

    StringBuffer sb = new StringBuffer();

    try {
      URL dest = new URL(url);
      URLConnection conn = dest.openConnection();

      conn.setDoOutput(true);

      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF8");
      System.out.println(writer.getEncoding());
      writer.write(data);
      writer.flush();

      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

      char[] buf = new char[MAX_READ];
      int readed = 0;
      while ((readed = reader.read(buf)) > 0) {
        sb.append(buf, 0, readed);
      }

    } catch (MalformedURLException ex) {
      Logger.getLogger(WasabiNetClient.class.getName()).log(Level.SEVERE, null, ex);
      throw new WasabiNetClientException(
          "Error al conectar con la url <" + url + ">:" + ex.getMessage());
    } catch (IOException ex) {
      Logger.getLogger(WasabiNetClient.class.getName()).log(Level.SEVERE, null, ex);
      throw new WasabiNetClientException("Error de lectura/escritura:" + ex.getMessage());
    }

    return sb.toString();
  }
Exemplo n.º 6
0
  private void validateNullableWarns(Injector injector, Dependency<?> dependency) {
    final List<LogRecord> logRecords = Lists.newArrayList();
    final Handler fakeHandler =
        new Handler() {
          @Override
          public void publish(LogRecord logRecord) {
            logRecords.add(logRecord);
          }

          @Override
          public void flush() {}

          @Override
          public void close() throws SecurityException {}
        };
    Logger.getLogger(Guice.class.getName()).addHandler(fakeHandler);
    try {
      injector.getInstance(Integer.class); // no exception, but assert it does log.
      LogRecord record = Iterables.getOnlyElement(logRecords);
      assertEquals(
          "Guice injected null into {0} (a {1}), please mark it @Nullable."
              + " Use -Dguice_check_nullable_provides_params=ERROR to turn this into an"
              + " error.",
          record.getMessage());
      assertEquals(Errors.convert(dependency.getKey()), record.getParameters()[1]);
    } finally {
      Logger.getLogger(Guice.class.getName()).removeHandler(fakeHandler);
    }
  }
Exemplo n.º 7
0
  private void runExperiment(String experimentCode) {
    Class experimentClass =
        Arrays.stream(experimentsAvailable)
            .filter(
                (Class<? extends BaseExperiment> filteredexperimentClass) -> {
                  try {
                    return filteredexperimentClass
                            .getConstructor()
                            .newInstance()
                            .getCodeName()
                            .compareTo(experimentCode)
                        == 0;
                  } catch (Exception ex) {
                    Logger.getLogger(Runner.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  return false;
                })
            .findFirst()
            .orElse(null);

    if (experimentClass != null) {
      try {
        BaseExperiment experiment = (BaseExperiment) experimentClass.getConstructor().newInstance();
        experiment.run(arguments);
      } catch (Exception ex) {
        Logger.getLogger(Runner.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemplo n.º 8
0
  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

    try {

      JOptionPane.showMessageDialog(rootPane, "Creando Pdf ");

      InputStream marca_agua;
      marca_agua = new FileInputStream("plantilla-para-programa02.jpg");
      int añoi = fechai.getCalendar().get(Calendar.YEAR);
      int mesi = fechai.getCalendar().get(Calendar.MONTH) + 1;
      int diai = fechai.getCalendar().get(Calendar.DAY_OF_MONTH);

      fi = añoi + "-" + mesi + "-" + diai;

      int añof = fechaf.getCalendar().get(Calendar.YEAR);
      int mesf = fechaf.getCalendar().get(Calendar.MONTH) + 1;
      int diaf = fechaf.getCalendar().get(Calendar.DAY_OF_MONTH);

      ff = añof + "-" + mesf + "-" + diaf;
      System.out.println(fi);
      System.out.println(ff);
      System.out.println(idc);

      n.conectar();

      Map parameters = new HashMap();

      parameters.put("fechai", fi);
      parameters.put("fechaf", ff);
      parameters.put("cliente", idc);
      parameters.put("marca", marca_agua);

      JasperReport report = JasperCompileManager.compileReport("estado_cuenta.jrxml");
      JasperPrint print = JasperFillManager.fillReport(report, parameters, n.coneccion);
      // Exporta el informe a PDF
      JasperExportManager.exportReportToPdfFile(print, "estado_cuenta.pdf");

      JOptionPane.showMessageDialog(rootPane, "Pdf creado correctamente enviando mail ");

      if (email.getText().length() == 0) {

        JOptionPane.showMessageDialog(rootPane, "Ingrese Un correo para poder enviar mail ");

      } else {

        JOptionPane.showMessageDialog(rootPane, "Enviando mail ");
        enviar();
      }

      // Para visualizar el pdf directamente desde java
      // JasperViewer.viewReport(print, false);

    } catch (ClassNotFoundException ex) {
      Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JRException ex) {
      Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
      Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Exemplo n.º 9
0
 /**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html;charset=UTF-8");
   try (PrintWriter out = response.getWriter()) {
     out.println("<html>");
     out.println("<head>");
     out.println("<title>Servlet TestServlet</title>");
     out.println("</head>");
     out.println("<body>");
     out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
     out.println("About to start the job<br>");
     JobOperator jo = BatchRuntime.getJobOperator();
     out.println("Got the job operator: " + jo + "<br>");
     try {
       jo.start("myJob", new Properties());
     } catch (JobSecurityException ex) {
       Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
     }
     out.println("Job submitted<br>");
     out.println("<br><br>Check server.log for output");
     out.println("</body>");
     out.println("</html>");
   } catch (JobStartException ex) {
     Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
Exemplo n.º 10
0
  String getRandomChannelWithVelociraptors(String exclude) {
    Connection con = null;
    String value = "";

    try {
      con = pool.getConnection(timeout);

      PreparedStatement s =
          con.prepareStatement(
              "SELECT `channel` FROM `channels` WHERE `channel` != ? AND `active_velociraptors` > 0 ORDER BY (RAND() * active_velociraptors) DESC LIMIT 1;");
      s.setString(1, exclude);
      s.executeQuery();

      ResultSet rs = s.getResultSet();
      while (rs.next()) {
        value = rs.getString("channel");
      }

      rs.close();
      s.close();
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    return value;
  }
Exemplo n.º 11
0
  void update_war(int db_id, long duration, long remaining, long time_to_start, int current_chain) {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      PreparedStatement s =
          con.prepareStatement(
              "UPDATE `wars` SET `duration` = ? ,`remaining` = ?, `time_to_start` = ?, `current_chain` = ? WHERE id = ?");
      s.setLong(1, duration);
      s.setLong(2, remaining);
      s.setLong(3, time_to_start);
      s.setInt(4, current_chain);
      s.setInt(5, db_id);
      s.executeUpdate();
      s.close();
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemplo n.º 12
0
  void joinChannel(Channel channel) {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      PreparedStatement s = con.prepareStatement("INSERT INTO `channels` (`channel`) VALUES (?)");
      s.setString(1, channel.getName().toLowerCase());
      s.executeUpdate();
      s.close();

      if (!this.channel_data.containsKey(channel.getName().toLowerCase())) {
        ChannelInfo new_channel = new ChannelInfo(channel.getName().toLowerCase());
        new_channel.setDefaultOptions();

        this.channel_data.put(channel.getName().toLowerCase(), new_channel);
      }

      this.saveChannelSettings(this.channel_data.get(channel.getName().toLowerCase()));
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemplo n.º 13
0
  String getSetting(String key) {
    Connection con = null;
    String value = "";

    try {
      con = pool.getConnection(timeout);

      PreparedStatement s = con.prepareStatement("SELECT `value` FROM `settings` WHERE `key` = ?");
      s.setString(1, key);
      s.executeQuery();

      ResultSet rs = s.getResultSet();
      while (rs.next()) {
        value = rs.getString("value");
      }
      rs.close();
      s.close();
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    return value;
  }
Exemplo n.º 14
0
  private void getIgnoreList() {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      Statement s = con.createStatement();
      s.executeQuery("SELECT `name`, `type` FROM `ignores`");

      ResultSet rs = s.getResultSet();
      this.ignore_list.clear();
      this.soft_ignore_list.clear();
      while (rs.next()) {
        if (rs.getString("type").equals("hard")) {
          this.ignore_list.add(rs.getString("name").toLowerCase());
        } else {
          this.soft_ignore_list.add(rs.getString("name").toLowerCase());
        }
      }
      rs.close();
      s.close();
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemplo n.º 15
0
  /**
   * Generate license plates from a file.
   *
   * @param filename
   */
  private void generateLicensePlates(String filename) {
    File licenseplatefile = getResourceFile(filename);
    BufferedReader in = null;
    try {
      in = new BufferedReader(new InputStreamReader(new FileInputStream(licenseplatefile)));
    } catch (FileNotFoundException ex) {
      Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<String> licensePlates = new ArrayList();
    String line;

    try {
      while ((line = in.readLine()) != null) {
        licensePlates.add(line);
      }
    } catch (IOException ex) {
      Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        in.close();
      } catch (IOException ex) {
        Logger.getLogger(MovementsDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    itLicensePlates = licensePlates.iterator();
  }
Exemplo n.º 16
0
  public void handleInit(QuickServer quickserver) throws Exception {
    Logger logger = null;
    FileHandler xmlLog = null;
    File log = new File("./log/");
    if (!log.canRead()) log.mkdir();
    try {
      logger = Logger.getLogger("");
      logger.setLevel(Level.FINEST);

      logger = Logger.getLogger("org.quickserver.net.qsadmin");
      xmlLog = new FileHandler("log/FtpServer_QSAdmin%u%g.xml", 1024 * 1024, 20, true);
      xmlLog.setLevel(Level.FINEST);
      logger.addHandler(xmlLog);

      logger = Logger.getLogger("org.quickserver");
      xmlLog = new FileHandler("log/FtpServer_QuickServer%u%g.xml", 1024 * 1024, 20, true);
      xmlLog.setLevel(Level.FINEST);
      logger.addHandler(xmlLog);

      logger = Logger.getLogger("ftpserver");
      xmlLog = new FileHandler("log/FtpServer%u%g.xml", 1024 * 1024, 20, true);
      xmlLog.setLevel(Level.FINEST);
      logger.addHandler(xmlLog);

      quickserver.setAppLogger(logger); // img
    } catch (IOException e) {
      System.err.println("Could not create txtLog FileHandler : " + e);
      throw e;
    }
  }
Exemplo n.º 17
0
  private static void setBenchmarkConfiguration(int udp_sender, int udp_receiver, boolean verbose) {

    if (verbose) {
      Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).setLevel(Level.ALL);
      for (Handler h : Logger.getLogger("").getHandlers()) h.setLevel(Level.ALL);
      Logger.getLogger(UDPConnector.class.toString()).setLevel(Level.ALL);

    } else {
      Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).setLevel(Level.SEVERE);
      Logger.getLogger("").setLevel(Level.SEVERE);
    }

    // Network configuration optimal for performance benchmarks
    NetworkConfig.createStandardWithoutFile()
        // Disable deduplication OR strongly reduce lifetime
        .setString(NetworkConfigDefaults.DEDUPLICATOR, NetworkConfigDefaults.NO_DEDUPLICATOR)
        .setInt(NetworkConfigDefaults.EXCHANGE_LIFECYCLE, 1500)
        .setInt(NetworkConfigDefaults.MARK_AND_SWEEP_INTERVAL, 2000)

        // Increase buffer for network interface to 10 MB
        .setInt(NetworkConfigDefaults.UDP_CONNECTOR_RECEIVE_BUFFER, 10 * 1024 * 1024)
        .setInt(NetworkConfigDefaults.UDP_CONNECTOR_SEND_BUFFER, 10 * 1024 * 1024)

        // Increase threads for receiving and sending packets through the socket
        .setInt(NetworkConfigDefaults.UDP_CONNECTOR_RECEIVER_THREAD_COUNT, udp_receiver)
        .setInt(NetworkConfigDefaults.UDP_CONNECTOR_SENDER_THREAD_COUNT, udp_sender)

        // Disable message logging
        .setBoolean(NetworkConfigDefaults.UDP_CONNECTOR_LOG_PACKETS, verbose);
  }
  public String getFingerprint() {
    try {
      Envelope e = new Envelope("GETFPRINT");
      e.addObject(nonce);
      nonce++;

      byte[] messageBytes = Envelope.toByteArray(e);

      // send message to request host key's hash
      output.writeObject(messageBytes);

      // receive host key hash
      e = Envelope.getEnvelopefromBytes((byte[]) input.readObject());

      if (e.getMessage().equals("OK") && (Integer) e.getObjContents().get(2) == nonce) {
        nonce++;
        // check publicKey File for server and fingerprint match
        // TODO
        pubKey = (PublicKey) e.getObjContents().get(0);
        return (String) e.getObjContents().get(1);
      } else {
        System.out.println("Nonce FAIL GETFPRINT");
        disconnect();
        return null;
      }
    } catch (ClassNotFoundException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    } catch (IOException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    }
  }
Exemplo n.º 19
0
  @Override
  public void run() {

    BufferedReader br = null;

    try {
      br = new BufferedReader(new FileReader(lista));
      String linha = null;
      while (br.ready()) {
        linha = br.readLine();

        if (sha1Password(linha).equalsIgnoreCase(getRecebe())) {
          System.out.println("Senha é : " + linha);
          System.exit(0);
        }
      }
    } catch (FileNotFoundException ex) {
      Logger.getLogger(DicionarioSha1.class.getName()).log(Level.SEVERE, null, ex);
      System.exit(0);
    } catch (IOException ex) {
      Logger.getLogger(DicionarioSha1.class.getName()).log(Level.SEVERE, null, ex);
      System.exit(0);
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(DicionarioSha2.class.getName()).log(Level.SEVERE, null, ex);
      System.exit(0);
    } finally {
      try {
        br.close();
      } catch (IOException ex) {
        Logger.getLogger(DicionarioSha1.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemplo n.º 20
0
 /** updates the command menu based on the currently selected entities */
 private void updateCommandMenu() {
   commands.clear();
   if (selectedEntities.size() > 0) {
     commands.add(MoveCommand.class);
     commands.add(FollowCommand.class);
     commands.add(EnterCommand.class);
     commands.add(AttackCommand.class);
   }
   clearCommandMenu();
   int i = 0;
   for (Iterator<Class<? extends Command>> it = commands.iterator(); it.hasNext(); ) {
     i++;
     try {
       Class<? extends Command> class1 = it.next();
       commandTexts[i].setText("F" + i + " - " + class1.newInstance().getName() + "  ");
     } catch (InstantiationException ex) {
       Logger.getLogger(UserCommandControl.class.getName()).log(Level.SEVERE, null, ex);
     } catch (IllegalAccessException ex) {
       Logger.getLogger(UserCommandControl.class.getName()).log(Level.SEVERE, null, ex);
     }
     if (i > 10) {
       return;
     }
   }
 }
  public final void readDirectory(
      String propertyDirectory, Languages currentLanguage, String directoryName)
      throws UnsupportedEncodingException, FileNotFoundException {

    String directory = propertyDirectory + "/" + directoryName;
    Logger.getLogger(PropertyFileReader.class.getName())
        .log(Level.INFO, "Reading directory " + directory);

    File file = new File(directory);
    File[] files = file.listFiles();

    if (null == files) {
      throw new FileNotFoundException("Directory " + directory + " does not exist.");
    } else {
      for (int i = 0; i < files.length; i++) {
        try {
          readPropertyFile(files[i], currentLanguage.code);
        } catch (FileNotFoundException ex) {
          Logger.getLogger(PropertyFileReader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
          Logger.getLogger(PropertyFileReader.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }
Exemplo n.º 22
0
 /**
  * issues a command with a location target to the selected entities
  *
  * @param command
  * @param location
  */
 private void doCommand(int command, Vector3f location) {
   for (Iterator<Spatial> it = selectedEntities.iterator(); it.hasNext(); ) {
     Spatial spatial1 = it.next();
     CommandControl commandControl = spatial1.getControl(CommandControl.class);
     if (commandControl == null) {
       return;
     }
     try {
       Command commandInst = commands.get(command).newInstance();
       commandInst.setPriority(10);
       commandControl.clearCommands();
       commandControl.initializeCommand(commandInst);
       Command.TargetResult info = commandInst.setTargetLocation(location);
       if (info == Command.TargetResult.Accept
           || info == Command.TargetResult.AcceptEnemy
           || info == Command.TargetResult.AcceptFriendly) {
         commandControl.addCommand(commandInst);
       }
     } catch (InstantiationException ex) {
       Logger.getLogger(UserCommandControl.class.getName()).log(Level.SEVERE, null, ex);
     } catch (IllegalAccessException ex) {
       Logger.getLogger(UserCommandControl.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
 }
Exemplo n.º 23
0
 public boolean closeDBStreams(Connection connection, PreparedStatement ps, ResultSet rs) {
   boolean status = true;
   if (null != rs) {
     try {
       rs.close();
     } catch (SQLException ex) {
       Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
       status = false;
     }
   }
   if (null != ps) {
     try {
       ps.close();
     } catch (SQLException ex) {
       Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
       status = false;
     }
   }
   if (null != connection) {
     try {
       connection.close();
     } catch (SQLException ex) {
       Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
       status = false;
     }
   }
   if (status) {
     //            Logger.getLogger(DatabaseHandler.class.getName()).info("Successfuly closed all
     // Database streams...");
   } else {
     Logger.getLogger(DatabaseHandler.class.getName())
         .severe("Could not close all Database streams... This may lead to memory leak..");
   }
   return status;
 }
  public void addContact(Contact c, String[] groups) {
    try {
      // Create the entry to insert
      ContactEntry contact = new ContactEntry();
      Name name = new Name();
      final String NO_YOMI = null;
      name.setFullName(new FullName(c.getName(), NO_YOMI));
      name.setGivenName(new GivenName(c.getName(), NO_YOMI));
      name.setFamilyName(new FamilyName(c.getSurname(), NO_YOMI));
      contact.setName(name);

      Email primaryMail = new Email();
      primaryMail.setAddress(c.getEmail());

      primaryMail.setPrimary(true);
      contact.addEmailAddress(primaryMail);

      URL postUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
      try {
        myService.insert(postUrl, contact);
      } catch (IOException ex) {
        Logger.getLogger(ContactsHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
      } catch (ServiceException ex) {
        Logger.getLogger(ContactsHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    } catch (MalformedURLException ex) {
      Logger.getLogger(ContactsHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  static void sendJSONResponse(HttpServletResponse response, Map<String, String> responseMap) {
    if (!Boolean.parseBoolean(responseMap.get("success"))) {
      int serverCode = 500;
      if (responseMap.containsKey("serverCode")) {
        serverCode = Integer.parseInt(responseMap.get("serverCode"));
      }
      response.setStatus(serverCode);
    }

    String responseContent = new Gson().toJson(responseMap);
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Content-Length", Integer.toString(responseContent.length()));

    Writer writer = null;
    try {
      writer = response.getWriter();
      writer.write(responseContent);
    } catch (IOException ex) {
      Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException ex) {
          Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }
Exemplo n.º 26
0
  public SearchQuery() {

    Properties props = new Properties(); // MWC
    InputStream instr = getClass().getResourceAsStream("dbConn.properties");
    try {
      props.load(instr);
    } catch (IOException ex) {
      Logger.getLogger(SearchQuery.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
      instr.close();
    } catch (IOException ex) {
      Logger.getLogger(SearchQuery.class.getName()).log(Level.SEVERE, null, ex);
    }

    String driver = props.getProperty("driver.name");
    String url = props.getProperty("server.name");
    String username = props.getProperty("user.name");
    String passwd = props.getProperty("user.password");
    try {
      Class.forName(driver);
    } catch (ClassNotFoundException ex) {
      Logger.getLogger(SearchQuery.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
      conn = DriverManager.getConnection(url, username, passwd);
    } catch (SQLException ex) {
      Logger.getLogger(SearchQuery.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Exemplo n.º 27
0
  /** @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) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
      UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(server_form.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(server_form.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(server_form.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(server_form.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    }
    // </editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(
        new Runnable() {
          public void run() {
            new server_form().setVisible(true);
          }
        });
  }
  public ComposeMailScreen(
      Properties config,
      Part replyMessage,
      String replyTo,
      String recipients,
      String subject,
      ArrayList<String> tags) {
    this(config);

    this.replyMessage = replyMessage;
    this.messageArea.setContentType("text/html");

    DefaultListModel model = (DefaultListModel) tagList.getModel();
    for (String tag : tags) {
      model.addElement(tag);
    }
    try {
      this.messageArea.setText(SEPERATOR + this.replyMessage.getContent().toString());
      this.toField.setText(replyTo);
      this.ccField.setText(recipients);
      this.subjectField.setText(subject);
    } catch (IOException ex) {
      Logger.getLogger(ComposeMailScreen.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MessagingException ex) {
      Logger.getLogger(ComposeMailScreen.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  private void btnViewItemsActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnViewItemsActionPerformed

    cmbItems.removeAllItems();

    // Deserializing itemlist
    try {
      itemList = this.itemService.Deserialize(ItemFile);
    } catch (IOException ex) {
      Logger.getLogger(SiteManagerUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
      Logger.getLogger(SiteManagerUI.class.getName()).log(Level.SEVERE, null, ex);
    }

    // adding the item to the combo box
    for (Item item : itemList) {
      cmbItems.addItem(
          item.getItemID()
              + " "
              + item.getItemName()
              + " ("
              + item.getItemType()
              + ") "
              + "Price = "
              + item.getItemPrice());
    }
  } // GEN-LAST:event_btnViewItemsActionPerformed
Exemplo n.º 30
0
  public void addToChannelGroup(String group, ChannelInfo channel) {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      PreparedStatement s =
          con.prepareStatement(
              "REPLACE INTO `channel_groups` SET `name` = ?, `channel_id` = (SELECT `id` FROM `channels` WHERE `channel` = ?)");
      s.setString(1, group.toLowerCase());
      s.setString(2, channel.channel.toLowerCase());
      s.executeUpdate();
      s.close();

      // Will do nothing if the channel is not in the list.
      if (!this.channel_groups.containsKey(group.toLowerCase())) {
        this.channel_groups.put(group.toLowerCase(), new HashSet<>());
      }

      this.channel_groups.get(group.toLowerCase()).add(channel);
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }