private void receiveMessages() throws IOException {
    // handshake (true) endpoint versions
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    // if this version is < the MS version the other node is trying
    // to connect with, the other node will disconnect
    out.writeInt(MessagingService.current_version);
    out.flush();
    DataInputStream in = new DataInputStream(socket.getInputStream());
    int maxVersion = in.readInt();
    // outbound side will reconnect if necessary to upgrade version
    assert version <= MessagingService.current_version;
    from = CompactEndpointSerializationHelper.deserialize(in);
    // record the (true) version of the endpoint
    MessagingService.instance().setVersion(from, maxVersion);
    logger.debug(
        "Set version for {} to {} (will use {})",
        from,
        maxVersion,
        MessagingService.instance().getVersion(from));

    if (compressed) {
      logger.debug("Upgrading incoming connection to be compressed");
      in = new DataInputStream(new SnappyInputStream(socket.getInputStream()));
    } else {
      in = new DataInputStream(new BufferedInputStream(socket.getInputStream(), 4096));
    }

    while (true) {
      MessagingService.validateMagic(in.readInt());
      receiveMessage(in, version);
    }
  }
示例#2
1
  public static String submitPostData(String pos, String data) throws IOException {
    Log.v("req", data);

    URL url = new URL(urlPre + pos);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    configConnection(connection);
    if (sCookie != null && sCookie.length() > 0) {
      connection.setRequestProperty("Cookie", sCookie);
    }
    connection.connect();

    // Send data
    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
    output.write(data.getBytes());
    output.flush();
    output.close();

    // check Cookie
    String cookie = connection.getHeaderField("set-cookie");
    if (cookie != null && !cookie.equals(sCookie)) {
      sCookie = cookie;
    }

    // Respond
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    connection.disconnect();
    String res = sb.toString();
    Log.v("res", res);
    return res;
  }
 public void func_73273_a(DataOutputStream p_73273_1_) throws IOException {
   p_73273_1_.writeInt(field_73329_a);
   p_73273_1_.writeInt(field_73327_b);
   p_73273_1_.writeInt(field_73328_c);
   p_73273_1_.writeInt(field_73325_d);
   p_73273_1_.write(field_73326_e);
 }
 /** Opens the log file */
 private void open() throws IOException {
   fos = new FileOutputStream(makeLogName());
   oos = new DataOutputStream(new BufferedOutputStream(fos));
   oos.writeShort(Magic.LOGFILE_HEADER);
   oos.flush();
   curTxn = -1;
 }
  public int a(String var1) {
    Short var2 = (Short) d.get(var1);
    if (var2 == null) {
      var2 = Short.valueOf((short) 0);
    } else {
      var2 = Short.valueOf((short) (var2.shortValue() + 1));
    }

    d.put(var1, var2);
    if (b == null) {
      return var2.shortValue();
    } else {
      try {
        File var3 = b.a("idcounts");
        if (var3 != null) {
          class_dn var4 = new class_dn();
          Iterator var5 = d.keySet().iterator();

          while (var5.hasNext()) {
            String var6 = (String) var5.next();
            short var7 = ((Short) d.get(var6)).shortValue();
            var4.a(var6, var7);
          }

          DataOutputStream var9 = new DataOutputStream(new FileOutputStream(var3));
          class_dx.a(var4, (DataOutput) var9);
          var9.close();
        }
      } catch (Exception var8) {
        var8.printStackTrace();
      }

      return var2.shortValue();
    }
  }
  private void configBody(String params) throws IOException {
    try {
      byte[] postData = params.getBytes(ENCODING_UTF);
      int postDataLength = postData.length;
      connection.setDoOutput(true);
      connection.setRequestProperty("charset", ENCODING_UTF);
      connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
      connection.setUseCaches(false);
      wr = new DataOutputStream(connection.getOutputStream());
      wr.write(postData);
    } catch (IOException e) {
      if (e instanceof ConnectException)
        throw new IOException("Problemas ao tentar conectar com o servidor.");

      throw new IOException("Problemas ao processar dados para envio.");
    } finally {
      if (wr != null) {
        try {
          wr.flush();
          wr.close();
        } catch (IOException e) {
          L.output(e.getMessage());
        }
      }
    }
  }
示例#7
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    DataInputStream input = new DataInputStream(request.getInputStream());

    byte buff[];
    int leido = input.readByte();
    int tamano = leido;
    buff = new byte[tamano];
    leido = input.read(buff, 0, tamano);
    if (leido < tamano) {
      log.error("final inesperado");
      throw new IOException("Se leyo menos de los esperado");
    }
    input.close();
    String login = new String(buff);
    UsuarioDao dao = new UsuarioDao();
    BeanUsuario usuario = dao.getUsuarioByLogin(login);
    DataOutputStream output = new DataOutputStream(response.getOutputStream());
    if (usuario != null) {
      output.writeByte(1);
      usuario.write(output);
    } else {
      output.writeByte(0);
    }
    output.close();
  }
  public ActionForward createClassifications(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws FenixFilterException, FenixServiceException, IOException {

    IUserView userView = UserView.getUser();

    DynaActionForm dynaActionForm = (DynaActionForm) form;
    Integer degreeCurricularPlanID = (Integer) dynaActionForm.get("degreeCurricularPlanID");
    Integer[] entryGradeLimits = (Integer[]) dynaActionForm.get("entryGradeLimits");
    Integer[] approvationRatioLimits = (Integer[]) dynaActionForm.get("approvationRatioLimits");
    Integer[] arithmeticMeanLimits = (Integer[]) dynaActionForm.get("arithmeticMeanLimits");

    Object[] args = {
      entryGradeLimits, approvationRatioLimits, arithmeticMeanLimits, degreeCurricularPlanID
    };
    ByteArrayOutputStream resultStream =
        (ByteArrayOutputStream)
            ServiceUtils.executeService("CreateClassificationsForStudents", args);

    String currentDate = new SimpleDateFormat("dd-MMM-yy.HH-mm").format(new Date());
    response.setHeader(
        "Content-disposition",
        "attachment;filename=" + degreeCurricularPlanID + "_" + currentDate + ".zip");
    response.setContentType("application/zip");
    DataOutputStream dos = new DataOutputStream(response.getOutputStream());
    dos.write(resultStream.toByteArray());
    dos.close();

    return null;
  }
示例#9
0
  public static void main(String[] args) {
    try {
      ServerSocket socket = new ServerSocket(8606, 50, InetAddress.getByName("localhost"));
      Socket client = socket.accept();

      OutputStream out = client.getOutputStream();
      InputStream in = client.getInputStream();

      DataOutputStream dout = new DataOutputStream(out);
      DataInputStream din = new DataInputStream(in);

      String line = null;

      while (true) {
        line = din.readUTF();
        System.out.println(line);
        dout.writeUTF(line);
      }

    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public String execSu(String cmd) {
    Log.d(TAG, "^ Executing as SU '" + cmd + "'");
    try {
      Process process = Runtime.getRuntime().exec("su");
      DataInputStream is = new DataInputStream(process.getInputStream());
      DataOutputStream os = new DataOutputStream(process.getOutputStream());
      os.writeBytes(cmd + "\n");
      os.writeBytes("exit\n");
      os.flush();
      os.close();

      BufferedReader reader = new BufferedReader(new InputStreamReader(is));

      try {
        String fullOutput = "";
        String line;
        while ((line = reader.readLine()) != null) {
          fullOutput = fullOutput + line + "\n";
        }
        return fullOutput;
      } catch (IOException e) { // It seems IOException is thrown when it reaches EOF.
        e.printStackTrace();
        Log.e(TAG, "^ execSU, IOException 1");
      }
      process.waitFor();

    } catch (IOException e) {
      e.printStackTrace();
      Log.e(TAG, "^ execSU, IOException 2");
    } catch (InterruptedException e) {
      e.printStackTrace();
      Log.e(TAG, "^ execSU, InterruptedException");
    }
    return "";
  }
  public int write(DataOutputStream ostream) throws IOException {
    preWrite();
    int retVal = 0;

    {
      /** fix dependent sizes for desc_header * */
    }

    {
      /** fix dependent sizes for service_name * */
    }

    // write desc_header
    if (desc_header != null) retVal += desc_header.write(ostream);
    // write service_id
    {
      ostream.writeByte((service_id & 0x00FF0000) >> 16);
      ostream.writeShort((service_id & 0x0000FFFF));
      retVal += 3;
    }
    // write bf1
    ostream.writeByte(bf1.getValue());
    retVal += 1;
    // write service_name
    {
      retVal += service_name.write(ostream);
    }
    postWrite();
    return retVal;
  }
示例#12
0
 public synchronized List<Sample> getSamples() {
   if (samples == null) {
     samples = new ArrayList<Sample>();
     long lastEnd = 0;
     for (Line sub : subs) {
       long silentTime = sub.from - lastEnd;
       if (silentTime > 0) {
         samples.add(new SampleImpl(ByteBuffer.wrap(new byte[] {0, 0})));
       } else if (silentTime < 0) {
         throw new Error("Subtitle display times may not intersect");
       }
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       try {
         dos.writeShort(sub.text.getBytes("UTF-8").length);
         dos.write(sub.text.getBytes("UTF-8"));
         dos.close();
       } catch (IOException e) {
         throw new Error("VM is broken. Does not support UTF-8");
       }
       samples.add(new SampleImpl(ByteBuffer.wrap(baos.toByteArray())));
       lastEnd = sub.to;
     }
   }
   return samples;
 }
 /** Abstract. Writes the raw packet data to the data stream. */
 public void writePacketData(DataOutputStream par1DataOutputStream) throws IOException {
   par1DataOutputStream.writeInt(sfxID);
   par1DataOutputStream.writeInt(posX);
   par1DataOutputStream.writeByte(posY & 0xff);
   par1DataOutputStream.writeInt(posZ);
   par1DataOutputStream.writeInt(auxData);
 }
示例#14
0
  public static void main(String argv[]) throws Exception {
    String sentence;
    String modifiedSentence;

    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

    Socket clientSocket = new Socket("localhost", 6789);

    while (true) {
      DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

      BufferedReader inFromServer =
          new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      sentence = inFromUser.readLine();

      outToServer.writeBytes(sentence + '\n');

      if (sentence.equals("EXIT")) {
        break;
      }

      modifiedSentence = inFromServer.readLine();

      System.out.println("FROM SERVER: " + modifiedSentence);
    }
    clientSocket.close();
  }
 private void logInitialBalance(int accountNo, int balance, long timeSubmittedNS)
     throws IOException {
   transferLog.writeByte(RecordTypes.InitialBalance.ordinal());
   transferLog.writeInt(accountNo);
   transferLog.writeInt(balance);
   transferLog.writeLong(timeSubmittedNS);
 }
示例#16
0
  public static ArrayList<Patient> getPatientList(Socket socket, ArrayList<Patient> patientList) {
    int id;
    String ic;
    String fname;
    String lname;
    int age;
    int cnumber;

    try {
      OutputStream output = socket.getOutputStream();
      DataOutputStream dos = new DataOutputStream(output);
      InputStream input = socket.getInputStream();
      DataInputStream dis = new DataInputStream(input);

      dos.writeInt(2);

      int numberOfPatients = dis.readInt();

      for (int i = 0; i < numberOfPatients; i++) {
        id = dis.readInt();
        ic = dis.readUTF();
        fname = dis.readUTF();
        lname = dis.readUTF();
        age = dis.readInt();
        cnumber = dis.readInt();

        patientList.add(new Patient(id, ic, fname, lname, age, cnumber));
      }

    } catch (IOException e) {
      System.out.println("Cannot get IO streams.");
    }

    return patientList;
  }
示例#17
0
  private static void getMedicineList(Socket socket) {
    int medicineID;
    String medicineName;
    String medicineUnit;
    double price;

    try {
      OutputStream output = socket.getOutputStream();
      DataOutputStream dos = new DataOutputStream(output);
      InputStream input = socket.getInputStream();
      DataInputStream dis = new DataInputStream(input);

      dos.writeInt(8);

      int numberOfMedicine = dis.readInt();

      for (int i = 0; i < numberOfMedicine; i++) {
        medicineID = dis.readInt();
        medicineName = dis.readUTF();
        medicineUnit = dis.readUTF();
        price = dis.readDouble();

        medicineList.add(new Medicine(medicineID, medicineName, medicineUnit, price));
      }

    } catch (IOException e) {
      System.out.println("Cannot get IO streams.");
    }
  }
示例#18
0
  private void save2RS() {
    RecordStore rs = null;
    try {
      RecordStore.deleteRecordStore("score");
      rs = RecordStore.openRecordStore("score", true);

      try {
        for (int i = 0; i < 5; i++) {
          ByteArrayOutputStream bytes;
          DataOutputStream dataOut = new DataOutputStream(bytes = new ByteArrayOutputStream());
          ScoreItem item = (ScoreItem) list.elementAt(i);
          dataOut.writeUTF(item.name);
          dataOut.writeInt(item.points);
          dataOut.writeInt(item.level);
          dataOut.writeLong(item.date);
          byte[] byteA = bytes.toByteArray();
          rs.addRecord(byteA, 0, byteA.length);
        }
      } catch (IOException exp) {
        RecordStore.deleteRecordStore("score");
        System.out.println("XXXXXXXXXXXXXXXXXXXXXX");
      }
      // System.out.println("size of rs after saving: "+ rs.getNumRecords());
      rs.closeRecordStore();
    } catch (RecordStoreException exp) {
      System.out.println("fehler: " + exp.toString());
      exp.printStackTrace();
    }
  }
示例#19
0
 /**
  * Recursively dumps a byte representation of a subtree onto a stream. Used by stringfor( InspTree
  * ). Publicly available in case you want to stringify a subtree and really think this way is less
  * work than doing it yourself. You'll want to make sure the "spaces" static variable is
  * initialized first :)
  *
  * @param subtreeRoot root of subtree to represent
  * @param pts way to stringify each position
  * @param ostream stream on which to represent the subtree
  * @param t tree, so children(.) can be called
  * @param indentation number of spaces to indent this level
  * @param indentation_increment amount by which indentation will be increased before writing
  *     children
  */
 public static void writeNodeAndChildren(
     Position subtreeRoot,
     PositionToString pts,
     DataOutputStream ostream,
     InspectableTree t,
     int indentation,
     int indentation_increment) {
   try {
     // indent, then write the subtreeRoot
     ostream.write(spaces, 0, indentation);
     ostream.writeBytes(pts.stringfor(subtreeRoot));
     ostream.writeBytes("\n");
   } catch (java.io.IOException e) {
     System.err.println("\nAn I/O error occurred: " + e);
     return;
   }
   PositionIterator pp = t.children(subtreeRoot);
   // recur on all children
   while (pp.hasNext())
     writeNodeAndChildren(
         pp.nextPosition(),
         pts,
         ostream,
         t,
         indentation + indentation_increment,
         indentation_increment);
 }
示例#20
0
  private void apply() {
    int str = tePower.getPowerStrength();
    int mode = tePower.getPowerMode().toInt();
    int size = tePower.getPacketSize();

    ByteArrayOutputStream byteArray = new ByteArrayOutputStream(24);
    DataOutputStream output = new DataOutputStream(byteArray);
    try {
      output.writeInt(str);
      output.writeInt(mode);
      output.writeInt(size);
      output.writeInt(x);
      output.writeInt(y);
      output.writeInt(z);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Packet250CustomPayload packet = new Packet250CustomPayload();
    packet.channel = "WiduX-CT-Chn";
    packet.data = byteArray.toByteArray();
    packet.length = byteArray.size();
    EntityClientPlayerMP player = (EntityClientPlayerMP) this.mc.thePlayer;
    player.sendQueue.addToSendQueue(packet);
    // PacketDispatcher.sendPacketToServer(packet);
    System.out.println("PacketSend");
  }
    protected JSONObject doInBackground(String... params) {
      try {
        URL url = new URL(params[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        JSONObject parameters = new JSONObject();
        parameters.put("hash", "274ffe280ad2956ea85f35986958095d");
        parameters.put("seed", "10");

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

        wr.writeBytes(parameters.toString());
        wr.flush();
        wr.close();

        BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
          result.append(line);
        }

        JSONObject obj = new JSONObject(result.toString());
        return obj;
      } catch (Exception e) {
        this.exception = e;
        return null;
      }
    }
示例#22
0
  private static void primitiveTypes() {
    try (DataOutputStream dataOutputStream =
        new DataOutputStream(new FileOutputStream("d:/myData.dat"))) {
      long[] longs = new long[] {1, 2, 3, 5, 4};

      for (long aLong : longs) {
        dataOutputStream.writeLong(aLong);
      }
    } catch (IOException e) {
      System.out.println(e);
    }

    try (DataInputStream dataInputStream =
        new DataInputStream(new FileInputStream("d:/myData.dat"))) {
      try {
        while (true) {
          System.out.println(dataInputStream.readLong());
        }
      } catch (EOFException e) {
        System.out.println("end");
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
示例#23
0
    public void run() {
      try {
        // 读取客户端数据
        DataInputStream input = new DataInputStream(socket.getInputStream());
        String clientInputStr = input.readUTF(); // 这里要注意和客户端输出流的写方法对应,否则会抛 EOFException
        // 处理客户端数据
        System.out.println("客户端发过来的内容:" + clientInputStr);

        // 向客户端回复信息
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        System.out.print("请输入:\t");
        // 发送键盘输入的一行
        String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
        out.writeUTF(s);

        out.close();
        input.close();
      } catch (Exception e) {
        System.out.println("服务器 run 异常: " + e.getMessage());
      } finally {
        if (socket != null) {
          try {
            socket.close();
          } catch (Exception e) {
            socket = null;
            System.out.println("服务端 finally 异常:" + e.getMessage());
          }
        }
      }
    }
示例#24
0
 public void perform() {
   while (isRunning) {
     while (dataStack.size() > 0) {
       DataPackage dataPackage = dataStack.elementAt(0);
       dataStack.removeElementAt(0);
       try {
         byte[] data = dataPackage.getAllData();
         // log.info("Send data len: " + data.length);
         os.writeInt(data.length);
         os.write(data);
         os.flush();
         lastTimeSend = System.currentTimeMillis();
       } catch (IOException e) {
         log.warn(
             "ERROR: WriterThread: IOException when try to write data which has header: "
                 + dataPackage.getHeader());
         client.detroy();
         return;
       } catch (Throwable ex) {
         log.warn("ERROR: WriterThread : faltal exception:", ex);
       }
     }
     try {
       sleep(20);
     } catch (InterruptedException e) {
     }
   }
 }
示例#25
0
  /** Does a 'get' command. */
  private void get(final String[] cmd) throws Exception {
    int fd = -1;
    if (cmd.length < 2) {
      throw new Exception("USAGE: get <path> [local-path]");
    }
    String filename = cmd[1];
    if (filename.charAt(0) != '/' && filename.charAt(0) != '\\') {
      filename = cwd + filename;
    }
    String localFilename = null;
    if (cmd.length > 2) {
      localFilename = cmd[2];
    } else {
      localFilename = (new java.io.File(filename)).getName();
    }

    byte[] pathBytes = filename.getBytes(charset);

    System.arraycopy(serverClient.returnInt(pathBytes.length), 0, serverClient.cmdOpen, 0, 4);
    out.write(serverClient.cmdOpen, 0, 9);
    out.write(pathBytes);
    out.flush();

    String response = serverClient.readCommandString();
    if (response.equals(serverClient.OPEN)) {
      fd = serverClient.getCode();
      if (fd < 0) System.out.println("Open returned: " + fd);
    } else {
      throw new Exception("Open returned: " + response + "(" + serverClient.getCode() + ")");
    }

    if (fd >= 0) {
      download(fd, localFilename);
    }
  }
示例#26
0
  public void run() {
    try {
      DataInputStream in = new DataInputStream(sockd.getInputStream());
      DataOutputStream out = new DataOutputStream(sockd.getOutputStream());

      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
      vdb.setBw(bw);

      String name;

      while ((name = br.readLine()) != null) {
        System.out.println("graph for " + name);
        vdb.buildGraph(name, max_depth, peers_only);
        vdb.convertGraph();
        System.out.println("graph for " + name + " is ready");
        break;
      }

      br.close();
      in.close();
      bw.close();
      out.close();

      sockd.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
示例#27
0
 private final void writeIndex(char type, DiskLruCacheEntry entry) throws IOException {
   indexWriter.writeByte(type);
   indexWriter.writeUTF(entry.key);
   if (type == CLEAN) {
     indexWriter.writeInt(entry.size);
   }
 }
示例#28
0
 public void func_73273_a(DataOutputStream p_73273_1_) throws IOException {
   func_73271_a(this.field_73468_a, p_73273_1_);
   p_73273_1_.writeByte(this.field_73466_b);
   p_73273_1_.writeByte(this.field_73467_c | (this.field_73464_d ? 1 : 0) << 3);
   p_73273_1_.writeByte(this.field_73465_e);
   p_73273_1_.writeBoolean(this.field_82564_f);
 }
 @Override
 protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream)
     throws IOException {
   pDataOutputStream.writeInt(this.mID);
   pDataOutputStream.writeFloat(this.mX);
   pDataOutputStream.writeFloat(this.mY);
 }
 /** Abstract. Writes the raw packet data to the data stream. */
 public void writePacketData(DataOutputStream par1DataOutputStream) throws IOException {
   par1DataOutputStream.writeInt(xPosition);
   par1DataOutputStream.write(yPosition);
   par1DataOutputStream.writeInt(zPosition);
   par1DataOutputStream.write(type);
   par1DataOutputStream.write(metadata);
 }