/**
   * Create bitarchive with access denied to location of admin data verify that exceptions are
   * thrown
   */
  @Test
  public void testAccessDenied() {
    // Make sure archive exists
    assertTrue("Inaccessible archive dir must exist", NOACCESS_ARCHIVE_DIR.exists());

    if (NOACCESS_ARCHIVE_DIR.canWrite()) {
      NOACCESS_ARCHIVE_DIR.setReadOnly();
    }

    // and that admin file is inaccessible
    assertFalse(
        "Must not be able to write to inaccessible admin file", NOACCESS_ARCHIVE_DIR.canWrite());

    try {
      Settings.set(
          ArchiveSettings.BITARCHIVE_SERVER_FILEDIR, NOACCESS_ARCHIVE_DIR.getAbsolutePath());
      Bitarchive ba = Bitarchive.getInstance();
      ba.close();
      fail("Accessing read-only archive should throw exception"); // do not come here
    } catch (PermissionDenied e) {
      // Expected case
      StringAsserts.assertStringContains(
          "Should mention noaccess dir", "noaccess/filedir", e.getMessage());
    }
  }
Example #2
1
  private void testReadOnlyFiles(boolean setReadOnly) throws Exception {
    new File(System.getProperty("java.io.tmpdir")).mkdirs();
    File f = File.createTempFile("test", "temp");
    assertTrue(f.canWrite());
    f.setReadOnly();
    assertTrue(!f.canWrite());
    f.delete();

    f = File.createTempFile("test", "temp");
    RandomAccessFile r = new RandomAccessFile(f, "rw");
    r.write(1);
    f.setReadOnly();
    r.close();
    assertTrue(!f.canWrite());
    f.delete();

    deleteDb("readonlyFiles");
    Connection conn = getConnection("readonlyFiles");
    Statement stat = conn.createStatement();
    stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
    stat.execute("INSERT INTO TEST VALUES(1, 'Hello')");
    stat.execute("INSERT INTO TEST VALUES(2, 'World')");
    assertTrue(!conn.isReadOnly());
    conn.close();

    if (setReadOnly) {
      setReadOnly();
      conn = getConnection("readonlyFiles");
    } else {
      conn = getConnection("readonlyFiles;ACCESS_MODE_DATA=r");
    }
    assertTrue(conn.isReadOnly());
    stat = conn.createStatement();
    stat.execute("SELECT * FROM TEST");
    assertThrows(ErrorCode.DATABASE_IS_READ_ONLY, stat).execute("DELETE FROM TEST");
    conn.close();

    if (setReadOnly) {
      conn = getConnection("readonlyFiles;DB_CLOSE_DELAY=1");
    } else {
      conn = getConnection("readonlyFiles;DB_CLOSE_DELAY=1;ACCESS_MODE_DATA=r");
    }
    stat = conn.createStatement();
    stat.execute("SELECT * FROM TEST");
    assertThrows(ErrorCode.DATABASE_IS_READ_ONLY, stat).execute("DELETE FROM TEST");
    stat.execute("SET DB_CLOSE_DELAY=0");
    conn.close();
  }
  /**
   * Return true if the fils exists and is readable and writable not locked by another process <br>
   * New version that works because it uses RandomAccessFile and will throw an exception if another
   * file has locked the file
   */
  public static boolean isUnlockedForWrite(File file) {
    if (file.exists() && file.canWrite()) {
      if (file.isDirectory()) {
        return true;
      }

      try {
        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        raf.close();

        debug(new Date() + " " + file + " OK!");

        return true;
      } catch (Exception e) {
        debug(new Date() + " " + file + " LOCKED! " + e.getMessage());
      }
    } else {
      debug(
          new Date()
              + " "
              + file
              + " LOCKED! File exists(): "
              + file.exists()
              + " File canWrite: "
              + file.canWrite());
    }

    return false;
  }
    @Override
    public ConversionRule build(File sourceDirectory, List<String> args)
        throws FatalConversionException {
      if (!(sourceDirectory.isDirectory()
          && sourceDirectory.canRead()
          && sourceDirectory.canWrite())) {
        throw new IllegalArgumentException(
            "sourceDirectory must be a directory with read/write permissions.");
      }
      File src = sourceDirectory;

      if (args.size() < 1) {
        throw new FatalConversionException(new IllegalArgumentException(usage()));
      }

      File dest = new File(args.get(0));

      if (!(dest.isDirectory() && dest.canRead() && dest.canWrite())) {
        throw new FatalConversionException(
            new IllegalArgumentException(
                "destinationDirectory must be a directory with read/write access."));
      }

      Log.info(LOGNAME, "Ready to convert from " + src + " to " + dest + ".");

      return new MP3ify(src, dest);
    }
  PluginInstallDialog(Studio app, PluginManagerDialog parent) {
    super(parent);
    this.app = app;
    plugins = parent.getInstallablePlugins();

    JPanel c = new JPanel(new BorderLayout(10, 10));
    c.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
    c.add(new JLabel("Select Plugins to install"), BorderLayout.NORTH);

    // JPanel p = new JPanel(new GridLayout(1,2,5,5));

    table = new JTable(new DataModel());
    table.setTableHeader(null);
    table.setShowGrid(false);
    TableColumn col = table.getColumn(table.getColumnName(0));
    col.setMaxWidth(col.getMinWidth());
    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    c.add(new JScrollPane(table), BorderLayout.WEST);

    table.getSelectionModel().addListSelectionListener(this);
    table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    info = new PluginInfoPanel();
    info.setBorder(BorderFactory.createTitledBorder("Plugin Info"));
    c.add(info, BorderLayout.CENTER);
    // c.add(p,BorderLayout.CENTER);

    JPanel bottom = new JPanel(new BorderLayout());
    JPanel cb = new JPanel(new BorderLayout());
    String dir = app.getUserExtensionsDir();
    cb1 = new JRadioButton("Install in user directory (" + dir + ")");
    File df = new File(dir);
    if (!df.exists()) df.mkdirs();
    cb1.setEnabled(dir != null && df.canWrite());
    cb1.setSelected(true);
    cb.add(cb1, BorderLayout.NORTH);
    dir = app.getSystemExtensionsDir();
    cb2 = new JRadioButton("Install in system directory (" + dir + ")");
    df = new File(dir);
    if (!df.exists()) df.mkdirs();
    cb2.setEnabled(dir != null && df.canWrite());
    cb.add(cb2, BorderLayout.SOUTH);
    ButtonGroup rg = new ButtonGroup();
    rg.add(cb1);
    rg.add(cb2);
    bottom.add(cb, BorderLayout.NORTH);

    install = new JButton("Install");
    install.addActionListener(this);
    install.setEnabled(false);
    close = new JButton("Close");
    close.addActionListener(this);
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(install);
    buttonPanel.add(close);
    bottom.add(buttonPanel, BorderLayout.SOUTH);
    c.add(bottom, BorderLayout.SOUTH);

    setContentPane(c);
  }
Example #6
0
  public static HttpURLConnection download(final HttpURLConnection con, final File file)
      throws IOException {
    if (file.exists()) {
      con.setIfModifiedSince(file.lastModified());
      con.connect();
      if (con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
        log.fine("Using " + file.getName() + " from cache");
        con.disconnect();
        return con;
      }
    }

    log.fine("Downloading new " + file.getName());

    final byte[] buffer = downloadBinary(con);

    if (!file.exists()) {
      file.createNewFile();
    }
    if (file.exists() && (!file.canRead() || file.canWrite())) {
      file.setReadable(true);
      file.setWritable(true);
    }
    if (file.exists() && file.canRead() && file.canWrite()) {
      final FileOutputStream fos = new FileOutputStream(file);
      fos.write(buffer);
      fos.flush();
      fos.close();
    }

    file.setLastModified(con.getLastModified());

    con.disconnect();
    return con;
  }
Example #7
0
 /*
  * Delete a single file from the filesystem.
  *
  * @param fileToDelete A <code>File</code> object representing the file to
  * be deleted.
  *
  * @throws IOException if any problem occurs deleting the file.
  */
 private void deleteFile(File fileToDelete) throws IOException {
   if ((fileToDelete != null)
       && fileToDelete.exists()
       && fileToDelete.isFile()
       && fileToDelete.canWrite()) {
     fileToDelete.delete();
   } else {
     String errorMessage = "";
     if (fileToDelete == null) {
       errorMessage = "Null pointer for file to delete.";
     } else {
       if (!fileToDelete.exists()) {
         errorMessage = "The file " + fileToDelete.getName() + " does not exist.";
       } else {
         if (!fileToDelete.isFile()) {
           errorMessage = fileToDelete.getName() + " is not a file.";
         } else {
           if (!fileToDelete.canWrite()) {
             errorMessage = "Cannot write to " + fileToDelete.getName();
           }
         }
       }
     }
     throw new IOException("Cannot delete file: " + errorMessage);
   }
 }
Example #8
0
  public boolean isAllowedFile(File file, FileActionEnum action) {
    boolean actionAllowed;
    if (file != null) {
      // - only classic linux in my mind (no acl or selinux)
      // P.S: sticky bit neither
      switch (action) {
        case READ:
          actionAllowed = file.canRead();
          break;
        case WRITE:
          actionAllowed = !file.exists() || file.canWrite();
          break;
        case DELETE:
          actionAllowed = file.getParentFile().canWrite();
          break;

          // relative to current directory:
        case CREATE_FILE:
          actionAllowed = file.canWrite();
          break;
        case CREATE_DIR:
          actionAllowed = file.canWrite();
          break;
        default:
          actionAllowed = false;
      }
    } else {
      actionAllowed = false;
    }
    return actionAllowed;
  }
Example #9
0
  /**
   * Verifies that the persistence layer is read for the new file to be persisted.
   *
   * @throws IOException if there are any issues in the persistence layer
   */
  private static void verifyPersistenceLayer(File aFile) throws IOException {
    if (aFile.getParentFile().getParentFile() == null) {
      throw new IOException(
          "Trying to create a file too close to the root of the file system is dangerous");
    }

    // check that the persistence dir exists
    File dir = new File(aFile.getParentFile().getAbsolutePath());

    if (!(dir.exists())) {
      LOG.info("Creating directory [" + dir.getAbsolutePath() + "]");
      if (!(dir.mkdirs())) {
        throw new IOException("Failed to create directory [" + dir.getAbsolutePath() + "]");
      }
    } else {
      if (!(dir.isDirectory()) || !(dir.canWrite())) {
        String err = "Cannot write to the directory [" + aFile.getAbsolutePath() + "]";
        LOG.error(err);
        throw new IOException(err);
      }
    }

    // now check that the actual file exists
    if (!(aFile.exists())) {
      createPersistenceFile(aFile);
    } else {
      if (!(aFile.isFile()) || !(aFile.canWrite())) {
        String err = "Cannot write to file [" + aFile.getAbsolutePath() + "]";
        LOG.error(err);
        throw new IOException(err);
      }
    }

    LOG.debug("File correctly set up");
  }
Example #10
0
 /**
  * @param configPath
  * @param checkUserHome if true tries to check if the file ${user.home}/.pdfsam/config.xml exists
  *     and can be written, if not tries to check if the file APPLICATIOH_PATH/config.xml can be
  *     written, if not copies the APPLICATIOH_PATH/config.xml to ${user.home}/.pdfsam/config.xml
  * @throws Exception
  */
 public XMLConfig(String configPath, boolean checkUserHome) throws Exception {
   File configFile = new File(configPath, "config.xml");
   if (checkUserHome) {
     File defaultConfigFile = new File(defaultDirectory, "config.xml");
     if (!(defaultConfigFile.exists() && defaultConfigFile.canWrite())) {
       if (!configFile.exists()) {
         throw new ConfigurationException("Unable to find configuration file.");
       }
       if (!configFile.canWrite()) {
         File defaultDir = new File(defaultDirectory);
         if (defaultDir.mkdirs()) {
           log.info(
               "Copying config.xml from "
                   + configFile.getPath()
                   + " to "
                   + defaultConfigFile.getPath());
           FileUtility.copyFile(configFile, defaultConfigFile);
           configFile = defaultConfigFile;
         } else {
           throw new ConfigurationException("Unable to create " + defaultDirectory);
         }
       }
     } else {
       configFile = defaultConfigFile;
     }
   }
   xmlConfigFile = configFile;
   document = XMLParser.parseXmlFile(xmlConfigFile);
 }
Example #11
0
  public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {

    /* Check access permission */
    if (!device.canRead() || !device.canWrite()) {
      try {
        /* Missing read/write permission, trying to chmod the file */
        Process su;
        su = Runtime.getRuntime().exec("/system/bin/su");
        String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
        su.getOutputStream().write(cmd.getBytes());
        if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
          throw new SecurityException();
        }
      } catch (Exception e) {
        e.printStackTrace();
        throw new SecurityException();
      }
    }

    mFd = open(device.getAbsolutePath(), baudrate, flags);
    if (mFd == null) {
      Log.e(TAG, "native open returns null");
      throw new IOException();
    }
    mFileInputStream = new FileInputStream(mFd);
    mFileOutputStream = new FileOutputStream(mFd);
    mDevPath = device.getAbsolutePath();
  }
Example #12
0
 private String createCacheDir(File baseDir, String subDir) {
   String cacheDirName = null;
   if (baseDir.isDirectory()) {
     if (baseDir.canWrite()) {
       if (subDir != null) {
         baseDir = new File(baseDir, subDir);
         baseDir.mkdir();
       }
       if (baseDir.exists() && baseDir.canWrite()) {
         File cacheDir = new File(baseDir, "cache");
         if (cacheDir.exists() || cacheDir.mkdirs()) {
           if (cacheDir.canWrite()) {
             cacheDirName = cacheDir.getAbsolutePath();
             CR3_SETTINGS_DIR_NAME = baseDir.getAbsolutePath();
           }
         }
       }
     } else {
       log.i(baseDir.toString() + " is read only");
     }
   } else {
     log.i(baseDir.toString() + " is not found");
   }
   return cacheDirName;
 }
Example #13
0
  /**
   * If the argument is the <i>identifier</i> parameter, then set the title of all contained
   * Tableaux to the value of the parameter; if the argument is the <i>uri</i> parameter, then check
   * to see whether it is writable, and call setModifiable() appropriately.
   *
   * @param attribute The attribute that changed.
   * @exception IllegalActionException If the base class throws it.
   */
  @Override
  public void attributeChanged(Attribute attribute) throws IllegalActionException {
    if (attribute == identifier) {
      Iterator tableaux = entityList(Tableau.class).iterator();

      while (tableaux.hasNext()) {
        Tableau tableau = (Tableau) tableaux.next();
        tableau.setTitle(identifier.getExpression());
      }
    } else if (attribute == uri) {
      URI uriValue = uri.getURI();

      if (uriValue == null) {
        // A new model, with no URI, is by default modifiable.
        _modifiableURI = true;
      } else {
        String protocol = uriValue.getScheme();

        if (!protocol.equals("file")) {
          _modifiableURI = false;
        } else {
          // Use just the path here in case we
          // are passed a URI that has a fragment.
          // If we had file:/C%7C/foo.txt#bar
          // then bar is the fragment.  Unfortunately,
          // new File(file:/C%7C/foo.txt#bar) will fail,
          // so we add the path.
          String path = uriValue.getPath();
          if (path != null) {
            File file = new File(path);

            try {
              if (path.indexOf("%20") == -1) {
                _modifiableURI = file.canWrite();
              } else {
                // FIXME: we need a better way to check if
                // a URL is writable.

                // Sigh.  If the filename has spaces in it,
                // then the URL will have %20s.  However,
                // the file does not have %20s.
                // See
                // https://chess.eecs.berkeley.edu/bugzilla/show_bug.cgi?id=153
                path = StringUtilities.substitute(path, "%20", " ");
                file = new File(path);
                _modifiableURI = file.canWrite();
              }
            } catch (java.security.AccessControlException accessControl) {
              // If we are running in a sandbox, then canWrite()
              // may throw an AccessControlException.
              _modifiableURI = false;
            }
          }
        }
      }
    } else {
      super.attributeChanged(attribute);
    }
  }
Example #14
0
 public XforJArguments(
     final File inputfile,
     final File outputfile,
     final File destdir,
     final File srcdir,
     final List<File> inputfiles,
     final boolean overwrite,
     final boolean minifyhtml,
     final boolean global,
     final boolean normalizespace,
     final boolean debug,
     final boolean warn,
     final boolean removelogs,
     final boolean useexternal,
     final File outputlibrary,
     final boolean escapexss)
     throws Throwable {
   if (inputfile != null && inputfile.exists() && !inputfile.canWrite()) {
     throw new IllegalArgumentException(
         "The following file may not be overwritten to: 'inputfile'.");
   }
   if (outputfile != null && outputfile.exists() && !outputfile.canWrite()) {
     throw new IllegalArgumentException(
         "The following file may not be overwritten to: 'outputfile'.");
   }
   if (destdir != null) {
     if (!destdir.exists() || !destdir.isDirectory()) {
       destdir.mkdirs();
     }
     if (!(destdir.exists() && destdir.isDirectory())) {
       throw new IllegalArgumentException(
           "Directory doesn't exist :'" + destdir + "'.  Given by argument 'destdir'.");
     }
   }
   if (srcdir != null) {
     if (!srcdir.exists() || !srcdir.isDirectory()) {
       srcdir.mkdirs();
     }
     if (!(srcdir.exists() && srcdir.isDirectory())) {
       throw new IllegalArgumentException(
           "Directory doesn't exist :'" + srcdir + "'.  Given by argument 'srcdir'.");
     }
   }
   this.inputfile = inputfile;
   this.outputfile = outputfile;
   this.destdir = destdir;
   this.srcdir = srcdir;
   this.inputfiles = inputfiles;
   this.overwrite = overwrite;
   this.minifyhtml = minifyhtml;
   this.global = global;
   this.normalizespace = normalizespace;
   this.debug = debug;
   this.warn = warn;
   this.removelogs = removelogs;
   this.useexternal = useexternal;
   this.outputlibrary = outputlibrary;
   this.escapexss = escapexss;
 }
Example #15
0
  public static Thumbnail getLastThumbnail(ContentResolver resolver, boolean isImage) {
    /*
     * Media image = getLastImageThumbnail(resolver); Media video =
     * getLastVideoThumbnail(resolver); Log.e("testthum",
     * "get last thumbnail called"); if (image == null && video == null)
     * return null; if (video == null) Log.e("testthum", "video is null");
     * Bitmap bitmap = null; Media lastMedia; // If there is only image or
     * video, get its thumbnail. If both exist, // get the thumbnail of the
     * one that is newer. if (image != null && (video == null ||
     * image.dateTaken >= video.dateTaken)) { Log.e("testthum",
     * "get thumbnail image"); bitmap =
     * Images.Thumbnails.getThumbnail(resolver, image.id,
     * Images.Thumbnails.MINI_KIND, null); lastMedia = image; } else {
     * Log.e("testthum", "get thumbnail video"); bitmap =
     * Video.Thumbnails.getThumbnail(resolver, video.id,
     * Video.Thumbnails.MINI_KIND, null); lastMedia = video; }
     */

    Media media = isImage ? getLastImageThumbnail(resolver) : getLastVideoThumbnail(resolver);
    if (media == null) {
      Log.d("dyb", "media is null");
      return null;
    }
    Bitmap bitmap = null;
    // If there is only image or video, get its thumbnail. If both exist,
    // get the thumbnail of the one that is newer.
    if (isImage) {
      File dir = new File(Storage.DIRECTORY);
      dir.mkdir();
      if (!dir.isDirectory() || !dir.canWrite()) {
        Log.d("dyb", "dir error");
        return null;
      }
      if (dir.listFiles().length == 0) {
        Log.d("mk", "dir.listFiles().length = " + dir.listFiles().length);
        return null;
      }
      bitmap =
          Images.Thumbnails.getThumbnail(resolver, media.id, Images.Thumbnails.MINI_KIND, null);
    } else {
      File dir = new File(Storage.DIRECTORY);
      dir.mkdir();
      if (!dir.isDirectory() || !dir.canWrite()) {
        Log.d("dyb", "dir error");
        return null;
      }
      if (dir.listFiles().length == 0) {
        Log.d("mk", "dir.listFiles().length = " + dir.listFiles().length);
        return null;
      }
      bitmap = Video.Thumbnails.getThumbnail(resolver, media.id, Video.Thumbnails.MINI_KIND, null);
    }

    // Ensure database and storage are in sync.
    if (Util.isUriValid(media.uri, resolver)) {
      return createThumbnail(media.uri, bitmap, media.orientation);
    }
    return null;
  }
Example #16
0
 /**
  * @Title: getExtSDCardPaths @Description: to obtain storage paths, the first path is
  * theoretically the returned value of Environment.getExternalStorageDirectory(), namely the
  * primary external storage. It can be the storage of internal device, or that of external sdcard.
  * If paths.size() >1, basically, the current device contains two type of storage: one is the
  * storage of the device itself, one is that of external sdcard. Additionally, the paths is
  * directory.
  *
  * @return List<String>
  * @throws IOException
  */
 public static List<String> getExtSDCardPaths() {
   List<String> paths = new ArrayList<String>();
   String extFileStatus = Environment.getExternalStorageState();
   File extFile = Environment.getExternalStorageDirectory();
   if (extFileStatus.equals(Environment.MEDIA_MOUNTED)
       && extFile.exists()
       && extFile.isDirectory()
       && extFile.canWrite()) {
     paths.add(extFile.getAbsolutePath());
   }
   Process process = null;
   try {
     process = Runtime.getRuntime().exec("mount");
     InputStream is = process.getInputStream();
     InputStreamReader isr = new InputStreamReader(is);
     BufferedReader br = new BufferedReader(isr);
     String line = null;
     int mountPathIndex = 1;
     while ((line = br.readLine()) != null) {
       // format of sdcard file system: vfat/fuse
       if ((!line.contains("fat") && !line.contains("fuse") && !line.contains("storage"))
           || line.contains("secure")
           || line.contains("asec")
           || line.contains("firmware")
           || line.contains("shell")
           || line.contains("obb")
           || line.contains("legacy")
           || line.contains("data")) {
         continue;
       }
       String[] parts = line.split(" ");
       int length = parts.length;
       if (mountPathIndex >= length) {
         continue;
       }
       String mountPath = parts[mountPathIndex].trim();
       if (!mountPath.contains("/") || mountPath.contains("data") || mountPath.contains("Data")) {
         continue;
       }
       File mountRoot = new File(mountPath);
       if (!mountRoot.exists() || !mountRoot.isDirectory() || !mountRoot.canWrite()) {
         continue;
       }
       boolean equalsToPrimarySD = mountPath.equals(extFile.getAbsolutePath());
       if (equalsToPrimarySD) {
         continue;
       }
       paths.add(mountPath);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       process.destroy();
     } catch (Exception e) {
     }
   }
   return paths;
 }
Example #17
0
  private boolean validateLocation(File dir) {

    if (!dir.exists() && dir.canWrite()) dir.mkdirs();

    if (!dir.exists() || !dir.isDirectory() || !dir.canWrite()) return false;

    return true;
  }
Example #18
0
  /**
   * Generates simple PDF, RTF and HTML files using only one Document object.
   *
   * @param args no arguments needed here
   */
  public static void main(String[] args) {

    System.out.println("Hello World in PDF, RTF and HTML");

    // step 1: creation of a document-object
    Document document = new Document();
    try {
      // step 2:
      // we create 3 different writers that listen to the document
      File file1 = new File("HelloWorldPdf.pdf");
      File file2 = new File("HelloWorldRtf.rtf");
      File file3 = new File("HelloWorldHtml.html");

      if (!file1.exists()) {
        file1.canWrite();
      }
      if (!file2.exists()) {
        file2.canWrite();
      }
      if (!file3.exists()) {
        file3.canWrite();
      }

      PdfWriter pdf = PdfWriter.getInstance(document, new FileOutputStream(file1));
      RtfWriter2 rtf = RtfWriter2.getInstance(document, new FileOutputStream(file2));
      HtmlWriter.getInstance(document, new FileOutputStream(file3));

      // step 3: we open the document
      document.open();
      // step 4: we add a paragraph to the document
      document.add(new Paragraph("Hello World"));

      // we make references
      Anchor pdfRef = new Anchor("see Hello World in PDF.");
      pdfRef.setReference("./HelloWorldPdf.pdf");

      Anchor rtfRef = new Anchor("see Hello World in RTF.");
      rtfRef.setReference("./HelloWorldRtf.rtf");

      // we add the references, but only to the HTML page:

      pdf.pause();
      rtf.pause();
      document.add(pdfRef);
      document.add(Chunk.NEWLINE);
      document.add(rtfRef);
      pdf.resume();
      rtf.resume();

    } catch (DocumentException de) {
      System.err.println(de.getMessage());
    } catch (IOException ioe) {
      System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();
  }
  /** Updates toolbar controls state. */
  protected void updateToolbarControlsState() {
    final File selectedFile = fileTree.getSelectedFile();

    folderUp.setEnabled(selectedFile != null && selectedFile.getParentFile() != null);

    folderNew.setEnabled(selectedFile != null && selectedFile.canWrite());
    remove.setEnabled(
        selectedFile != null && selectedFile.getParentFile() != null && selectedFile.canWrite());
  }
Example #20
0
  public static final void deleteAllFixedSpawns(Player p, NPCHandler handle) {
    File spawn = FileLocator.getNPCFixedSpawnsFile(), pres = FileLocator.getNPCPresetPathingFile();
    if (spawn.canRead() && spawn.canWrite()) {
      if (spawn.exists()) {
        loader.read();
        for (SyncWrapper wrap : loader.getReadableData()) {
          SimpleNPC rem = handle.getSimpleNPCByName(wrap.getTag());
          if (rem != null) {
            rem.destroyNPCObject();
          }
        }
        spawn.delete();
        try {
          spawn.createNewFile();
          loader.add("NPC_COUNT", 0);
          loader.write();
          QuestX.logChat(p, LocaleBundle.getString("all_fxied_spawns_del"));
        } catch (IOException e) {
          QuestX.logChat(p, LocaleBundle.getString("error_del_fs_file"));
          e.printStackTrace();
        }
      } else {
        QuestX.logChat(p, LocaleBundle.getString("no_fs_file"));
      }
    } else {
      QuestX.logChat(p, LocaleBundle.getString("fs_file_locked"));
    }

    presetNPCs.clear();

    if (pres.canRead() && pres.canWrite()) {
      if (pres.exists()) {
        pres.delete();
        try {
          pres.createNewFile();
          io.clearWriteArray();
          io.add("NULL", 0);
          io.write();
          QuestX.logChat(p, LocaleBundle.getString("all_preset_del"));
        } catch (IOException e) {
          QuestX.logChat(p, LocaleBundle.getString("error_del_pp_file"));
          e.printStackTrace();
        }
      } else {
        QuestX.logChat(p, LocaleBundle.getString("no_pp_file"));
      }
    } else {
      QuestX.logChat(p, LocaleBundle.getString("pp_file_locked"));
    }

    FixedSpawnsDisplay.updateSoftReference();
    PresetPathsDisplay.updateSoftReference();
  }
  public boolean validaParametros() {
    if (StringUtils.isBlank(textArquivoDeEntrada.getText())) {
      warn("O arquivo de entrada é obrigatório");
      return false;
    }

    if (StringUtils.isBlank(textArquivoDeSaida.getText())) {
      warn("O arquivo de saida é obrigatório");
      return false;
    }

    arquivoDeEntrada = new File(textArquivoDeEntrada.getText());
    if (!arquivoDeEntrada.exists()) {
      warn("O arquivo de entrada não existe");
      return false;
    }
    if (!arquivoDeEntrada.isFile()) {
      warn("O arquivo de entrada não é um arquivo");
      return false;
    }
    if (!arquivoDeEntrada.canRead()) {
      warn("O arquivo de entrada não está acessível");
      return false;
    }

    arquivoDeSaida = new File(textArquivoDeSaida.getText());
    if (arquivoDeSaida.exists()) {
      if (!arquivoDeSaida.isFile()) {
        warn("O arquivo de saida é inválido");
        return false;
      }
      if (!arquivoDeSaida.canWrite()) {
        warn("O arquivo de saida está protegido contra escrita");
        return false;
      }
    }

    arquivoDeSaidaDir = arquivoDeSaida.getParentFile();
    if (arquivoDeSaidaDir == null && !arquivoDeSaida.isAbsolute()) {
      arquivoDeSaidaDir = new File(".");
    }
    if (arquivoDeSaidaDir.exists()) {
      if (!arquivoDeSaidaDir.canWrite()) {
        warn("O diretório do arquivo de saida está protegido contra escrita");
        return false;
      }
    } else if (!arquivoDeSaidaDir.mkdirs()) {
      warn("O diretório do arquivo de saida não pôde ser criado");
      return false;
    }

    return true;
  }
Example #22
0
 //// cleanupCache
 private void cleanupCache(NntpArticleHeader header) {
   log.debug("cleaning up cache files");
   try {
     NntpArticlePartID[] ids = header.getParts();
     if ((ids != null) && (ids.length > 0)) {
       for (int x = 0; x < ids.length; x++) {
         try {
           NntpArticlePartID currentPart = ids[x];
           File cachefile =
               new File(
                   cacheDir
                       + File.separator
                       + header.getServer()
                       + "."
                       + header.getGroup()
                       + "."
                       + currentPart.getIdAsString());
           if (cachefile.exists()) {
             log.debug("is writable: " + cachefile.canWrite());
             if (!cachefile.delete()) {
               log.warn("failed removing cachefile: " + cachefile.toString());
             }
           }
         } catch (SecurityException se) {
           log.warn("caught exception removing cachefile: " + se.getMessage());
         }
       }
     } else {
       try {
         File cachefile =
             new File(
                 cacheDir
                     + File.separator
                     + header.getServer()
                     + "."
                     + header.getGroup()
                     + "."
                     + header.getID());
         if (cachefile.exists()) {
           log.debug("is writable: " + cachefile.canWrite());
           if (!cachefile.delete()) {
             log.warn("failed removing cachefile: " + cachefile.toString());
           }
         }
       } catch (SecurityException se) {
         log.warn("caught exception removing cachefile: " + se.getMessage());
       }
     }
   } catch (NullPointerException npe) {
     log.error("what happened, null pointer exception: " + npe.getMessage());
   }
 }
  @SuppressWarnings({"ResultOfMethodCallIgnored"})
  protected static void markFileUsed(java.io.File file) {
    if (file == null) return;

    long currentTime = System.currentTimeMillis();

    if (file.canWrite()) file.setLastModified(currentTime);

    if (file.isDirectory()) return;

    java.io.File parent = file.getParentFile();
    if (parent != null && parent.canWrite()) parent.setLastModified(currentTime);
  }
Example #24
0
  private File getTempRoot() {
    File tempDir = new File(System.getProperty("java.io.tmpdir"));

    // check if temp dir is writeable
    if (!tempDir.canWrite()) {
      // try home dir
      tempDir = new File(System.getProperty("user.home"));
      if (!tempDir.canWrite()) {
        // try current working dir
        tempDir = new File(System.getProperty("user.dir"));
      }
    }
    return tempDir;
  }
Example #25
0
 @Test(timeout = 30000)
 public void testCreateLocalTempFile() throws IOException {
   setupDirs();
   final File baseFile = new File(tmp, "base");
   File tmp1 = FileUtil.createLocalTempFile(baseFile, "foo", false);
   File tmp2 = FileUtil.createLocalTempFile(baseFile, "foo", true);
   assertFalse(tmp1.getAbsolutePath().equals(baseFile.getAbsolutePath()));
   assertFalse(tmp2.getAbsolutePath().equals(baseFile.getAbsolutePath()));
   assertTrue(tmp1.exists() && tmp2.exists());
   assertTrue(tmp1.canWrite() && tmp2.canWrite());
   assertTrue(tmp1.canRead() && tmp2.canRead());
   tmp1.delete();
   tmp2.delete();
   assertTrue(!tmp1.exists() && !tmp2.exists());
 }
Example #26
0
  @Override
  public void pushEntries(
      BibtexDatabase database,
      final BibtexEntry[] entries,
      final String keyString,
      MetaData metaData) {

    couldNotFindPipe = false;
    couldNotWrite = false;

    String lyxpipeSetting = Globals.prefs.get(JabRefPreferences.LYXPIPE);
    if (!lyxpipeSetting.endsWith(".in")) {
      lyxpipeSetting = lyxpipeSetting + ".in";
    }
    File lp = new File(lyxpipeSetting); // this needs to fixed because it gives "asdf" when going
    // prefs.get("lyxpipe")
    if (!lp.exists() || !lp.canWrite()) {
      // See if it helps to append ".in":
      lp = new File(lyxpipeSetting + ".in");
      if (!lp.exists() || !lp.canWrite()) {
        couldNotFindPipe = true;
        return;
      }
    }

    final File lyxpipe = lp;

    JabRefExecutorService.INSTANCE.executeAndWait(
        new Runnable() {

          @Override
          public void run() {
            try {
              FileWriter fw = new FileWriter(lyxpipe);
              BufferedWriter lyx_out = new BufferedWriter(fw);
              String citeStr;

              citeStr = "LYXCMD:sampleclient:citation-insert:" + keyString;
              lyx_out.write(citeStr + "\n");

              lyx_out.close();

            } catch (IOException excep) {
              couldNotWrite = true;
            }
          }
        });
  }
  public void loadProperties(String configFile) {

    if (configFile.startsWith("jar:")) {
      configFile = configFile.substring(4);

      final InputStream is = this.getClass().getResourceAsStream(configFile);

      if (is != null) {
        configInputStream = is;
      } else {
        throw new RuntimeException("unable to open resource stream for " + configFile);
      }
    } else {

      // Check if filename is actually a url
      if (configFile.startsWith("http:")) {
        try {

          // Create input stream for the file
          final URL url = new URL(configFile);
          final URLConnection con = url.openConnection();
          con.setDoOutput(true);
          configInputStream = url.openStream();

        } catch (final MalformedURLException e) {
          e.printStackTrace();
        } catch (final IOException e) {
          e.printStackTrace();
        }
      }

      if (configInputStream == null) {
        // If starts with file specification, remove it as not needed or supported.
        if (configFile.startsWith("file:/")) {
          configFile = configFile.substring(6);
        }
        final File p = new File(configFile);
        if (p.exists() || (!p.exists() && !p.canWrite())) {
          this.configFile = configFile;
        } else {
          throw new RuntimeException();
        }
        isReadOnly = !p.canWrite();
      }
    }

    loadProperties();
  }
 public static void setReadOnlyAttribute(@NotNull String path, boolean readOnlyFlag) {
   final boolean writableFlag = !readOnlyFlag;
   final File file = new File(path);
   if (!file.setWritable(writableFlag) && file.canWrite() != writableFlag) {
     LOG.warn("Can't set writable attribute of '" + path + "' to " + readOnlyFlag);
   }
 }
Example #29
0
 @Override
 public Map<String, ?> getAttributes(URI uri, Map<?, ?> options) {
   Map<String, Object> result = new HashMap<String, Object>();
   String filePath = uri.toFileString();
   File file = new File(filePath);
   if (file.exists()) {
     Set<String> requestedAttributes = getRequestedAttributes(options);
     if (requestedAttributes == null
         || requestedAttributes.contains(IURIConverter.ATTRIBUTE_TIME_STAMP)) {
       result.put(IURIConverter.ATTRIBUTE_TIME_STAMP, file.lastModified());
     }
     if (requestedAttributes == null
         || requestedAttributes.contains(IURIConverter.ATTRIBUTE_LENGTH)) {
       result.put(IURIConverter.ATTRIBUTE_LENGTH, file.length());
     }
     if (requestedAttributes == null
         || requestedAttributes.contains(IURIConverter.ATTRIBUTE_READ_ONLY)) {
       result.put(IURIConverter.ATTRIBUTE_READ_ONLY, !file.canWrite());
     }
     if (requestedAttributes == null
         || requestedAttributes.contains(IURIConverter.ATTRIBUTE_HIDDEN)) {
       result.put(IURIConverter.ATTRIBUTE_HIDDEN, file.isHidden());
     }
     if (requestedAttributes == null
         || requestedAttributes.contains(IURIConverter.ATTRIBUTE_DIRECTORY)) {
       result.put(IURIConverter.ATTRIBUTE_DIRECTORY, file.isDirectory());
     }
   }
   return result;
 }
 public void setDumpDir(File dumpDir) {
   if (!dumpDir.isDirectory() || !dumpDir.canWrite() || !dumpDir.canRead()) {
     throw new RuntimeDroolsException(
         "Drools dump directory is not accessible: " + dumpDir.toString());
   }
   this.dumpDirectory = dumpDir;
 }