/**
   * Sort-based shuffle data uses an index called "shuffle_ShuffleId_MapId_0.index" into a data file
   * called "shuffle_ShuffleId_MapId_0.data". This logic is from IndexShuffleBlockResolver, and the
   * block id format is from ShuffleDataBlockId and ShuffleIndexBlockId.
   */
  private ManagedBuffer getSortBasedShuffleBlockData(
      ExecutorShuffleInfo executor, int shuffleId, int mapId, int reduceId) {
    File indexFile =
        getFile(
            executor.localDirs,
            executor.subDirsPerLocalDir,
            "shuffle_" + shuffleId + "_" + mapId + "_0.index");

    DataInputStream in = null;
    try {
      in = new DataInputStream(new FileInputStream(indexFile));
      in.skipBytes(reduceId * 8);
      long offset = in.readLong();
      long nextOffset = in.readLong();
      return new FileSegmentManagedBuffer(
          conf,
          getFile(
              executor.localDirs,
              executor.subDirsPerLocalDir,
              "shuffle_" + shuffleId + "_" + mapId + "_0.data"),
          offset,
          nextOffset - offset);
    } catch (IOException e) {
      throw new RuntimeException("Failed to open file: " + indexFile, e);
    } finally {
      if (in != null) {
        JavaUtils.closeQuietly(in);
      }
    }
  }
Example #2
1
 /** Read LocalVariableTable attribute. */
 public LocVarData(DataInputStream in) throws IOException {
   start_pc = in.readShort();
   length = in.readShort();
   name_cpx = in.readShort();
   sig_cpx = in.readShort();
   slot = in.readShort();
 }
  protected final List<AbstractAudioChunk> parseChunks(
      DataInputStream dis, Map<Integer, AudioChunkParser> chunkParserMap)
      throws UnsupportedAudioFileException, IOException {
    ArrayList<AbstractAudioChunk> parsedChunks = new ArrayList<AbstractAudioChunk>();

    int currKey;
    int chunkLength = 0;
    int chunkRead = 0;
    do {
      if (dis.available() == 0) break;
      advanceChunk(dis, chunkLength, chunkRead);
      if (dis.available() == 0) break;
      try {
        currKey = dis.readInt();
        if (dis.available() == 0) break;
        chunkLength = readChunkLength(dis);
      } catch (IOException e) {
        break;
      }
      Integer currKeyObj = new Integer(currKey);
      if (chunkParserMap.containsKey(currKeyObj)) {
        parsedChunks.add((chunkParserMap.get(currKeyObj)).parseChunk(dis, chunkLength));
        chunkRead = chunkLength;
      } else chunkRead = 0;
    } while (true);
    return parsedChunks;
  }
  public PtsFileConverter(GetOpt opts) {
    FileInputStream fin;
    DataInputStream ins = null;
    FileWriter fout = null;
    try {

      String inFileString = opts.getString("infile");
      String[] inFiles = inFileString.split(",");
      fout = new FileWriter(opts.getString("outfile"), false);
      for (int i = 0; i < inFiles.length; i++) {
        fin = new FileInputStream(inFiles[i]);
        ins = new DataInputStream(fin);

        FeatureCategory type;
        if (opts.getString("type").equals("color")) {
          type = FeatureCategory.COLOR;
        } else if (opts.getString("type").equals("shape")) {
          type = FeatureCategory.SHAPE;
        } else {
          type = FeatureCategory.SIZE;
        }

        if (ins != null && fout != null) {
          convertFile(ins, fout, type);
        }
        ins.close();
        fin.close();
      }

    } catch (Exception ex) {
      System.err.println("ERR: " + ex);
      ex.printStackTrace();
    }
  }
Example #5
0
  public static void main(String[] args) throws NumberFormatException, IOException {

    FileInputStream inFile = new FileInputStream(new File("C-small-practice.in"));
    DataInputStream in = new DataInputStream(inFile);
    FileOutputStream outFile = new FileOutputStream(new File("out.txt"));
    DataOutputStream out = new DataOutputStream(outFile);

    int cases = Integer.parseInt(in.readLine());

    t9Map = new HashMap<String, String>();
    fillMap();

    for (int i = 1; i <= cases; i++) {
      out.writeBytes("Case #" + i + ": ");
      String t9, t9last = "";

      String text = in.readLine();
      for (int j = 0; j < text.length(); j++) {

        t9 = t9Map.get(String.valueOf(text.charAt(j)));

        // do we need a break? (letters are on same button)
        if (j > 0 && (t9.charAt(0)) == t9last.charAt(0)) {
          out.writeBytes(" ");
        }

        out.writeBytes(t9);
        t9last = t9;
      }
      out.writeBytes("\n");
    }
  }
  public void unmarshal(DataInputStream dis) {
    super.unmarshal(dis);

    try {
      minefieldID.unmarshal(dis);
      requestingEntityID.unmarshal(dis);
      requestID = (short) dis.readUnsignedByte();
      numberOfPerimeterPoints = (short) dis.readUnsignedByte();
      pad2 = (short) dis.readUnsignedByte();
      numberOfSensorTypes = (short) dis.readUnsignedByte();
      dataFilter = dis.readInt();
      requestedMineType.unmarshal(dis);
      for (int idx = 0; idx < numberOfPerimeterPoints; idx++) {
        Point anX = new Point();
        anX.unmarshal(dis);
        requestedPerimeterPoints.add(anX);
      }

      for (int idx = 0; idx < numberOfSensorTypes; idx++) {
        TwoByteChunk anX = new TwoByteChunk();
        anX.unmarshal(dis);
        sensorTypes.add(anX);
      }

    } // end try
    catch (Exception e) {
      System.out.println(e);
    }
  } // end of unmarshal method
Example #7
0
 @SuppressWarnings("deprecation")
 public void writeLogs(String taskId, OutputStream output) {
   try (FileInputStream input = new FileInputStream(getLogFile(taskId))) {
     DataInputStream dataInput = new DataInputStream(input);
     output.write("[\n".getBytes());
     byte[] buffer = new byte[4 * 1024];
     boolean needComma = false;
     try {
       while (true) {
         IOUtils.skip(input, 1);
         String line = dataInput.readLine();
         if (line == null || line.isEmpty()) {
           break;
         }
         int length = Integer.parseInt(line);
         if (length > buffer.length) {
           buffer = new byte[length];
         }
         IOUtils.readFully(input, buffer, 0, length);
         if (needComma) {
           output.write(",\n".getBytes());
         } else {
           needComma = true;
         }
         output.write(buffer, 0, length);
       }
     } catch (EOFException ignored) {
       // EOF reached
     }
     output.write("]\n".getBytes());
   } catch (Throwable throwable) {
     Throwables.propagate(throwable);
   }
 }
Example #8
0
  /** Internal method. Connect to searchd and exchange versions. */
  private Socket _Connect() {
    if (_socket != null) return _socket;

    _connerror = false;
    Socket sock = null;
    try {
      sock = new Socket();
      sock.setSoTimeout(_timeout);
      InetSocketAddress addr = new InetSocketAddress(_host, _port);
      sock.connect(addr, _timeout);

      DataInputStream sIn = new DataInputStream(sock.getInputStream());
      int version = sIn.readInt();
      if (version < 1) {
        sock.close();
        _error = "expected searchd protocol version 1+, got version " + version;
        return null;
      }

      DataOutputStream sOut = new DataOutputStream(sock.getOutputStream());
      sOut.writeInt(VER_MAJOR_PROTO);

    } catch (IOException e) {
      _error = "connection to " + _host + ":" + _port + " failed: " + e;
      _connerror = true;

      try {
        if (sock != null) sock.close();
      } catch (IOException e1) {
      }
      return null;
    }

    return sock;
  }
Example #9
0
  public void consume(byte[] buffer, int offset, int length) throws IOException {
    DataInputStream in = new DataInputStream(new ByteArrayInputStream(buffer, offset, length));
    do {
      processOne(in);

    } while (in.readBoolean());
  }
Example #10
0
  void ReceiveFile() throws Exception {
    String fileName;

    fileName = din.readUTF();

    if (fileName != null && !fileName.equals("NOFILE")) {
      System.out.println("Receiving File");
      File f =
          new File(
              System.getProperty("user.home")
                  + "/Desktop"
                  + "/"
                  + fileName.substring(fileName.lastIndexOf("/") + 1));
      System.out.println(f.toString());
      f.createNewFile();
      FileOutputStream fout = new FileOutputStream(f);
      int ch;
      String temp;
      do {
        temp = din.readUTF();
        ch = Integer.parseInt(temp);
        if (ch != -1) {
          fout.write(ch);
        }
      } while (ch != -1);
      System.out.println("Received File : " + fileName);
      fout.close();
    } else {
    }
  }
 @Nullable
 private DataInputStream createFSDataStream(File dataStorageRoot) {
   if (myInitialFSDelta == null) {
     // this will force FS rescan
     return null;
   }
   try {
     final File file = new File(dataStorageRoot, FS_STATE_FILE);
     final InputStream fs = new FileInputStream(file);
     byte[] bytes;
     try {
       bytes = FileUtil.loadBytes(fs, (int) file.length());
     } finally {
       fs.close();
     }
     final DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));
     final int version = in.readInt();
     if (version != FSState.VERSION) {
       return null;
     }
     final long savedOrdinal = in.readLong();
     if (savedOrdinal + 1L != myInitialFSDelta.getOrdinal()) {
       return null;
     }
     return in;
   } catch (FileNotFoundException ignored) {
   } catch (Throwable e) {
     LOG.error(e);
   }
   return null;
 }
 /**
  * Loads a <code>DecisionState</code> object from the given input stream.
  *
  * @param dis the data input stream
  * @return a newly constructed decision state
  * @throws IOException if an error occurs
  */
 public static State loadBinary(DataInputStream dis) throws IOException {
   int index = dis.readInt();
   char c = dis.readChar();
   int qtrue = dis.readInt();
   int qfalse = dis.readInt();
   return new DecisionState(index, c, qtrue, qfalse);
 }
Example #13
0
  public void run() throws IOException {
    ServerSocket server = new ServerSocket(this.portNumber);
    this.socket = server.accept();
    this.socket.setTcpNoDelay(true);
    server.close();

    DataInputStream in = new DataInputStream(this.socket.getInputStream());
    final DataOutputStream out = new DataOutputStream(this.socket.getOutputStream());
    while (true) {
      final String className = in.readUTF();
      Thread thread =
          new Thread() {
            public void run() {
              try {
                loadAndRun(className);
                out.writeBoolean(true);
                System.err.println(VerifyTests.class.getName());
                System.out.println(VerifyTests.class.getName());
              } catch (Throwable e) {
                e.printStackTrace();
                try {
                  System.err.println(VerifyTests.class.getName());
                  System.out.println(VerifyTests.class.getName());
                  out.writeBoolean(false);
                } catch (IOException e1) {
                  // ignore
                }
              }
            }
          };
      thread.start();
    }
  }
  private void func_22181_a(
      File file, ArrayList arraylist, int i, int j, IProgressUpdate iprogressupdate) {
    Collections.sort(arraylist);
    byte abyte0[] = new byte[4096];
    int i1;
    for (Iterator iterator = arraylist.iterator();
        iterator.hasNext();
        iprogressupdate.setLoadingProgress(i1)) {
      ChunkFile chunkfile = (ChunkFile) iterator.next();
      int k = chunkfile.func_22323_b();
      int l = chunkfile.func_22321_c();
      RegionFile regionfile = RegionFileCache.func_22193_a(file, k, l);
      if (!regionfile.func_22202_c(k & 0x1f, l & 0x1f)) {
        try {
          DataInputStream datainputstream =
              new DataInputStream(
                  new GZIPInputStream(new FileInputStream(chunkfile.func_22324_a())));
          DataOutputStream dataoutputstream =
              regionfile.getChunkDataOutputStream(k & 0x1f, l & 0x1f);
          for (int j1 = 0; (j1 = datainputstream.read(abyte0)) != -1; ) {
            dataoutputstream.write(abyte0, 0, j1);
          }

          dataoutputstream.close();
          datainputstream.close();
        } catch (IOException ioexception) {
          ioexception.printStackTrace();
        }
      }
      i++;
      i1 = (int) Math.round((100D * (double) i) / (double) j);
    }

    RegionFileCache.func_22192_a();
  }
Example #15
0
 public static boolean HTTPRequestToFile(
     File file, String inUrl, String method, String data, List headers) {
   boolean success = false;
   try {
     if (file.exists()) file.delete();
   } catch (Exception e) {
     Logger.getLogger(com.bombdiggity.util.HTTPUtils.class)
         .error(
             (new StringBuilder("HTTPUtils.HTTPRequestToFile delete ("))
                 .append(file)
                 .append("): ")
                 .append(e.toString())
                 .toString());
   }
   try {
     DataOutputStream printout = null;
     DataInputStream input = null;
     URL url = new URL(inUrl);
     URLConnection urlConn = url.openConnection();
     urlConn.setDoInput(true);
     urlConn.setDoOutput(true);
     urlConn.setUseCaches(false);
     if (headers != null) {
       for (Iterator iter = headers.iterator(); iter.hasNext(); ) {
         Map nameValuePair = (Map) iter.next();
         String key;
         String value;
         for (Iterator iter2 = nameValuePair.keySet().iterator();
             iter2.hasNext();
             urlConn.setRequestProperty(key, value)) {
           key = (String) iter2.next();
           value = (String) nameValuePair.get(key);
         }
       }
     }
     if (data != null) {
       byte inData[] = data.getBytes("UTF-8");
       printout = new DataOutputStream(urlConn.getOutputStream());
       printout.write(inData);
       printout.flush();
       printout.close();
       printout = null;
     }
     input = new DataInputStream(urlConn.getInputStream());
     DataOutputStream dataOut = new DataOutputStream(new FileOutputStream(file, false));
     int rChunk = 0x10000;
     byte myData[] = new byte[rChunk];
     do {
       int bytesRead = input.read(myData, 0, rChunk);
       if (bytesRead == -1) break;
       dataOut.write(myData, 0, bytesRead);
       Thread.sleep(1L);
     } while (true);
     input.close();
     input = null;
     success = true;
   } catch (Exception exception) {
   }
   return success;
 }
Example #16
0
 public void run() {
   try {
     boolean connected = true;
     System.out.println("a client has connected!");
     dis = new DataInputStream(s.getInputStream());
     dos = new DataOutputStream(s.getOutputStream());
     while (connected) {
       int cid = clients.indexOf(this) + 1;
       try {
         String str = dis.readUTF();
         System.out.println(str);
         for (int i = 0; i < clients.size(); i++) {
           clients.get(i).dos.writeUTF("Client" + cid + ":" + str);
         }
       } catch (IOException e) {
         connected = false;
       }
     }
     dis.close();
     dos.close();
     s.close();
     clients.remove(this);
     System.out.println("a client is qiut!");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #17
0
  static String gaukZodi(String fileName) {

    // String zodis;
    String strLine = "";
    int zodziuSkaicius = 0;
    List<String> zodziai = new ArrayList<String>(); // naudoju kolekcijas

    try {
      FileInputStream fstream = new FileInputStream(fileName);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      while ((strLine = br.readLine()) != null) {
        zodziai.add(strLine); // ieskau reikiamo atsitiktinio zodzio
        zodziuSkaicius++;
      }

      // uzdarom faila
      in.close();

    } catch (Exception e) { // Iesko klaidu
      System.err.println("Error: " + e.getMessage());
    }
    // generuoju atsitiktini skaiciu
    Random atsitiktiniai = new Random();
    int skaicius = atsitiktiniai.nextInt(zodziuSkaicius);

    // gaunu atsitiktini skaiciu atitinkanti zodi
    strLine = zodziai.get(skaicius);
    strLine = eiluteBeTarpu(strLine);
    strLine = strLine.toUpperCase();

    return (strLine);
  }
  public void handleCustomPayload(Packet250CustomPayload par1Packet250CustomPayload) {
    if ("MC|BEdit".equals(par1Packet250CustomPayload.channel)) {
      try {
        DataInputStream datainputstream =
            new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        ItemStack itemstack = Packet.readItemStack(datainputstream);

        if (!ItemWritableBook.validBookTagPages(itemstack.getTagCompound())) {
          throw new IOException("Invalid book tag!");
        }

        ItemStack itemstack2 = playerEntity.inventory.getCurrentItem();

        if (itemstack != null
            && itemstack.itemID == Item.writableBook.shiftedIndex
            && itemstack.itemID == itemstack2.itemID) {
          itemstack2.setTagCompound(itemstack.getTagCompound());
        }
      } catch (Exception exception) {
        exception.printStackTrace();
      }
    } else if ("MC|BSign".equals(par1Packet250CustomPayload.channel)) {
      try {
        DataInputStream datainputstream1 =
            new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        ItemStack itemstack1 = Packet.readItemStack(datainputstream1);

        if (!ItemEditableBook.validBookTagContents(itemstack1.getTagCompound())) {
          throw new IOException("Invalid book tag!");
        }

        ItemStack itemstack3 = playerEntity.inventory.getCurrentItem();

        if (itemstack1 != null
            && itemstack1.itemID == Item.writtenBook.shiftedIndex
            && itemstack3.itemID == Item.writableBook.shiftedIndex) {
          itemstack3.setTagCompound(itemstack1.getTagCompound());
          itemstack3.itemID = Item.writtenBook.shiftedIndex;
        }
      } catch (Exception exception1) {
        exception1.printStackTrace();
      }
    } else if ("MC|TrSel".equals(par1Packet250CustomPayload.channel)) {
      try {
        DataInputStream datainputstream2 =
            new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        int i = datainputstream2.readInt();
        Container container = playerEntity.craftingInventory;

        if (container instanceof ContainerMerchant) {
          ((ContainerMerchant) container).setCurrentRecipeIndex(i);
        }
      } catch (Exception exception2) {
        exception2.printStackTrace();
      }
    } else {
      ModLoader.serverCustomPayload(this, par1Packet250CustomPayload);
    }
  }
  private void runBuild(final MessageHandler msgHandler, CanceledStatus cs) throws Throwable {
    final File dataStorageRoot = Utils.getDataStorageRoot(myProjectPath);
    if (dataStorageRoot == null) {
      msgHandler.processMessage(
          new CompilerMessage(
              "build",
              BuildMessage.Kind.ERROR,
              "Cannot determine build data storage root for project " + myProjectPath));
      return;
    }
    if (!dataStorageRoot.exists()) {
      // invoked the very first time for this project. Force full rebuild
      myBuildType = BuildType.PROJECT_REBUILD;
    }

    final DataInputStream fsStateStream = createFSDataStream(dataStorageRoot);

    if (fsStateStream != null) {
      // optimization: check whether we can skip the build
      final boolean hasWorkToDoWithModules = fsStateStream.readBoolean();
      if (myBuildType == BuildType.MAKE
          && !hasWorkToDoWithModules
          && scopeContainsModulesOnly(myBuildRunner.getScopes())
          && !containsChanges(myInitialFSDelta)) {
        updateFsStateOnDisk(dataStorageRoot, fsStateStream, myInitialFSDelta.getOrdinal());
        return;
      }
    }

    final BuildFSState fsState = new BuildFSState(false);
    try {
      final ProjectDescriptor pd = myBuildRunner.load(msgHandler, dataStorageRoot, fsState);
      myProjectDescriptor = pd;
      if (fsStateStream != null) {
        try {
          try {
            fsState.load(fsStateStream, pd.getModel(), pd.getBuildRootIndex());
            applyFSEvent(pd, myInitialFSDelta);
          } finally {
            fsStateStream.close();
          }
        } catch (Throwable e) {
          LOG.error(e);
          fsState.clearAll();
        }
      }
      myLastEventOrdinal = myInitialFSDelta != null ? myInitialFSDelta.getOrdinal() : 0L;

      // free memory
      myInitialFSDelta = null;
      // ensure events from controller are processed after FSState initialization
      myEventsProcessor.startProcessing();

      myBuildRunner.runBuild(pd, cs, myConstantSearch, msgHandler, myBuildType);
    } finally {
      saveData(fsState, dataStorageRoot);
    }
  }
Example #20
0
  /**
   * Load in the filesystem image. It's a big list of filenames and blocks. Return whether we should
   * "re-save" and consolidate the edit-logs
   */
  boolean loadFSImage(File fsdir, File edits) throws IOException {
    //
    // Atomic move sequence, to recover from interrupted save
    //
    File curFile = new File(fsdir, FS_IMAGE);
    File newFile = new File(fsdir, NEW_FS_IMAGE);
    File oldFile = new File(fsdir, OLD_FS_IMAGE);

    // Maybe we were interrupted between 2 and 4
    if (oldFile.exists() && curFile.exists()) {
      oldFile.delete();
      if (edits.exists()) {
        edits.delete();
      }
    } else if (oldFile.exists() && newFile.exists()) {
      // Or maybe between 1 and 2
      newFile.renameTo(curFile);
      oldFile.delete();
    } else if (curFile.exists() && newFile.exists()) {
      // Or else before stage 1, in which case we lose the edits
      newFile.delete();
    }

    //
    // Load in bits
    //
    if (curFile.exists()) {
      DataInputStream in =
          new DataInputStream(new BufferedInputStream(new FileInputStream(curFile)));
      try {
        int numFiles = in.readInt();
        for (int i = 0; i < numFiles; i++) {
          UTF8 name = new UTF8();
          name.readFields(in);
          int numBlocks = in.readInt();
          if (numBlocks == 0) {
            unprotectedAddFile(name, null);
          } else {
            Block blocks[] = new Block[numBlocks];
            for (int j = 0; j < numBlocks; j++) {
              blocks[j] = new Block();
              blocks[j].readFields(in);
            }
            unprotectedAddFile(name, blocks);
          }
        }
      } finally {
        in.close();
      }
    }

    if (edits.exists() && loadFSEdits(edits) > 0) {
      return true;
    } else {
      return false;
    }
  }
Example #21
0
  /**
   * Load an edit log, and apply the changes to the in-memory structure
   *
   * <p>This is where we apply edits that we've been writing to disk all along.
   */
  int loadFSEdits(File edits) throws IOException {
    int numEdits = 0;

    if (edits.exists()) {
      DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(edits)));
      try {
        while (in.available() > 0) {
          byte opcode = in.readByte();
          numEdits++;
          switch (opcode) {
            case OP_ADD:
              {
                UTF8 name = new UTF8();
                name.readFields(in);
                ArrayWritable aw = new ArrayWritable(Block.class);
                aw.readFields(in);
                Writable writables[] = (Writable[]) aw.get();
                Block blocks[] = new Block[writables.length];
                System.arraycopy(writables, 0, blocks, 0, blocks.length);
                unprotectedAddFile(name, blocks);
                break;
              }
            case OP_RENAME:
              {
                UTF8 src = new UTF8();
                UTF8 dst = new UTF8();
                src.readFields(in);
                dst.readFields(in);
                unprotectedRenameTo(src, dst);
                break;
              }
            case OP_DELETE:
              {
                UTF8 src = new UTF8();
                src.readFields(in);
                unprotectedDelete(src);
                break;
              }
            case OP_MKDIR:
              {
                UTF8 src = new UTF8();
                src.readFields(in);
                unprotectedMkdir(src.toString());
                break;
              }
            default:
              {
                throw new IOException("Never seen opcode " + opcode);
              }
          }
        }
      } finally {
        in.close();
      }
    }
    return numEdits;
  }
Example #22
0
 @SuppressWarnings("unused")
 // TODO: consider delete this method
 private File readFile(DataInputStream reader) throws IOException {
   int filePathSize = reader.readInt();
   byte[] filePathInByteArray = new byte[filePathSize];
   reader.read(filePathInByteArray);
   String filePath = new String(filePathInByteArray);
   return new File(filePath);
 }
Example #23
0
  private int Load_Nodes(DataInputStream inStream) {
    // need to open file and load data
    int node_id;
    int x_cor;
    int y_cor;
    // int n_nodes, n_edges, node_cnt, arrow_status;
    Node n;
    String line;
    String item1, item2, item3, item4;

    node_id = 0;
    x_cor = 0;
    y_cor = 0;
    // n_nodes = 0;
    // n_edges = 0;
    // arrow_status = -1;

    try {

      if ((line = inStream.readLine()) != null) {
        StringTokenizer Data = new StringTokenizer(line, " ");
        item1 = Data.nextToken();
        n_nodes = Integer.parseInt(item1);
        item2 = Data.nextToken();
        n_edges = Integer.parseInt(item2);
        item3 = Data.nextToken();
        arrow_status = Integer.parseInt(item3);
        // item4 = Data.nextToken();
        // type = Integer.parseInt( item4 );
        // graph = new GraphClass( n_nodes, n_edges, arrow_status );
        nodes = new Node[n_nodes];
        edges = new Edge[n_edges];

        // ???

        while ((this.Node_Cnt() < n_nodes) && ((line = inStream.readLine()) != null)) {
          Data = new StringTokenizer(line, " ");
          item1 = Data.nextToken();
          item2 = Data.nextToken();
          item3 = Data.nextToken();
          node_id = Integer.parseInt(item1);
          x_cor = Integer.parseInt(item2);
          y_cor = Integer.parseInt(item3);
          n = new Node(node_id, x_cor, y_cor);
          this.Add_Node(n);
        }
        if (n_nodes != 0) {
          source_node = nodes[0];
        }
      }
    } catch (IOException e) {
      System.err.println("error in file" + e.toString());
      System.exit(1);
    }
    return this.Node_Cnt();
  }
Example #24
0
 public void unmarshal(DataInputStream dis) {
   try {
     x = dis.readFloat();
     y = dis.readFloat();
     z = dis.readFloat();
   } // end try
   catch (Exception e) {
     System.out.println(e);
   }
 } // end of unmarshal method
 /** Read the contents of a file. */
 String read(File f) throws IOException {
   byte[] bytes = new byte[(int) f.length()];
   DataInputStream in = new DataInputStream(new FileInputStream(f));
   try {
     in.readFully(bytes);
   } finally {
     in.close();
   }
   return new String(bytes);
 }
Example #26
0
 // read Image
 public static void ReadImage(String File_name, int imgSize) throws IOException {
   DataInputStream in = new DataInputStream(new FileInputStream(File_name));
   for (int i = 0; i < imgSize; i++)
     for (int j = 0; j < imgSize; j++) {
       DeImage[i][j] = in.readInt();
       // DeImage[i][j]= (int) in.readUnsignedByte();
       // OriginImage[i][j]= (int) in.readUnsignedByte();
     }
   in.close();
 }
Example #27
0
  /**
   * Read the class file header.
   *
   * @param in The stream from which to read.
   * @exception IOException If an error occurs while reading.
   */
  void readHeader(DataInputStream in) throws IOException {
    int magic = in.readInt();

    if (magic != 0xCAFEBABE) {
      throw new ClassFormatError("Bad magic number.");
    }

    int major = in.readUnsignedShort();
    int minor = in.readUnsignedShort();
  }
  public void unmarshal(DataInputStream dis) {
    super.unmarshal(dis);

    try {
      minefieldID.unmarshal(dis);
      requestingEntityID.unmarshal(dis);
      minefieldSequenceNumbeer = (int) dis.readUnsignedShort();
      requestID = (short) dis.readUnsignedByte();
      pduSequenceNumber = (short) dis.readUnsignedByte();
      numberOfPdus = (short) dis.readUnsignedByte();
      numberOfMinesInThisPdu = (short) dis.readUnsignedByte();
      numberOfSensorTypes = (short) dis.readUnsignedByte();
      pad2 = (short) dis.readUnsignedByte();
      dataFilter = dis.readInt();
      mineType.unmarshal(dis);
      for (int idx = 0; idx < numberOfSensorTypes; idx++) {
        TwoByteChunk anX = new TwoByteChunk();
        anX.unmarshal(dis);
        sensorTypes.add(anX);
      }

      pad3 = (short) dis.readUnsignedByte();
      for (int idx = 0; idx < numberOfMinesInThisPdu; idx++) {
        Vector3Float anX = new Vector3Float();
        anX.unmarshal(dis);
        mineLocation.add(anX);
      }

    } // end try
    catch (Exception e) {
      System.out.println(e);
    }
  } // end of unmarshal method
Example #29
0
  public HierarchyParams(InputStream in) throws IOException {
    DataInputStream d = new DataInputStream(in);
    String s = null;
    StringBuffer buffer = new StringBuffer();
    do {
      s = d.readLine();
      if (s != null) buffer.append(s + "\n");
    } while (s != null);

    processFormattedData(buffer.toString());
  }
  /** Reads the entire state of the MersenneTwister RNG from the stream */
  public void readState(DataInputStream stream) throws IOException {
    int len = mt.length;
    for (int x = 0; x < len; x++) mt[x] = stream.readInt();

    len = mag01.length;
    for (int x = 0; x < len; x++) mag01[x] = stream.readInt();

    mti = stream.readInt();
    __nextNextGaussian = stream.readDouble();
    __haveNextNextGaussian = stream.readBoolean();
  }