Ejemplo n.º 1
0
  private void createUnixScript(
      String jarPath, File scriptDestinationDir, String wrapperPropertiesPath) throws IOException {
    String unixWrapperScriptHead =
        IOUtils.toString(getClass().getResourceAsStream("unixWrapperScriptHead.txt"));
    String unixWrapperScriptTail =
        IOUtils.toString(getClass().getResourceAsStream("unixWrapperScriptTail.txt"));

    String fillingUnix =
        ""
            + UNIX_NL
            + "STARTER_MAIN_CLASS="
            + FULLY_QUALIFIED_WRAPPER_NAME
            + UNIX_NL
            + "CLASSPATH="
            + CURRENT_DIR_UNIX
            + "/"
            + FilenameUtils.separatorsToUnix(jarPath)
            + UNIX_NL
            + "WRAPPER_PROPERTIES="
            + CURRENT_DIR_UNIX
            + "/"
            + FilenameUtils.separatorsToUnix(wrapperPropertiesPath)
            + UNIX_NL;

    String unixScript = unixWrapperScriptHead + fillingUnix + unixWrapperScriptTail;
    File unixScriptFile = new File(scriptDestinationDir, "gradlew");
    FileUtils.writeStringToFile(unixScriptFile, unixScript);
    createExecutablePermission(unixScriptFile);
  }
Ejemplo n.º 2
0
  /**
   * Creates a new StockFile entry in the database with the given StockFile object and establishes
   * an association between the StockFile object with the current user within UserSession
   *
   * @param file
   * @return
   * @throws SQLException
   */
  public boolean createFile(StockFile file) throws SQLException {
    if (!inDatabase(file)) {
      try {

        ps =
            conn.prepareStatement(
                "INSERT INTO "
                    + "file (version,last_sync_by,created_by,file_name,file_path) "
                    + "VALUES (?,?,?,?,?);");

        ps.setFloat(1, file.getVersion());
        ps.setString(2, file.getLastSyncBy());
        ps.setString(3, file.getCreatedBy());
        ps.setString(4, FilenameUtils.separatorsToUnix(file.getRelativePath()));
        ps.setString(5, FilenameUtils.separatorsToUnix(file.getRemoteHomePath()));

        ps.executeUpdate();
        System.out.println("Added file to database.");

      } catch (SQLException sqlex) {
        System.out.println("INS: Error code: " + sqlex.getErrorCode());
        throw sqlex;
      }
    } else {
      updateFile(file);
      return false;
    }

    this.psclose();
    return true;
  }
Ejemplo n.º 3
0
  /**
   * Updates the entry in file and user_file table that corresponds to the given Stockfile object
   *
   * @param file
   * @return TODO
   * @throws SQLException
   */
  public boolean updateFile(StockFile file) throws SQLException {

    if (!inDatabase(file)) {
      file.setRemoteHomePath(
          "/stockfiles/" + StockFileSession.getInstance().getCurrentUser().getUserName());
      createFile(file);
      return false;
    } else {
      try {

        ps =
            conn.prepareStatement(
                "UPDATE file "
                    + "SET version = ?, last_sync_by = ?,created_by = ? "
                    + "WHERE file_name = ? AND file_path = ? ");

        ps.setFloat(1, file.getVersion());
        ps.setString(2, file.getLastSyncBy());
        ps.setString(3, file.getCreatedBy());
        ps.setString(4, FilenameUtils.separatorsToUnix(file.getRelativePath()));
        ps.setString(5, FilenameUtils.separatorsToUnix(file.getRemoteHomePath()));

        ps.executeUpdate();

      } catch (SQLException sqlex) {
        System.out.println("UPD Error code: " + sqlex.getErrorCode());
        throw sqlex;
      }
      this.psclose();
      return true;
    }
  }
Ejemplo n.º 4
0
    /**
     * Prepare Olink database files for chunked HTML output.
     *
     * @param baseConfiguration Common configuration for all executions
     * @throws MojoExecutionException Failed to prepare the target DB files.
     */
    void buildChunkedHTMLOlinkDB(final ArrayList<MojoExecutor.Element> baseConfiguration)
        throws MojoExecutionException {
      ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>();
      cfg.add(element(name("xincludeSupported"), isXincludeSupported));
      cfg.add(
          element(
              name("sourceDirectory"),
              FilenameUtils.separatorsToUnix(xmlSourceDirectory.getPath())));
      cfg.add(element(name("chunkedOutput"), "true"));
      cfg.add(
          element(
              name("htmlCustomization"),
              FilenameUtils.separatorsToUnix(chunkedHTMLCustomization.getPath())));

      Set<String> docNames = DocUtils.getDocumentNames(xmlSourceDirectory, getDocumentSrcName());
      if (docNames.isEmpty()) {
        throw new MojoExecutionException("No document names found.");
      }

      for (String docName : docNames) {
        cfg.add(element(name("currentDocid"), docName));
        cfg.add(element(name("includes"), docName + "/" + getDocumentSrcName()));
        cfg.add(element(name("collectXrefTargets"), "only"));
        cfg.add(
            element(
                name("targetsFilename"),
                FilenameUtils.separatorsToUnix(getBuildDirectory().getPath())
                    + "/"
                    + docName
                    + "-chunked.target.db"));

        executeMojo(
            plugin(
                groupId("com.agilejava.docbkx"),
                artifactId("docbkx-maven-plugin"),
                version(getDocbkxVersion())),
            goal("generate-html"),
            configuration(cfg.toArray(new Element[0])),
            executionEnvironment(getProject(), getSession(), getPluginManager()));

        File outputDir =
            new File(
                getDocbkxOutputDirectory(),
                "html"
                    + File.separator
                    + docName
                    + File.separator
                    + FilenameUtils.getBaseName(getDocumentSrcName()));
        try {
          FileUtils.deleteDirectory(outputDir);
        } catch (IOException e) {
          throw new MojoExecutionException("Cannot delete " + outputDir);
        }
      }
    }
Ejemplo n.º 5
0
  /**
   * Validates the given entry name by removing different slashes that might appear in the begining
   * of the name and any occurences of relative paths like "../", so we can protect from path
   * traversal attacks
   *
   * @param entryName Name of zip entry
   */
  private static String validateEntryName(String entryName) {
    entryName = FilenameUtils.separatorsToUnix(entryName);
    entryName = PathUtils.trimLeadingSlashes(entryName);
    entryName = removeDotSegments(entryName);

    return entryName;
  }
Ejemplo n.º 6
0
  /**
   * Removes the entry in the file table that corresponds to the given StockFile object provided
   *
   * @param file
   * @throws SQLException
   */
  public void removeFile(StockFile file) throws SQLException {

    try {

      ps = conn.prepareStatement("DELETE FROM file WHERE file_name = ? AND file_path = ?");

      ps.setString(1, FilenameUtils.separatorsToUnix(file.getRelativePath()));
      ps.setString(2, FilenameUtils.separatorsToUnix(file.getRemoteHomePath()));

      ps.executeUpdate();

    } catch (SQLException sqlex) {
      throw sqlex;
    }

    this.psclose();
  }
Ejemplo n.º 7
0
    /**
     * Build chunked HTML pages from DocBook XML sources.
     *
     * @param baseConfiguration Common configuration for all executions
     * @throws MojoExecutionException Failed to build the output.
     */
    void buildChunkedHTML(final ArrayList<MojoExecutor.Element> baseConfiguration)
        throws MojoExecutionException {
      ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>();
      cfg.addAll(baseConfiguration);
      cfg.add(element(name("includes"), "*/" + getDocumentSrcName()));
      cfg.add(element(name("chunkedOutput"), "true"));
      cfg.add(
          element(
              name("htmlCustomization"),
              FilenameUtils.separatorsToUnix(chunkedHTMLCustomization.getPath())));
      cfg.add(element(name("targetDatabaseDocument"), buildChunkedHTMLTargetDB()));

      // Copy images from source to build. DocBook XSL does not copy the
      // images, because XSL does not have a facility for copying files.
      // Unfortunately, neither does docbkx-tools.

      String baseName = FilenameUtils.getBaseName(getDocumentSrcName());

      Set<String> docNames = DocUtils.getDocumentNames(xmlSourceDirectory, getDocumentSrcName());
      if (docNames.isEmpty()) {
        throw new MojoExecutionException("No document names found.");
      }

      for (String docName : docNames) {
        File srcDir = new File(imageSourceDirectory, docName + File.separator + "images");
        File destDir =
            new File(
                getDocbkxOutputDirectory(),
                "html"
                    + File.separator
                    + docName
                    + File.separator
                    + baseName
                    + File.separator
                    + "images");
        try {
          if (srcDir.exists()) {
            FileUtils.copyDirectory(srcDir, destDir);
          }
        } catch (IOException e) {
          throw new MojoExecutionException(
              "Failed to copy images from " + srcDir + " to " + destDir);
        }
      }

      executeMojo(
          plugin(
              groupId("com.agilejava.docbkx"),
              artifactId("docbkx-maven-plugin"),
              version(getDocbkxVersion())),
          goal("generate-html"),
          configuration(cfg.toArray(new Element[0])),
          executionEnvironment(getProject(), getSession(), getPluginManager()));
    }
Ejemplo n.º 8
0
 @Override
 public void finishedInstallation() {
   try {
     File folderForVersionToRun = updateSystem.getFolderForVersionToRun();
     Properties properties = new Properties();
     properties.setProperty(
         "library.folder",
         FilenameUtils.separatorsToUnix(folderForVersionToRun.getAbsolutePath()));
     new PropertiesSaver("anathema.properties").save(properties);
   } catch (IOException e) {
     // handle exception
   }
 }
Ejemplo n.º 9
0
  @Override
  public void deleteMovie(String path) {
    List<MovieFileImpl> movieFiles;
    // No file extension, should be a directory
    if (StringUtils.isEmpty(FilenameUtils.getExtension(path))) {
      if (!path.endsWith(SystemUtils.FILE_SEPARATOR)) {
        path = path + SystemUtils.FILE_SEPARATOR;
      }
      path = FilenameUtils.separatorsToUnix(path);
      movieFiles =
          this.entityManager
              .createQuery(
                  "SELECT m FROM MOVIE_FILE m WHERE m.filePath LIKE ?1", MovieFileImpl.class)
              .setParameter(1, path + "%")
              .getResultList();
    }
    // Path is file
    else {
      path = FilenameUtils.separatorsToUnix(path);
      movieFiles =
          this.entityManager
              .createQuery(
                  "SELECT m FROM MOVIE_FILE m WHERE m.absolutePath = ?1", MovieFileImpl.class)
              .setParameter(1, path)
              .getResultList();
    }

    // Delete old movies
    if (movieFiles != null && !movieFiles.isEmpty()) {
      for (MovieFile movieFile : movieFiles) {
        Movie movie = movieFile.getMovie();
        if (movie != null && movie.getFilesCount() == 1) {
          this.entityManager.remove(movie);
        } else {
          this.entityManager.remove(movieFile);
        }
      }
    }
  }
Ejemplo n.º 10
0
  @Override
  public void deleteImage(String path) {
    List<ImageFileImpl> imageFiles;
    // No file extension, should be a directory
    if (StringUtils.isEmpty(FilenameUtils.getExtension(path))) {
      if (!path.endsWith(SystemUtils.FILE_SEPARATOR)) {
        path = path + SystemUtils.FILE_SEPARATOR;
      }
      path = FilenameUtils.separatorsToUnix(path);
      imageFiles =
          this.entityManager
              .createQuery(
                  "SELECT i FROM IMAGE_FILE i WHERE i.filePath LIKE ?1", ImageFileImpl.class)
              .setParameter(1, path + "%")
              .getResultList();
    }
    // Path is file
    else {
      path = FilenameUtils.separatorsToUnix(path);
      imageFiles =
          this.entityManager
              .createQuery(
                  "SELECT i FROM IMAGE_FILE i WHERE i.absolutePath = ?1", ImageFileImpl.class)
              .setParameter(1, path)
              .getResultList();
    }

    // Delete old images
    if (imageFiles != null && !imageFiles.isEmpty()) {
      for (ImageFile imageFile : imageFiles) {
        Image image = imageFile.getImage();
        if (image != null) {
          this.entityManager.remove(image);
        } else {
          this.entityManager.remove(imageFile);
        }
      }
    }
  }
Ejemplo n.º 11
0
 /**
  * Prepare Apache FOP for output formats like PDF. This step involves font metrics generation.
  *
  * @throws MojoExecutionException Failed to prepare FOP.
  */
 void prepareFOP() throws MojoExecutionException {
   String fontsDir = FilenameUtils.separatorsToUnix(fontsDirectory.getPath());
   executeMojo(
       plugin(
           groupId("com.agilejava.docbkx"),
           artifactId("docbkx-fop-support"),
           version(getDocbkxVersion())),
       goal("generate"),
       configuration(
           element(name("ansi"), ansi),
           element(name("sourceDirectory"), fontsDir),
           element(name("targetDirectory"), fontsDir)),
       executionEnvironment(getProject(), getSession(), getPluginManager()));
 }
Ejemplo n.º 12
0
  /**
   * Checks if the given StockFile already exists in the database
   *
   * @param file
   * @return true if the given StockFile already exists in the database
   * @throws SQLException
   */
  public boolean inDatabase(StockFile file) throws SQLException {

    try {

      ps = conn.prepareStatement("SELECT * FROM file WHERE file_name = ? AND file_path = ?");

      ps.setString(1, FilenameUtils.separatorsToUnix(file.getRelativePath()));
      ps.setString(2, FilenameUtils.separatorsToUnix(file.getRemoteHomePath()));

      rs = ps.executeQuery();

      if (rs.next()) {
        this.psclose();
        return true;
      } else {
        this.psclose();
        return false;
      }

    } catch (SQLException sqlex) {
      System.out.println("FIND: Error code: " + sqlex.getErrorCode());
      throw sqlex;
    }
  }
Ejemplo n.º 13
0
  @Override
  public void processAsset(AssetFile asset) throws IOException {
    Path assetFile = asset.getSourceFile();
    Path assetDir = assetFile.getParent();
    String assetFileName = assetFile.getFileName().toString();
    String assetPath;

    if (assetDir == null) {
      assetPath = "";
    } else {
      assetPath = assetDir.toAbsolutePath().toString();
      assetPath = FilenameUtils.separatorsToUnix(assetPath) + "/";
    }

    // fix path for all assets with (shared)assets extension
    boolean changed = false;
    for (AssetRef ref : asset.getReferences()) {
      Path refFile = Paths.get(ref.getFilePath());
      String refExt = FilenameUtils.getExtension(refFile.getFileName().toString());
      if (refExt.endsWith("assets") && Files.notExists(refFile)) {
        String filePathOld = ref.getFilePath();
        String filePathNew = assetPath + FilenameUtils.getName(ref.getFilePath());
        Path refFileNew = Paths.get(filePathNew);

        if (Files.exists(refFileNew)) {
          L.log(Level.FINE, "Fixed reference: {0} -> {1}", new Object[] {filePathOld, filePathNew});
          ref.setFilePath(filePathNew);
          changed = true;
        } else {
          L.log(Level.FINE, "Fixed reference not found: {0}", refFileNew);
        }
      }
    }

    if (!changed) {
      L.fine("No references changed, skipping saving");
      return;
    }

    // create backup by renaming the original file
    Path assetFileBackup = assetFile.resolveSibling(assetFileName + ".bak");
    Files.move(assetFile, assetFileBackup, StandardCopyOption.REPLACE_EXISTING);

    // save asset
    asset.save(assetFile);
  }
Ejemplo n.º 14
0
  public ClazzpathUnit addClazzpathUnit(final File pFile, final String pId) throws IOException {
    if (pFile.isFile()) {
      return addClazzpathUnit(new FileInputStream(pFile), pId);
    }
    if (pFile.isDirectory()) {
      final String prefix =
          FilenameUtils.separatorsToUnix(
              FilenameUtils.normalize(
                  new StringBuilder(pFile.getAbsolutePath())
                      .append(File.separatorChar)
                      .toString()));
      final boolean recursive = true;
      @SuppressWarnings("unchecked")
      final Iterator<File> files = FileUtils.iterateFiles(pFile, new String[] {"class"}, recursive);
      return addClazzpathUnit(
          new Iterable<Resource>() {

            public Iterator<Resource> iterator() {
              return new Iterator<Clazzpath.Resource>() {

                public boolean hasNext() {
                  return files.hasNext();
                }

                public Resource next() {
                  final File file = files.next();
                  return new Resource(file.getAbsolutePath().substring(prefix.length())) {

                    @Override
                    InputStream getInputStream() throws IOException {
                      return new FileInputStream(file);
                    }
                  };
                }

                public void remove() {
                  throw new UnsupportedOperationException();
                }
              };
            }
          },
          pId,
          true);
    }
    throw new IllegalArgumentException();
  }
Ejemplo n.º 15
0
    /**
     * Returns element array for common configuration of all executions of the docbkx-maven-plugin.
     *
     * @return Configuration applicable to all executions
     */
    ArrayList<MojoExecutor.Element> getBaseConfiguration() {
      ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>();

      cfg.add(element(name("draftMode"), isDraftMode));
      cfg.add(element(name("draftWatermarkImage"), draftWatermarkURL));
      cfg.add(element(name("highlightSource"), useSyntaxHighlighting));
      cfg.add(element(name("sectionAutolabel"), areSectionsAutolabeled));
      cfg.add(
          element(
              name("sectionLabelIncludesComponentLabel"), doesSectionLabelIncludeComponentLabel));
      cfg.add(element(name("xincludeSupported"), isXincludeSupported));
      cfg.add(
          element(
              name("sourceDirectory"),
              FilenameUtils.separatorsToUnix(xmlSourceDirectory.getPath())));

      return cfg;
    }
Ejemplo n.º 16
0
    /**
     * Build reference manual pages from DocBook XML sources.
     *
     * @param baseConfiguration Common configuration for all executions
     * @throws MojoExecutionException Failed to build the output.
     */
    void buildManpages(final ArrayList<MojoExecutor.Element> baseConfiguration)
        throws MojoExecutionException {
      ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>();
      cfg.addAll(baseConfiguration);
      cfg.add(element(name("includes"), "*/" + getDocumentSrcName()));
      cfg.add(
          element(
              name("manpagesCustomization"),
              FilenameUtils.separatorsToUnix(manpagesCustomization.getPath())));

      executeMojo(
          plugin(
              groupId("com.agilejava.docbkx"),
              artifactId("docbkx-maven-plugin"),
              version(getDocbkxVersion())),
          goal("generate-manpages"),
          configuration(cfg.toArray(new Element[0])),
          executionEnvironment(getProject(), getSession(), getPluginManager()));
    }
Ejemplo n.º 17
0
  private String createDigitalObject(File file) throws HarvesterException, StorageException {
    String objectId;
    DigitalObject object;
    if (forceUpdate) {
      object = StorageUtils.storeFile(getStorage(), file, !forceLocalStorage);
    } else {
      String oid = StorageUtils.generateOid(file);
      String pid = StorageUtils.generatePid(file);
      object = getStorage().createObject(oid);
      if (forceLocalStorage) {
        try {
          object.createStoredPayload(pid, new FileInputStream(file));
        } catch (FileNotFoundException ex) {
          throw new HarvesterException(ex);
        }
      } else {
        object.createLinkedPayload(pid, file.getAbsolutePath());
      }
    }
    // update object metadata
    Properties props = object.getMetadata();
    props.setProperty("render-pending", "true");
    props.setProperty("file.path", FilenameUtils.separatorsToUnix(file.getAbsolutePath()));
    objectId = object.getId();

    // Store rendition information if we have it
    String ext = FilenameUtils.getExtension(file.getName());
    for (String chain : renderChains.keySet()) {
      Map<String, List<String>> details = renderChains.get(chain);
      if (details.get("fileTypes").contains(ext)) {
        storeList(props, details, "harvestQueue");
        storeList(props, details, "indexOnHarvest");
        storeList(props, details, "renderQueue");
      }
    }

    object.close();
    return objectId;
  }
Ejemplo n.º 18
0
 /**
  * Upload files.
  *
  * @param user current user
  * @param path path
  * @param description description
  * @param file multipart file
  * @param model model
  * @return script/scriptList
  */
 @RequestMapping(value = "/upload/**", method = RequestMethod.POST)
 public String uploadFiles(
     User user,
     @RemainedPath String path,
     @RequestParam("description") String description,
     @RequestParam("uploadFile") MultipartFile file,
     ModelMap model) {
   try {
     FileEntry fileEntry = new FileEntry();
     if (fileEntry.getFileType().isEditable()) {
       fileEntry.setContent(new String(file.getBytes()));
     } else {
       fileEntry.setContentBytes(file.getBytes());
     }
     fileEntry.setDescription(description);
     fileEntry.setPath(
         FilenameUtils.separatorsToUnix(FilenameUtils.concat(path, file.getOriginalFilename())));
     fileEntryService.save(user, fileEntry);
     return "redirect:/script/list/" + path;
   } catch (IOException e) {
     LOG.error("Error while getting file content:" + e.getMessage(), e);
     throw new NGrinderRuntimeException("Error while getting file content:" + e.getMessage(), e);
   }
 }
Ejemplo n.º 19
0
 /**
  * Determines the template based on the info stored in the xcdf file
  *
  * @param solution the dashboard file descriptor solution path part
  * @param path the dashboard file descriptor path part
  * @param action the dashboard file descriptor name
  * @param defaultTemplate the default template to use in case the defined is not available no if
  *     no template is provided
  * @return boolean with the success of the operation
  * @throws InvalidCdfOperationException
  */
 public boolean determineDashboardTemplating(
     final String solution, final String path, final String action, String defaultTemplate)
     throws InvalidCdfOperationException {
   return determineDashboardTemplating(
       FilenameUtils.separatorsToUnix(Util.joinPath(solution, path, action)), defaultTemplate);
 }
Ejemplo n.º 20
0
 /**
  * Determines if a dashboard is to be rendered using require or using legacy javascript structure
  *
  * @param solution the dashboard file descriptor solution path part
  * @param path the dashboard file descriptor path part
  * @param action the dashboard file descriptor name
  * @return boolean with the success of the operation
  * @throws InvalidCdfOperationException
  */
 public boolean determineRequireDashboard(
     final String solution, final String path, final String action)
     throws InvalidCdfOperationException {
   return determineRequireDashboard(
       FilenameUtils.separatorsToUnix(Util.joinPath(solution, path, action)));
 }
  private int parseResourceDefinitions(final Node actionRootNode, final ILogger logger) {

    resourceDefinitions = new ListOrderedMap();

    try {
      List resources = actionRootNode.selectNodes("resources/*"); // $NON-NLS-1$

      // TODO create objects to represent the types
      // TODO need source variable list
      Iterator resourcesIterator = resources.iterator();

      Node resourceNode;
      String resourceName;
      String resourceTypeName;
      String resourceMimeType;
      int resourceType;
      ActionSequenceResource resource;
      Node typeNode, mimeNode;
      while (resourcesIterator.hasNext()) {
        resourceNode = (Node) resourcesIterator.next();
        typeNode = resourceNode.selectSingleNode("./*"); // $NON-NLS-1$
        if (typeNode != null) {
          resourceName = resourceNode.getName();
          resourceTypeName = typeNode.getName();
          resourceType = ActionSequenceResource.getResourceType(resourceTypeName);
          String resourceLocation = XmlDom4JHelper.getNodeText("location", typeNode); // $NON-NLS-1$
          if ((resourceType == IActionSequenceResource.SOLUTION_FILE_RESOURCE)
              || (resourceType == IActionSequenceResource.FILE_RESOURCE)) {
            if (resourceLocation == null) {
              logger.error(
                  Messages.getInstance()
                      .getErrorString(
                          "SequenceDefinition.ERROR_0008_RESOURCE_NO_LOCATION",
                          resourceName)); //$NON-NLS-1$
              continue;
            }
          } else if (resourceType == IActionSequenceResource.STRING) {
            resourceLocation = XmlDom4JHelper.getNodeText("string", resourceNode); // $NON-NLS-1$
          } else if (resourceType == IActionSequenceResource.XML) {
            // resourceLocation = XmlHelper.getNodeText("xml", resourceNode); //$NON-NLS-1$
            Node xmlNode = typeNode.selectSingleNode("./location/*"); // $NON-NLS-1$
            // Danger, we have now lost the character encoding of the XML in this node
            // see BISERVER-895
            resourceLocation = (xmlNode == null) ? "" : xmlNode.asXML(); // $NON-NLS-1$
          }
          mimeNode = typeNode.selectSingleNode("mime-type"); // $NON-NLS-1$
          if (mimeNode != null) {
            resourceMimeType = mimeNode.getText();
            if ((resourceType == IActionSequenceResource.SOLUTION_FILE_RESOURCE)
                || (resourceType == IActionSequenceResource.FILE_RESOURCE)) {
              resourceLocation = FilenameUtils.separatorsToUnix(resourceLocation);
              if (!resourceLocation.startsWith("/")) { // $NON-NLS-1$
                String parentDir = FilenameUtils.getFullPathNoEndSeparator(xactionPath);
                if (parentDir.length() == 0) {
                  parentDir = RepositoryFile.SEPARATOR;
                }
                resourceLocation =
                    FilenameUtils.separatorsToUnix(
                        FilenameUtils.concat(parentDir, resourceLocation));
              }
            }
            resource =
                new ActionSequenceResource(
                    resourceName, resourceType, resourceMimeType, resourceLocation);
            resourceDefinitions.put(resourceName, resource);
          } else {
            logger.error(
                Messages.getInstance()
                    .getErrorString(
                        "SequenceDefinition.ERROR_0007_RESOURCE_NO_MIME_TYPE",
                        resourceName)); //$NON-NLS-1$
          }
        }
        // input = new ActionParameter( resourceName, resourceType, null
        // );
        // resourceDefinitions.put( inputName, input );
      }
      return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_OK;
    } catch (Exception e) {
      logger.error(
          Messages.getInstance().getErrorString("SequenceDefinition.ERROR_0006_PARSING_RESOURCE"),
          e); //$NON-NLS-1$
    }
    return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_INVALID_ACTION_DOC;
  }
Ejemplo n.º 22
0
 /**
  * Checks and normalizes the given path
  *
  * @param path The path to clean up
  * @return a normalized version of the path, with single separators between path components and
  *     dot components resolved
  */
 public static String cleanPath(String path) throws InvalidPathException {
   validatePath(path);
   return FilenameUtils.separatorsToUnix(FilenameUtils.normalizeNoEndSeparator(path));
 }
Ejemplo n.º 23
0
 /**
  * Utility method used when viewing a topic.
  *
  * @param request The current servlet request object.
  * @param next The current Spring ModelAndView object.
  * @param pageInfo The current WikiPageInfo object, which contains information needed for
  *     rendering the final JSP page.
  * @param pageTitle The title of the page being rendered.
  * @param topic The Topic object for the topic being displayed.
  * @param sectionEdit Set to <code>true</code> if edit links should be displayed for each section
  *     of the topic.
  * @throws Exception Thrown if any error occurs during processing.
  */
 protected static void viewTopic(
     HttpServletRequest request,
     ModelAndView next,
     WikiPageInfo pageInfo,
     WikiMessage pageTitle,
     Topic topic,
     boolean sectionEdit)
     throws Exception {
   // FIXME - what should the default be for topics that don't exist?
   if (topic == null) {
     throw new WikiException(new WikiMessage("common.exception.notopic"));
   }
   WikiUtil.validateTopicName(topic.getName());
   if (topic.getTopicType() == Topic.TYPE_REDIRECT
       && (request.getParameter("redirect") == null
           || !request.getParameter("redirect").equalsIgnoreCase("no"))) {
     Topic child = Utilities.findRedirectedTopic(topic, 0);
     if (!child.getName().equals(topic.getName())) {
       pageInfo.setRedirectName(topic.getName());
       pageTitle = new WikiMessage("topic.title", child.getName());
       topic = child;
     }
   }
   String virtualWiki = topic.getVirtualWiki();
   String topicName = topic.getName();
   WikiUser user = Utilities.currentUser();
   if (sectionEdit && !ServletUtil.isEditable(virtualWiki, topicName, user)) {
     sectionEdit = false;
   }
   ParserInput parserInput = new ParserInput();
   parserInput.setContext(request.getContextPath());
   parserInput.setLocale(request.getLocale());
   parserInput.setWikiUser(user);
   parserInput.setTopicName(topicName);
   parserInput.setUserIpAddress(request.getRemoteAddr());
   parserInput.setVirtualWiki(virtualWiki);
   parserInput.setAllowSectionEdit(sectionEdit);
   ParserDocument parserDocument = new ParserDocument();
   String content = Utilities.parse(parserInput, parserDocument, topic.getTopicContent());
   // FIXME - the null check should be unnecessary
   if (parserDocument != null && parserDocument.getCategories().size() > 0) {
     LinkedHashMap categories = new LinkedHashMap();
     for (Iterator iterator = parserDocument.getCategories().keySet().iterator();
         iterator.hasNext(); ) {
       String key = (String) iterator.next();
       String value =
           key.substring(
               NamespaceHandler.NAMESPACE_CATEGORY.length()
                   + NamespaceHandler.NAMESPACE_SEPARATOR.length());
       categories.put(key, value);
     }
     next.addObject("categories", categories);
   }
   topic.setTopicContent(content);
   if (topic.getTopicType() == Topic.TYPE_CATEGORY) {
     loadCategoryContent(next, virtualWiki, topic.getName());
   }
   if (topic.getTopicType() == Topic.TYPE_IMAGE || topic.getTopicType() == Topic.TYPE_FILE) {
     Collection fileVersions =
         WikiBase.getDataHandler().getAllWikiFileVersions(virtualWiki, topicName, true);
     for (Iterator iterator = fileVersions.iterator(); iterator.hasNext(); ) {
       // update version urls to include web root path
       WikiFileVersion fileVersion = (WikiFileVersion) iterator.next();
       String url =
           FilenameUtils.normalize(
               Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH)
                   + "/"
                   + fileVersion.getUrl());
       url = FilenameUtils.separatorsToUnix(url);
       fileVersion.setUrl(url);
     }
     next.addObject("fileVersions", fileVersions);
     if (topic.getTopicType() == Topic.TYPE_IMAGE) {
       next.addObject("topicImage", new Boolean(true));
     } else {
       next.addObject("topicFile", new Boolean(true));
     }
   }
   pageInfo.setSpecial(false);
   pageInfo.setTopicName(topicName);
   next.addObject(ServletUtil.PARAMETER_TOPIC_OBJECT, topic);
   if (pageTitle != null) {
     pageInfo.setPageTitle(pageTitle);
   }
 }
Ejemplo n.º 24
0
 private DefaultInputFile(File file, String path, Map<String, String> attributes) {
   this.absolutePath = PathUtils.canonicalPath(file);
   this.path = FilenameUtils.separatorsToUnix(path);
   this.attributes = attributes;
 }
Ejemplo n.º 25
0
 private String getRelativePath(File root, String absolutePath) {
   String retval = absolutePath;
   retval = absolutePath.substring(root.getAbsolutePath().length());
   retval = FilenameUtils.separatorsToUnix(retval);
   return retval;
 }
Ejemplo n.º 26
0
  /**
   * Get the relative path from one file to another, specifying the directory separator. If one of
   * the provided resources does not exist, it is assumed to be a file unless it ends with '/' or
   * '\'.
   *
   * @param target targetPath is calculated to this file
   * @param base basePath is calculated from this file
   * @param separator directory separator. The platform default is not assumed so that we can test
   *     Unix behaviour when running on Windows (for example)
   * @return
   */
  public static String relativize(
      final String targetPath, final String basePath, final String fileSeparator)
      throws PathRelativizationException {

    // Normalize the paths
    String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
    String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);

    // Undo the changes to the separators made by normalization
    if (fileSeparator.equals("/")) {
      normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
      normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);

    } else if (fileSeparator.equals("\\")) {
      normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
      normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
    } else {
      throw new IllegalArgumentException("Unrecognised dir separator '" + fileSeparator + "'");
    }

    String[] base = normalizedBasePath.split(Pattern.quote(fileSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(fileSeparator));

    // First get all the common elements. Store them as a string,
    // and also count how many of them there are.
    StringBuffer common = new StringBuffer();

    int commonIndex = 0;
    while (commonIndex < target.length
        && commonIndex < base.length
        && target[commonIndex].equals(base[commonIndex])) {
      common.append(target[commonIndex] + fileSeparator);
      commonIndex++;
    }

    if (commonIndex == 0) {
      // No single common path element. This most
      // likely indicates differing drive letters, like C: and D:.
      // These paths cannot be relativized.
      throw new PathRelativizationException(
          "No common path element found for '"
              + normalizedTargetPath
              + "' and '"
              + normalizedBasePath
              + "'");
    }

    // The number of directories we have to backtrack depends on whether the base is a file or a dir
    // For example, the relative path from
    //
    // /foo/bar/baz/gg/ff to /foo/bar/baz
    //
    // ".." if ff is a file
    // "../.." if ff is a directory
    //
    // The following is a heuristic to figure out if the base refers to a file or dir. It's not
    // perfect, because
    // the resource referred to by this path may not actually exist, but it's the best I can do
    boolean baseIsFile = true;

    File baseResource = new File(normalizedBasePath);

    if (baseResource.exists()) {
      baseIsFile = baseResource.isFile();

    } else if (basePath.endsWith(fileSeparator)) {
      baseIsFile = false;
    }

    StringBuffer relative = new StringBuffer();

    if (base.length != commonIndex) {
      int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

      for (int i = 0; i < numDirsUp; i++) {
        relative.append(".." + fileSeparator);
      }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return relative.toString();
  }
Ejemplo n.º 27
0
    /**
     * Build FO documents from DocBook XML sources, including fonts.
     *
     * @param baseConfiguration Common configuration for all executions
     * @param format Specific output format (pdf, rtf)
     * @throws MojoExecutionException Failed to build the output.
     */
    void buildFO(final ArrayList<MojoExecutor.Element> baseConfiguration, final String format)
        throws MojoExecutionException {
      if (!(format.equalsIgnoreCase("pdf") || format.equalsIgnoreCase("rtf"))) {
        throw new MojoExecutionException(
            "Output format " + format + " is not supported." + " Use either pdf or rtf.");
      }

      ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>();
      cfg.addAll(baseConfiguration);
      cfg.add(
          element(
              name("foCustomization"), FilenameUtils.separatorsToUnix(foCustomization.getPath())));

      // If you update this list, also see copyFonts().
      String fontDir = FilenameUtils.separatorsToUnix(fontsDirectory.getPath());
      cfg.add(
          element(
              name("fonts"),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSans"),
                  element(name("style"), "normal"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSans.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSans-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSans"),
                  element(name("style"), "normal"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSansCondensed-Bold.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSansCondensed-Bold-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSans"),
                  element(name("style"), "italic"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSans-Oblique.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSans-Oblique-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSans"),
                  element(name("style"), "italic"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSansCondensed-BoldOblique.ttf"),
                  element(
                      name("metricsFile"),
                      fontDir + "/DejaVuSansCondensed-BoldOblique-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSansMono"),
                  element(name("style"), "normal"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSansMono.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSansMono-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSansMono"),
                  element(name("style"), "normal"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSansMono-Bold.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSansMono-Bold-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSansMono"),
                  element(name("style"), "italic"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSansMono-Oblique.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSansMono-Oblique-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSansMono"),
                  element(name("style"), "italic"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSansMono-BoldOblique.ttf"),
                  element(
                      name("metricsFile"), fontDir + "/DejaVuSansMono-BoldOblique-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSerif"),
                  element(name("style"), "normal"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSerif.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSerif-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSerif"),
                  element(name("style"), "normal"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSerifCondensed-Bold.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSerifCondensed-Bold-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSerif"),
                  element(name("style"), "italic"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSerif-Italic.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSerif-Italic-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSerif"),
                  element(name("style"), "italic"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSerifCondensed-BoldItalic.ttf"),
                  element(
                      name("metricsFile"),
                      fontDir + "/DejaVuSerifCondensed-BoldItalic-metrics.xml"))));

      Set<String> docNames = DocUtils.getDocumentNames(xmlSourceDirectory, getDocumentSrcName());
      if (docNames.isEmpty()) {
        throw new MojoExecutionException("No document names found.");
      }

      // When using generated sources, copy the images manually.
      if (xmlSourceDirectory != getDocbkxSourceDirectory()) {
        for (String docName : docNames) {
          File srcDir = new File(imageSourceDirectory, docName + File.separator + "images");
          File destDir = new File(xmlSourceDirectory, docName + File.separator + "images");
          try {
            if (srcDir.exists()) {
              FileUtils.copyDirectory(srcDir, destDir);
            }
          } catch (IOException e) {
            throw new MojoExecutionException(
                "Failed to copy images from " + srcDir + " to " + destDir);
          }
        }
      }

      for (String docName : docNames) {
        cfg.add(element(name("includes"), docName + "/" + getDocumentSrcName()));

        // Permit hyphenation.
        Dependency offo = new Dependency();
        offo.setGroupId("net.sf.offo");
        offo.setArtifactId("fop-hyph");
        offo.setVersion("1.2");
        offo.setScope("runtime");
        Plugin plugin =
            plugin(
                groupId("com.agilejava.docbkx"),
                artifactId("docbkx-maven-plugin"),
                version(getDocbkxVersion()));
        plugin.addDependency(offo);

        executeMojo(
            plugin,
            goal("generate-" + format),
            configuration(cfg.toArray(new Element[0])),
            executionEnvironment(getProject(), getSession(), getPluginManager()));

        // Avoid each new document overwriting the last.
        File file =
            new File(
                getDocbkxOutputDirectory(),
                format
                    + File.separator
                    + FilenameUtils.getBaseName(getDocumentSrcName())
                    + "."
                    + format);
        renameDocument(file, docName);
      }
    }
Ejemplo n.º 28
0
 public String getMessageFilesCacheUrl() {
   return FilenameUtils.separatorsToUnix(FilenameUtils.normalize(languagesCacheUrl));
 }