コード例 #1
1
  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
  /**
   * @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;
  }
コード例 #3
0
ファイル: Server.java プロジェクト: Rubatharisan/radis-server
  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;
      }
    }
  }
コード例 #4
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();
    }
  }
コード例 #5
0
ファイル: RaidCommands.java プロジェクト: Whytemeet/nexusbot
  /** 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();
      }
    }
  }
コード例 #6
0
ファイル: NeuralNetwork.java プロジェクト: geomois/ciex2
  // 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;
  }
コード例 #7
0
ファイル: MiscUtilities.java プロジェクト: zukov/Jpicedt
 /**
  * @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;
 }
コード例 #8
0
  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;
  }
コード例 #9
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();
    }
  }
コード例 #10
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;
  }
コード例 #11
0
  /**
   * 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();
    }
  }
コード例 #12
0
 @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();
   }
 }
コード例 #13
0
  /*
   * 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();
    }
  }
コード例 #14
0
  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;
  }
コード例 #15
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();
   }
 }
コード例 #16
0
ファイル: JokeServer.java プロジェクト: cloera/Joke-Server
  /**
   * * 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
    }
  }
コード例 #17
0
ファイル: App.java プロジェクト: youruncleda/BlackHole
  /** 使用示例 读取模型,识别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();
    }
  }
コード例 #18
0
  /** 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));
  }
コード例 #19
0
  // 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();
  }
コード例 #20
0
ファイル: Saver.java プロジェクト: mirinda/Morning-trainer
  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;
  }
コード例 #21
0
ファイル: UploadImg.java プロジェクト: mehulsbhatt/MDBU-BAP
  /** @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();
    }
  }
コード例 #22
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();
   }
 }
コード例 #23
0
ファイル: Main.java プロジェクト: eugenyberkut/z1907
 private List<Student> readStudentsFromBinaryFile(String filename) throws FileNotFoundException {
   try (ObjectInputStream stream = new ObjectInputStream(new FileInputStream(filename))) {
     Object object = stream.readObject();
     return (List<Student>) object;
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   }
   return new ArrayList<>();
 }
コード例 #24
0
  private void deSerialize(ObjectInputStream in) throws DuplicateBibException {
    Object o;
    try {
      while ((o = in.readObject()) != null) {
        Race raceFromSerialized = (Race) o;

        this.date = raceFromSerialized.date;
        this.name = raceFromSerialized.name;
        this.location = raceFromSerialized.location;
        setNbrGates(raceFromSerialized.nbrGates); // this.nbrGates = race.nbrGates;// = 25;
        this.upstreamGates = raceFromSerialized.upstreamGates;
        this.judgingSections = raceFromSerialized.judgingSections;
        for (JudgingSection s : judgingSections) {
          // must assign all transients, otherwise they are null and cause problsm
          s.setClientDeviceAttached(new Boolean(false));
        }

        // Race Status
        this.pendingRerun = raceFromSerialized.pendingRerun;
        this.activeRuns = raceFromSerialized.activeRuns;
        this.completedRuns = raceFromSerialized.completedRuns;

        this.startList = raceFromSerialized.startList;
        this.runsStartedOrCompletedCnt = raceFromSerialized.runsStartedOrCompletedCnt;
        this.currentRunIteration =
            raceFromSerialized.currentRunIteration; // are we on 1st runs, or 2nd runs ?
        this.racers = raceFromSerialized.racers;
        this.tagHeuerEnabled =
            raceFromSerialized.tagHeuerEnabled; // todo REMOVE ->tagHeuerEmulation =
        // raceFromSerialized.tagHeuerEmulation;
        this.microgateEnabled = raceFromSerialized.microgateEnabled;
        this.microgateEnabled = raceFromSerialized.timyEnabled;

        this.icfPenalties = raceFromSerialized.icfPenalties;
      }

    } catch (InvalidClassException ice) {
      clearRace();
      System.out.println("All data cleared, incompatible race object version information");
    } catch (EOFException io) {
      // io.printStackTrace();

    } catch (IOException io) {
      io.printStackTrace();
    } catch (ClassNotFoundException cnfe) {
      cnfe.printStackTrace();
    }
    String duplicates = lookForDuplicateBibsInTheSameClass();
    if (duplicates != null) {
      log.error(duplicates);
      throw new DuplicateBibException();
    }
  }
コード例 #25
0
 public TreeMap<String, TreeSet<Note>> read(String path) {
   TreeMap<String, TreeSet<Note>> source = null;
   try (FileInputStream fin = new FileInputStream(path);
       ObjectInputStream oin =
           new ObjectInputStream(fin)) { // Поток для чтения (сериализации) объектов
     source = (TreeMap<String, TreeSet<Note>>) oin.readObject();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ClassNotFoundException f) {
     f.printStackTrace();
   }
   return source;
 }
コード例 #26
0
ファイル: UserTab.java プロジェクト: 0lri/paparazzi
 /**
  * load the object from a file
  *
  * @param nomfichier
  * @return
  */
 public static UserTab unserialize(String nomfichier) {
   try {
     FileInputStream fichier = new FileInputStream(nomfichier);
     ObjectInputStream ois = new ObjectInputStream(fichier);
     UserTab usrtab = (UserTab) ois.readObject();
     return usrtab;
   } catch (java.io.IOException e) {
     e.printStackTrace();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   }
   return null;
 }
コード例 #27
0
 public void run() {
   String texto = "";
   while (repetir) {
     try {
       Empleados e = (Empleados) inObjeto.readObject();
       textarea1.setText("");
       textarea1.setForeground(Color.blue);
       if (e == null) {
         textarea1.setForeground(Color.red);
         PintaMensaje("<<EL EMPLEADO NO EXISTE>>");
       } else {
         texto =
             "Empleado: "
                 + e.getEmpNo()
                 + "\n   "
                 + "Oficio: "
                 + e.getOficio()
                 + "\tApellido: "
                 + e.getApellido()
                 + "\n    "
                 + "Comisión: "
                 + e.getComision()
                 + "\tDirección: "
                 + e.getDir()
                 + "\n    "
                 + "Alta: "
                 + e.getFechaAlt()
                 + "\tSalario: "
                 + e.getSalario()
                 + "\n    "
                 + "Departamento: "
                 + e.getDepartamentos().getDnombre();
         textarea1.append(texto);
       }
     } catch (SocketException s) {
       repetir = false;
     } catch (IOException e) {
       e.printStackTrace();
       repetir = false;
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
       repetir = false;
     }
   }
   try {
     socket.close();
     System.exit(0);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
コード例 #28
0
 public static Object arrayToObject(byte[] b, int offset) {
   try {
     int len = arrayToInteger(b, offset);
     ByteArrayInputStream bais = new ByteArrayInputStream(b, offset + 4, len);
     ObjectInputStream ois = new ObjectInputStream(bais);
     return ois.readObject();
   } catch (IOException e) {
     e.printStackTrace();
     throw new RuntimeException("unable to deserialize packet (io error)", e);
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
     throw new RuntimeException("unable to deserialize packet (class not found)", e);
   }
 }
コード例 #29
0
 private void deSerializeXML(ObjectInputStream in) {
   Object o;
   try {
     while ((o = in.readObject()) != null) {
       System.out.println(o);
     }
   } catch (IOException e) {
     e.printStackTrace(); // To change body of catch statement use File | Settings | File
     // Templates.
   } catch (ClassNotFoundException e) {
     e.printStackTrace(); // To change body of catch statement use File | Settings | File
     // Templates.
   }
 }
コード例 #30
0
 public List_entity getAllLists() {
   List_entity listentities = new List_entity();
   try {
     out.println("select");
     ObjectInputStream receiveFromServer = new ObjectInputStream(sock.getInputStream());
     List_entity le = (List_entity) receiveFromServer.readObject();
     //            listentities.add(le);
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   }
   return listentities;
 }