Exemple #1
0
  private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    railo.runtime.img.Image ri =
        new railo.runtime.img.Image(1, 1, BufferedImage.TYPE_INT_RGB, Color.BLACK);
    Image img = Image.getInstance(ri.getBufferedImage(), null, false);
    img.setAbsolutePosition(1, 1);

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null) master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {
      int len = reader.getNumberOfPages();
      PdfStamper stamp = new PdfStamper(reader, os);

      Set _pages = doc.getPages();
      for (int i = 1; i <= len; i++) {
        if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue;
        PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0);
        cb.setGState(gs1);
        cb.addImage(img);
      }
      if (bookmarks != null) stamp.setOutlines(master);
      stamp.close();
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
 private void set(SQLException sqle, String detail) {
   String sqleMessage = sqle != null ? sqle.getMessage() : "";
   if (detail != null) {
     if (!StringUtil.isEmpty(sqleMessage)) setDetail(detail + "\n" + sqleMessage);
     else setDetail(detail);
   } else {
     if (!StringUtil.isEmpty(sqleMessage)) setDetail(sqleMessage);
   }
 }
  protected void _init(PageContext pc, Map<String, String> arguments) {
    this.pc = pc;

    // header
    HttpServletRequest req = pc.getHttpServletRequest();

    header = new StringBuffer();
    createHeader(header, "context-path", req.getContextPath());
    createHeader(header, "remote-user", req.getRemoteUser());
    createHeader(header, "remote-addr", req.getRemoteAddr());
    createHeader(header, "remote-host", req.getRemoteHost());
    createHeader(
        header,
        "script-name",
        StringUtil.emptyIfNull(req.getContextPath())
            + StringUtil.emptyIfNull(req.getServletPath()));
    createHeader(header, "server-name", req.getServerName());
    createHeader(header, "protocol", req.getProtocol());
    createHeader(header, "server-port", Caster.toString(req.getServerPort()));
    createHeader(
        header,
        "path-info",
        StringUtil.replace(
            StringUtil.emptyIfNull(req.getRequestURI()),
            StringUtil.emptyIfNull(req.getServletPath()),
            "",
            true));
    // createHeader(header,"path-translated",pc.getBasePageSource().getDisplayPath());
    createHeader(header, "query-string", req.getQueryString());
    createHeader(header, "unit", unitShortToString(unit));
    createHeader(header, "min-time-nano", min + "");

    content = new StringBuffer();

    // directory
    String strDirectory = arguments.get("directory");
    if (dir == null) {
      if (StringUtil.isEmpty(strDirectory)) {
        dir = getTemp(pc);
      } else {
        try {
          dir = ResourceUtil.toResourceNotExisting(pc, strDirectory, false);
          if (!dir.exists()) {
            dir.createDirectory(true);
          } else if (dir.isFile()) {
            err(
                pc,
                "can not create directory [" + dir + "], there is already a file with same name.");
          }
        } catch (Throwable t) {
          err(pc, t);
          dir = getTemp(pc);
        }
      }
    }
    file = dir.getRealResource((pc.getId()) + "-" + CreateUUID.call(pc) + ".exl");
    file.createNewFile();
    start = System.currentTimeMillis();
  }
  /**
   * Constructor of the class
   *
   * @param sqle
   */
  @Override
  public CatchBlock getCatchBlock(Config config) {
    String strSQL = sql == null ? "" : sql.toString();
    if (StringUtil.isEmpty(strSQL)) strSQL = Caster.toString(getAdditional().get("SQL", ""), "");

    String datasourceName = datasource == null ? "" : datasource.getName();
    if (StringUtil.isEmpty(datasourceName))
      datasourceName = Caster.toString(getAdditional().get("DataSource", ""), "");

    CatchBlock sct = super.getCatchBlock(config);
    sct.setEL("NativeErrorCode", new Double(errorcode));
    sct.setEL("DataSource", datasourceName);
    sct.setEL("SQLState", sqlstate);
    sct.setEL("Sql", strSQL);
    sct.setEL("queryError", strSQL);
    sct.setEL("where", "");
    return sct;
  }
  public ByteArrayHttpEntity(byte[] barr, String contentType) {
    super(barr);
    contentLength = barr == null ? 0 : barr.length;

    if (StringUtil.isEmpty(contentType, true)) {
      Header h = getContentType();
      if (h != null) strContentType = h.getValue();
    } else this.strContentType = contentType;
  }
  private boolean isValid(Config config, String serverPassword) {
    if (StringUtil.isEmpty(serverPassword, true)) {
      try {
        PageContextImpl pc = (PageContextImpl) ThreadLocalPageContext.get();
        serverPassword = pc.getServerPassword();
      } catch (Throwable t) {
      }
    }
    config = ThreadLocalPageContext.getConfig(config);

    if (config == null || StringUtil.isEmpty(serverPassword, true)) return false;
    try {
      config.getConfigServer(serverPassword);
      return true;
    } catch (PageException e) {
      return false;
    }
  }
Exemple #7
0
  private void doActionDeletePages() throws PageException, IOException, DocumentException {
    required("pdf", "deletePage", "pages", pages, true);
    required("pdf", "deletePage", "source", source);

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);

    if (destination == null && StringUtil.isEmpty(name)) {
      if (doc.getResource() == null)
        throw new ApplicationException(
            "source is not based on a resource, destination attribute is required");
      destination = doc.getResource();
    } else if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {
      PDFUtil.concat(new PDFDocument[] {doc}, os, true, true, true, version);
    } finally {
      // if(document!=null)document.close();
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
 @Override
 public String getParent() {
   if (StringUtil.isEmpty(parent)) return null;
   return provider
       .getScheme()
       .concat("://")
       .concat(zip.getCompressFile().getPath())
       .concat("!")
       .concat(parent);
 }
Exemple #9
0
  /**
   * returns if a value of the list contains given value, case sensitive
   *
   * @param list list to search in
   * @param value value to serach
   * @param delimeter delimeter of the list
   * @return position in list or 0
   */
  public static int listContains(String list, String value, String delimeter) {
    if (StringUtil.isEmpty(value)) return -1;

    Array arr = listToArray(list, delimeter);
    int len = arr.size();

    for (int i = 1; i <= len; i++) {
      if (arr.get(1, "").toString().indexOf(value) != -1) return i;
    }
    return -1;
  }
Exemple #10
0
  private static boolean validExtension(String[] extensions, String file) {

    String ext = ResourceUtil.getExtension(file, "");
    ext = railo.runtime.type.util.ListUtil.first(ext, "/", true);

    if (StringUtil.isEmpty(ext)) return true;
    for (int i = 0; i < extensions.length; i++) {
      if (ext.equalsIgnoreCase(extensions[i])) return true;
    }
    return false;
  }
  public Component getEntityByCFCName(String cfcName, boolean unique) throws PageException {
    String name = cfcName;
    int pointIndex = cfcName.lastIndexOf('.');
    if (pointIndex != -1) {
      name = cfcName.substring(pointIndex + 1);
    } else cfcName = null;

    ComponentPro cfc;
    String[] names = null;
    // search array (array exist when cfcs is in generation)

    if (arr != null) {
      names = new String[arr.size()];
      int index = 0;
      Iterator<ComponentPro> it2 = arr.iterator();
      while (it2.hasNext()) {
        cfc = it2.next();
        names[index++] = cfc.getName();
        if (isEntity(cfc, cfcName, name)) // if(cfc.equalTo(name))
        return unique ? (Component) cfc.duplicate(false) : cfc;
      }
    } else {
      // search cfcs
      Iterator<Entry<String, CFCInfo>> it = cfcs.entrySet().iterator();
      Entry<String, CFCInfo> entry;
      while (it.hasNext()) {
        entry = it.next();
        cfc = entry.getValue().getCFC();
        if (isEntity(cfc, cfcName, name)) // if(cfc.instanceOf(name))
        return unique ? (Component) cfc.duplicate(false) : cfc;

        // if(name.equalsIgnoreCase(HibernateCaster.getEntityName(cfc)))
        //	return cfc;
      }
      names = cfcs.keySet().toArray(new String[cfcs.size()]);
    }

    // search by entityname //TODO is this ok?
    CFCInfo info = cfcs.get(name.toLowerCase());
    if (info != null) {
      cfc = info.getCFC();
      return unique ? (Component) cfc.duplicate(false) : cfc;
    }

    throw new ORMException(
        this,
        "entity ["
            + name
            + "] "
            + (StringUtil.isEmpty(cfcName) ? "" : "with cfc name [" + cfcName + "] ")
            + "does not exist, existing  entities are ["
            + railo.runtime.type.List.arrayToList(names, ", ")
            + "]");
  }
  private PageContextImpl createPageContext(
      CFMLFactory factory,
      ComponentAccess app,
      String applicationName,
      String cfid,
      Collection.Key methodName)
      throws PageException {
    Resource root = factory.getConfig().getRootDirectory();
    String path = app.getPageSource().getFullRealpath();

    // Request
    HttpServletRequestDummy req =
        new HttpServletRequestDummy(root, "localhost", path, "", null, null, null, null, null);
    if (!StringUtil.isEmpty(cfid))
      req.setCookies(new Cookie[] {new Cookie("cfid", cfid), new Cookie("cftoken", "0")});

    // Response
    OutputStream os = DevNullOutputStream.DEV_NULL_OUTPUT_STREAM;
    try {
      Resource out =
          factory
              .getConfig()
              .getConfigDir()
              .getRealResource("output/" + methodName.getString() + ".out");
      out.getParentResource().mkdirs();
      os = out.getOutputStream(false);
    } catch (IOException e) {
      e.printStackTrace();
      // TODO was passiert hier
    }
    HttpServletResponseDummy rsp = new HttpServletResponseDummy(os);

    // PageContext
    PageContextImpl pc =
        (PageContextImpl)
            factory.getRailoPageContext(factory.getServlet(), req, rsp, null, false, -1, false);
    // ApplicationContext
    ClassicApplicationContext ap =
        new ClassicApplicationContext(
            factory.getConfig(),
            applicationName,
            false,
            app == null ? null : ResourceUtil.getResource(pc, app.getPageSource(), null));
    initApplicationContext(pc, app);
    ap.setName(applicationName);
    ap.setSetSessionManagement(true);
    // if(!ap.hasName())ap.setName("Controler")
    // Base
    pc.setBase(app.getPageSource());

    return pc;
  }
Exemple #13
0
  /**
   * returns if a value of the list contains given value, case sensitive, ignore empty positions
   *
   * @param list list to search in
   * @param value value to serach
   * @param delimeter delimeter of the list
   * @return position in list or 0
   */
  public static int listContainsIgnoreEmpty(String list, String value, String delimeter) {
    if (StringUtil.isEmpty(value)) return -1;
    Array arr = listToArrayRemoveEmpty(list, delimeter);
    int count = 0;
    int len = arr.size();

    for (int i = 1; i <= len; i++) {
      String item = arr.get(i, "").toString();
      if (item.indexOf(value) != -1) return count;
      count++;
    }
    return -1;
  }
Exemple #14
0
  public Query execute(PageContext pc, SQL sql, String prettySQL, int maxrows)
      throws PageException {
    if (StringUtil.isEmpty(prettySQL)) prettySQL = SQLPrettyfier.prettyfie(sql.getSQLString());

    ZqlParser parser = new ZqlParser(new ByteArrayInputStream(prettySQL.getBytes()));
    Vector statements;
    try {
      statements = parser.readStatements();
    } catch (Throwable t) {
      throw Caster.toPageException(t);
    }
    return execute(statements, pc, sql, maxrows);
  }
Exemple #15
0
 public static String getType(Property prop) {
   String type = prop.getType();
   if (StringUtil.isEmpty(type)
       || "any".equalsIgnoreCase(type)
       || "object".equalsIgnoreCase(type)) {
     String fieldType = Caster.toString(prop.getMeta().get(FIELD_TYPE, null), null);
     if ("one-to-many".equalsIgnoreCase(fieldType) || "many-to-many".equalsIgnoreCase(fieldType)) {
       return "array";
     }
     return "any";
   }
   return type;
 }
 private void loadNamingStrategy(ORMConfiguration ormConf) throws PageException {
   String strNamingStrategy = ormConf.namingStrategy();
   if (StringUtil.isEmpty(strNamingStrategy, true)) {
     namingStrategy = DefaultNamingStrategy.INSTANCE;
   } else {
     strNamingStrategy = strNamingStrategy.trim();
     if ("default".equalsIgnoreCase(strNamingStrategy))
       namingStrategy = DefaultNamingStrategy.INSTANCE;
     else if ("smart".equalsIgnoreCase(strNamingStrategy))
       namingStrategy = SmartNamingStrategy.INSTANCE;
     else namingStrategy = new CFCNamingStrategy(strNamingStrategy);
   }
 }
Exemple #17
0
  private void doActionProtect() throws PageException, IOException, DocumentException {
    required("pdf", "protect", "source", source);

    if (StringUtil.isEmpty(newUserPassword) && StringUtil.isEmpty(newOwnerPassword))
      throw new ApplicationException(
          "at least one of the following attributes must be defined [newUserPassword,newOwnerPassword]");

    PDFDocument doc = toPDFDocument(source, password, null);

    if (destination == null) {
      destination = doc.getResource();
      if (destination == null)
        throw new ApplicationException(
            "source is not based on a resource, destination file is required");
    } else if (destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    boolean destIsSource = doc.getResource() != null && destination.equals(doc.getResource());

    // output
    OutputStream os = null;
    if (destIsSource) {
      os = new ByteArrayOutputStream();
    } else {
      os = destination.getOutputStream();
    }

    try {
      PDFUtil.encrypt(doc, os, newUserPassword, newOwnerPassword, permissions, encrypt);
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        IOUtil.copy(
            new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
            destination,
            true); // MUST overwrite
      }
    }
  }
  private static void addEventListeners(
      PageContext pc, Configuration config, ORMConfiguration ormConfig, Map<String, CFCInfo> cfcs)
      throws PageException {
    if (!ormConfig.eventHandling()) return;
    String eventHandler = ormConfig.eventHandler();
    AllEventListener listener = null;
    if (!StringUtil.isEmpty(eventHandler, true)) {
      // try {
      Component c = pc.loadComponent(eventHandler.trim());

      listener = new AllEventListener(c);
      // config.setInterceptor(listener);
      // }catch (PageException e) {e.printStackTrace();}
    }
    config.setInterceptor(new InterceptorImpl(listener));
    EventListeners listeners = config.getEventListeners();

    // post delete
    List<EventListener> list = merge(listener, cfcs, EventListener.POST_DELETE);
    listeners.setPostDeleteEventListeners(list.toArray(new PostDeleteEventListener[list.size()]));

    // post insert
    list = merge(listener, cfcs, EventListener.POST_INSERT);
    listeners.setPostInsertEventListeners(list.toArray(new PostInsertEventListener[list.size()]));

    // post update
    list = merge(listener, cfcs, EventListener.POST_UPDATE);
    listeners.setPostUpdateEventListeners(list.toArray(new PostUpdateEventListener[list.size()]));

    // post load
    list = merge(listener, cfcs, EventListener.POST_LOAD);
    listeners.setPostLoadEventListeners(list.toArray(new PostLoadEventListener[list.size()]));

    // pre delete
    list = merge(listener, cfcs, EventListener.PRE_DELETE);
    listeners.setPreDeleteEventListeners(list.toArray(new PreDeleteEventListener[list.size()]));

    // pre insert
    // list=merge(listener,cfcs,EventListener.PRE_INSERT);
    // listeners.setPreInsertEventListeners(list.toArray(new PreInsertEventListener[list.size()]));

    // pre load
    list = merge(listener, cfcs, EventListener.PRE_LOAD);
    listeners.setPreLoadEventListeners(list.toArray(new PreLoadEventListener[list.size()]));

    // pre update
    // list=merge(listener,cfcs,EventListener.PRE_UPDATE);
    // listeners.setPreUpdateEventListeners(list.toArray(new PreUpdateEventListener[list.size()]));
  }
  private boolean isEntity(ComponentPro cfc, String cfcName, String name) {
    if (!StringUtil.isEmpty(cfcName)) {
      if (cfc.equalTo(cfcName)) return true;

      if (cfcName.indexOf('.') != -1) {
        String path = cfcName.replace('.', '/') + ".cfc";
        Resource[] locations = ormConf.getCfcLocations();
        for (int i = 0; i < locations.length; i++) {
          if (locations[i].getRealResource(path).equals(cfc.getPageSource().getFile())) return true;
        }
        return false;
      }
    }

    if (cfc.equalTo(name)) return true;
    return name.equalsIgnoreCase(HibernateCaster.getEntityName(cfc));
  }
  /**
   * Constructor of the class
   *
   * @param provider
   * @param zip
   * @param path
   * @param caseSensitive
   */
  CompressResource(
      CompressResourceProvider provider, Compress zip, String path, boolean caseSensitive) {
    if (StringUtil.isEmpty(path)) path = "/";
    this.provider = provider;
    this.zip = zip;
    this.path = path;

    if ("/".equals(path)) {
      this.parent = null;
      this.name = "";
    } else {
      String[] pn = ResourceUtil.translatePathName(path);
      this.parent = pn[0];
      this.name = pn[1];
    }

    this.caseSensitive = caseSensitive;
  }
Exemple #21
0
  public static String call(PageContext pc, String cacheName) throws FunctionException {

    if (StringUtil.isEmpty(cacheName, true)
        || "all".equals(cacheName = cacheName.trim().toLowerCase())) {
      PagePoolClear.call(pc);
      ComponentCacheClear.call(pc);
      CTCacheClear.call(pc);
      queryCache(pc);
      tagCache(pc);
      functionCache(pc);
    } else if ("template".equals(cacheName) || "page".equals(cacheName)) {
      PagePoolClear.call(pc);
    } else if ("component".equals(cacheName) || "cfc".equals(cacheName)) {
      ComponentCacheClear.call(pc);
    } else if ("customtag".equals(cacheName) || "ct".equals(cacheName)) {
      CTCacheClear.call(pc);
    } else if ("query".equals(cacheName) || "object".equals(cacheName)) {
      queryCache(pc);
    } else if ("tag".equals(cacheName)) {
      tagCache(pc);
    } else if ("function".equals(cacheName)) {
      functionCache(pc);
    } else
      throw new FunctionException(
          pc,
          "cacheClear",
          1,
          "cacheName",
          ExceptionUtil.similarKeyMessage(
              new String[] {
                "all", "template", "component", "customtag", "query", "tag", "function"
              },
              cacheName,
              "cache name",
              "cache names"));

    return null;
  }
Exemple #22
0
  private static boolean isUSorEuroDateEuro(String str, boolean isEuro) {
    if (StringUtil.isEmpty(str)) return false;

    for (int i = 0; i < DATE_DEL.length; i++) {
      Array arr = railo.runtime.type.List.listToArrayRemoveEmpty(str, DATE_DEL[i]);
      if (arr.size() != 3) continue;

      int month =
          Caster.toIntValue(arr.get(isEuro ? 2 : 1, Constants.INTEGER_0), Integer.MIN_VALUE);
      int day = Caster.toIntValue(arr.get(isEuro ? 1 : 2, Constants.INTEGER_0), Integer.MIN_VALUE);
      int year = Caster.toIntValue(arr.get(3, Constants.INTEGER_0), Integer.MIN_VALUE);

      if (month == Integer.MIN_VALUE) continue;
      if (month > 12) continue;
      if (day == Integer.MIN_VALUE) continue;
      if (day > 31) continue;
      if (year == Integer.MIN_VALUE) continue;
      if (DateTimeUtil.getInstance().toTime(null, year, month, day, 0, 0, 0, 0, Long.MIN_VALUE)
          == Long.MIN_VALUE) continue;
      return true;
    }
    return false;
  }
Exemple #23
0
  private void doActionMerge()
      throws ApplicationException, PageException, IOException, DocumentException {

    if (source == null && params == null && directory == null)
      throw new ApplicationException(
          "at least one of the following constellation must be defined"
              + " attribute source, attribute directory or cfpdfparam child tags");
    if (destination == null && StringUtil.isEmpty(name, true))
      throw new ApplicationException(
          "at least one of the following attributes must be defined " + "[destination,name]");
    if (destination != null && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    ArrayList docs = new ArrayList();
    PDFDocument doc;
    boolean isListing = false;

    // source
    if (source != null) {
      if (Decision.isArray(source)) {
        Array arr = Caster.toArray(source);
        int len = arr.size();
        for (int i = 1; i <= len; i++) {
          docs.add(doc = toPDFDocument(arr.getE(i), password, null));
          doc.setPages(pages);
        }
      } else if (source instanceof String) {
        String[] sources =
            List.toStringArrayTrim(List.listToArrayRemoveEmpty((String) source, ','));
        for (int i = 0; i < sources.length; i++) {
          docs.add(doc = toPDFDocument(sources[i], password, null));
          doc.setPages(pages);
        }
      } else docs.add(toPDFDocument(source, password, null));
    }
    boolean destIsSource = false;

    // params
    if (directory != null && !directory.isDirectory()) {
      if (!directory.exists())
        throw new ApplicationException("defined attribute directory does not exist");
      throw new ApplicationException("defined attribute directory is not a directory");
    }
    if (params != null) {
      Iterator it = params.iterator();
      PDFParamBean param;
      while (it.hasNext()) {
        param = (PDFParamBean) it.next();
        docs.add(doc = toPDFDocument(param.getSource(), param.getPassword(), directory));
        doc.setPages(param.getPages());
      }
    } else if (directory != null) {
      isListing = true;
      Resource[] children = ResourceUtil.listResources(directory, filter);

      if (ascending) {
        for (int i = children.length - 1; i >= 0; i--) {
          if (destination != null && children[i].equals(destination)) destIsSource = true;
          docs.add(doc = toPDFDocument(children[i], password, null));
          doc.setPages(pages);
        }
      } else {
        for (int i = 0; i < children.length; i++) {
          if (destination != null && children[i].equals(destination)) destIsSource = true;
          docs.add(doc = toPDFDocument(children[i], password, null));
          doc.setPages(pages);
        }
      }
    }

    int doclen = docs.size();
    if (doclen == 0) throw new ApplicationException("you have to define at leat 1 pdf file");

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    /*com.lowagie.text.Document document=null;
    PdfCopy copy=null;
    PdfReader pr;
    Set pages;
    int size;*/

    try {
      if (!isListing) stopOnError = true;
      PDFUtil.concat(
          (PDFDocument[]) docs.toArray(new PDFDocument[docs.size()]),
          os,
          keepBookmark,
          false,
          stopOnError,
          version);
      /*
      boolean init=false;
      for(int d=0;d<doclen;d++) {
      	doc=(PDFDocument) docs.get(d);
      	pages=doc.getPages();
      	try {
      		pr=doc.getPdfReader();
      		print.out(pr.getCatalog().getKeys());

      	}
      	catch(Throwable t) {
      		if(isListing && !stopOnError)continue;
      		throw Caster.toPageException(t);
      	}
      	print.out("d+"+d);
      	if(!init) {
      		init=true;
      		print.out("set");
      		document = new com.lowagie.text.Document(pr.getPageSizeWithRotation(1));
      		copy = new PdfCopy(document,os);
      		document.open();
      	}
      	size=pr.getNumberOfPages();
      	print.out("pages:"+size);
      	for(int page=1;page<=size;page++) {
      		if(pages==null || pages.contains(Constants.Integer(page))) {
      			copy.addPage(copy.getImportedPage(pr, page));
      		}
      	}
      }*/
    } finally {
      // if(document!=null)document.close();
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name))
          pageContext.setVariable(name, ((ByteArrayOutputStream) os).toByteArray());
      }
    }
  }
Exemple #24
0
  private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
      throw new ApplicationException(
          "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    // image
    Image img = null;
    if (image != null) {
      railo.runtime.img.Image ri =
          railo.runtime.img.Image.createImage(pageContext, image, false, false, true);
      img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
      byte[] barr;
      try {
        Resource res = Caster.toResource(pageContext, copyFrom, true);
        barr = IOUtil.toBytes(res);
      } catch (ExpressionException ee) {
        barr = Caster.toBinary(copyFrom);
      }
      img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);
    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
      int index = position.indexOf(',');
      if (index == -1)
        throw new ApplicationException(
            "attribute [position] has a invalid value ["
                + position
                + "],"
                + "value should follow one of the following pattern [40,50], [40,] or [,50]");
      String strX = position.substring(0, index).trim();
      String strY = position.substring(index + 1).trim();
      if (!StringUtil.isEmpty(strX)) x = Caster.toIntValue(strX);
      if (!StringUtil.isEmpty(strY)) y = Caster.toIntValue(strY);
    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null) master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {

      int len = reader.getNumberOfPages();
      PdfStamper stamp = new PdfStamper(reader, os);

      if (len > 0) {
        if (x == UNDEFINED || y == UNDEFINED) {
          PdfImportedPage first = stamp.getImportedPage(reader, 1);
          if (y == UNDEFINED) y = (first.getHeight() - img.getHeight()) / 2;
          if (x == UNDEFINED) x = (first.getWidth() - img.getWidth()) / 2;
        }
        img.setAbsolutePosition(x, y);
        // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

      }

      // rotation
      if (rotation != 0) {
        img.setRotationDegrees(rotation);
      }

      Set _pages = doc.getPages();
      for (int i = 1; i <= len; i++) {
        if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue;
        PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
        PdfGState gs1 = new PdfGState();
        // print.out("op:"+opacity);
        gs1.setFillOpacity(opacity);
        // gs1.setStrokeOpacity(opacity);
        cb.setGState(gs1);
        cb.addImage(img);
      }
      if (bookmarks != null) stamp.setOutlines(master);
      stamp.close();
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
Exemple #25
0
  static final void validate(String validate, Struct validateParams, Object obj)
      throws PageException {
    if (StringUtil.isEmpty(validate, true)) return;
    validate = validate.trim().toLowerCase();

    if (!validate.equals("regex") && !Decision.isValid(validate, obj))
      throw new ExpressionException(createMessage(validate, obj));

    // range
    if (validateParams == null) return;

    if (validate.equals("integer") || validate.equals("numeric") || validate.equals("number")) {
      double min = Caster.toDoubleValue(validateParams.get(MIN, null), Double.NaN);
      double max = Caster.toDoubleValue(validateParams.get(MAX, null), Double.NaN);
      double d = Caster.toDoubleValue(obj);
      if (!Double.isNaN(min) && d < min)
        throw new ExpressionException(
            validate
                + " ["
                + Caster.toString(d)
                + "] is out of range, value must be more than or equal to ["
                + min
                + "]");
      if (!Double.isNaN(max) && d > max)
        throw new ExpressionException(
            validate
                + " ["
                + Caster.toString(d)
                + "] is out of range, value must be less than or equal to ["
                + max
                + "]");
    } else if (validate.equals("string")) {
      double min = Caster.toDoubleValue(validateParams.get(MIN_LENGTH, null), Double.NaN);
      double max = Caster.toDoubleValue(validateParams.get(MAX_LENGTH, null), Double.NaN);
      String str = Caster.toString(obj);
      int l = str.length();
      if (!Double.isNaN(min) && l < ((int) min))
        throw new ExpressionException(
            "string ["
                + str
                + "] is to short ["
                + l
                + "], the string must be at least ["
                + min
                + "] characters");
      if (!Double.isNaN(max) && l > ((int) max))
        throw new ExpressionException(
            "string ["
                + str
                + "] is to long ["
                + l
                + "], the string can have a maximal length of ["
                + max
                + "] characters");
    } else if (validate.equals("regex")) {
      String pattern = Caster.toString(validateParams.get(PATTERN, null), null);
      String value = Caster.toString(obj);
      if (!StringUtil.isEmpty(pattern, true) && !IsValid.regex(value, pattern))
        throw new ExpressionException(
            "the string ["
                + value
                + "] does not match the regular expression pattern ["
                + pattern
                + "]");
    }
  }
Exemple #26
0
  @Override
  public void evaluate(Tag tag, TagLibTag libTag) throws EvaluatorException {
    String ns = libTag.getTagLib().getNameSpaceAndSeparator();
    String loopName = ns + "loop";
    String whileName = ns + "while";

    // label
    String label = null;

    Attribute attrLabel = tag.getAttribute("label");
    if (attrLabel != null) {
      TagBreak tb = (TagBreak) tag;
      label = variableToString(tag, attrLabel, null);
      if (label != null) {
        tb.setLabel(label = label.trim());
        tag.removeAttribute("label");
      } else if (ASMUtil.isLiteralAttribute(tag, attrLabel, ASMUtil.TYPE_STRING, false, true)) {
        LitString ls = (LitString) CastString.toExprString(tag.getAttribute("label").getValue());
        label = ls.getString();
        if (!StringUtil.isEmpty(label, true)) {
          tb.setLabel(label = label.trim());
          tag.removeAttribute("label");
        } else label = null;
      }
    }

    // no base tag found
    if (!ASMUtil.hasAncestorBreakFCStatement(tag, label)) {
      if (tag.isScriptBase()) {
        if (StringUtil.isEmpty(label))
          throw new EvaluatorException(
              "Wrong Context, " + libTag.getName() + " must be inside a looping statement or tag");
        throw new EvaluatorException(
            "Wrong Context, "
                + libTag.getName()
                + " must be inside a looping statement or tag with the label ["
                + label
                + "]");
      }

      if (StringUtil.isEmpty(label))
        throw new EvaluatorException(
            "Wrong Context, tag "
                + libTag.getFullName()
                + " must be inside a "
                + loopName
                + " or "
                + whileName
                + " tag");
      throw new EvaluatorException(
          "Wrong Context, tag "
              + libTag.getFullName()
              + " must be inside a "
              + loopName
              + " or "
              + whileName
              + " tag with the label ["
              + label
              + "]");
    }
  }
Exemple #27
0
 /** @see org.apache.commons.httpclient.methods.multipart.PartBase#getCharSet() */
 public String getCharSet() {
   String cs = super.getCharSet();
   if (StringUtil.isEmpty(cs)) return null;
   return cs;
 }
 @Override
 public Resource getParentResource() {
   if (StringUtil.isEmpty(parent)) return null;
   return new CompressResource(provider, zip, parent, caseSensitive);
 }
 /** @return the charset */
 public String getCharset() {
   if (StringUtil.isEmpty(charset, true)) return null;
   return charset;
 }
 /**
  * Constructor of the class
  *
  * @param type
  * @param subtype
  * @param charset
  */
 public ContentTypeImpl(String type, String subtype, String charset) {
   this.type = StringUtil.isEmpty(type, true) ? null : type.trim().toLowerCase();
   this.subtype = StringUtil.isEmpty(subtype, true) ? null : subtype.trim().toLowerCase();
   this.charset = StringUtil.isEmpty(charset, true) ? null : charset.trim().toLowerCase();
 }