public void actionPerformed(ActionEvent event) {
   int i;
   JButton aux = (JButton) event.getSource();
   if (aux == closeCompra) {
     try {
       String[] information = {
         JOptionPane.showInputDialog(null, "nombre"),
         JOptionPane.showInputDialog(null, "numero de targeta")
       };
       ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
       oos.writeObject(information);
       oos.flush();
       oos.writeObject(products);
       oos.flush();
       oos.writeObject(comprados);
       oos.flush();
       cleanTable();
       comprados.clear();
     } catch (Exception e) {
       System.out.print("\nerror al cerrar la compra " + e.getMessage());
     }
     return;
   }
   for (i = 0; aux != mostrador.addCar[i]; i++) {;
   }
   if (products.get(i).getPiesas() > 0) {
     products.get(i).popParts();
     addCompra(products.get(i));
     total.setText("total: " + comprados.getLast().getTotal());
   } else {
     JOptionPane.showMessageDialog(null, "no seas menso ya no hay mas piesas! :@");
   }
 }
  public void run() {
    try {
      ObjectOutputStream outputStream = new ObjectOutputStream(_clientSocket.getOutputStream());
      outputStream.flush();

      DataInputStream inputStream = new DataInputStream(_clientSocket.getInputStream());

      while (true) {
        String request = inputStream.readUTF();

        Trace.info("Received request: " + request);

        RMResult response = processIfComposite(request);
        if (response == null) {
          response = processIfCIDRequired(request);
          if (response == null) {
            response = processAtomicRequest(request);
          }
        }

        outputStream.writeObject(response);
        outputStream.flush();
      }
    } catch (EOFException eof) {
      Trace.info("A client closed a connection.");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 private void handleKeepAlive() {
   Connection c = null;
   try {
     netCode = ois.readInt();
     c = checkConnectionNetCode();
     if (c != null && c.getState() == Connection.STATE_CONNECTED) {
       oos.writeInt(ACK_KEEP_ALIVE);
       oos.flush();
       System.out.println("->ACK_KEEP_ALIVE"); // $NON-NLS-1$
     } else {
       System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$
       oos.writeInt(NOT_CONNECTED);
       oos.flush();
     }
   } catch (IOException e) {
     System.out.println("handleKeepAlive: " + e.getMessage()); // $NON-NLS-1$
     if (c != null) {
       c.setState(Connection.STATE_DISCONNECTED);
       System.out.println(
           "Connection closed with "
               + c.getRemoteAddress()
               + //$NON-NLS-1$
               ":"
               + c.getRemotePort()); // $NON-NLS-1$
     }
   }
 }
Exemple #4
0
  public synchronized void sendItem(long index, Entry<?> item) {
    try {
      ObjectOutputStream oOut = null;
      DataBlockOutputStream bout = null;
      try {
        bout = new DataBlockOutputStream(this.dataFile.getBlockSize());

        oOut = new ObjectOutputStream(bout);
        oOut.writeObject(item.getItem());
        oOut.flush();
      } finally {
        if (oOut != null) {
          oOut.flush();
          oOut.close();
        }
      }

      String idx = Long.toString(index, Character.MAX_RADIX);
      long reference = this.index.get(idx, this.indexFile);

      if (reference == -1) {
        reference = DataChain.save(bout.getBlocks(), this.dataFile);
        this.index.registry(idx, reference, this.indexFile);
      } else {
        reference = DataChain.update(reference, bout.getBlocks(), this.dataFile);
        this.index.registry(idx, reference, this.indexFile);
      }
      this.dataFile.flush();
      this.indexFile.flush();
    } catch (Throwable e) {
      throw new IllegalStateException(e);
    }
  }
  @Override
  public void write(String path) throws IOException {
    File dir = FileUtils.getFile(path, "ensemble", getName());
    if (!dir.isDirectory()) {
      dir.mkdirs();
    }
    ObjectOutputStream oop =
        new ObjectOutputStream(new FileOutputStream(new File(dir, "similarityCoefficients")));
    oop.writeObject(simlarityCoefficients);
    oop.flush();
    oop.close();

    oop = new ObjectOutputStream(new FileOutputStream(new File(dir, "mostSimilarCoefficients")));
    oop.writeObject(mostSimilarCoefficients);
    oop.flush();
    oop.close();

    oop = new ObjectOutputStream(new FileOutputStream(new File(dir, "similarityInterpolator")));
    oop.writeObject(similarityInterpolator);
    oop.flush();
    oop.close();

    oop = new ObjectOutputStream(new FileOutputStream(new File(dir, "mostSimilarInterpolator")));
    oop.writeObject(mostSimilarInterpolator);
    oop.flush();
    oop.close();
  }
    @Override
    public void run() {
      // TODO Auto-generated method stub
      try {
        Socket tempSocket = new Socket(ipname, port);
        System.out.println("发起与PC的连接~~~~~~~~~~~··");

        ObjectOutputStream clientOutputStream =
            new ObjectOutputStream(tempSocket.getOutputStream());
        ObjectInputStream clientInputStream = new ObjectInputStream(tempSocket.getInputStream());

        // 向服务器输出Producer信息
        PacketBean packetBean = new PacketBean();
        ProducerBean producerBean = new ProducerBean();
        producerBean.setAndroidName(androidId);
        producerBean.setPasswd(passwd);
        packetBean.setPacketType(PacketBean.PRODUCER_INFO);
        packetBean.setData(producerBean);
        clientOutputStream.writeObject(packetBean);
        clientOutputStream.flush();
        clientInputStream.readObject();
        ByteArrayOutputStream myoutputstream = new ByteArrayOutputStream();

        while (true) {
          try {
            myoutputstream = streamIt.getOutstream();
            byte[] datas = myoutputstream.toByteArray();
            // System.out.println("图片数据的长度: " + datas.length);
            PacketBean data = new PacketBean(PacketBean.TYPE_IMAGE, datas);
            // PacketBean data = new PacketBean("producer",datas);

            clientOutputStream.writeObject(data);
            // System.out.println("发送了图片~~~~~~~~~~~~~~~~~~~~");

            data = (PacketBean) clientInputStream.readObject();
            // clientInputStream.close();
            clientOutputStream.flush();
            // clientOutputStream.close();

            myoutputstream.flush();
            // myoutputstream.close();
            // Thread.sleep(2000);
          } catch (Exception e) {
            // TODO: handle exception
            System.out.println("Connection Close~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            // break;
          } /*finally{
            	clientInputStream.close();
            	clientOutputStream.close();
            	tempSocket.close();
            }*/
        }
        // tempSocket.close();
      } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
      }
    }
Exemple #7
0
  public Game(boolean host) {
    try {
      if (host) {
        System.out.println("Hosting...");
        server = new ServerSocket(port, 4, InetAddress.getByName(serverIP));
        System.out.println("Ready!\nAwaiting client...");
        client = server.accept();
        System.out.println("Client connected!\nBuffering...");
        out = new ObjectOutputStream(client.getOutputStream());
        in = new ObjectInputStream(client.getInputStream());
        System.out.println("Buffered!\nPinging for 256 bytes...");
        long start = System.currentTimeMillis();
        byte[] ping = new byte[256];
        in.read(ping);
        System.out.println("Latency: " + (System.currentTimeMillis() - start));
        out.writeLong(start);
        out.flush();
        System.out.println("Starting threads...");
        new ThreadSend(world, out);
        new ThreadReceive(world, in);
        System.out.println("Started!\nCreating game world...");
      } else {
        System.out.println("Connecting...");
        socket = new Socket(connectIP, port);
        System.out.println("Connected!\nBuffering...");
        in = new ObjectInputStream(socket.getInputStream());
        out = new ObjectOutputStream(socket.getOutputStream());
        byte[] ping = new byte[256];
        new Random().nextBytes(ping);
        System.out.println("Buffered\nPinging for 256 bytes...");
        out.write(ping);
        out.flush();
        long latency = in.readLong();
        System.out.println("Latency: " + (System.currentTimeMillis() - latency));
        System.out.println("Starting threads...");
        new ThreadReceive(world, in);
        new ThreadSend(world, out);
        System.out.println("Started!\nCreating game world...");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      Display.setDisplayMode(new DisplayMode(width, height));
      Display.create();
    } catch (Exception e) {
      e.printStackTrace();
    }

    world.init();

    while (!Display.isCloseRequested()) {
      if (ended) break;
      world.update();
    }

    Display.destroy();
  }
  /*
   * (non-Javadoc) <p>Title: writeObject</p> <p>Description: 将缓存写入本地</p>
   *
   *
   *
   * @see
   * com.ucap.cloud.business.formserver.data.outin.IDataInputOutput#writeObject
   * (java.lang.Object)
   */
  public void writeObject() {
    // 1.得到当前的用户名
    // 2.根据用户名得到IdfUserModel对象
    // 3.将IdfUserModel对象写入缓存
    // 4.序列化发布的匿名表单
    ObjectOutputStream out;
    // add by sunjq
    try {
      AllNiMingIdfModel allnm =
          (AllNiMingIdfModel) this.ccache.getVluae("allNiMingIdf"); // 依据idfname获取匿名表单
      File file = new File(this.getUrl() + this.path + "niming.txt");
      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }

      out = new ObjectOutputStream(new FileOutputStream(file));
      // 写入的是IdfUserModel对象
      out.writeObject(allnm);
      // 清空流
      out.flush();
      // 关闭流
      out.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    // end add
    Set<String> userMap = alreadyuser.keySet();
    for (String userid : userMap) {
      IdfUserModel user = (IdfUserModel) this.ccache.getVluae(userid);
      if (null == user) {
        return;
      }

      try {
        File file =
            new File(this.getUrl() + this.path + userid + "/" + "useridf/" + (userid + ".txt"));
        if (!file.getParentFile().exists()) {
          file.getParentFile().mkdirs();
        }

        out = new ObjectOutputStream(new FileOutputStream(file));
        // 写入的是IdfUserModel对象
        out.writeObject(user);
        // 清空流
        out.flush();
        // 关闭流
        out.close();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
Exemple #9
0
  public static void main(String[] args) {
    int id = -1, port = -1;
    String host = "";

    // Parse host and port of the middleware and id of the client.
    try {
      host = args[0];
      port = Integer.parseInt(args[1]);
      id = Integer.parseInt(args[2]);
    } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
      logger.error("Usage: java -jar Client <host> <port> <client-id>");
      System.exit(1);
    }

    // Try to open a connection to the middleware
    try {
      socket = new Socket(host, port);
      oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
      oos.flush();
      ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
    } catch (IOException e) {
      logger.error("Error occurred while connecting to the middleware.");
    }

    // Initialize scanner to parse user input
    sc = new Scanner(System.in);
    // Initialize a map with different command handlers
    Map<String, CommandBuilder> commandsMap = initializeCommands();
    while (sc.hasNextLine()) {
      try {
        // Build a command read from standard input
        String commandArgs[] = sc.nextLine().split("\\s+");
        Command command =
            commandsMap.get(commandArgs[0] + commandArgs[1]).createCommand(sc, id, commandArgs);

        // Send the command to the middleware
        oos.writeUnshared(command);
        oos.flush();

        // Read the response and calculate the elapsed time
        long start = System.currentTimeMillis();
        String response = (String) ois.readUnshared();
        long end = System.currentTimeMillis();
        logger.info(response + " Responsetime: " + (end - start) + "ms");
      } catch (ArrayIndexOutOfBoundsException
          | NumberFormatException
          | NullPointerException
          | NoSuchElementException
          | IllegalStateException e) {
        logger.error("Invalid command");
      } catch (IOException | ClassNotFoundException e) {
        logger.error("Connection error");
      }
    }
    close();
  }
  public static void main(String[] args) throws IOException, ClassNotFoundException {

    FileOutputStream fout = null;
    ObjectOutputStream out = null;

    FileInputStream fin = null;
    ObjectInputStream in = null;

    SerializeClass obj = null;
    SerializeClass s = null;

    // Serialization for is-a relationship Starts
    obj = new SerializeClass(1, "Dushyant");

    // Serialization
    fout = new FileOutputStream("file.txt");
    out = new ObjectOutputStream(fout);

    out.writeObject(obj);
    out.flush();
    fout.close();
    out.close();

    // De-Serialization
    fin = new FileInputStream("file.txt");
    in = new ObjectInputStream(fin);
    s = (SerializeClass) in.readObject();
    System.out.println(s.getId() + " " + s.getName());

    fin.close();
    in.close();

    // Serialization for is-a relationship Ends

    // Serialization for has-a relationship Starts
    obj = new SerializeClass(1, "Dushyant");
    obj.setCityAndState(new CityState("Gurgaon", "Haryana"));
    fout = new FileOutputStream("file.txt");
    out = new ObjectOutputStream(fout);
    out.writeUTF(obj.getName()); // 1
    out.writeUTF(obj.getCityAndState().getCityName()); // 1
    out.writeUTF(obj.getCityAndState().getStateName()); // 1
    out.flush();
    out.close();

    fin = new FileInputStream("file.txt");
    in = new ObjectInputStream(fin);
    s = new SerializeClass();
    s.setCityAndState(new CityState());
    s.setName(in.readUTF()); // 2
    s.getCityAndState().setCityName(in.readUTF()); // 2
    s.getCityAndState().setStateName(in.readUTF()); // 2

    System.out.println(s);
    // Serialization for has-a relationship Ends
  }
Exemple #11
0
  // Initializes a GameClinet over port to the given host,
  // requesting to join using the given handle
  private GameClient(String host, int port, String handle) throws IOException {
    conn = new Socket(host, port);
    oos = new ObjectOutputStream(conn.getOutputStream());
    oos.flush();
    ois = new ObjectInputStream(conn.getInputStream());

    oos.writeUTF(handle);
    oos.flush();

    runReceiveThread();
  }
Exemple #12
0
 /**
  * 将对象转换成byte数组
  *
  * @param object
  * @return
  * @throws Exception
  */
 public static byte[] serializeObject(Object object) throws Exception {
   if (object == null) {
     return null;
   }
   ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000);
   ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
   os.flush();
   os.writeObject(object);
   os.flush();
   byte[] returnValue = byteStream.toByteArray();
   os.close();
   os = null;
   return returnValue;
 }
  private void button_percent_do_dialogActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_button_percent_do_dialogActionPerformed
    // TODO add your handling code here:

    if (operationIndex == 1) {
      try {
        out.writeObject("CREATE_PERCENT");
        out.flush();
        Percent temp = new Percent();
        PercentPK tempPK = new PercentPK();
        tempPK.setValue(Double.parseDouble(jTextField1.getText()));
        tempPK.setCurrencyId(Integer.parseInt(jTextField2.getText()));
        tempPK.setDepositTypeId(Integer.parseInt(jTextField3.getText()));
        temp.setPercentPK(tempPK);
        out.writeObject(temp);
        out.flush();
        boolean isDone = (boolean) in.readObject();
        if (isDone) {
          this.dispose();
        }
      } catch (IOException ex) {
        Logger.getLogger(CurrencyDialog.class.getName()).log(Level.SEVERE, null, ex);
      } catch (ClassNotFoundException ex) {
        Logger.getLogger(CurrencyDialog.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    if (operationIndex == 2) {
      try {
        out.writeObject("UPDATE_PERCENT");
        out.flush();
        Percent temp = new Percent();
        PercentPK tempPK = new PercentPK();
        tempPK.setId(Integer.parseInt(jLabel5.getText()));
        tempPK.setValue(Double.parseDouble(jTextField1.getText()));
        tempPK.setCurrencyId(Integer.parseInt(jTextField2.getText()));
        tempPK.setDepositTypeId(Integer.parseInt(jTextField3.getText()));
        temp.setPercentPK(tempPK);
        out.writeObject(temp);
        out.flush();
        boolean isDone = (boolean) in.readObject();
        if (isDone) {
          this.dispose();
        }
      } catch (IOException ex) {
        Logger.getLogger(CurrencyDialog.class.getName()).log(Level.SEVERE, null, ex);
      } catch (ClassNotFoundException ex) {
        Logger.getLogger(CurrencyDialog.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  } // GEN-LAST:event_button_percent_do_dialogActionPerformed
 public void enviarDatos(String mensaje, int origen) {
   try {
     if (origen == 1) {
       salida.writeObject(mensaje);
       salida.flush();
     } else if (origen == 0) {
       salida.writeObject("SERVIDOR>>> " + mensaje);
       salida.flush();
       mostrarMensaje("\nSERVIDOR>>> " + mensaje);
     }
   } catch (IOException excepcionES) {
     SkServidorView.jtaMensajeServidor.append("\nError al escribir objeto");
   }
 }
Exemple #15
0
  private void startServer() {
    System.out.println("Starting server...");
    try {
      ServerSocket servSocket = new ServerSocket(6789);
      // endless Server-loop
      int methID;
      Benutzer ben = new Benutzer();
      while (true) {
        Socket client = servSocket.accept();
        System.out.println("Accepted client...");
        ObjectInputStream in = new ObjectInputStream(client.getInputStream());
        ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
        System.out.println("Received both Streams on ServerOrb...");
        methID = in.readInt();
        System.out.println("Read the Method-ID...");
        try {
          ben = (Benutzer) in.readObject();
          System.out.println("Received Benutzer-object...");
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        }

        if (methID == 1) {
          out.writeBoolean(bv.benutzerOk(ben));
          out.flush();
          System.out.println("Flushed for Boolean-Value...");
          System.out.println("Boolean bei methID==1 zurueckgegeben.");
          System.out.println();
        } else if (methID == 2) {
          try {
            bv.benutzerEintragen(ben);
            System.out.println("Benutzer erfolgreich in die Datenhaltung eingetragen.#");
            out.writeObject(ben);
            out.flush();
            System.out.println("Wrote Benutzer-Object with manual flush...");
            System.out.println();
          } catch (BenutzerSchonVorhandenException e) {
            out.writeObject(e);
            System.out.println("BenutzerSchonVorhandenException wurde verschickt.");
          }
        }
        in.close();
        out.close();
        System.out.println("Closed OutputStream on ServerOrb...");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @Override
  public void run() {
    try {
      System.out.println("Peticion de " + soc.getInetAddress().getHostAddress());
      salida.writeObject(camaras);
      salida.flush();
      salida.writeObject(alertas);
      salida.flush();

      salida.close();
      soc.close();
    } catch (IOException ex) {
      Logger.getLogger(conexionMovil.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
 private TaskObjectsExecutionResults runObject(TaskObjectsExecutionRequest obj)
     throws IOException, PDBatchTaskExecutorException {
   Object res = null;
   try {
     setAvailability(false);
     _oos.writeObject(obj);
     _oos.flush();
     res = _ois.readObject();
     setAvailability(true);
   } catch (IOException e) { // worker closed connection
     processException(e);
     throw e;
   } catch (ClassNotFoundException e) {
     processException(e);
     throw new IOException("stream has failed");
   }
   if (res instanceof TaskObjectsExecutionResults) {
     _isPrevRunSuccess = true;
     return (TaskObjectsExecutionResults) res;
   } else {
     PDBatchTaskExecutorException e =
         new PDBatchTaskExecutorException("worker failed to run tasks");
     if (_isPrevRunSuccess == false && !sameAsPrevFailedJob(obj._tasks)) {
       processException(e); // twice a loser, kick worker out
     }
     _isPrevRunSuccess = false;
     _prevFailedBatch = obj._tasks;
     throw e;
   }
 }
 private PDBTEW2Listener(PDBTExecSingleCltWrkInitSrv srv, Socket s) throws IOException {
   _srv = srv;
   _s = s;
   _ois = new ObjectInputStream(_s.getInputStream());
   _oos = new ObjectOutputStream(_s.getOutputStream());
   _oos.flush();
 }
Exemple #19
0
 /** 克隆Serializable */
 @SuppressWarnings("unchecked")
 public static <T> T cloneSerializable(T src) throws RuntimeException {
   ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream();
   ObjectOutputStream out = null;
   ObjectInputStream in = null;
   T dest = null;
   try {
     out = new ObjectOutputStream(memoryBuffer);
     out.writeObject(src);
     out.flush();
     in = new ObjectInputStream(new ByteArrayInputStream(memoryBuffer.toByteArray()));
     dest = (T) in.readObject();
   } catch (Exception e) {
     throw new RuntimeException(e);
   } finally {
     if (out != null) {
       try {
         out.close();
         out = null;
       } catch (Exception e) {
       }
     }
     if (in != null) {
       try {
         in.close();
         in = null;
       } catch (Exception e) {
       }
     }
   }
   return dest;
 }
  public byte[] getContentHash() {
    byte[] bytes = null;

    try {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);

      objectStream.writeObject(components);
      objectStream.writeObject(pointers);
      objectStream.flush();

      bytes = byteStream.toByteArray();
    } catch (IOException ioe) {
      // too bad we don't have a good way to throw a serialziation exception
      return null;
    }

    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
      return null;
    }

    md.reset();
    md.update(bytes);

    return md.digest();
  }
 private void createDB() throws IOException {
   File db = new File(dbLocation);
   ObjectOutputStream w = new ObjectOutputStream(new FileOutputStream(dbLocation));
   w.writeObject(digestDB);
   w.flush();
   w.close();
 }
  /*------------------------------------------------------------ */
  protected Object encodeName(Object value) throws IOException {
    if (value instanceof Number
        || value instanceof String
        || value instanceof Boolean
        || value instanceof Date) {
      return value;
    } else if (value.getClass().equals(HashMap.class)) {
      BasicDBObject o = new BasicDBObject();
      for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
        if (!(entry.getKey() instanceof String)) {
          o = null;
          break;
        }
        o.append(encodeName(entry.getKey().toString()), encodeName(entry.getValue()));
      }

      if (o != null) return o;
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bout);
    out.reset();
    out.writeUnshared(value);
    out.flush();
    return bout.toByteArray();
  }
 @Override
 public void run() {
   while (running) {
     if (queue.size() == 0) {
       try {
         Thread.sleep(20);
       } catch (InterruptedException ex) {
         // üres
       }
       continue;
     }
     Token aToken = queue.remove(0);
     try {
       objectOutput.writeObject(aToken.outputMsg);
       objectOutput.flush();
     } catch (IOException e) {
       onException(e);
     }
     /*
      * Értesíteni a szálat ami küldte ezt a "Token"-t, hogy befejeztük a vele kapcsolatos műveletetek
      */
     synchronized (aToken) {
       aToken.notify();
     }
   } // "while" ciklus végét jelző zárójel
 }
Exemple #24
0
  /**
   * @param state the object returned from <code>UIView.processSaveState</code>
   * @return If {@link
   *     com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter#SerializeServerStateDeprecated}
   *     is <code>true</code>, serialize and return the state, otherwise, return <code>state</code>
   *     unchanged.
   */
  protected Object handleSaveState(Object state) {

    if (webConfig.isOptionEnabled(SerializeServerStateDeprecated)
        || webConfig.isOptionEnabled(SerializeServerState)) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
      ObjectOutputStream oas = null;
      try {
        oas =
            serialProvider.createObjectOutputStream(
                ((compressViewState) ? new GZIPOutputStream(baos, 1024) : baos));
        //noinspection NonSerializableObjectPassedToObjectStream
        oas.writeObject(state);
        oas.flush();
      } catch (Exception e) {
        throw new FacesException(e);
      } finally {
        if (oas != null) {
          try {
            oas.close();
          } catch (IOException ioe) {
            if (LOGGER.isLoggable(Level.FINEST)) {
              LOGGER.log(Level.FINEST, "Closing stream", ioe);
            }
          }
        }
      }
      return baos.toByteArray();
    } else {
      return state;
    }
  }
  public static void writeComplete(String filename, InterestPointListInfo ipl) {

    ObjectOutputStream out = null;
    try {
      out = new ObjectOutputStream(new FileOutputStream(filename));
      List<SURFInterestPoint> list = ipl.getList();
      out.writeInt(list.size());
      for (SURFInterestPoint ip : list) {
        out.writeObject(ip);
      }
      out.writeInt(ipl.getWidth());
      out.writeInt(ipl.getHeight());
      out.flush();
    } catch (Exception e) {
      logger.error(e.getMessage());
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          logger.error(e.getMessage());
        }
      }
    }
  }
 @Override
 public <T> T run(Callable<T> r) {
   T result = null;
   try {
     synchronized (store) {
       result = r.call();
       File temp = new File(store.getParentFile(), "temp_" + store.getName());
       FileOutputStream file = new FileOutputStream(temp);
       ObjectOutputStream out = new ObjectOutputStream(file);
       out.writeObject(properties);
       out.writeObject(maps);
       out.flush();
       out.close();
       file.flush();
       file.close();
       Files.move(
           temp.toPath(),
           store.toPath(),
           StandardCopyOption.ATOMIC_MOVE,
           StandardCopyOption.REPLACE_EXISTING);
     }
   } catch (Exception e) {
     // If something happened here, that is a serious bug so we need to assert.
     throw Assert.failure("Failure flushing FlatFileKeyValueStorage", e);
   }
   return result;
 }
Exemple #27
0
 public static void main(String[] args) {
   String str;
   Socket sock = null;
   ObjectOutputStream writer = null;
   Scanner kb = new Scanner(System.in);
   try {
     sock = new Socket("127.0.0.1", 4445);
   } catch (IOException e) {
     System.out.println("Could not connect.");
     System.exit(-1);
   }
   try {
     writer = new ObjectOutputStream(sock.getOutputStream());
   } catch (IOException e) {
     System.out.println("Could not create write object.");
     System.exit(-1);
   }
   str = kb.nextLine();
   try {
     writer.writeObject(str);
     writer.flush();
   } catch (IOException e) {
     System.out.println("Could not write to buffer");
     System.exit(-1);
   }
   try {
     sock.close();
   } catch (IOException e) {
     System.out.println("Could not close connection.");
     System.exit(-1);
   }
   System.out.println("Wrote and exited successfully");
 }
  /** java.io.ObjectOutputStream#writeUnshared(java.lang.Object) */
  public void test_writeUnshared2() throws Exception {
    // Regression for HARMONY-187
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);

    Object o = new Object[1];
    oos.writeObject(o);
    oos.writeUnshared(o);
    oos.writeObject(o);
    oos.flush();

    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));

    Object[] oa = new Object[3];
    for (int i = 0; i < oa.length; i++) {
      oa[i] = ois.readObject();
    }

    oos.close();
    ois.close();

    // All three conditions must be met
    assertNotSame("oa[0] != oa[1]", oa[0], oa[1]);
    assertNotSame("oa[1] != oa[2]", oa[1], oa[2]);
    assertSame("oa[0] == oa[2]", oa[0], oa[2]);
  }
Exemple #29
0
 public void enviar(ConexionPaquete paquete) throws IOException {
   synchronized (os_bloqueo) {
     os.reset();
     os.writeObject(paquete);
     os.flush();
   }
 }
Exemple #30
0
  @SuppressWarnings("boxing") // no need to worry about boxing here
  @Test
  public void testSerialization() throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    try (final ObjectOutputStream oos = new ObjectOutputStream(out)) {
      oos.writeObject(CSVFormat.DEFAULT);
      oos.flush();
    }

    final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
    final CSVFormat format = (CSVFormat) in.readObject();

    assertNotNull(format);
    assertEquals("delimiter", CSVFormat.DEFAULT.getDelimiter(), format.getDelimiter());
    assertEquals("encapsulator", CSVFormat.DEFAULT.getQuoteCharacter(), format.getQuoteCharacter());
    assertEquals("comment start", CSVFormat.DEFAULT.getCommentMarker(), format.getCommentMarker());
    assertEquals(
        "record separator", CSVFormat.DEFAULT.getRecordSeparator(), format.getRecordSeparator());
    assertEquals("escape", CSVFormat.DEFAULT.getEscapeCharacter(), format.getEscapeCharacter());
    assertEquals(
        "trim",
        CSVFormat.DEFAULT.getIgnoreSurroundingSpaces(),
        format.getIgnoreSurroundingSpaces());
    assertEquals(
        "empty lines", CSVFormat.DEFAULT.getIgnoreEmptyLines(), format.getIgnoreEmptyLines());
  }