public int ReadDb(Socket sock, String path) throws IOException {
   DataInputStream dis =
       new DataInputStream(sock.getInputStream()); // get the socket's input stream
   String c = dis.readUTF();
   if (c.contains("ok")) {
     System.out.println("file esistente sul server");
   } else if (c.contains("notfound")) {
     screenAlert("Periodo di tempo non esistente sul server");
     System.out.println("file non esistente sul server");
     dis.close();
     sock.close();
     return 0;
   }
   InputStream in = sock.getInputStream();
   FileOutputStream out = new FileOutputStream(path);
   byte[] buf = new byte[80192]; // buffer
   int len = 0;
   while ((len = in.read(buf)) != -1) {
     out.write(buf, 0, len); // write buffer
     System.out.println("reading " + len);
   }
   dis.close();
   out.flush();
   out.close();
   in.close();
   sock.close();
   return 1;
 }
Beispiel #2
1
 private static long[] Fm() {
   long[] arrayOfLong = {0L, 0L};
   File localFile = new File(cFH);
   if (!localFile.exists()) return arrayOfLong;
   DataInputStream localDataInputStream;
   int i;
   try {
     localDataInputStream = new DataInputStream(new FileInputStream(localFile));
     i = localDataInputStream.readInt();
     if ((i < 180L) || (i > 3600L)) {
       localDataInputStream.close();
       return arrayOfLong;
     }
   } catch (Exception localException) {
     new StringBuilder("getFromFile Exception:").append(localException.getStackTrace()).toString();
     return arrayOfLong;
   }
   long l = i;
   arrayOfLong[0] = l;
   int j = localDataInputStream.readInt();
   if (j > System.currentTimeMillis() / 1000L) {
     localDataInputStream.close();
     return arrayOfLong;
   }
   arrayOfLong[1] = j;
   localDataInputStream.close();
   return arrayOfLong;
 }
 public void read(String fileName, AbstractMatrix matrix) throws IOException {
   DataInputStream in = null;
   try {
     FileInputStream fstream = new FileInputStream(fileName);
     in = new DataInputStream(fstream);
     BufferedReader br = new BufferedReader(new InputStreamReader(in));
     String strLine;
     strLine = br.readLine();
     strLine = br.readLine();
     int i = 0;
     while ((strLine = br.readLine()) != null) {
       String[] elements = strLine.split(" ");
       for (int j = 0; j < elements.length; j++) {
         Double value = Double.parseDouble(elements[j]);
         matrix.setValue(value, i, j);
       }
       i++;
     }
     in.close();
   } catch (Exception e) {
     log.error("Error: " + e.getMessage());
   } finally {
     if (in != null) in.close();
   }
 }
Beispiel #4
1
  /**
   * Handle the socket as a SEND.
   *
   * @return false when socket is closed (or should be closed), true will cause the method to be
   *     called again.
   */
  protected boolean handleSend() {
    try {
      final byte[] data = new byte[blockSize];
      final int bytesRead = fileIn.read(data);
      readSize += bytesRead;

      if (bytesRead > 0) {
        for (DCCTransferHandler handler : handlers.get(DCCTransferHandler.class)) {
          handler.dataTransferred(this, bytesRead);
        }
        out.write(data, 0, bytesRead);
        out.flush();

        // Wait for acknowledgement packet.
        if (!turbo) {
          int bytesReceived;
          do {
            bytesReceived = in.readInt();
          } while (readSize - bytesReceived > 0);
        }

        if (readSize == size) {
          fileIn.close();

          // Process all the ack packets that may have been sent.
          // In true turbo dcc mode, none will have been sent and the socket
          // will just close, in fast-dcc mode all the acks will be here,
          // So keep reading acks until the socket closes (IOException) or we
          // have received all the acks.
          if (turbo) {
            int ack;
            do {
              try {
                ack = in.readInt();
              } catch (IOException e) {
                break;
              }
            } while (ack > 0 && readSize - ack > 0);
          }

          return false;
        }

        return true;
      } else if (bytesRead < 0) {
        fileIn.close();
        return true;
      }
    } catch (IOException e) {
      return false;
    }
    return false;
  }
Beispiel #5
1
  public void DownloadBinaryViaSerial(){
		// TODO Auto-generated method stub
		//System.out.println("Download running...");
		byte[] buff = new byte[2048];
		
		int size;
		
		
		try {
			binaryInput = new DataInputStream(new FileInputStream(binaryPathFromSketch));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			System.out.println("File not found : "+binaryPathFromSketch);
			e1.printStackTrace();
		}
		
		//System.out.println("Start uploading");
		try {
			while((size = binaryInput.read(buff)) > -1){
				output.write(buff, 0, size);
				
				//fileSize += size;
				/*for(int i=0 ; i < size ; i++){
					checkSumByte += buff[i];
				}*/
			
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			binaryInput.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	   /* File file = new File(binaryPathFromSketch);
	    System.out.println("[ROBOTIS]binary size : "+file.length()+"Bytes");*/
		checkSumByte = ArmCompiler.getChecksumOfBinary(); //[ROBOTIS]2012-12-19 change method to calculate checksum for mac OS x
		String outTemp = String.format("0x%x", checkSumByte);
		//System.out.println("Checksum : "+outTemp);
		//SerialWrite(checkSumByte);
		port.setDTR(true);
		write(checkSumByte);
		
		try {
			binaryInput.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  }
Beispiel #6
0
  @Override
  public Transmissible execute(Context context) {
    try {
      Thread.sleep(5000); // Le temps de se scynchroniser.
      // Verification des security codes
      dis =
          new DataInputStream(
              new BufferedInputStream(
                  new FileInputStream(new File(context.getFilesDir(), "monSC.txt"))));
      int sC = dis.readInt();
      dis.close();
      if (sC != monSC) return new Transmission(ErreurTransmission.SCINCORRECT);
      dis =
          new DataInputStream(
              new BufferedInputStream(
                  new FileInputStream(new File(context.getFilesDir(), "tonSC.txt"))));
      sC = dis.readInt();
      if (sC != tonSC) return new Transmission(ErreurTransmission.SCINCORRECT);

      // On met ce client dans la liste d'attente

      oos =
          new ObjectOutputStream(
              new BufferedOutputStream(
                  new FileOutputStream(new File(context.getFilesDir(), "enCours.txt"))));

      oos.writeObject(adresse);
      oos.flush();

      // On envoie alors sa fiche bumpfriend perso

      Log.i("Connexion", context.getFilesDir().toString());
      ois =
          new ObjectInputStream(
              new FileInputStream(new File(context.getFilesDir(), "fichePerso.txt")));

      return (BumpFriend) ois.readObject();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      try {
        dis.close();
        oos.close();
        ois.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return new Transmission(ErreurTransmission.PROBLEMETRAITEMENT);
  }
  private void receiveFile(File path, Socket socket) {
    System.out.println("recive file...");
    try {
      // поток для приема строки от сервера содержащей название файла
      DataInputStream disFileName = new DataInputStream(socket.getInputStream());
      System.out.println("Created new INstream...");
      // считуем имя файла
      String FileName = disFileName.readUTF();
      System.out.println("Recive File name: (" + FileName + ")");
      // создаем новый входной поток для записи принятого файла
      DataInputStream input = new DataInputStream(socket.getInputStream());
      // создаем новый файл в созданной нами директории
      File file = new File(path.getPath() + File.separator + FileName);
      filePath = file.getPath() + "\\" + file.getName();
      System.out.println("recive file: " + FileName);
      // создаем новый выходной поток чтобы сохранить созданный файл на диск
      System.out.println("Creted new stream..." + file.getPath());
      FileOutputStream output = new FileOutputStream(file);
      System.out.println("New Stream is created!");
      // создаем массив типа byte с количесством элементов (байт) равным 1024 (1 Кбайт)
      byte[] b = new byte[1024];
      // принимаем и сохраняем файл на диск
      System.out.println("Save File...");
      int count = 0; // переенная счетчика
      while (true) {
        count = input.read(b);
        if (count > 0) {
          output.write(b, 0, count);
        }
        if (count == -1) {
          System.out.println("File is saved!");
          output.close();

          break;
        }
      }
      disFileName.close();
      input.close();
    } catch (Exception e) {
      System.out.println("Error: File not recive...");
    }
    if (socket != null) {
      try {
        socket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #8
0
  public static String readFile(File file) {
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;
    StringBuilder br = new StringBuilder();
    try {
      fis = new FileInputStream(file);
      bis = new BufferedInputStream(fis);
      dis = new DataInputStream(bis);

      while (dis.available() != 0) {
        br.append(dis.readLine() + "\n");
      }

      // dispose all the resources after using them.
      fis.close();
      bis.close();
      dis.close();
      return br.toString();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return new String();
  }
  @Override
  public void start(String adaptorID, String type, long offset, ChunkReceiver dest)
      throws AdaptorException {
    try {
      String dummyAdaptorID = adaptorID;
      this.dest = dest;

      outBuf = new File(BUF_DIR, adaptorID);
      long newOffset = offset;
      if (outBuf.length() > 0) {
        DataInputStream dis = new DataInputStream(new FileInputStream(outBuf));
        while (dis.available() > 0) {
          Chunk c = ChunkImpl.read(dis);
          fSize += c.getData().length;
          long seq = c.getSeqID();
          if (seq > offset) {
            dest.add(c);
            newOffset = seq;
          }
        }
        // send chunks that are outstanding
        dis.close();
      }
      outToDisk = new DataOutputStream(new FileOutputStream(outBuf, true));

      inner.start(dummyAdaptorID, innerType, newOffset, this);
    } catch (IOException e) {
      throw new AdaptorException(e);
    } catch (InterruptedException e) {
      throw new AdaptorException(e);
    }
  }
  /**
   * See if there are array elements.
   *
   * @param dbl0 Value of the first (maybe only) array element
   * @param result ResultSet for the sample table with blob
   * @return Array with given element and maybe more.
   * @throws Exception on error, including 'cancel'
   */
  private double[] readBlobArrayElements(final double dbl0, final ResultSet result)
      throws Exception {
    final String datatype;
    if (reader.isOracle()) datatype = result.getString(7);
    else datatype = result.getString(8);

    // ' ' or NULL indicate: Scalar, not an array
    if (datatype == null || " ".equals(datatype) || result.wasNull()) return new double[] {dbl0};

    // Decode BLOB
    final byte[] bytes = result.getBytes(reader.isOracle() ? 8 : 9);
    final ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
    final DataInputStream data = new DataInputStream(stream);
    if ("d".equals(datatype)) { // Read Double typed array elements
      final int nelm = data.readInt();
      final double[] array = new double[nelm];
      for (int i = 0; i < nelm; i++) array[i] = data.readDouble();
      data.close();
      return array;
    }
    // TODO Decode 'l' Long and 'i' Integer?
    else {
      throw new Exception("Sample BLOBs of type '" + datatype + "' are not decoded");
    }
  }
Beispiel #11
0
 public static void WriteLog(String log, int nbLines) {
   if (nbLines == -1) {
     WriteFile("log.txt", getDateTime() + " >> " + log + "\n", true);
   } else {
     try {
       FileInputStream fstream = new FileInputStream("log.txt");
       DataInputStream in = new DataInputStream(fstream);
       BufferedReader br = new BufferedReader(new InputStreamReader(in));
       String strLine;
       Vector<String> totalLines = new Vector<String>();
       while ((strLine = br.readLine()) != null) {
         totalLines.add(strLine);
       }
       if (totalLines.size() > nbLines) {
         String content = "";
         for (int i = totalLines.size() - nbLines; i <= totalLines.size() - 1; i++) {
           content += totalLines.get(i) + "\n";
         }
         WriteFile("log.txt", content, false);
       }
       in.close();
     } catch (Exception e) {
       Utilities.WriteLogTrace(e);
     }
     WriteLog(log);
   }
 }
  // This method will read synapse.xml files
  public String readSynapseFile() throws Exception {
    ESBCommon esbCommon = new ESBCommon(selenium);
    Properties properties = new Properties();
    String conCatLines = "exact:";
    try {
      // Open the file
      FileInputStream fstream =
          new FileInputStream(esbCommon.getCarbonHome() + "/conf/synapse.xml");
      // Get the object of DataInputStream
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      // Read File Line By Line
      while ((strLine = br.readLine()) != null) {
        strLine = strLine.trim();
        conCatLines = conCatLines + strLine + " ";
      }
      // Close the input stream
      in.close();
      // return conCatLines;
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
    return conCatLines;
  }
  private void b() {
    try {
      d.clear();
      if (b == null) {
        return;
      }

      File var1 = b.a("idcounts");
      if ((var1 != null) && var1.exists()) {
        DataInputStream var2 = new DataInputStream(new FileInputStream(var1));
        class_dn var3 = class_dx.a(var2);
        var2.close();
        Iterator var4 = var3.c().iterator();

        while (var4.hasNext()) {
          String var5 = (String) var4.next();
          class_eb var6 = var3.c(var5);
          if (var6 instanceof class_dz) {
            class_dz var7 = (class_dz) var6;
            short var9 = var7.e();
            d.put(var5, Short.valueOf(var9));
          }
        }
      }
    } catch (Exception var10) {
      var10.printStackTrace();
    }
  }
Beispiel #14
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());
          }
        }
      }
    }
Beispiel #15
0
  /**
   * Parses a saved text Brain and returns a Brain object
   *
   * @param file filename for the saved Brain
   * @param sigmoid sigmoid value for the saved Brain (maybe encode in text representation in the
   *     future)
   * @return a Brain object equivalent to the text representation
   */
  public static Brain loadText(String file, double sigmoid) {
    // Set up pointer fields to populate
    ArrayList<NNode> nodes = new ArrayList<NNode>();
    ArrayList<Gene> genes = new ArrayList<Gene>();
    ArrayList<Integer> integers = new ArrayList<Integer>();

    // Attempt to process the text file
    try {
      FileInputStream fstream = new FileInputStream(file);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine = br.readLine();

      while (processLine(file, strLine, integers, nodes, genes)) {
        strLine = br.readLine();
      }
      in.close();
    } catch (IOException e) {
      Braincraft.reportError("Could not load Brain from file " + file + ".");
      return null;
    }

    if (nodes.size() == 0 || genes.size() == 0 || integers.size() == 0) {
      Braincraft.reportError("Could not load Brain from file " + file + ".");
      return null;
    }

    HashMap<Integer, NNode> loadedmap = new HashMap<Integer, NNode>();
    for (NNode n : nodes) {
      loadedmap.put(n.ID, n);
    }

    return new Brain(null, integers.get(0), genes, loadedmap, sigmoid);
  }
Beispiel #16
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();
    }
  }
Beispiel #17
0
 // Loads the data from the specified file.
 // Returns null if failure.
 public static Thumbnail loadFrom(File file) {
   Uri uri = null;
   Bitmap bitmap = null;
   FileInputStream f = null;
   BufferedInputStream b = null;
   DataInputStream d = null;
   try {
     f = new FileInputStream(file);
     b = new BufferedInputStream(f, BUFSIZE);
     d = new DataInputStream(b);
     uri = Uri.parse(d.readUTF());
     bitmap = BitmapFactory.decodeStream(d);
     d.close();
   } catch (IOException e) {
     Log.i(TAG, "Fail to load bitmap. " + e);
     return null;
   } finally {
     Util.closeSilently(f);
     Util.closeSilently(b);
     Util.closeSilently(d);
   }
   Thumbnail thumbnail = createThumbnail(uri, bitmap, 0);
   if (thumbnail != null) thumbnail.setFromFile(true);
   return thumbnail;
 }
  public static Pair<String[], int[]> listAll(int parentId) {
    try {
      r.lock();
      try {
        final DataInputStream input = readAttribute(parentId, CHILDREN_ATT);
        if (input == null)
          return Pair.create(ArrayUtil.EMPTY_STRING_ARRAY, ArrayUtil.EMPTY_INT_ARRAY);

        final int count = DataInputOutputUtil.readINT(input);
        final int[] ids = ArrayUtil.newIntArray(count);
        final String[] names = ArrayUtil.newStringArray(count);
        for (int i = 0; i < count; i++) {
          int id = DataInputOutputUtil.readINT(input);
          id = id >= 0 ? id + parentId : -id;
          ids[i] = id;
          names[i] = getName(id);
        }
        input.close();
        return Pair.create(names, ids);
      } finally {
        r.unlock();
      }
    } catch (Throwable e) {
      throw DbConnection.handleError(e);
    }
  }
  private static void checkAttributesSanity(
      final int attributeRecordId,
      final IntArrayList usedAttributeRecordIds,
      final IntArrayList validAttributeIds)
      throws IOException {
    assert !usedAttributeRecordIds.contains(attributeRecordId);
    usedAttributeRecordIds.add(attributeRecordId);

    final DataInputStream dataInputStream = getAttributesStorage().readStream(attributeRecordId);
    try {
      while (dataInputStream.available() > 0) {
        int attId = DataInputOutputUtil.readINT(dataInputStream);
        int attDataRecordId = DataInputOutputUtil.readINT(dataInputStream);
        assert !usedAttributeRecordIds.contains(attDataRecordId);
        usedAttributeRecordIds.add(attDataRecordId);
        if (!validAttributeIds.contains(attId)) {
          assert getNames().valueOf(attId).length() > 0;
          validAttributeIds.add(attId);
        }
        getAttributesStorage().checkSanity(attDataRecordId);
      }
    } finally {
      dataInputStream.close();
    }
  }
  public NameGenerator() {

    this.males = new ArrayList<String>();
    this.females = new ArrayList<String>();
    this.lastnames = new ArrayList<String>();
    this.random = new Random();

    // load from file
    try {
      DataInputStream in =
          new DataInputStream(NameGenerator.class.getResourceAsStream("FirstNameMales"));
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      while ((strLine = br.readLine()) != null) {
        this.males.add(strLine);
      }

      in = new DataInputStream(NameGenerator.class.getResourceAsStream("FirstNameFemales"));
      br = new BufferedReader(new InputStreamReader(in));
      while ((strLine = br.readLine()) != null) {
        this.females.add(strLine);
      }

      in = new DataInputStream(NameGenerator.class.getResourceAsStream("LastNames"));
      br = new BufferedReader(new InputStreamReader(in));
      while ((strLine = br.readLine()) != null) {
        this.lastnames.add(strLine);
      }

      in.close();
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }
  }
  public static List<ReconcilationDTO> analyse(InputStream fstream, List<Order> orders) {
    List<ReconcilationDTO> rs = new ArrayList<ReconcilationDTO>();
    try {

      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      String sdate = "";
      while ((strLine = br.readLine()) != null) {
        // System.out.println(strLine);

        if (strLine != null) {
          if (strLine.startsWith("0")) {
            sdate = StringUtil.split(strLine, "|")[2];
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            sdate = new SimpleDateFormat("dd MMM yyyy").format(format.parse(sdate));
          } else if (strLine.startsWith("1")) {
            List<ReconcilationDTO> dtos = getDTO(strLine, orders);
            for (ReconcilationDTO dto : dtos) {
              dto.setDate(sdate);
              rs.add(dto);
            }
          }
        }
      }
      in.close();
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }
    return rs;
  }
Beispiel #22
0
  @Override
  public void close() {
    if (debug)
      OLogManager.instance()
          .info(
              this,
              "%s - Closing socket...",
              socket != null ? " null possible previous close" : socket.getRemoteSocketAddress());

    try {
      if (in != null) {
        in.close();
        // in = null;
      }
    } catch (IOException e) {
      OLogManager.instance().debug(this, "Error during closing of input stream", e);
    }

    try {
      if (out != null) {
        out.close();
        // out = null;
      }
    } catch (IOException e) {
      OLogManager.instance().debug(this, "Error during closing of output stream", e);
    }

    super.close();
  }
Beispiel #23
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();
  }
Beispiel #24
0
  public static void main(String[] args) {
    try {
      Socket s1 = new Socket("127.0.0.1", 57643);

      InputStream is = s1.getInputStream();
      DataInputStream dis = new DataInputStream(is);
      System.out.println(dis.readUTF());

      OutputStream os = s1.getOutputStream();
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeUTF("Oh my gosh...");

      dis.close();
      is.close();
      dos.close();
      os.close();

      s1.close();
    } catch (ConnectException connExc) {
      connExc.printStackTrace();
      System.out.println("Server connection failed");
    } catch (IOException ioExc) {
      ioExc.printStackTrace();
    }
  }
  private static ArrayListWritable<PairOfInts> deserializePosting(BytesWritable inputBytes) {

    ArrayListWritable<PairOfInts> posting = new ArrayListWritable<PairOfInts>();
    DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(inputBytes.getBytes()));
    int prevDocID = 0;

    try {
      while (true) {
        int left = WritableUtils.readVInt(dataIn);
        int right = WritableUtils.readVInt(dataIn);

        if (right != 0) {
          posting.add(new PairOfInts(left + prevDocID, right));
          prevDocID += left;
        }
      }
    } catch (EOFException e) {
    } catch (IOException e) {
    }

    try {
      dataIn.close();
    } catch (IOException e) {
    }

    return posting;
  }
Beispiel #26
0
  @SuppressWarnings("deprecation")
  private static void resetEcoChar(File charFile) {
    try {

      String cheatStatus, tempData, tempAdd = "";
      int curEquip = 0, curItem = 0, curBank = 0;
      File tempCharFile = new File(charDir.toString() + "ECOBOOST$TEMP");
      DataInputStream fileStream = new DataInputStream(new FileInputStream(charFile));
      BufferedWriter tempOut = new BufferedWriter(new FileWriter(tempCharFile));

      while ((tempData = fileStream.readLine()) != null) {
        if ((!tempData.trim().startsWith("character-item ="))
            && (!tempData.trim().startsWith("character-bank ="))) {
          tempAdd = tempData.trim();

          if (tempData.trim().startsWith("character-equip =")) {
            tempAdd = "character-equip = " + curEquip + "\t-1\t0";
            curEquip++;
          }
          tempOut.write(tempAdd);
          tempOut.newLine();
        }
      }
      fileStream.close();
      tempOut.close();
      charFile.delete();
      tempCharFile.renameTo(charFile);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #27
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Logger.getLogger(getClass()).debug("LOGIN device J2ME");

    final UserWorkerLocal userWorkerLocal = ServiceLocator.lookupLocal(UserWorkerLocal.JNDI_NAME);
    final SubjectWorkerLocal subjectWorkerLocal =
        ServiceLocator.lookupLocal(SubjectWorkerLocal.JNDI_NAME);

    DataInputStream dis = null;
    try {
      dis = new DataInputStream(request.getInputStream());
      final String login = dis.readUTF();
      final String password = dis.readUTF();

      final User user = userWorkerLocal.login(login, password);

      final String deviceId = subjectWorkerLocal.loginDevice(user);
      final byte[] resultBytes = deviceId.getBytes("utf-8");
      response.setContentLength(resultBytes.length);
      response.getOutputStream().write(resultBytes);
    } catch (LoginFailedException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } finally {
      if (dis != null) {
        dis.close();
      }
    }
  }
  @Deprecated
  private static List<String> readComponentsFile() {
    List<String> componentStrings = new LinkedList<String>();

    try {

      InputStream is = ComponentManager.class.getClassLoader().getResourceAsStream(componentsFile);
      DataInputStream in = new DataInputStream(is);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String line;

      while ((line = br.readLine()) != null) {
        if (!(line.startsWith("#")
            || line.startsWith("//")
            || line.startsWith("%")
            || line.length() <= 1)) {
          componentStrings.add(line);
        }
      }

      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return componentStrings;
  }
Beispiel #29
0
 /**
  * Close the Event reader
  *
  * @throws IOException
  */
 @Override
 public void close() throws IOException {
   if (in != null) {
     in.close();
   }
   in = null;
 }
Beispiel #30
0
  public static double[][] load(String inPath, int maxFrames) throws IOException {

    FileInputStream fos = new FileInputStream(inPath);
    GZIPInputStream gzout = new GZIPInputStream(fos);
    DataInputStream daos = new DataInputStream(gzout);

    int idx = inPath.indexOf(".aac_"); // 64
    String[] a = inPath.substring(idx + 5).split("-");
    int frameRate = Integer.parseInt(a[0]); // 44100
    int frames = Integer.parseInt(a[1]); // 54856
    int bands = Integer.parseInt(a[2].split(".dat")[0]); // 335

    double[][] data3 = new double[Math.min(frames, maxFrames)][bands];

    int n = 0;
    while (daos.available() > 0 && n < frames * bands) {
      byte b = daos.readByte();
      // n = j*data.length + i
      int j = n / frames;
      int i = n % frames;
      n++;
      if (i >= maxFrames) continue;
      data3[i * TARGET_FRAME_RATE / frameRate][j] = b;
    }
    daos.close();
    return data3;
  }