Ejemplo n.º 1
1
  @Override
  public void run() {
    try {
      // Open socket
      socket = new Socket("127.0.0.1", 5432);
      // Get input streams
      DataOutputStream writer =
          new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
      DataInputStream scanner = new DataInputStream(socket.getInputStream());
      // Send calculation data
      writer.writeDouble(zoom);
      writer.writeDouble(zoomTranslateX);
      writer.writeDouble(zoomTranslateY);
      writer.writeInt(level);
      writer.writeInt(mode);
      writer.flush();
      System.out.println("Sent data");

      // Wait for server to do calculations
      while (scanner.available() == 0) {
        Thread.sleep(level);
      }
      System.out.println("Start drawing");
      // Start reading and drawing
      application.clearKochPanel();
      int counter = 0;
      while (true) {
        if (scanner.available() > 0) {
          application.drawEdge(
              new Edge(
                  scanner.readDouble(),
                  scanner.readDouble(),
                  scanner.readDouble(),
                  scanner.readDouble(),
                  Color.hsb(scanner.readDouble(), 1, 1)));
          counter = 0;
        } else {
          Thread.sleep(10);
          counter++;
          if (counter > 10) {
            break;
          }
        }
      }
      System.out.println("Finished drawing!");

      writer.writeChar('H');
      writer.flush();
      writer.close();
      scanner.close();
      socket.close();
    } catch (Exception e) {
      System.out.println("Receiving edges failed!");
      System.out.println(e.getMessage());
      Thread.currentThread().interrupt();
    }
  }
Ejemplo n.º 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;
  }
  @SuppressWarnings("deprecation")
  public String runAsUser(String command) {
    String output = new String();

    try {
      Process p = Runtime.getRuntime().exec("sh");
      DataOutputStream os = new DataOutputStream(p.getOutputStream());
      DataInputStream is = new DataInputStream(p.getInputStream());

      os.writeBytes("exec " + command + "\n");
      os.flush();

      String line = new String();
      while ((line = is.readLine()) != null) {
        output = output + line;
      }

      // os.writeBytes("exit\n");
      os.flush();
      p.waitFor();

    } catch (Throwable e) {
      Log.i(MyApp.TAG, e.getMessage().toString());
    }

    return output;
  }
Ejemplo n.º 4
0
  private void sendEntityBodyToClient(
      DataOutputStream socketOutputStream, HtmlResponse htmlResponse, boolean isChunked)
      throws IOException {

    byte[] content = htmlResponse.getEntityBody();

    if (!isChunked) {
      try {
        socketOutputStream.write(content, 0, content.length);
        socketOutputStream.flush();
      } catch (IOException e) {
        System.out.println("Writing the answer caused an error" + e.toString());
      }
    } else {

      int currentIndexStart = 0;
      int currentIndexEnd = Math.min(CHUNCKED_BYTES - 1, content.length - 1);
      int lengthOfBytesSent = currentIndexEnd - currentIndexStart + 1;

      while (currentIndexStart < content.length - 1) {
        socketOutputStream.writeBytes(Integer.toHexString(lengthOfBytesSent) + CRLF);
        socketOutputStream.write(content, currentIndexStart, lengthOfBytesSent);
        socketOutputStream.writeBytes(CRLF);
        socketOutputStream.flush();

        currentIndexStart = currentIndexEnd + 1;
        currentIndexEnd = Math.min(currentIndexStart + CHUNCKED_BYTES - 1, content.length - 1);
        lengthOfBytesSent = currentIndexEnd - currentIndexStart + 1;
      }

      socketOutputStream.writeBytes("0" + CRLF);
      socketOutputStream.writeBytes(CRLF);
      socketOutputStream.flush();
    }
  }
Ejemplo n.º 5
0
 public void sendMessage(String sendMessage) {
   try {
     out = new DataOutputStream(socket2.getOutputStream());
     if (sendMessage.equals("Windows")) {
       out.writeByte(0x1);
       out.flush();
       return;
     }
     if (sendMessage.equals("Unix")) {
       out.writeByte(0x2);
       out.flush();
       return;
     }
     if (sendMessage.equals("Linux")) {
       out.writeByte(0x3);
       out.flush();
     } else {
       out.writeUTF(sendMessage);
       out.flush();
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     if (out != null) {
       try {
         out.close();
       } catch (IOException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
       }
     }
   }
 }
  private void writeChunkString(byte[] string, DataOutputStream writer) {

    try {
      ByteArrayInputStream fis = new ByteArrayInputStream(string);
      byte[] bFile = new byte[1024];
      int chunkSize = 0;

      // read until the end of the stream.
      while ((chunkSize = fis.read(bFile)) != -1) {
        writer.writeBytes(Integer.toHexString(chunkSize));
        writer.writeBytes("\r\n");
        writer.flush();
        writer.write(bFile, 0, chunkSize);
        writer.writeBytes("\r\n");
        writer.flush();
      }

      fis.close();
      writer.writeBytes(Integer.toHexString(0));
      writer.writeBytes("\r\n");
      writer.flush();
      writer.writeBytes("\r\n");
      writer.flush();
    } catch (FileNotFoundException e) {
      System.err.println("ERROR: File Not Found");
    } catch (IOException e) {
      System.err.println("ERROR: IO Exception");
    }
  }
Ejemplo n.º 7
0
  /**
   * Execute command as root.
   *
   * @param cmd Command to be executed as ROOT
   * @return true if execution succeed, false otherwise
   */
  public static boolean execAsRoot(String cmd) {
    if (cmd == null || cmd.equals("")) throw new IllegalArgumentException();

    boolean retval = false;

    try {
      Process suProcess = Runtime.getRuntime().exec("su");
      DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());

      os.writeBytes(cmd + "\n");
      os.flush();
      os.writeBytes("exit\n");
      os.flush();

      try {
        int suProcessRetval = suProcess.waitFor();
        if (255 != suProcessRetval) {
          // Root access granted
          retval = true;
        } else {
          // Root access denied
          retval = false;
        }
      } catch (Exception ex) {
        Log.e("Error executing root action", ex.toString());
      }
    } catch (IOException ex) {
      Log.w("ROOT", "Can't get root access", ex);
    } catch (SecurityException ex) {
      Log.w("ROOT", "Can't get root access", ex);
    } catch (Exception ex) {
      Log.w("ROOT", "Error executing internal operation", ex);
    }
    return retval;
  }
Ejemplo n.º 8
0
  /**
   * 以root权限执行命令
   *
   * @param strings
   */
  public static void sudo(String... strings) {
    DataOutputStream outputStream = null;
    BufferedReader inputStream = null;
    try {
      Process su = Runtime.getRuntime().exec("su");
      outputStream = new DataOutputStream(su.getOutputStream());
      inputStream = new BufferedReader(new InputStreamReader(su.getInputStream()));

      for (String s : strings) {
        outputStream.writeBytes(s + "\n");
        outputStream.flush();
      }

      outputStream.writeBytes("exit\n");
      outputStream.flush();
      try {
        int status = su.waitFor();
        System.out.println("status: " + status);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      String result = inputStream.readLine();
      System.out.println("result: " + result);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (outputStream != null) {
        try {
          outputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 9
0
 public static String execRootCmd(String cmd) {
   String result = "result : ";
   try {
     Process p = Runtime.getRuntime().exec("su ");
     OutputStream outStream = p.getOutputStream();
     DataOutputStream dOutStream = new DataOutputStream(outStream);
     InputStream inStream = p.getInputStream();
     DataInputStream dInStream = new DataInputStream(inStream);
     String str1 = String.valueOf(cmd);
     String str2 = str1 + "\n";
     dOutStream.writeBytes(str2);
     dOutStream.flush();
     String str3 = null;
     String line = "";
     while ((line = dInStream.readLine()) != null) {
       Log.d("result", str3);
       str3 += line;
     }
     dOutStream.writeBytes("exit\n");
     dOutStream.flush();
     p.waitFor();
     return result;
   } catch (Exception e) {
     e.printStackTrace();
     return result;
   }
 }
Ejemplo n.º 10
0
 public static int runA2sd(int mode) {
   String command = "";
   if (mode == 0) // remove a2sd
   command = "echo \"n\" | /system/bin/a2sd remove";
   else if (mode == 1) // a2sd
   command = "echo \"n\" | /system/bin/a2sd install";
   else if (mode == 2) // dc2sd
   command = "echo \"y\" | /system/bin/a2sd install";
   if (!command.equals("")) {
     try {
       Process process = Runtime.getRuntime().exec("su");
       Log.e(TAG, "Executing: " + command);
       DataOutputStream outputStream = new DataOutputStream(process.getOutputStream());
       DataInputStream inputStream = new DataInputStream(process.getInputStream());
       outputStream.writeBytes(command + "\n");
       outputStream.flush();
       outputStream.writeBytes("exit\n");
       outputStream.flush();
       process.waitFor();
     } catch (IOException e) {
       return -1;
     } catch (InterruptedException e) {
       return -2;
     }
     return 0;
   }
   return -3;
 }
Ejemplo n.º 11
0
 public void run() {
   while (true) {
     try {
       int buttonID = Button.waitForPress();
       switch (buttonID) {
         case 2:
           racecarOutputStream.writeInt(LEFT);
           racecarOutputStream.flush();
           System.out.println("Sent Left Signal");
           break;
         case 4:
           racecarOutputStream.writeInt(RIGHT);
           racecarOutputStream.flush();
           System.out.println("Sent Right Signal");
           break;
         case 1:
           System.out.println("Sending Forward Signal");
           racecarOutputStream.writeInt(FWD);
           racecarOutputStream.flush();
           System.out.println("Sent Forward Signal");
           break;
         case 8:
           racecarOutputStream.writeInt(STOP);
           racecarOutputStream.flush();
           System.out.println("Sent stop Signal");
           break;
         default:
           break;
       }
     } catch (Exception e) {
       // nothing
     }
   }
 }
Ejemplo n.º 12
0
  /**
   * Method to return entity body. The requested resource is read and returned back to the client.
   * If the request is for a folder itself, or '/' the root, an 'index.html' file is opened if it
   * exists and its contents are returned as an entity-body in a valid response
   */
  public void sendResponse() {
    try {
      if (httpDetails.get("Mime Type").startsWith("image/")) {
        File imageFile = new File(httpDetails.get("Full path"));
        FileInputStream fs = new FileInputStream(imageFile);
        byte[] data = new byte[(int) imageFile.length()];
        fs.read(data, 0, (int) imageFile.length());
        fs.close();
        outStream.write(data);
        outStream.flush();
      } else {
        FileReader file = new FileReader(httpDetails.get("Full path"));
        BufferedReader buff = new BufferedReader(file);
        Scanner s = new Scanner(buff);

        while (s.hasNext()) {
          outStream.writeBytes(s.nextLine());
        }
        outStream.flush();
        System.out.println("Response Sent");
      }

    } catch (IOException e) {
      sendHeader(500, "Internal Server Error");
      hasErrors = true;
    } catch (Exception e) {
      try {
        outStream.writeBytes("");
        sendHeader(500, "Internal Server Error");
        hasErrors = true;
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
Ejemplo n.º 13
0
  public void run() {
    try {
      try {
        outStream = serverSocket.getOutputStream();
        inStream = serverSocket.getInputStream();
        dOutStream = new DataOutputStream(outStream);
        dInStream = new DataInputStream(inStream);

        int ID = dInStream.readInt() - 8091;

        dOutStream.writeInt(ChunkNum);

        dOutStream.writeInt(Neighbors[ID][0]);
        dOutStream.writeInt(Neighbors[ID][1]);

        for (int i = ID; i < ChunkNum; i = i + 3) {
          File fileChunk = new File("chunk" + i + ".pdf");

          dOutStream.writeInt((int) fileChunk.length());
          dOutStream.flush();

          byte[] byteArray = new byte[(int) fileChunk.length()];

          fInStream = new FileInputStream(fileChunk);
          bInStream = new BufferedInputStream(fInStream);
          int bytesRead = bInStream.read(byteArray, 0, byteArray.length);
          // fOutStream = (FileOutputStream)outStream;

          if (bytesRead != -1) {
            System.out.println("Bytes read before writing to client " + bytesRead);
            dOutStream.write(byteArray, 0, bytesRead);
            dOutStream.flush();
          }
          System.out.println(
              "Size of chunk " + i + " is " + (int) fileChunk.length() + ", peer is " + ID);

          if (bInStream != null) {
            bInStream.close();
          }
          if (fInStream != null) {
            fInStream.close();
          }
        }
        dOutStream.writeInt(-100);
        dOutStream.flush();
      } finally {
        if (outStream != null) {
          outStream.close();
        }
        if (inStream != null) {
          inStream.close();
        }
        if (serverSocket != null) {
          serverSocket.close();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public boolean checkSetDevicePermissions() {
   java.lang.Process process = null;
   DataOutputStream os = null;
   try {
     File f = new File(MSM_DEVICE);
     if (f.canRead() && f.canWrite() /* && f1.canRead() && f1.canWrite() */) {
       return true;
     }
     process = Runtime.getRuntime().exec("su");
     os = new DataOutputStream(process.getOutputStream());
     os.flush();
     os.writeBytes("chmod 0666 " + MSM_DEVICE + "\n");
     os.flush();
     os.writeBytes("exit\n");
     os.flush();
     process.waitFor();
   } catch (Exception e) {
     return false;
   } finally {
     try {
       if (os != null) os.close();
       process.destroy();
     } catch (Exception e) {
     }
   }
   return true;
 }
Ejemplo n.º 15
0
 private void sendMessage() throws IOException {
   dataOut.flush();
   byte[] buff = outBuffer.toByteArray();
   int len = buff.length;
   dataOut = new DataOutputStream(out);
   dataOut.write(messageType);
   dataOut.writeInt(len + 4);
   dataOut.write(buff);
   dataOut.flush();
 }
Ejemplo n.º 16
0
  void removeEntry(String entry, boolean first) {
    String[] params = entry.split(",");
    entry = params[0] + " " + params[1];
    List<String> hosts = new ArrayList<String>();
    try {
      Process proc = Runtime.getRuntime().exec("cat /etc/hosts");
      BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      String line = null;
      while ((line = reader.readLine()) != null) {
        if (!line.equals("") && line != null) {
          if (line.contains(entry) && first) {
            first = false;
          } else if (line.contains(entry) && !first) {
            hosts.add(line);
          } else if (!line.contains(entry)) {
            hosts.add(line);
          }
        }
      }
    } catch (Exception e) {

    }
    if (hosts.size() > 0) {
      try {
        Process proc = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(proc.getOutputStream());
        os.writeBytes("mount -o rw,remount -t " + fs + " " + block + " /system\n");
        os.writeBytes("echo '' > /etc/hosts\n");
        for (String s : hosts) {
          os.writeBytes("echo '" + s + "' >> /etc/hosts\n");
        }
        os.writeBytes("mount -o ro,remount -t " + fs + " " + block + " /system\n");
        os.writeBytes("exit\n");
        os.flush();
        os.close();
        proc.waitFor();
      } catch (Exception e) {

      }
    } else {
      try {
        Process proc = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(proc.getOutputStream());
        os.writeBytes("mount -o rw,remount -t " + fs + " " + block + " /system\n");
        os.writeBytes("echo '' > /etc/hosts\n");
        os.writeBytes("mount -o ro,remount -t " + fs + " " + block + " /system\n");
        os.writeBytes("exit\n");
        os.flush();
        os.close();
        proc.waitFor();
      } catch (Exception e) {

      }
    }
  }
  /**
   * * Method to face the key exchange protocol. Here a basic Diffie-Hellman protocol is implemented
   * (book version). From the server, client receives global parameters and client must calculate
   * the shared key.
   *
   * @throws IOException Communication errors will throw this one
   * @throws ParseException Appears if something unexpected is received
   */
  private void exchangePhase() throws IOException, ParseException {
    DHExStartRequest startRequest = new DHExStartRequest(++counter);
    log.debug("Message to send: [" + startRequest.toJSON() + "]");
    writer.write(startRequest.toJSON().getBytes("UTF-8"));
    writer.flush();

    // get the public parameters and calculate the shared key
    byte[] buff = new byte[BUFFER_SIZE];
    reader.read(buff);
    String reply = new String(buff, "UTF-8");

    log.debug("Message received: [" + reply + "]");
    DHExStartResponse response = new DHExStartResponse();
    response.fromJSON(StringParser.getUTFString(reply));

    generator = response.getGenerator();
    prime = response.getPrime();
    pkServer = response.getPkServer();
    skClient = response.getSkClient();

    // after that the client got the public parameters, it calculates the shared key
    if (skClient != BigInteger.ZERO) {
      BigInteger[] pair = DHEx.createDHPair(generator, prime, skClient);
      pkClient = pair[1];
    } else {
      BigInteger tempKey = DHEx.createPrivateKey(2048);
      BigInteger[] pair = DHEx.createDHPair(generator, prime, tempKey);
      skClient = pair[0];
      pkClient = pair[1];
    }

    DHExRequest dhexRequest = new DHExRequest(pkClient, ++counter);
    log.debug("Message to send: [" + dhexRequest.toJSON() + "]");
    writer.write(dhexRequest.toJSON().getBytes("UTF-8"));
    writer.flush();

    // calculate the shared key
    buff = new byte[BUFFER_SIZE];
    reader.read(buff);
    reply = new String(buff, "UTF-8");

    log.debug("Message received: [" + reply + "]");
    DHExResponse dhResponse = new DHExResponse();
    dhResponse.fromJSON(StringParser.getUTFString(reply));

    sharedKey = DHEx.getDHSharedKey(pkServer, skClient, prime);
    log.debug("The shared key is: [" + sharedKey + "]");

    // finalize the process sending the shared key (for checking only)
    DHExDoneRequest doneRequest = new DHExDoneRequest(sharedKey, ++counter);
    log.debug("Message to send: [" + doneRequest.toJSON() + "]");
    writer.write(doneRequest.toJSON().getBytes("UTF-8"));
    writer.flush();
  }
Ejemplo n.º 18
0
  /**
   * method to start the udp server
   *
   * @param portAddress
   */
  @SuppressWarnings("resource")
  public void TCPServer(int portAddress) {

    Socket socket = null;
    try {
      ServerSocket serverSocket = new ServerSocket(portAddress);
      while (true) {
        socket = serverSocket.accept();
        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        OutputStream os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        String sendMessage = "";
        String number = br.readLine();
        String temp[];
        temp = number.replace("$$$spliter$$$", "|").split("\\|");
        // if user wants to get the time from the server
        if (temp[0].charAt(0) == '1' || temp[0].charAt(0) == '0') {
          String sendMessage1 = tsapp.name + "";
          // if the user wants to get time in calender format
          if (temp[0].charAt(0) == '0') {
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(tsapp.name);
            sendMessage1 = c.toInstant() + "\n";
          }
          dos.writeBytes(sendMessage1 + "\n");
          dos.flush();
        }
        // if the user wants to set the time
        else if (temp[0].charAt(0) == '2') {
          // if the user did'nt send username or password
          if (temp[1].equals("")) sendMessage = ("Invalid User:\n");
          // if the user sends username and password
          else if (temp[1].equals(tsapp.actualUserName + tsapp.actualPassWord)) {
            sendMessage = ("Valid User: Data set on the server is" + temp[2] + "\n");
            tsapp.name = Long.parseLong(temp[2]);
          }
          // if the username and password does'nt match
          else sendMessage = ("Invalid User:\n");
          dos.writeBytes(sendMessage + "\n");
          dos.flush();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        socket.close();
      } catch (Exception e) {
      }
    }
  }
Ejemplo n.º 19
0
  /** Main entry to the program. */
  public static void main(String[] args) {
    RemoteControl remote = new RemoteControl();

    RemoteDevice racecar = Bluetooth.getKnownDevice("Batmobile");

    if (racecar == null) {
      System.out.println("No Such device existed");
      System.exit(1);
    }
    BTConnection racecarConnection = Bluetooth.connect(racecar);

    if (racecarConnection == null) {
      System.out.println("Connection Failed");
      System.exit(1);
    } else {
      System.out.println("Connected to Racecar");
    }

    DataOutputStream dos = racecarConnection.openDataOutputStream();
    try {
      System.out.println("Sending controller signal");
      dos.writeInt(CONTROLLER_DEVICE);
      dos.flush();
      System.out.println("Sent Controller signal");
    } catch (Exception ex) {
      // Do nothing
    }
    remote.setRacecarConnection(racecarConnection);
    remote.setRacecarOutputStream(dos);

    // Waiting for flag to set us off here
    System.out.println("Waiting for Flag connection");
    NXTConnection flagConnection = Bluetooth.waitForConnection();
    System.out.println("Connected to flag");
    DataInputStream dis = flagConnection.openDataInputStream();
    try {
      int check = dis.readInt();
      if (check == FLAG_SIGNAL) {
        System.out.println("Recived flag signal");
        dos.writeInt(FLAG_SIGNAL);
        dos.flush();
        System.out.println("sent flag signal to racecar");
        dis.close();
        remote.run();
      } else {
        System.out.println("Did not recieve flag connection");
      }

    } catch (Exception e) {

    }
  }
Ejemplo n.º 20
0
  @Override
  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to " + server.getRemoteSocketAddress());
        DataInputStream in = new DataInputStream(server.getInputStream());

        DataOutputStream out = new DataOutputStream(server.getOutputStream());

        String request = in.readUTF();
        String[] split = request.split("#");
        if (split[0].compareTo("login") == 0) {
          if (db.checkLogin(split[1], split[2])) {
            out.writeUTF("true#" + System.currentTimeMillis());
          } else {
            out.writeUTF("false");
          }
        } else if (split[0].compareTo("sync") == 0) {
          List<Tugas> tasks = db.getTugas(split[1]);
          out.flush();
          out.writeInt(serialize(tasks).length);
          out.flush();
          for (int i = 0; i < tasks.size(); i++) {
            System.out.println(i);
            System.out.println(
                tasks.get(i).getId()
                    + tasks.get(i).getNama()
                    + tasks.get(i).getDeadline().toString()
                    + tasks.get(i).isStatus()
                    + tasks.get(i).getLast_mod()
                    + tasks.get(i).getKategori()
                    + tasks.get(i).getAssignee()
                    + tasks.get(i).getTag());
          }
          out.write(serialize(tasks), 0, serialize(tasks).length);
          System.out.print(serialize(tasks).length);
        } else if (split[0].compareTo("update") == 0) {
          db.Update(
              Integer.parseInt(split[1]),
              Boolean.parseBoolean(split[2]),
              Long.parseLong(split[3], 10));
          System.out.println("update");
        }

        server.close();
      } catch (IOException e) {

      }
    }
  }
Ejemplo n.º 21
0
 @Override
 public int commit() {
   String key;
   String value;
   rm();
   try {
     for (Map.Entry<String, String> i : map.entrySet()) {
       key = i.getKey();
       value = i.getValue();
       Integer ndirectory = Math.abs(key.getBytes("UTF-8")[0] % N);
       Integer nfile = Math.abs((key.getBytes("UTF-8")[0] / N) % N);
       String pathToDir = path + File.separator + ndirectory.toString() + ".dir";
       File file = new File(pathToDir);
       if (!file.exists()) {
         file.mkdir();
       }
       String pathToFile =
           path
               + File.separator
               + ndirectory.toString()
               + ".dir"
               + File.separator
               + nfile.toString()
               + ".dat";
       file = new File(pathToFile);
       if (!file.exists()) {
         file.createNewFile();
       }
       DataOutputStream outStream = new DataOutputStream(new FileOutputStream(pathToFile, true));
       byte[] byteWord = key.getBytes("UTF-8");
       outStream.writeInt(byteWord.length);
       outStream.write(byteWord);
       outStream.flush();
       byteWord = value.getBytes("UTF-8");
       outStream.writeInt(byteWord.length);
       outStream.write(byteWord);
       outStream.flush();
       outStream.close();
     }
   } catch (IOException e) {
     System.err.println(e.getMessage());
     System.exit(-1);
   }
   TableState ts = new TableState(map, unsavedChanges, numberOfElements);
   tableStates.put(++numberOfState, ts);
   int n = unsavedChanges;
   unsavedChanges = 0;
   return n;
 }
Ejemplo n.º 22
0
 /**
  * Method to check for errors. For now, the method checks for 404, 500, 501 & 505 and sends
  * corresponding status messages.
  *
  * @return boolean true indicates presence of errors
  */
 public void checkErrors() {
   if (hasErrors != true) {
     if (!new File(httpDetails.get("Full path")).exists()) {
       hasErrors = true;
       sendHeader(404, "Not Found");
       try {
         outStream.writeBytes(
             "<html><head><title>Page not found</title></head><body><b>HTTP 404 - The page was not found.</b></body></html>\r\n");
         outStream.flush();
       } catch (IOException e) {
         hasErrors = true;
       }
     } else if (new File(httpDetails.get("Full path")).length() == 0) {
       hasErrors = true;
       sendHeader(500, "Internal Server Error");
       try {
         outStream.writeBytes(
             "<html><head><title>Internal Server Error</title></head><body><b>HTTP 500 - Internal Server Error</b></body></html>\r\n");
         outStream.flush();
       } catch (IOException e) {
         hasErrors = true;
       }
     }
     if (!(httpDetails.get("Version").equals("HTTP/1.0")
         || httpDetails.get("Version").equals("HTTP/1.1"))) {
       hasErrors = true;
       sendHeader(505, "HTTP Version Not Supported");
       try {
         outStream.writeBytes(
             "<html><head><title>HTTP Version Not Supported</title></head><body><b>HTTP 505 - HTTP Version Not Supported</b></body></html>\r\n");
         outStream.flush();
       } catch (IOException e) {
         hasErrors = true;
       }
     }
     if (!(httpDetails.get("Request Type").equals("GET")
         || httpDetails.get("Request Type").equals("HEAD"))) {
       hasErrors = true;
       sendHeader(501, "Not Implemented");
       try {
         outStream.writeBytes(
             "<html><head><title>Not Implemented</title></head><body><b>HTTP 501 - Not Implemented</b></body></html>\r\n");
         outStream.flush();
       } catch (IOException e) {
         hasErrors = true;
       }
     }
   }
 }
  private boolean receiveLine() throws IOException, ParseException {
    long messageLength = 0L, lineNumber = 0L;

    // we read the size of the line corpus
    byte[] buff = new byte[BUFFER_SIZE];
    reader.read(buff);
    String reply = new String(buff, "UTF-8");

    // two possible messages could be received, next length and text done
    // but client also can request some info...
    log.debug("Message received: [" + reply + "]");
    if (reply.contains(ServerMessageType.SERVER_TEXT_DONE.toString())) return true;
    else if (reply.contains(ServerMessageType.SERVER_NEXT_LENGTH.toString())) {
      NextLengthResponse response = new NextLengthResponse();
      response.fromJSON(StringParser.getUTFString(reply));

      messageLength = response.getLength();
      lineNumber = response.getId();
    } else {
      NextLengthRequest request = new NextLengthRequest(++counter);
      log.debug("Message to send: [" + request.toJSON() + "]");
      writer.write(request.toJSON().getBytes("UTF-8"));
      writer.flush();
    }

    // Send Acknowledgement of Message Length
    MessageLengthReceivedRequest msgACKRequest = null;
    msgACKRequest = new MessageLengthReceivedRequest(lineNumber, ++counter);
    log.debug("Message to send: [" + msgACKRequest.toJSON() + "]");
    writer.write(msgACKRequest.toJSON().getBytes("UTF-8"));
    writer.flush();

    // Get complete TEXT Message
    TextResponse response = strictReceive(messageLength);

    // decrypt the content of the message
    String decryptedBody = decrypt(response.getBody());
    System.out.println("SERVER_TEXT <<<<<<<<<<<< ID: " + response.getId());
    System.out.println("Cipher Text: \n" + response.getBody());
    System.out.println("Plain Text: \n" + decryptedBody);

    // Inform Client TEXT Message Received
    TextReceivedRequest request = new TextReceivedRequest(lineNumber, ++counter);
    log.debug("Message to send: [" + request.toJSON() + "]");
    writer.write(request.toJSON().getBytes("UTF-8"));
    writer.flush();

    return false;
  }
Ejemplo n.º 24
0
      @Override
      public void run() {
        try {
          // Get the address of the incoming connection
          String address = connection.getInetAddress().getHostAddress();
          // and the incoming port
          int port = connection.getPort();
          // Here is a stream that will be sent to the connect client
          DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
          // NOTE: Right now, there is no authenticator...
          //    so all of the clients are accepted.
          if (authenticator == null) {
            // Just add the peer (client) if there's no Authenticator
            ZmqHostEndpoint.this.addClient(address, port);
            // Indicator, to the client, that we connected well.
            outputStream.writeUTF("1 " + ZmqHostEndpoint.this.port);
            // make sure it really goes (down) get the plunger!
            outputStream.flush();

          } else {
            // Otherwise authenticate the connection request
            DataInputStream inputStream = new DataInputStream(connection.getInputStream());
            String token = inputStream.readUTF(); // Blocking call
            if (authenticator.isAuthenticated(address, port, token)) {
              ZmqHostEndpoint.this.addClient(address, port);
              outputStream.writeUTF("1 " + ZmqHostEndpoint.this.port);
              outputStream.flush();
            } else {
              System.out.println(
                  "Connection request from " + address + ":" + port + " is not " + "authenticated");
              outputStream.writeUTF("0 Authentication Failed");
              outputStream.flush();
            }
            inputStream.close();
          }
          // close the stream, done writing for now.
          outputStream.close();
        } catch (IOException e) {
          // TODO
          e.printStackTrace();
        } finally {
          try {
            connection.close();
          } catch (IOException e) {
            // We're boned
            e.printStackTrace();
          }
        }
      }
Ejemplo n.º 25
0
 /**
  * Dump the map to a DataOutputStream
  *
  * @param dos the stream
  * @throws IOException
  */
 public void dumpMap(DataOutputStream dos) throws IOException {
   dos.writeInt(lines.length);
   for (int i = 0; i < lines.length; i++) {
     dos.writeFloat(lines[i].x1);
     dos.writeFloat(lines[i].y1);
     dos.writeFloat(lines[i].x2);
     dos.writeFloat(lines[i].y2);
     dos.flush();
   }
   dos.writeInt(boundingRect.x);
   dos.writeInt(boundingRect.y);
   dos.writeInt(boundingRect.width);
   dos.writeInt(boundingRect.height);
   dos.flush();
 }
Ejemplo n.º 26
0
  public boolean RootCommand(String command) {
    Process process = null;
    DataOutputStream os = null;
    // DataInputStream is = null;
    tv_out.setText("");
    int result = -1;
    try {
      process = Runtime.getRuntime().exec("su");
      os = new DataOutputStream(process.getOutputStream());
      // is = new DataInputStream(process.getInputStream());
      BufferedReader is = new BufferedReader(new InputStreamReader(process.getInputStream()));
      os.writeBytes(command);
      os.flush();
      os.writeBytes("exit\n");
      os.flush();
      String line = "";
      string = "";
      while ((line = is.readLine()) != null) {
        Log.i("is out---", "2134" + line);
        string += line + "\n";
      }
      process.waitFor();
      result = process.exitValue();
      Log.i("is out---", result + "");

    } catch (Exception e) {
      Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
      tv_out.append("ROOT REEOR" + e.getMessage());
      return false;
    } finally {
      try {
        if (os != null) {
          os.close();
        }
        process.destroy();
      } catch (Exception e) {
        Log.d("*** DEBUG ***", "Root SUC-e ");
      }
    }
    if (result == 0) {
      tv_out.setText(string);
      tv_out.append("Success!/执行成功!");
      return true;
    } else {
      tv_out.setText("Faild,No ROOT?/失败,请先给root权限? ");
      return false;
    }
  }
  public void handleResponse(HTTPResponse res, Socket connection) {
    String response = res.GenerateResponse();
    DataOutputStream writer;

    try {
      if (connection.getOutputStream() != null) {
        writer = new DataOutputStream(connection.getOutputStream());
        System.out.println(response);

        if (!connection.isClosed()) {
          writer.writeBytes(response);
          writer.flush();
        }

        // Send The File and Close Response As Http protocol request
        if (res.getPathToFile() != null && res.fileIsExpected()) {
          File file = new File(res.getPathToFile());

          // serving without chunked transfer
          if (!res.v_isChunked) {
            byte[] fileToSend;

            if (file.getName().equals("params_info.html")) {
              fileToSend = res.templatedHTML;
            } else {
              fileToSend = Utils.readFile(file);
            }

            if (!connection.isClosed()) {
              writer.write(fileToSend, 0, fileToSend.length);
              writer.flush();
            }

            // serving as chunks
          } else {
            if (file.getName().equals("params_info.html")) {
              writeChunkString(res.templatedHTML, writer);
            } else {
              writeChunkData(new File(res.getPathToFile()), writer);
            }
          }
        }
        writer.close();
      }
    } catch (IOException e) {
      System.err.println("Network Problem: Socket was Closed");
    }
  }
Ejemplo n.º 28
0
 /** 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;
 }
Ejemplo n.º 29
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);
    }
  }
Ejemplo n.º 30
0
  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());
        }
      }
    }
  }