Ejemplo n.º 1
0
 /**
  * ** Returns true if the specified character is a valid character to use in ** an ID ** @param ch
  * The character ** @return True if the specified character is a valid character to use in ** an
  * ID
  */
 public static boolean isValidIDChar(char ch) {
   // At a minimum, avoid the following special chars:
   //   $   - substitution character
   //   {}  - have had problems using this character in MySQL
   //   %   - MySQL wildcard character
   //   *   - generic wildcard character
   //   \   - escape character
   //   ?   - just don't use it
   //   ,   - will get confused as a field separator
   //   |   - will get confused as a field separator
   //   /   - will get confused as a field separator
   //   =   - will get confused as a key=value separator
   //   "'` - quotation characters
   //   #   - possible beginning of comment
   //   ~   - just don't use it
   //   ?   - just don't use it
   //   ^   - just don't use it
   // Pending possibles:
   //   !   - Looks like '|'?
   //   -   - ?
   //   +   - ?
   // @abc,#abc,_abc,.abc,&abc
   if (Character.isLetterOrDigit(ch)) {
     return true;
   } else if ((ch == '.') || (ch == '_')) {
     // definately accept these
     return true;
   } else if ((ch == '@') || (ch == '&') || (ch == '-')) {
     // we'll consider these
     return true;
   } else {
     return false;
   }
 }
Ejemplo n.º 2
0
 /* return string representation of fault code */
 public static String GetFaultString(long fault) {
   if (fault > 0L) {
     StringBuffer sb = new StringBuffer();
     if ((fault & TYPE_MASK) == TYPE_J1708) {
       // SID: "128/s123/1"
       // PID: "128/123/1"
       boolean active = DTOBDFault.DecodeActive(fault);
       int mid = DTOBDFault.DecodeSystem(fault);
       int fmi = DTOBDFault.DecodeFMI(fault);
       if (!active) {
         sb.append("[");
       }
       sb.append(mid); // MID
       sb.append("/");
       if (DTOBDFault.IsJ1708_SID(fault)) {
         int sid = DTOBDFault.DecodePidSid(fault);
         sb.append("s").append(sid); // SID "128/s123/1"
       } else {
         int pid = DTOBDFault.DecodePidSid(fault);
         sb.append(pid); // PID "128/123/1"
       }
       sb.append("/");
       sb.append(fmi); // FMI
       if (!active) {
         sb.append("]");
       }
       return sb.toString();
     } else if ((fault & TYPE_MASK) == TYPE_J1939) {
       // SPN: "128/1"
       boolean active = DTOBDFault.DecodeActive(fault);
       int spn = DTOBDFault.DecodeSystem(fault);
       int fmi = DTOBDFault.DecodeFMI(fault);
       sb.append(spn); // SPN
       sb.append("/");
       sb.append(fmi); // FMI
       return sb.toString();
     } else if ((fault & TYPE_MASK) == TYPE_OBDII) {
       // DTC: "P0071" [was "024C"]
       boolean active = DTOBDFault.DecodeActive(fault);
       int sysChar = DTOBDFault.DecodeSystem(fault); // System: powertrain
       int subSys = DTOBDFault.DecodeSPID(fault); // Mfg/Subsystem/Problem
       if (Character.isLetter((char) sysChar)) {
         sb.append((char) sysChar);
       } else {
         sb.append("U");
       }
       if ((subSys & 0x8000) != 0) {
         sb.append("1");
       } else {
         sb.append("0");
       }
       String subSysStr = String.valueOf(1000 + ((subSys & 0xFFF) % 1000));
       sb.append(subSysStr.substring(1));
       return sb.toString();
     } else {
       // unrecognized
     }
   }
   return "";
 }
  /**
   * Parses a sql with named parameters. The parameter-index mappings are put into the map, and the
   * parsed sql is returned.
   *
   * @param sql sql with named parameters
   * @return the parsed sql
   */
  private static String parseNamedSql(String sql, Map<String, List<Integer>> nameIndexMap) {
    // I was originally using regular expressions, but they didn't work well for ignoring
    // parameter-like strings inside quotes.
    int length = sql.length();
    StringBuffer parsedSql = new StringBuffer(length);
    boolean inSingleQuote = false;
    boolean inDoubleQuote = false;
    int index = 1;
    for (int i = 0; i < length; i++) {
      char c = sql.charAt(i);
      if (inSingleQuote) {
        if (c == '\'') {
          inSingleQuote = false;
        }
      } else if (inDoubleQuote) {
        if (c == '"') {
          inDoubleQuote = false;
        }
      } else {
        if (c == '\'') {
          inSingleQuote = true;
        } else if (c == '"') {
          inDoubleQuote = true;
        } else if (c == ':'
            && i + 1 < length
            && Character.isJavaIdentifierStart(sql.charAt(i + 1))) {
          int j = i + 2;
          while (j < length && Character.isJavaIdentifierPart(sql.charAt(j))) {
            j++;
          }
          String name = sql.substring(i + 1, j);
          c = '?'; // replace the parameter with a question mark
          i += name.length(); // skip past the end if the parameter
          List<Integer> indexList = nameIndexMap.get(name);
          if (indexList == null) {
            indexList = new LinkedList<Integer>();
            nameIndexMap.put(name, indexList);
          }
          indexList.add(index);
          index++;
        }
      }
      parsedSql.append(c);
    }

    return parsedSql.toString();
  }
Ejemplo n.º 4
0
 // Convenience method for the LookupAction constructor
 private static boolean isVowel(char c) {
   switch (Character.toLowerCase(c)) {
     case 'a':
     case 'e':
     case 'i':
     case 'o':
     case 'u':
       return true;
     default:
       return false;
   }
 }
Ejemplo n.º 5
0
 public Field(String s) {
   String f[] = StringTools.parseString(s, FIELD_VALUE_SEPARATOR);
   if ((f.length > 0) && (f[0].length() > 0) && Character.isLetter(f[0].charAt(0))) {
     this.isHiRes = (f.length > 0) ? f[0].equalsIgnoreCase("H") : false;
     this.type = (f.length > 1) ? StringTools.parseInt(f[1], -1) : -1;
   } else {
     this.type = (f.length > 0) ? StringTools.parseInt(f[0], -1) : -1;
     this.isHiRes = (f.length > 1) ? f[1].equalsIgnoreCase("H") : false;
   }
   this.index = (f.length > 2) ? StringTools.parseInt(f[2], 0) : 0;
   this.length = (f.length > 3) ? StringTools.parseInt(f[3], 0) : 0;
   this.isValid = (f.length == 4) && (this.type >= 0) && (this.index >= 0) && (this.length > 0);
 }
Ejemplo n.º 6
0
 /**
  * ** Filters an ID String, convertering all letters to lowercase and ** removing invalid
  * characters ** @param text The ID String to filter ** @return The filtered ID String
  */
 public static String FilterID(String text) {
   // ie. "sky.12", "acme@123"
   if (text != null) {
     StringBuffer sb = new StringBuffer();
     for (int i = 0; i < text.length(); i++) {
       char ch = Character.toLowerCase(text.charAt(i));
       if (DBRecordKey.isValidIDChar(ch)) {
         sb.append(ch);
       }
     }
     return sb.toString();
   } else {
     return "";
   }
 }
Ejemplo n.º 7
0
 /**
  * This util method is used to retrieve the string tokens resides in a particular udt parameter.
  *
  * @param param Name of the parameter
  * @return
  */
 public static Queue<String> getTokens(String param) {
   boolean isString = false;
   Queue<String> tokens = new LinkedBlockingQueue<String>();
   char[] chars = param.toCharArray();
   StringBuilder columnName = new StringBuilder();
   for (int i = 0; i < chars.length; i++) {
     Character c = chars[i];
     if (!".".equals(c.toString()) && !"[".equals(c.toString()) && !"]".equals(c.toString())) {
       isString = true;
       columnName.append(c.toString());
       if (i == chars.length - 1) {
         tokens.add(columnName.toString());
       }
     } else {
       if (isString) {
         tokens.add(columnName.toString());
         columnName = new StringBuilder();
         isString = false;
       }
       tokens.add(c.toString());
     }
   }
   return tokens;
 }
Ejemplo n.º 8
0
  // initiate either a server or a user session
  public void run() {
    if (isDaemon) {
      daemon();
      return;
    }
    ;

    boolean loggedIn = false;
    int i, h1;
    String di, str1, user = "******", user_id = "0";
    InetAddress localNode;
    byte dataBuffer[] = new byte[1024];
    String command = null;
    StringBuffer statusMessage = new StringBuffer(40);
    File targetFile = null;

    try {
      // start mysql
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      this.db_conn = DriverManager.getConnection(db_url);
      this.db_stmt = this.db_conn.createStatement();

      this.db_stmt.executeUpdate("INSERT INTO test_table (name) VALUES ('hello world')");

      incoming.setSoTimeout(inactivityTimer); // enforce I/O timeout
      remoteNode = incoming.getInetAddress();
      localNode = InetAddress.getLocalHost();

      BufferedReader in =
          new BufferedReader(new InputStreamReader(incoming.getInputStream(), TELNET));
      PrintWriter out =
          new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(), TELNET), true);
      str1 = "220 Flickr FTP Server Ready";
      out.println(str1);
      if (log) System.out.println(remoteNode.getHostName() + " " + str1);

      boolean done = false;
      char dataType = 0;

      while (!done) {
        statusMessage.setLength(0);

        // obtain and tokenize command
        String str = in.readLine();
        if (str == null) break; // EOS reached
        i = str.indexOf(' ');
        if (i == -1) i = str.length();
        command = str.substring(0, i).toUpperCase().intern();
        if (log)
          System.out.print(
              user
                  + "@"
                  + remoteNode.getHostName()
                  + " "
                  + (String) ((command != "PASS") ? str : "PASS ***"));
        str = str.substring(i).trim();

        try {
          if (command == "USER") {

            user = str;
            statusMessage.append("331 Password");

          } else if (command == "PASS") {

            String pass = str;
            String pass_md5 = md5(pass);

            this.db_rs =
                this.db_stmt.executeQuery(
                    "SELECT * FROM users WHERE email='"
                        + user
                        + "' AND password='******'");
            if (this.db_rs.first()) {
              loggedIn = true;
              user_id = this.db_rs.getString("id");
              System.out.println("Account id is " + user_id);
            }

            statusMessage.append(loggedIn ? "230 logged in User" : "530 Login Incorrect");

          } else if (!loggedIn) {

            statusMessage.append("530 Not logged in");

          } else if (command == "RETR") {

            statusMessage.append("999 Not likely");

          } else if (command == "STOR") {

            out.println(BINARY_XFER);

            // trim a leading slash off the filename if there is one
            if (str.substring(0, 1).equals("/")) str = str.substring(1);
            String filename = user_id + "_" + str;
            // TODO: sanitise filename
            targetFile = new File(upload_root + "/" + filename);

            RandomAccessFile dataFile = null;
            InputStream inStream = null;
            OutputStream outStream = null;
            BufferedReader br = null;
            PrintWriter pw = null;

            try {
              int amount;
              dataSocket = setupDataLink();

              // ensure timeout on reads.
              dataSocket.setSoTimeout(inactivityTimer);

              dataFile = new RandomAccessFile(targetFile, "rw");

              inStream = dataSocket.getInputStream();
              while ((amount = inStream.read(dataBuffer)) != -1)
                dataFile.write(dataBuffer, 0, amount);

              statusMessage.append(XFER_COMPLETE);

              shell_exec(ingest_path + " " + user_id + " " + filename);
            } finally {
              try {
                if (inStream != null) inStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (outStream != null) outStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataFile != null) dataFile.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e1) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "REST") {

            statusMessage.append("502 Sorry, no resuming");

          } else if (command == "TYPE") {

            if (Character.toUpperCase(str.charAt(0)) == 'I') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504 Only binary baybee");
            }

          } else if (command == "DELE"
              || command == "RMD"
              || command == "XRMD"
              || command == "MKD"
              || command == "XMKD"
              || command == "RNFR"
              || command == "RNTO"
              || command == "CDUP"
              || command == "XCDUP"
              || command == "CWD"
              || command == "SIZE"
              || command == "MDTM") {

            statusMessage.append("502 None of that malarky!");

          } else if (command == "QUIT") {

            statusMessage.append(COMMAND_OK).append("GOOD BYE");
            done = true;

          } else if (command == "PWD" | command == "XPWD") {

            statusMessage.append("257 \"/\" is current directory");

          } else if (command == "PORT") {

            int lng, lng1, lng2, ip2;
            String a1 = "", a2 = "";
            lng = str.length() - 1;
            lng2 = str.lastIndexOf(",");
            lng1 = str.lastIndexOf(",", lng2 - 1);

            for (i = lng1 + 1; i < lng2; i++) {
              a1 = a1 + str.charAt(i);
            }

            for (i = lng2 + 1; i <= lng; i++) {
              a2 = a2 + str.charAt(i);
            }

            remotePort = Integer.parseInt(a1);
            ip2 = Integer.parseInt(a2);
            remotePort = (remotePort << 8) + ip2;
            statusMessage.append(COMMAND_OK).append(remotePort);

          } else if (command == "LIST" | command == "NLST") {

            try {

              out.println("150 ASCII data");
              dataSocket = setupDataLink();

              PrintWriter out2 = new PrintWriter(dataSocket.getOutputStream(), true);

              if ((command == "NLST")) {
                out2.println(".");
                out2.println("..");
              } else {
                out2.println("total 8.0k");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 .");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 ..");
              }

              // socket MUST be closed before signalling EOD
              dataSocket.close();
              dataSocket = null;
              statusMessage.setLength(0);
              statusMessage.append(XFER_COMPLETE);
            } finally {
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "NOOP") {

            statusMessage.append(COMMAND_OK);

          } else if (command == "SYST") {

            statusMessage.append("215 UNIX"); // allows NS to do long dir

          } else if (command == "MODE") {

            if (Character.toUpperCase(str.charAt(0)) == 'S') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "STRU") {

            if (str.equals("F")) {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "PASV") {

            try {

              int num = 0, j = 0;
              if (passiveSocket != null)
                try {
                  passiveSocket.close();
                } catch (Exception e) {
                }
              ;
              passiveSocket = new ServerSocket(0); // any port

              // ensure timeout on reads.
              passiveSocket.setSoTimeout(inactivityTimer);

              statusMessage.append("227 Entering Passive Mode (");
              String s = localNode.getHostAddress().replace('.', ','); // get host #
              statusMessage.append(s).append(',');
              num = passiveSocket.getLocalPort(); // get port #
              j = (num >> 8) & 0xff;
              statusMessage.append(j);
              statusMessage.append(',');
              j = num & 0xff;
              statusMessage.append(j);
              statusMessage.append(')');
            } catch (Exception e) {
              try {
                if (passiveSocket != null) passiveSocket.close();
              } catch (Exception e1) {
              }
              ;
              passiveSocket = null;
              throw e;
            }

          } else {
            statusMessage.append("502 unimplemented ").append(command);
          }
        }

        // shutdown causes an interruption to be thrown
        catch (InterruptedException e) {
          throw (e);
        } catch (Exception e) // catch all for any errors (including files)
        {
          statusMessage.append(FAULT).append(e.getMessage());
          if (debug) {
            System.out.println("\nFAULT - lastfile " + targetFile);
            e.printStackTrace();
          }
          ;
        }

        // send result status to remote
        out.println(statusMessage);
        if (log) System.out.println("\t" + statusMessage);
      }
    } catch (Exception e) // usually network errors (including timeout)
    {
      if (log) System.out.println("forced instance exit " + e);
      if (debug) e.printStackTrace();
    } finally // exiting server instance
    {
      // tear down mysql
      if (this.db_rs != null) {
        try {
          this.db_rs.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_stmt != null) {
        try {
          this.db_stmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_pstmt != null) {
        try {
          this.db_pstmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_conn != null) {
        try {
          this.db_conn.close();
        } catch (SQLException SQLE) {;
        }
      }

      forceClose();
    }
  }
    public void actionPerformed(ActionEvent ae) {
      try {

        Integer num1 = Integer.parseInt(tfdid.getText());
        if (num1.equals(null)) {
          System.out.println("num");
          throw new BlankException();
        }

        String name1 = tfname.getText();
        int a;
        a = name1.charAt(0);
        if (name1.equals("") || a == 32) {
          throw new BlankException();
        } else {
          for (int i = 0; i < name1.length(); i++) {
            boolean check = Character.isLetter(name1.charAt(i));
            a = name1.charAt(i);
            System.out.print("  " + a);
            if (!((a >= 65 && a <= 90) || (a >= 97 && a <= 122) || (a == 32) || (a == 46))) {
              throw new NameEx();
            }
          }
        }

        String addr1 = taadd.getText();
        if (addr1.equals(null)) {
          System.out.println("addr");
          throw new BlankException();
        }

        String contact1 = tftel.getText();

        String spec1 = taspecial.getText();
        String workf1 = tfworkf.getText();
        String workt1 = tfworkt.getText();

        String str =
            "UPDATE DOC SET name=?,address=?,contact=?,specialization=?,workfrom=?,workto=? WHERE did=?";

        Statement st1 = cn.createStatement();

        PreparedStatement psmt = cn.prepareStatement(str);
        psmt.setString(1, name1);
        psmt.setString(2, addr1);
        psmt.setString(3, contact1);
        psmt.setString(4, spec1);
        psmt.setString(5, workf1);
        psmt.setString(6, workt1);
        psmt.setInt(7, num1);

        psmt.executeUpdate();

        JOptionPane.showMessageDialog(
            new JFrame(), "Data Modified successfully!", "Done!", JOptionPane.INFORMATION_MESSAGE);

      } catch (SQLException sq) {
        String message = "Enter Valid Doctor ID and Contact.";
        JOptionPane.showMessageDialog(new JFrame(), message, "ERROR!", JOptionPane.ERROR_MESSAGE);
        System.out.println(sq);
      } catch (BlankException be) {
        JOptionPane.showMessageDialog(
            new JFrame(), "Please Enter All The Fields", "ERROR!", JOptionPane.ERROR_MESSAGE);
      } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(
            new JFrame(),
            "Patient Number and Contact Number Must Contain Digits.",
            "ERROR!",
            JOptionPane.ERROR_MESSAGE);
      } catch (NameEx ne) {
        JOptionPane.showMessageDialog(
            new JFrame(), "Invalid Name", "ERROR!", JOptionPane.ERROR_MESSAGE);
      } catch (Exception e) {
        System.out.println(e);
        JOptionPane.showMessageDialog(
            new JFrame(), "Enter Valid Date", "Error", JOptionPane.ERROR_MESSAGE);
      }
    }