public boolean existFile(File file) {
   boolean res = false;
   int senderID = this.getProfileID(file.getSender());
   int receiverID = this.getProfileID(file.getReceiver());
   if (senderID != -1 && receiverID != -1) {
     try {
       // creates a SQL Statement object in order to execute the SQL insert command
       stmt = conn.createStatement();
       ResultSet result =
           stmt.executeQuery(
               "SELECT * FROM FILES WHERE Size="
                   + (int) file.length()
                   + " AND Sender="
                   + senderID
                   + " AND Receiver="
                   + receiverID
                   + " AND Filename LIKE '"
                   + file.getName()
                   + "%'");
       if (result.next()) {
         res = true;
       }
     } catch (SQLException ex) {
       Logger.getLogger(DataService.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
   return res;
 }
 @Test
 public void shouldMoveOkFileToDone() throws Exception {
     template.sendBodyAndHeader("file://data/in/",getOkFile(), Exchange.FILE_NAME, "okfile.txt");
     Thread.sleep(2000);
     File target = new File("data/out/");
     assertTrue("file not moved to done", target.exists());
 }
  @RequestMapping(value = "/validate", method = RequestMethod.POST)
  public void file(File file, BindingResult resultx, HttpServletRequest request, Model model) {

    // Instantiate CWRC XML validator
    CwrcXmlValidator validator = new CwrcXmlValidator();

    // Instantiate a Validator object
    // CwrcValidator validator = CwrcValidatorFactory.NewValidator("CwrcJavaXmlValidator");

    // Do the validation and obtain results.
    Document report =
        validator.ValidateDocContent(file.getSch(), file.getContent(), file.getType());

    // Exporting the validation-result DOM object into a string.
    String xml;
    try {
      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer();

      StringWriter writer = new StringWriter();
      StreamResult result = new StreamResult(writer);
      Source source = new DOMSource(report.getDocumentElement());
      transformer.transform(source, result);
      writer.close();
      xml = writer.toString();
    } catch (Exception e) {
      xml =
          "<validation-result><status>fail</status><error><message>"
              + e.getMessage()
              + "</message></error></validation-result>";
    }

    // Export results for printing
    model.addAttribute("result", xml);
  }
Example #4
0
    @Override
    protected void doRun() {
      File file;

      while ((file = filesToSave.poll()) != null || saveCount.get() < FILES_COUNT) {
        if (file != null) {
          byte data[] = file.generateData();
          dataStore.storeData(file.getSessionId(), file.getId(), data);

          if (saveCount.get() % READ_MODULO == 0) {
            filesToRead1.add(file);
          }
          saveCount.incrementAndGet();
          bytesWritten.addAndGet(data.length);
        }

        try {
          Thread.sleep(random.nextInt(SLEEP_MAX));
        } catch (InterruptedException e) {
          log.error(e.getMessage(), e);
        }
      }

      saveDone.set(true);
    }
Example #5
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
    File file = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    ViewHolder viewHolder; // view lookup cache stored in tag
    if (convertView == null) {
      viewHolder = new ViewHolder();
      LayoutInflater inflater = LayoutInflater.from(getContext());
      convertView = inflater.inflate(R.layout.contact_item, parent, false);
      viewHolder.name = (TextView) convertView.findViewById(R.id.name);
      viewHolder.createdAt = (TextView) convertView.findViewById(R.id.occupation);
      viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
      convertView.setTag(viewHolder);
    } else {
      viewHolder = (ViewHolder) convertView.getTag();
    }
    // Populate the data into the template view using the data object
    viewHolder.name.setText(file.getFileName());
    SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
    try {
      Date date = isoFormat.parse(file.getCreatedAt());
      SimpleDateFormat outputDateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
      viewHolder.createdAt.setText(outputDateFormat.format(date));
    } catch (ParseException e) {
      viewHolder.createdAt.setText(file.getCreatedAt());
    }

    int[] images = {R.drawable.file_icon, R.drawable.image_icon};
    int selected = images[file.getFileName().charAt(0) % 2];

    viewHolder.image.setImageBitmap(BitmapFactory.decodeResource(parent.getResources(), selected));
    // Return the completed view to render on screen
    return convertView;
  }
Example #6
0
  /**
   * Deletes a <code>File</code> with the given name from the internal <code>File</code> list
   * Post-condition: <code>File</code> with the passed in filename will be deleted and its <code>
   * Blocks</code> added back to available <code>Blocks</code>
   *
   * @param filename the name of the <code>File</code>
   * @return successful deletion message
   * @throws NoSuchFileException if the filename does not match any existing <code>File</code>
   */
  public String delete(String filename) throws NoSuchFileException {

    Iterator<File> itr = FAT32.iterator();
    boolean fileFound = false;

    // Iterate through list of files to look for filename
    while (itr.hasNext()) {
      File file = itr.next();
      if (file.getName().equals(filename)) {
        fileFound = true;
        // Iterate through file's blocks, adding them back to available blocks
        for (int i = 0; i < bytesBlocks(file.getBytes()); i++) {
          freeBlocks.add(file.remove());
        }
        // Remove file
        itr.remove();
      }
    }

    // Throw an exception or return appropriate message
    if (fileFound == false) {
      throw new NoSuchFileException(filename + " does not exist!");
    } else {
      return filename + " deleted successfully!\n";
    }
  }
Example #7
0
  /**
   * Creates a <code>File</code> and places it into FAT32, the <code>File</code> list.
   * Pre-condition: size must be greater than 0 Post-condition: creates a <code>File</code> with
   * appropriate number of blocks and places it into internal <code>File</code> list (FAT32)
   *
   * @param filename the name of the <code>File</code>
   * @param size bytes in the <code>File</code>
   * @return successful creation message
   * @throws InSufficientDiskSpaceException if there are not enough blocks to create <code>File
   *     </code>
   * @throws DuplicateFileException if a <code>File</code> with given filename already exists
   */
  public String create(String filename, int size)
      throws InsufficientDiskSpaceException, DuplicateFileException {

    Iterator<File> findDuplicates = FAT32.iterator();
    // Go through file list to find duplicates first
    while (findDuplicates.hasNext()) {
      if (findDuplicates.next().getName().equalsIgnoreCase(filename)) {
        throw new DuplicateFileException();
      }
    }
    // Check for available space
    if (size > (freeBlocks.size() * blockSize)) {
      throw new InsufficientDiskSpaceException("Not enough disk space to create new file.\n");
    } else {
      File file = new File(size, blockSize, filename);
      Iterator<Block> itr = freeBlocks.iterator();
      // Iterate through list of available blocks, adding them to the new file as needed
      for (int i = 0; i < bytesBlocks(size); i++) {
        if (itr.hasNext()) {
          file.add(itr.next());
          // After block is added to file, it's removed from available blocks
          itr.remove();
        }
      }

      // Add file to file table
      FAT32.add(file);
      return filename + " created successfully!\n";
    }
  }
Example #8
0
  public void oldGameCheck() {

    File F = new File();
    if (F.isEmpty()) {
      JOptionPane.showMessageDialog(null, "No data from previous games found!");
    }
  }
 public SloccountReport(SloccountReport old, FileFilter filter) {
   this();
   for (File f : old.getFiles()) {
     if (filter.include(f)) {
       this.add(f.getName(), f.getLanguage(), f.getModule(), f.getLineCount());
     }
   }
 }
 /**
  * Removes all the files in this folder.
  *
  * @return True if any files were successfully removed
  */
 public boolean removeFiles() {
   final File[] files = getFiles();
   boolean success = true;
   for (File element : files) {
     success = element.remove() && success;
   }
   return success;
 }
 public String getDirectoryFilesName(String path, User currentUser, Directory currentDir)
     throws FileUnknownException, AccessDeniedException {
   if (path.equals(".")) return currentDir.getDirectoryFilesName();
   else if (path.equals("..")) return currentDir.getFather().getDirectoryFilesName();
   File target = absolutePath(path, currentUser, currentDir).getFileByName(getLastPathToken(path));
   target.checkAccessRead(currentUser);
   return target.getDirectoryFilesName();
 }
Example #12
0
 public void resetBy(File another) {
   super.resetBy(another);
   setId(another.getId());
   setDir(another.getDir());
   setName(another.getName());
   setSize(another.getSize());
   setProductionId(another.getProductionId());
 }
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    File file = new File();
    int menuOption;

    do {
      do {
        System.out.println("1. Diplay the content of a file");
        System.out.println("2. Merge files");
        System.out.println("3. Quit");

        System.out.print("Select a menu option: ");

        menuOption = scanner.nextInt();
      } while (menuOption < 1 || menuOption > 3);

      switch (menuOption) {
        case 1:
          System.out.print("Enter a file path: ");
          String path = scanner.next();

          try {
            String fileString = file.loadFile(path);
            System.out.print(fileString);
          } catch (FileNotFoundException ex) {
            System.out.println("File not found " + ex);
          } catch (IOException ex) {
            System.out.println("Read error " + ex);
          } catch (Exception ex) {
            System.out.println("Unknown error " + ex);
          }
          break;
        case 2:
          System.out.print("How many files will be merged: ");
          int numberOfSources = scanner.nextInt();
          String[] sources = new String[numberOfSources];

          for (int i = 0; i < numberOfSources; i++) {
            System.out.printf("Enter the path of source #%d: ", i + 1);
            sources[i] = scanner.next();
          }

          System.out.print("Enter the path of the target file: ");
          String target = scanner.next();

          try {
            file.mergeFiles(sources, target);
          } catch (FileNotFoundException ex) {
            System.out.println("File not found " + ex);
          } catch (IOException ex) {
            System.out.println("Read/Write error " + ex);
          } catch (Exception ex) {
            System.out.println("Unknown error " + ex);
          }
          break;
      }
    } while (menuOption != 3);
  }
  String readFile(String path, Directory currentDirectory, User currentUser)
      throws FileUnknownException, IsNotPlainFileException, AccessDeniedException {

    Directory directory = absolutePath(path, currentUser, currentDirectory);
    String filename = getLastPathToken(path);
    File f = directory.getFileByName(filename);
    f.checkAccessRead(currentUser);
    return f.printContent(currentUser);
  }
Example #15
0
 @Override
 public String[] listAll() throws IOException {
   final Transaction txn = env.getAndCheckCurrentTransaction();
   final ArrayList<String> allFiles = new ArrayList<>((int) vfs.getNumberOfFiles(txn));
   for (final File file : vfs.getFiles(txn)) {
     allFiles.add(file.getPath());
   }
   return allFiles.toArray(new String[allFiles.size()]);
 }
Example #16
0
 public void listener(UploadEvent event) throws Exception {
   UploadItem item = event.getUploadItem();
   File file = new File();
   file.setLength(item.getData().length);
   file.setName(item.getFileName());
   file.setData(item.getData());
   files.add(file);
   uploadsAvailable--;
 }
 /** Simplify the names. */
 public void simplifyNames() {
   String root = this.getRootFolder();
   for (File f : this.getFiles()) {
     f.simplifyName(root);
   }
   for (Folder f : this.getFolders()) {
     f.simplifyName(root);
   }
 }
 public File getLongestFile() {
   File longest = null;
   for (File f : this.getFiles()) {
     if (longest == null || f.getLineCount() > longest.getLineCount()) {
       longest = f;
     }
   }
   return longest;
 }
Example #19
0
 /**
  * Constructs a new FileOutputStream on the File {@code file}. The parameter {@code append}
  * determines whether or not the file is opened and appended to or just opened and overwritten.
  *
  * @param file the file to which this stream writes.
  * @param append indicates whether or not to append to an existing file.
  * @throws FileNotFoundException if the {@code file} cannot be opened for writing.
  * @throws SecurityException if a {@code SecurityManager} is installed and it denies the write
  *     request.
  * @see java.lang.SecurityManager#checkWrite(FileDescriptor)
  * @see java.lang.SecurityManager#checkWrite(String)
  */
 public FileOutputStream(File file, boolean append) throws FileNotFoundException {
   super();
   if (file.getPath().isEmpty() || file.isDirectory()) {
     throw new FileNotFoundException(file.getAbsolutePath());
   }
   fd = new FileDescriptor();
   fd.readOnly = false;
   fd.descriptor = open(file.getAbsolutePath(), append);
 }
Example #20
0
 public void indexFile(File file) {
   if (file != null)
     System.out.println(
         file.getInfo()
             + " "
             + "Thread "
             + Thread.currentThread().getId()
             + "\t"
             + file.getPath());
 }
Example #21
0
  public static void main(String[] args) {

    Directory directory = new Directory(new TextFile(), new AudioFile(), new ImageFile());

    directory.setFilesInDir(new AudioFile(), new AudioFile(), new TextFile());

    for (File f : directory.getFilesList()) {
      System.out.println(f.getCurrentString());
    }
  }
  void createPlainFile(String path, Directory currentDirectory, User currentUser)
      throws InvalidFileNameException, InvalidMaskException, FileAlreadyExistsException {

    Directory directory = absolutePath(path, currentUser, currentDirectory);
    String filename = getLastPathToken(path);
    directory.checkAccessWrite(currentUser);

    for (File f : directory.getFilesSet()) {
      if (f.getFilename().equals(filename)) throw new FileAlreadyExistsException(filename);
    }
    directory.addFile(
        new PlainFile(
            this.generateUniqueId(), filename, currentUser.getUmask(), currentUser, directory));
  }
 public String insertFile(File file) throws SQLException {
   String newName = file.getName() + "_" + (this.getFileLastID() + 1);
   if (isFriend(file.getSender(), file.getReceiver())
       && !existFile(file)) { // Check if the sender and receiver are friends
     try {
       // creates a SQL Statement object in order to execute the SQL insert command
       stmt = conn.createStatement();
       stmt.execute(
           "INSERT INTO Files (Filename, Size, Sender, Receiver, DateUpload, TimeUpload ) "
               + "VALUES ('"
               + newName
               + "', "
               + (int) file.length()
               + ", "
               + getProfileID(file.getSender())
               + ", "
               + getProfileID(file.getReceiver())
               + ", '"
               + file.getDateUpload()
               + "' , '"
               + file.getTimeUpload()
               + "')");
       stmt.close();
       // System.out.println("Requête executée");
     } catch (SQLException e) {
       // System.err.println(e.toString());
       e.toString();
       throw e;
     }
     return newName;
   } else {
     return null;
   }
 }
Example #24
0
 private void openFile(File file) {
   // ATM supports only images.
   if (file.getType().equals("image/png")) {
     Embedded embedded = new Embedded(file.getName(), file.getResource());
     VerticalLayout layout = new VerticalLayout();
     layout.setMargin(true);
     Window w = new Window(file.getName(), layout);
     layout.addComponent(embedded);
     layout.setSizeUndefined();
     getMainWindow().addWindow(w);
   } else if (file.getType().equals("text/csv")) {
     showSpreadsheet(file);
   }
 }
Example #25
0
  /**
   * Creates a new text file with given contents at the given full path-list. If a text file already
   * exists at said path, overwrite it. In either case, return the new text file.
   *
   * @param pathList The full path of the new file as a list of file names in descending order from
   *     the root of the file system.
   * @param contents The text contents of the new file.
   * @return The newly written text file.
   * @throws IsADirectoryException If the user attempts to overwrite the root directory.
   * @throws NoSuchFileException If one of the new file's specified ancestors does not exist.
   * @throws NotADirectoryException If one of the new file's specified ancestors is a text file.
   * @throws IllegalFilenameException If the name of the new text file as specified by pathList
   *     contains any illegal characters.
   */
  public static TextFile createTextFile(String[] pathList, String newContents)
      throws FileException {
    try {
      // Attempt to create a new text file at the specified path.
      return new TextFile(pathList, newContents);

      // If a file already exists at said path, overwrite it if it's a text
      // file, but not if it's a directory.
    } catch (DuplicateFileException e) {
      File duplicateFile = e.getDuplicateFile();

      duplicateFile.overwrite(newContents);
      return (TextFile) duplicateFile;
    }
  }
Example #26
0
 @Override
 public String getSource(Resource reference) {
   Resource resource = getResource(reference);
   if (resource instanceof File) {
     File file = (File) resource;
     Project module = currentProject;
     ProjectDefinition def = projectTree.getProjectDefinition(module);
     try {
       return FileUtils.readFileToString(new java.io.File(def.getBaseDir(), file.getPath()));
     } catch (IOException e) {
       throw new IllegalStateException("Unable to read file content " + reference, e);
     }
   }
   return null;
 }
Example #27
0
  public static void checkFile(File file) {
    // Check optional fields
    // NOTE checksum be checked
    Long size = file.getSize();
    if (size != null) {
      assertTrue(file.size >= 0, "File size must be greater than or equal to 0");
    }
    Long bytesTransferred = file.getBytesTransferred();
    if (bytesTransferred != null) {
      assertTrue(bytesTransferred >= 0, "Bytes transferred must be greater than or equal to 0");
    }

    // Check parent type
    checkEntityType(file);
  }
Example #28
0
  /**
   * Constructor
   *
   * @param f the excel file
   * @param sst the shared string table
   * @param fr formatting records
   * @param sb the bof record which indicates the start of the sheet
   * @param wb the bof record which indicates the start of the sheet
   * @param nf the 1904 flag
   * @param wp the workbook which this sheet belongs to
   * @throws BiffException
   */
  DefaultSheet(
      File f,
      SSTRecord sst,
      FormattingRecords fr,
      BOFRecord sb,
      BOFRecord wb,
      boolean nf,
      WorkbookParser wp)
      throws BiffException {
    excelFile = f;
    sharedStrings = sst;
    formattingRecords = fr;
    sheetBof = sb;
    workbookBof = wb;
    columnInfosArray = new ArrayList();
    sharedFormulas = new ArrayList();
    hyperlinks = new ArrayList();
    rowProperties = new ArrayList(10);
    columnInfosInitialized = false;
    rowRecordsInitialized = false;
    nineteenFour = nf;
    workbook = wp;
    workbookSettings = workbook.getSettings();

    // Mark the position in the stream, and then skip on until the end
    startPosition = f.getPos();

    if (sheetBof.isChart()) {
      // Set the start pos to include the bof so the sheet reader can handle it
      startPosition -= (sheetBof.getLength() + 4);
    }

    Record r = null;
    int bofs = 1;

    while (bofs >= 1) {
      r = f.next();

      // use this form for quick performance
      if (r.getCode() == Type.EOF.value) {
        bofs--;
      }

      if (r.getCode() == Type.BOF.value) {
        bofs++;
      }
    }
  }
  private FileMetaData getFileContentInfo(File file) {
    try {
      MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
      queryParams.add("redirect", "meta");
      ClientResponse resp =
          getRootApiWebResource()
              .path("files")
              .path(String.valueOf(file.getId()))
              .path("content")
              .queryParams(queryParams)
              .accept(MediaType.APPLICATION_OCTET_STREAM)
              .accept(MediaType.TEXT_HTML)
              .accept(MediaType.APPLICATION_XHTML_XML)
              .get(ClientResponse.class);

      String sResp = resp.getEntity(String.class);
      FileMetaData fileInfo =
          mapper.readValue(
              mapper.readValue(sResp, JsonNode.class).findPath(RESPONSE).toString(),
              FileMetaData.class);
      logger.info(fileInfo.toString());
      return fileInfo;
    } catch (BaseSpaceException bs) {
      throw bs;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
  private static void createTopology(File topoDir, String name, boolean goodTopology)
      throws Exception {
    File descriptor = new File(topoDir, name);

    if (descriptor.exists()) {
      descriptor.delete();
      descriptor = new File(topoDir, name);
    }

    FileOutputStream stream = new FileOutputStream(descriptor, false);
    if (goodTopology) {
      createTopology().toStream(stream);
    } else {
      createBadTopology().toStream(stream);
    }
    stream.close();
  }