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();
  }
  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();
    }
  }
Exemple #3
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);
  }
Exemple #4
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();
   }
 }
 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;
 }
  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);
    }
  }
Exemple #7
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;
  }
Exemple #8
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;
    }
  }
 private void closeReader(DataInputStream reader) {
   try {
     if (reader != null) {
       reader.close();
     }
   } catch (IOException ioe) {
     throw new RuntimeException(ioe);
   }
 }
 // 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();
 }
 /** 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);
 }
 public void connectionclose() {
   try {
     is.close();
     os.close();
     dis.close();
     dos.close();
     sPort.close();
   } catch (Exception e) {
     System.out.println("close" + e);
   }
 }
  /** Close the serial port. */
  public void delete() {
    // Close the serial port
    try {
      if (inputStream != null) inputStream.close();
      outputStream.close();
    } catch (IOException e) {

    }
    mbedSerialPort.removeEventListener();
    mbedSerialPort.close();
    mbedPort.close();
  }
  public static void main(String[] args) throws JsonParseException, IOException {
    byte[] tAuctHist = null;
    byte[] tAuctHist1 = null;
    try {
      File tAuctHistFile = new File("/tmp/tauctHist.json");
      File tAuctHistFile1 = new File("/tmp/tauctHist1.json");
      tAuctHist = new byte[(int) tAuctHistFile.length()];
      tAuctHist1 = new byte[(int) tAuctHistFile1.length()];
      DataInputStream dis = new DataInputStream(new FileInputStream(tAuctHistFile));
      dis.readFully(tAuctHist);
      dis.close();

      dis = new DataInputStream(new FileInputStream(tAuctHistFile1));
      dis.readFully(tAuctHist1);
      dis.close();
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

    HashMap<String, StatsCounter> auctMap = fromJson(tAuctHist);
    System.out.println(MinprocParser.getAuctHistAsJsonString(auctMap));
  }
 public static byte[] HTTPRequestToByteArray(
     String inUrl, String method, String data, List headers) {
   byte ret[] = (byte[]) null;
   ByteArrayOutputStream byteOut = null;
   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());
     byteOut = new ByteArrayOutputStream();
     DataOutputStream dataOut = new DataOutputStream(byteOut);
     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;
     ret = byteOut.toByteArray();
   } catch (Exception exception) {
   }
   return ret;
 }
Exemple #16
0
  /**
   * Constructor. This constructor parses the class file from the byte array
   *
   * @param code A byte array containing the class data
   */
  public ClassFile(File classFileSource, byte[] code, ExtensionInfo ext) {
    this.classFileSource = classFileSource;
    this.extensionInfo = ext;

    try {
      ByteArrayInputStream bin = new ByteArrayInputStream(code);
      DataInputStream in = new DataInputStream(bin);
      read(in);
      in.close();
      bin.close();
    } catch (IOException e) {
      throw new InternalCompilerError("I/O exception on ByteArrayInputStream");
    }
  }
 public int[] readProgress() {
   int progress[] = new int[2];
   try {
     DataInputStream in =
         new DataInputStream(new BufferedInputStream(new FileInputStream(resume_file)));
     progress[0] = in.readInt();
     progress[1] = in.readInt();
     in.close();
   } catch (FileNotFoundException e) {
     Log.e(TAG, "readProgress file not found.");
   } catch (IOException e) {
     Log.e(TAG, e.getMessage());
   }
   return progress;
 }
  public void nick_name(String msg) {
    try {
      String name = msg.substring(13);
      this.setName(name);
      Vector v = father.onlineList;
      boolean isRepeatedName = false;
      int size = v.size();
      for (int i = 0; i < size; i++) {
        ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
        if (tempSat.getName().equals(name)) {
          isRepeatedName = true;
          break;
        }
      }
      if (isRepeatedName == true) {
        dout.writeUTF("<#NAME_REPEATED#>");
        din.close();
        dout.close();
        sc.close();
        flag = false;
      } else {
        v.add(this);
        father.refreshList();
        String nickListMsg = "";
        StringBuilder nickListMsgSb = new StringBuilder();
        size = v.size();
        for (int i = 0; i < size; i++) {
          ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
          nickListMsgSb.append("!");
          nickListMsgSb.append(tempSat.getName());
        }
        nickListMsgSb.append("<#NICK_LIST#>");
        nickListMsg = nickListMsgSb.toString();
        Vector tempv = father.onlineList;
        size = tempv.size();
        for (int i = 0; i < size; i++) {
          ServerAgentThread tempSat = (ServerAgentThread) tempv.get(i);
          tempSat.dout.writeUTF(nickListMsg);
          if (tempSat != this) {
            tempSat.dout.writeUTF("<#MSG#>" + this.getName() + "is now online....");
          }
        }
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 static String getContent(File dir, String f) {
   DataInputStream in = null;
   try {
     in = new DataInputStream(new FileInputStream(new File(dir, f)));
     return in.readUTF();
   } catch (IOException ignore) {
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException ignore) {
       }
     }
   }
   return null;
 }
  /** @param args the command line arguments */
  public static void main(String[] args) {
    // TODO code application logic here

    long lNumOfLines = 0;
    List list1 = new ArrayList();

    try {
      FileInputStream fstream = new FileInputStream("n:\\myphd\\dataset\\gps.csv");
      // 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) {
        // Print the content on the console
        lNumOfLines++;
        list1.add(strLine.trim());
      }
      // Close the input stream
      in.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }

    long lTotal = 1000000;
    long numberOfLines = 0;
    long lStep = lTotal / lNumOfLines;
    System.out.println("lTotal:" + lTotal + " numberOfLines:" + numberOfLines + "lStep:" + lStep);
    float fSpeed = 100;
    float newfSpeed = 0;
    for (int iNum = 0; iNum < lStep; iNum++) {
      Random randomGenerator = new Random();
      int randomInt = randomGenerator.nextInt(1000);
      float f = (float) randomInt / 10000.0f;
      System.out.println("Random Int:" + randomInt + " f:" + f);
      if ((randomInt % 2) == 0) {
        newfSpeed = fSpeed + fSpeed * f;
        System.out.println("Even");
      } else {
        newfSpeed = fSpeed - fSpeed * f;
        System.out.println("odd");
      }
      // InsertInstance(fLat,fLon,fAlt,fSpeed,sDate,sTimestamp,sBTAddress,sBTName,sURI);
      System.out.println("generated speed:" + newfSpeed);
    }
  }
Exemple #21
0
  public void open(String fileName) throws IOException {
    File file = new File(fileName);
    size = (int) file.length() / UNIT_SIZE;
    check = new int[size];
    base = new int[size];

    DataInputStream is = null;
    try {
      is = new DataInputStream(new BufferedInputStream(new FileInputStream(file), BUF_SIZE));
      for (int i = 0; i < size; i++) {
        base[i] = is.readInt();
        check[i] = is.readInt();
      }
    } finally {
      if (is != null) is.close();
    }
  }
Exemple #22
0
 protected byte[] getJarEntryBytes(JarFile jarFile, JarEntry je) throws IOException {
   DataInputStream dis = null;
   byte[] jeBytes = null;
   try {
     long lSize = je.getSize();
     if (lSize <= 0 || lSize >= Integer.MAX_VALUE) {
       throw new IllegalArgumentException(
           "Size [" + lSize + "] not valid for war entry [" + je + "]");
     }
     jeBytes = new byte[(int) lSize];
     InputStream is = jarFile.getInputStream(je);
     dis = new DataInputStream(is);
     dis.readFully(jeBytes);
   } finally {
     if (dis != null) dis.close();
   }
   return jeBytes;
 }
 /**
  * Send a plugin JAR file to the client
  *
  * @param data the plugin name
  */
 private void sendPlugin(ObjectConnection oc, String data) {
   DataInputStream dis = null;
   try {
     dis = new DataInputStream(new FileInputStream(APPLICATIONS_DIRECTORY + data + ".jar"));
     byte[] buf = new byte[dis.available()];
     dis.readFully(buf);
     oc.write(buf);
   } catch (Exception e) {
     Logging.getLogger().warning("Unable to send the file: " + data + ".jar");
   } finally {
     if (dis != null) {
       try {
         dis.close();
       } catch (IOException ioe) {
       }
     }
   }
 }
Exemple #24
0
  private static PermissionInfo[] getPermissionInfos(URL resource, Framework framework) {
    if (resource == null) return null;
    PermissionInfo[] info = EMPTY_PERM_INFO;
    DataInputStream in = null;
    try {
      in = new DataInputStream(resource.openStream());
      ArrayList permissions = new ArrayList();
      BufferedReader reader;
      try {
        reader = new BufferedReader(new InputStreamReader(in, "UTF8")); // $NON-NLS-1$
      } catch (UnsupportedEncodingException e) {
        reader = new BufferedReader(new InputStreamReader(in));
      }

      while (true) {
        String line = reader.readLine();
        if (line == null) /* EOF */ break;
        line = line.trim();
        if ((line.length() == 0)
            || line.startsWith("#")
            || line.startsWith("//")) /* comments */ // $NON-NLS-1$ //$NON-NLS-2$
        continue;

        try {
          permissions.add(new PermissionInfo(line));
        } catch (IllegalArgumentException iae) {
          /* incorrectly encoded permission */
          if (framework != null)
            framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.getBundle(0), iae);
        }
      }
      int size = permissions.size();
      if (size > 0) info = (PermissionInfo[]) permissions.toArray(new PermissionInfo[size]);
    } catch (IOException e) {
      // do nothing
    } finally {
      try {
        if (in != null) in.close();
      } catch (IOException ee) {
        // do nothing
      }
    }
    return info;
  }
  /*load influence matrix with T indicating interdependencies*/
  private void loadMatrixFile() {
    try {
      FileInputStream fstream = new FileInputStream(matrixFile);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      int line = 0;
      while ((strLine = br.readLine()) != null) {
        if (!strLine.equals("")) { // in case there is an extra empty line at the end
          String[] result = strLine.split(",");
          // check policy choice size (cols)
          /// System.out.println("N is "+Globals.N);
          if (result.length != Globals.N) {
            System.err.println("incorrect number of policy choices (too many columns)");
            System.exit(0);
          }

          // check policy choice size (rows)
          if (line >= Globals.N) {
            System.err.println("incorrect number of policy choices (too many rows)");
            System.exit(0);
          }

          // System.out.println("N: " + result.length);
          boolean[] temp = new boolean[result.length];
          for (int i = 0; i < result.length; i++) {
            if (result[i].equals("x")) {
              temp[i] = true;
            } else {
              temp[i] = false;
            }
            // System.out.println(result[x]);
          }
          interdependencies.add(new Interdependence(line, temp));
        }
        line++;
      }
      // Close the input stream
      in.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
 @SuppressWarnings("ThrowFromFinallyBlock")
 private byte[] getFileBytes(File classFile) throws IOException {
   DataInputStream dis = null;
   byte[] jeBytes = null;
   try {
     long lSize = classFile.length();
     if (lSize <= 0 || lSize >= Integer.MAX_VALUE) {
       throw new IllegalArgumentException(
           "Size [" + lSize + "] not valid for classpath file [" + classFile + "]");
     }
     jeBytes = new byte[(int) lSize];
     InputStream is = new FileInputStream(classFile);
     dis = new DataInputStream(is);
     dis.readFully(jeBytes);
   } finally {
     if (dis != null) dis.close();
   }
   return jeBytes;
 }
 byte[] download(File f) {
   if (!f.exists()) {
     IJ.error("Plugin Installer", "File not found: " + f);
     return null;
   }
   byte[] data = null;
   try {
     int len = (int) f.length();
     InputStream in = new BufferedInputStream(new FileInputStream(f));
     DataInputStream dis = new DataInputStream(in);
     data = new byte[len];
     dis.readFully(data);
     dis.close();
   } catch (Exception e) {
     IJ.error("Plugin Installer", "" + e);
     data = null;
   }
   return data;
 }
Exemple #28
0
  public void readFile() throws IOException {
    try {

      FileInputStream fstream = new FileInputStream("dataIn.txt");
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      String strLine;
      int memi = -1;
      int strLineMemory = 59;

      while ((strLine = br.readLine()) != null) {

        t.data[strLineMemory++][1] = String.valueOf(strLine);
        memi++;

        size++;
        while ((strLine = br.readLine()) != null && !strLine.startsWith("*")) {

          String[] arr = strLine.split(" ");
          String command = arr[0];
          String operand = arr[1];

          toMemory(command, operand, memarray[memi]);
          memarray[memi] = memarray[memi] + 2;
          System.out.printf("%s %s ", command, operand);
        }
      }

      in.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }

    MOSMain mos = new MOSMain();
    mos.planner();

    t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    t.setSize(830, 800);
    t.setVisible(true);
    t.setTitle("Printer");
    sortTime();
  }
  /**
   * Create a HeapPage from a set of bytes of data read from disk. The format of a HeapPage is a set
   * of header bytes indicating the slots of the page that are in use, some number of tuple slots.
   * Specifically, the number of tuples is equal to:
   *
   * <p>floor((BufferPool.PAGE_SIZE*8) / (tuple size * 8 + 1))
   *
   * <p>where tuple size is the size of tuples in this database table, which can be determined via
   * {@link Catalog#getTupleDesc}. The number of 8-bit header words is equal to:
   *
   * <p>ceiling(no. tuple slots / 8)
   *
   * <p>
   *
   * @see Database#getCatalog
   * @see Catalog#getTupleDesc
   * @see BufferPool#PAGE_SIZE
   */
  public HeapPage(HeapPageId id, byte[] data) throws IOException {
    this.pid = id;
    this.td = Database.getCatalog().getTupleDesc(id.getTableId());
    this.numSlots = getNumTuples();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    // allocate and read the header slots of this page
    header = new byte[getHeaderSize()];
    for (int i = 0; i < header.length; i++) header[i] = dis.readByte();

    try {
      // allocate and read the actual records of this page
      tuples = new Tuple[numSlots];
      for (int i = 0; i < tuples.length; i++) tuples[i] = readNextTuple(dis, i);
    } catch (NoSuchElementException e) {
      e.printStackTrace();
    }
    dis.close();

    setBeforeImage();
  }
  /**
   * Helper constructor to create a heap page to be used as buffer.
   *
   * @param data - Data to be put in tmp page
   * @param td - Tuple description for the corresponding table.
   * @throws IOException
   */
  private HeapPage(byte[] data, TupleDesc td) throws IOException {
    this.pid =
        null; // No need of a pid here as this page serves as a dummy buffer page and is meant to be
              // used independent of BufferManager.
    this.td = td;
    this.numSlots = (BufferPool.PAGE_SIZE * 8) / ((td.getSize() * 8) + 1);

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
    this.header = new Header(dis);

    try {
      // allocate and read the actual records of this page
      tuples = new Tuple[numSlots];
      for (int i = 0; i < numSlots; i++) {
        tuples[i] = readNextTuple(dis, i);
      }
    } catch (NoSuchElementException e) {
      e.printStackTrace();
    }

    dis.close();
  }