public AppletControl(String u, int w, int h, String user, String p) {

    PARAMETERS.put("RemoteHost", u.split("//")[1].split(":")[0]);
    PARAMETERS.put("RemotePort", u.split(":")[2].split("/")[0]);
    System.out.println(PARAMETERS.toString());
    this.url = u;
    URL[] url = new URL[1];
    try {

      url[0] = new URL(u);
      URLClassLoader load = new URLClassLoader(url);
      try {
        try {
          app = (Applet) load.loadClass("aplug").newInstance();
          app.setSize(w, h);
          app.setStub(this);
          app.setVisible(true);
        } catch (InstantiationException ex) {
          ex.printStackTrace();
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        }
      } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
      }
    } catch (MalformedURLException ex) {
      ex.printStackTrace();
    }
  }
示例#2
0
  public void run() {
    boolean gotByePacket = false;

    try {
      /* stream to read from client */
      ObjectInputStream fromClient = new ObjectInputStream(socket.getInputStream());
      Packet packetFromClient;

      /* stream to write back to client */
      ObjectOutputStream toClient = new ObjectOutputStream(socket.getOutputStream());

      // writer to the disk
      // String file = "list";

      // while (( packetFromClient = (Packet) fromClient.readObject()) != null) {
      /* create a packet to send reply back to client */

      packetFromClient = (Packet) fromClient.readObject();
      Packet packetToClient = new Packet();
      packetToClient.type = Packet.LOOKUP_REPLY;
      packetToClient.data = new ArrayList<String>();

      if (packetFromClient.type == Packet.LOOKUP_REQUEST) {
        // called by client
        System.out.println("Request from Client:" + packetFromClient.type);

        packetToClient.type = Packet.LOOKUP_REPLY;
        long start = packetFromClient.start;
        long length = packetFromClient.length;

        if (start > dict.size()) {
          // set the error field, return
          packetToClient.error_code = Packet.ERROR_OUT_OF_RANGE;
        } else {
          for (int i = (int) start; i < start + length && i < dict.size(); i++) {
            packetToClient.data.add(dict.get(i));
          }
        }

        toClient.writeObject(packetToClient);
        // continue;
      }

      // }

      /* cleanup when client exits */
      fromClient.close();
      toClient.close();
      socket.close();

      // close the filehandle

    } catch (IOException e) {
      if (!gotByePacket) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException e) {
      if (!gotByePacket) e.printStackTrace();
    }
  }
示例#3
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    PrintWriter writer = response.getWriter();
    String noteName = request.getParameter("noteName");
    String note = request.getParameter("note");

    try {
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/evernoteDB");

      Statement st = con.createStatement();

      st.executeUpdate(
          "INSERT INTO note (noteName, note) VALUES ('" + noteName + "','" + note + "')");

      response.sendRedirect("/userNotes.jsp");
    } catch (ClassNotFoundException e) {
      writer.println("Couldn't load database driver: " + e.getMessage());
    } catch (SQLException e) {
      writer.println("SQLException caught: " + e.getMessage());
    } catch (Exception e) {
      writer.println(e);
    }
  }
  // get drivername, user, pw & server, and return connection id
  public void serve(InputStream i, OutputStream o) throws IOException {
    // TODOServiceList.getSingleInstance();
    initialize();
    NameListMessage nameListMessage = null;

    try {
      // read input to know which target panel is required
      ObjectInputStream input = new ObjectInputStream(i);
      nameListMessage = (NameListMessage) input.readObject();

      // parse the required panel
      parseSqlFile(nameListMessage);

    } catch (ClassNotFoundException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      nameListMessage.errorMessage = ex.toString();
    }

    // send object to the caller
    ObjectOutputStream output = new ObjectOutputStream(o);
    output.writeObject(nameListMessage);

    // end socket connection
    o.close();
    i.close();
  }
示例#5
0
  // Load a neural network from memory
  public NeuralNetwork loadGenome() {

    // Read from disk using FileInputStream
    FileInputStream f_in = null;
    try {
      f_in = new FileInputStream("./memory/mydriver.mem");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    // Read object using ObjectInputStream
    ObjectInputStream obj_in = null;
    try {
      obj_in = new ObjectInputStream(f_in);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Read an object
    try {
      return (NeuralNetwork) obj_in.readObject();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    return null;
  }
示例#6
0
  public void run() {
    while (true) {
      try {
        System.out.println("Server name: " + serverSocket.getInetAddress().getHostName());
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to " + server.getRemoteSocketAddress());

        ObjectInputStream objectIn = new ObjectInputStream(server.getInputStream());

        try {
          Recipe rec = (Recipe) objectIn.readObject();
          startHMI(rec, rec.getProductName());

          //				System.out.println("Object Received: width: "+rec.getWidth()+" height:
          // "+rec.getHeight());
        } catch (ClassNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out.writeUTF(
            "Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
        server.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
  static Vector loadPrefs(
      String f, DataAccessPoint sourceDb, DataAccessPoint targetDb, Traceable tracer) {

    TransferTable t;
    Vector tTable = null;

    try {
      FileInputStream fis = new FileInputStream(f);
      ObjectInputStream ois = new ObjectInputStream(fis);

      tTable = (Vector) ois.readObject();

      for (int i = 0; i < tTable.size(); i++) {
        t = (TransferTable) tTable.elementAt(i);
        t.tracer = tracer;
        t.sourceDb = (TransferDb) sourceDb;
        t.destDb = targetDb;
      }
    } catch (ClassNotFoundException e) {
      System.out.println("class not found pb in LoadPrefs : " + e.toString());

      tTable = new Vector();
    } catch (IOException e) {
      System.out.println("IO pb in LoadPrefs : actionPerformed" + e.toString());

      tTable = new Vector();
    }

    return (tTable);
  }
  public void conectarBaseDeDatos() {
    try {
      final String CONTROLADOR = "org.postgresql.Driver";
      Class.forName(CONTROLADOR);
      // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb";
      conexion =
          DriverManager.getConnection(
              "jdbc:postgresql://" + main.ipSeleccionada + "/" + objUtils.nameBD, user, pass);
      // conexion = DriverManager.getConnection("jdbc:postgresql://127.0.0.1/goliak_jg", "postgres",
      // "majcp071102kaiser");

      sentencia = conexion.createStatement();
      /*JOptionPane.showMessageDialog(null, "si conecta");*/
    } catch (ClassNotFoundException ex1) {
      // ex1.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver." + ex1.getMessage());
      System.exit(1);
    } catch (SQLException ex) {
      // ex.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(
          null,
          "Error Creacion Statement."
              + ex.getMessage()
              + " / "
              + url
              + " / "
              + user
              + " / "
              + pass);
      System.exit(1);
    }
  }
 @SuppressWarnings({"boxing", "unchecked"})
 public void loadCache() {
   this.cache.clear();
   try {
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(CACHE_FILE));
     this.remoteDiscoveryImpl.syso("load cache");
     try {
       final int cacheSize = (Integer) in.readObject();
       //					syso("size "+cacheSize);
       for (int i = 0; i < cacheSize; ++i) {
         HashMap<RemoteManagerEndpoint, Entry> rmee = new HashMap<RemoteManagerEndpoint, Entry>();
         Class<? extends Plugin> plugin = (Class<? extends Plugin>) in.readObject();
         this.remoteDiscoveryImpl.syso(plugin.getCanonicalName());
         //						syso("\t"+i+"'"+pluginName+"'");
         int numEntries = (Integer) in.readObject();
         //						syso("\t"+numEntries);
         for (int j = 0; j < numEntries; ++j) {
           Entry entry = (Entry) in.readObject();
           //							syso("\t\t"+entry);
           rmee.put(entry.manager, entry);
         }
         this.cache.put(plugin, rmee);
       }
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
     } finally {
       in.close();
     }
   } catch (FileNotFoundException e) {
     this.remoteDiscoveryImpl.logger.warning("Loading cache file" + CACHE_FILE + " failed.");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 // AQUI VOYA  OBTENER EL SERVDUIOR QUEMADO EN UN ARCHIVO DE TEXTO
 public void conectarBaseDeDatos2() {
   try {
     final String CONTROLADOR = "org.postgresql.Driver";
     Class.forName(CONTROLADOR);
     // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb";
     conexion = DriverManager.getConnection(url2, user, pass);
     sentencia = conexion.createStatement();
     /*JOptionPane.showMessageDialog(null, "si conecta");*/
   } catch (ClassNotFoundException ex1) {
     // ex1.printStackTrace();
     javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver." + ex1.getMessage());
     System.exit(1);
   } catch (SQLException ex) {
     // ex.printStackTrace();
     javax.swing.JOptionPane.showMessageDialog(
         null,
         "Error Creacion Statement."
             + ex.getMessage()
             + " / "
             + url2
             + " / "
             + user
             + " / "
             + pass);
     System.exit(1);
   }
 }
示例#11
0
  /**
   * Loads training set from the specified file
   *
   * @param filePath training set file
   * @return loded training set
   */
  public static DataSet load(String filePath) {
    ObjectInputStream oistream = null;

    try {
      File file = new File(filePath);
      if (!file.exists()) {
        throw new FileNotFoundException("Cannot find file: " + filePath);
      }

      oistream = new ObjectInputStream(new FileInputStream(filePath));
      DataSet tSet = (DataSet) oistream.readObject();

      return tSet;

    } catch (IOException ioe) {
      ioe.printStackTrace();
    } catch (ClassNotFoundException cnfe) {
      cnfe.printStackTrace();
    } finally {
      if (oistream != null) {
        try {
          oistream.close();
        } catch (IOException ioe) {
        }
      }
    }

    return null;
  }
示例#12
0
  public void testSerial() {
    assertTrue(_nbhm.isEmpty());
    final String k1 = "k1";
    final String k2 = "k2";
    assertThat(_nbhm.put(k1, "v1"), nullValue());
    assertThat(_nbhm.put(k2, "v2"), nullValue());

    // Serialize it out
    try {
      FileOutputStream fos = new FileOutputStream("NBHM_test.txt");
      ObjectOutputStream out = new ObjectOutputStream(fos);
      out.writeObject(_nbhm);
      out.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    // Read it back
    try {
      File f = new File("NBHM_test.txt");
      FileInputStream fis = new FileInputStream(f);
      ObjectInputStream in = new ObjectInputStream(fis);
      NonBlockingIdentityHashMap nbhm = (NonBlockingIdentityHashMap) in.readObject();
      in.close();
      assertThat(
          "serialization works",
          nbhm.toString(),
          anyOf(is("{k1=v1, k2=v2}"), is("{k2=v2, k1=v1}")));
      if (!f.delete()) throw new IOException("delete failed");
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
  }
  /**
   * @param file
   * @return whether or not the file is loaded
   */
  public static boolean load(File file) {

    boolean loaded = false;

    try {
      FileInputStream fileIn = new FileInputStream(file);
      ObjectInputStream in = new ObjectInputStream(fileIn);
      reservations = (Reservation[]) in.readObject();
      in.close();
      fileIn.close();

      loaded = true;

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    System.out.println("Read binary file " + file);

    return loaded;
  }
示例#14
0
 /**
  * @return an instanciation of the given content-type class name, or null if class wasn't found
  */
 public static ContentType getContentTypeFromClassName(String contentTypeClassName) {
   if (contentTypeClassName == null)
     contentTypeClassName = getAvailableContentTypes()[DEFAULT_CONTENT_TYPE_INDEX];
   ContentType ct = null;
   try {
     Class clazz = Class.forName(contentTypeClassName);
     ct = (ContentType) clazz.newInstance();
   } catch (ClassNotFoundException cnfex) {
     if (jpicedt.Log.DEBUG) cnfex.printStackTrace();
     JPicEdt.getMDIManager()
         .showMessageDialog(
             "The pluggable content-type you asked for (class "
                 + cnfex.getLocalizedMessage()
                 + ") isn't currently installed, using default instead...",
             Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"),
             JOptionPane.ERROR_MESSAGE);
   } catch (Exception ex) {
     if (jpicedt.Log.DEBUG) ex.printStackTrace();
     JPicEdt.getMDIManager()
         .showMessageDialog(
             ex.getLocalizedMessage(),
             Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"),
             JOptionPane.ERROR_MESSAGE);
   }
   return ct;
 }
 /**
  * This function loads a class from file into the JVM given its fully-qualified name.
  *
  * @param classInfo the fully-qualified class name
  * @return a Class object representing the class name if such a class is defined, otherwise null
  */
 private static Class<?> getClass(String classInfo) {
   try {
     return ClassLoader.getSystemClassLoader().loadClass(classInfo);
   } catch (ClassNotFoundException e) {
     throw new RuntimeException(e.toString());
   }
 }
示例#16
0
  /** 使用示例 读取模型,识别CT局部病变 */
  public void test2() {
    try {

      // 实例化ObjectInputStream对象
      /*ObjectInputStream ois = new ObjectInputStream(App.class.getResourceAsStream("RandomForest"));*/
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream("conf/RandomForest"));

      try {
        // 读取对象people,反序列化
        RandomForest randomForest = (RandomForest) ois.readObject();
        ImageFeature imageFeature = new ImageFeature();
        /** 图像局部特征提取,参数:图象文件路径,划取区域坐标(x1,y1),(x2,y2) 返回:图像特征向量 */
        double[] data =
            imageFeature.getFeature(
                App.class.getClassLoader().getResource("IMG-0002-00011.jpg").getFile(),
                0,
                0,
                125,
                125);
        /** 识别算法调用 参数:图像特征向量 返回:病变类型(int型),1:正常;2:肝癌;3:肝血管瘤;4:肝囊肿;5:其他 */
        int type = randomForest.predictType(data);
        System.out.println("RandomForest predict:" + type);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Creates the brain and launches if it is an agent. The brain class is given as a String. The
   * name argument is used to instantiate the name of the corresponding agent. If the gui flag is
   * true, a bean is created and associated to this agent.
   */
  public void makeBrain(String className, String name, boolean gui, String behaviorFileName) {
    try {
      Class c;
      // c = Class.forName(className);
      c = madkit.kernel.Utils.loadClass(className);
      myBrain = (Brain) c.newInstance();
      myBrain.setBody(this);
      if (myBrain instanceof AbstractAgent) {
        String n = name;
        if (n == null) {
          n = getLabel();
        }
        if (n == null) {
          n = getID();
        }
        if (behaviorFileName != null) setBehaviorFileName(behaviorFileName);
        getStructure().getAgent().doLaunchAgent((AbstractAgent) myBrain, n, gui);
      }

    } catch (ClassNotFoundException ev) {
      System.err.println("Class not found :" + className + " " + ev);
      ev.printStackTrace();
    } catch (InstantiationException e) {
      System.err.println("Can't instanciate ! " + className + " " + e);
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      System.err.println("illegal access! " + className + " " + e);
      e.printStackTrace();
    }
  }
示例#18
0
  /** DOCUMENT ME! */
  public void loadRaids() {
    File f = new File(REPO);

    if (!f.exists()) {
      return;
    }

    FileInputStream fIn = null;
    ObjectInputStream oIn = null;

    try {
      fIn = new FileInputStream(REPO);
      oIn = new ObjectInputStream(fIn);
      // de-serializing object
      raids = (HashMap<String, GregorianCalendar>) oIn.readObject();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        oIn.close();
        fIn.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
  /*
   * launch process config input: className and args
   */
  public void launchProcessConfig(String className, String[] args)
      throws SecurityException, NoSuchMethodException {

    try {
      Class<?> processClass = Class.forName(className);
      // System.out.print("processClass is " + processClass.toString());
      MigratableProcess process;
      process =
          (MigratableProcess)
              processClass.getConstructor(String[].class).newInstance((Object) args);
      //			process = (MigratableProcess) processClass.newInstance();
      System.out.println("MP is " + process.toString());
      processList.add(process);

    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } // TestProcess test = new TestProcess();
    catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#20
0
 // TODO Der kommer en EOF exception når der forsøges at readObject.
 // TODO Brug sharedpref til at gemme og læse tamagotchi.
 private synchronized void loadTamagotchiFromFile() {
   FileInputStream fis = null;
   try {
     available.acquire();
     Log.d(TAMAGOTCHI, "Loading the tamagotchi from: " + fileName);
     fis = this.openFileInput(fileName);
     ObjectInputStream is = new ObjectInputStream(fis);
     // is.reset();
     // TODO Bug when reading a tama from filesystem
     // Steps to reproduce: Kill with the app context menu thingie, start app again.
     tama = (Tamagotchi) is.readObject();
     if (tama == null) return;
     is.close();
     fis.close();
     initializePlayingfield();
     Log.d(TAMAGOTCHI, "Done loading the tama");
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   } catch (OptionalDataException e) {
     e.printStackTrace();
   } catch (StreamCorruptedException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (InterruptedException e) {
     e.printStackTrace();
   } finally {
     available.release();
   }
 }
示例#21
0
  /**
   * * run takes in stream of bytes from client, deserializes it as Cookie, and calls sendResponse
   * to output back to client. If received client object is not an expected class then a
   * ClassNotFoundException is thrown. Socket is then closed when work is done.
   */
  public void run() {
    ObjectInputStream inputObject = null;
    ObjectOutputStream outputObject = null;

    try {
      inputObject =
          new ObjectInputStream(
              socket.getInputStream()); // inputObject used to store stream of bytes from client
      outputObject =
          new ObjectOutputStream(
              socket.getOutputStream()); // outputObject used to send bytes back to client

      try {
        Response responseToClient = new Response(); // Response object to be sent back to client
        Cookie clientCookie;
        clientCookie =
            (Cookie)
                inputObject
                    .readObject(); // deserializes object, casts it as Cookie, and stores it in
                                   // clientCookie
        sendResponse(
            clientCookie,
            responseToClient,
            outputObject); // sendResponse is called to send output to client
      } catch (
          ClassNotFoundException
              exp) { // throws ClassNotFoundException if inputObject cannot be read as Cookie object
        System.out.println("Cannot find class object");
        exp.printStackTrace();
      }
      socket.close(); // close socket to requested server
    } catch (IOException exp) { // throw IOException if inputObject is not of type ObjectInputStream
      System.out.println(exp); // or outputObject is not of type ObjectOutputStream
    }
  }
  public void conectarBDdinamic(String ip) {

    if (ip == null) {
      ip = "192.168.8.231";
    }
    url = "jdbc:postgresql://" + ip + "/ventasalm";
    // javax.swing.JOptionPane.showMessageDialog(null, url);
    String estado;
    try {

      final String CONTROLADOR = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
      Class.forName(CONTROLADOR);
      // System.getProperty( "user.dir" )+"/CarpetaBD/NombredelaBasedeDatos.mdb";
      conexion = DriverManager.getConnection(url, user, pass);
      sentencia = conexion.createStatement();
      // estado="Conectado Correctamente";
    } catch (ClassNotFoundException ex1) {
      ex1.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(null, "Error Carga Driver");
      estado = "Servidor no esta disponible";
      // System.exit(1);
    } catch (SQLException ex) {
      ex.printStackTrace();
      javax.swing.JOptionPane.showMessageDialog(null, "Error Creacion Statement");
      estado = "Servidor no esta disponible";
      // System.exit(1);
    }
    // return estado;
  }
  public List<Supplier> GetSuppliers() {
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    List<Supplier> suppliers = new ArrayList<Supplier>();

    try {
      fis = new FileInputStream("Suppliers.dat");
      ois = new ObjectInputStream(fis);

      while (true) {
        try {
          suppliers.add((Supplier) ois.readObject());
        } catch (EOFException ex) {
          break;
        }
      }
    } catch (IOException ex) {
      System.out.println("Falha ao Ler arquivo de fornecedores!");
      ex.getStackTrace();
    } catch (ClassNotFoundException e) {
      System.out.println("Falha ao Ler arquivo de fornecedores!");
      e.printStackTrace();
    } finally {
      try {
        if (ois != null) ois.close();
        if (fis != null) fis.close();
      } catch (IOException ex) {
        System.out.println("Falha ao Ler arquivo de fornecedores!");
        ex.getStackTrace();
      }
    }

    return suppliers;
  }
  /** Method: addToFile(LinkedList<GameNode> g) */
  @Test
  public void testAddToFile() throws Exception {
    GameNode testGameNode = new GameNode();
    testGameNode.setPlayer("rarry");
    testGameNode.setOpponent("lobertie");
    testGameNode.setGameName("raddle");
    testGameNode.setWinLose(true);
    testGameNode.setScore(29);
    LinkedList<GameNode> testLLGN = new LinkedList<GameNode>();
    testLLGN.add(testGameNode);
    testScoreboard.addToFile(testLLGN);

    LinkedList<GameNode> temp = new LinkedList<GameNode>();
    ObjectInputStream i = null;
    try {
      i = new ObjectInputStream(new FileInputStream("gameStats.ser"));
      temp = (LinkedList<GameNode>) i.readObject();
      i.close();
    } catch (FileNotFoundException e) {

    } catch (IOException e) {

    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    assertTrue(
        "The Object read from file contains the testGameNode added to file",
        temp.contains(testGameNode));
  }
示例#25
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");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Statement stmt;
    ResultSet rs;
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456";
      con = DriverManager.getConnection(connectionUrl);

      if (con != null) {
        System.out.println("connected to mysql");
      }
    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e.toString());
    } catch (ClassNotFoundException cE) {
      System.out.println("Class Not Found Exception: " + cE.toString());
    }

    try {
      stmt = con.createStatement();

      System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'");
      rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'");

      while (rs.next()) {

        if (rs.getObject(1).toString().equals(username)) {

          out.println("<h1>To username pou epileksate uparxei hdh</h1>");
          out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>");

          stmt.close();
          rs.close();
          return;
        }
      }
      stmt.close();
      rs.close();

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>Your registration is completed  " + username + "</h1>");
        out.println("<a href=\"index.jsp\">go to the login menu</a>");
        registerListener.Register(username);
      } else {
        out.println("<h1>To username pou epileksate uparxei hdh</h1>");
        out.println("<a href=\"project3.html\">Register</a>");
      }
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
示例#26
0
  public static Results initResults() {

    Results results;
    String state = Environment.getExternalStorageState();

    if (state.equals(Environment.MEDIA_MOUNTED)) { // TODO: MEDIA_READONLY
      // is exists folders
      File file = new File(Environment.getExternalStorageDirectory(), "morning-trainer");

      if (!file.isDirectory())
        Log.e(
            "mirinda1",
            file.delete()
                ? "delete"
                : "cannot delete file :" + file.getPath()); // TODO and what? if can't delete
      if (file.mkdir()) Log.i("mirinda1", "create directory: " + file.getName());
      appPath = file.getPath();

      file = new File(appPath, user);
      if (!file.isDirectory())
        Log.e("mirinda1", file.delete() ? "delete" : "cannot delete file :" + file.getPath());
      if (file.mkdir()) Log.i("mirinda1", "create directory: " + file.getName());
      userPath = file.getPath();

      String[] lst = file.list();
      Log.i("mirinda1", Arrays.toString(lst));
      // load data
      try {
        file = new File(userPath, SERIALIZED);
        if (!file.exists()) throw new IOException("not exist");
        if (!file.isFile()) throw new IOException("not a file"); // TODO my exceptions

        FileInputStream inputStream = new FileInputStream(file);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        results = (Results) objectInputStream.readObject();
        Log.i("mirinda1", results.toString());
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
        results = null;
      } catch (OptionalDataException e) {
        e.printStackTrace();
        results = null;
      } catch (FileNotFoundException e) {
        Log.e("mirinda1", "File not found");
        results = null;
      } catch (StreamCorruptedException e) {
        e.printStackTrace();
        results = null;
      } catch (IOException e) {
        Log.e("mirinda1", "" + e.getMessage());
        results = new Results(user);
      }
    } else {
      Log.e("mirinda1", "SD card didn't mounted");
      results = null;
    }
    return results;
  }
 /** {@inheritDoc} */
 @Override
 public Object decode(InputStream source) throws IOException {
   try {
     ObjectInputStream objectIn = new ObjectInputStream(source);
     return objectIn.readObject();
   } catch (ClassNotFoundException e) {
     throw new IllegalStateException(e.getMessage());
   }
 }
  public static void main(String[] args) {
    try {
      String sp1 = "/home/caoc/alterAligner/SCORE_DROP/all_mtx/" + args[0] + ".mtx";
      String sp2 = "/home/caoc/alterAligner/SCORE_DROP/all_mtx/" + args[1] + ".mtx";
      System.out.println(args[0]);
      //                                String sp1 =
      // "/home/caoc/alterAligner/SCORE_DROP/all_fasta/" + args[0] ;
      //                               String sp2 =  "/home/caoc/alterAligner/SCORE_DROP/all_fasta/"
      // + args[1] ;

      Class parserClass = Class.forName("alterAligner.sequenceProfileParsers.PSSMParser");
      Class scoreFunctionClass =
          Class.forName("alterAligner.scoreFunctionStrategies.WeightedSumStrategy");
      SequenceProfileParser aParser = (SequenceProfileParser) parserClass.newInstance();
      ScoreFunctionStrategy aStrategy = (ScoreFunctionStrategy) scoreFunctionClass.newInstance();
      Aligner aligner = new Aligner(aStrategy, (float) 10, (float) 0.5);
      SequenceProfile seqPro1 = aParser.parse(new File(sp1));
      SequenceProfile seqPro2 = aParser.parse(new File(sp2));
      Alignment alignment = aligner.smithWatermanAlign(seqPro1, seqPro2);
      BufferedWriter writer =
          new BufferedWriter(
              new FileWriter(
                  "/home/caoc/alterAligner/SCORE_DROP/all_ws_alignment/"
                      + args[0]
                      + "__"
                      + args[1]
                      + ".ws.fasta"));
      writer.append(
          ">"
              + alignment.getName1()
              + "\t"
              + alignment.getStart1()
              + "\t"
              + alignment.getEnd1()
              + "\n");
      writer.append(alignment.getSequence1AsString() + "\n");
      writer.append(
          ">"
              + alignment.getName2()
              + "\t"
              + alignment.getStart2()
              + "\t"
              + alignment.getEnd2()
              + "\n");
      writer.append(alignment.getSequence2AsString() + "\n");
      writer.close();
    } catch (FileNotFoundException e) {
      System.out.println("Failed to open file! " + e.getMessage());
    } catch (IOException e) {
      System.out.println("Failed to read the file! " + e.getMessage());
    } catch (ClassNotFoundException e) {
      System.out.println("Failed to find the class! " + e.getMessage());
    } catch (Exception e) {
      System.out.println("Failed to due to do alignment! " + e.getMessage());
      e.printStackTrace();
    }
  }
示例#29
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // TODO Auto-generated method stub
    HttpSession session = request.getSession();
    request.setCharacterEncoding("UTF-8");

    BufferedInputStream fileIn = new BufferedInputStream(request.getInputStream());
    String fn = request.getParameter("fileName");
    byte[] buf = new byte[1024];
    File file = new File("/var/www/uploadres/" + session.getAttribute("username") + fn);
    BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file));
    while (true) {
      int bytesIn = fileIn.read(buf, 0, 1024);
      if (bytesIn == -1) break;
      else fileOut.write(buf, 0, bytesIn);
    }

    fileOut.flush();
    fileOut.close();
    System.out.println(file.getAbsolutePath());

    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      try {
        Connection conn = DriverManager.getConnection(url, user, pwd);
        Statement stmt = conn.createStatement();
        String sql =
            "UPDATE Users SET photo = '"
                + file.getName()
                + "' WHERE username='******'";
        stmt.execute(sql);
        //				PreparedStatement pstmt = conn.prepareStatement("UPDATE Users SET photo = ? WHERE
        // username='******'");
        //				InputStream inp = new BufferedInputStream(new FileInputStream(file));
        //				pstmt.setBinaryStream(1, inp, (int)file.length());
        //				pstmt.executeUpdate();
        System.out.println("OK");
      } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#30
0
 /*
  * build methods, initialization of the database
  */
 public void buildConnect() {
   try {
     Class.forName(jdbcDriver);
     connection = DriverManager.getConnection(dbUrl, user, passwd);
     statement = connection.createStatement();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }