protected void importMergedRegions(Sheet poiSheet, SSheet sheet) {
   // merged cells
   // reference RangeImpl.getMergeAreas()
   int nMerged = poiSheet.getNumMergedRegions();
   final SheetImpl sheetImpl = (SheetImpl) sheet;
   for (int i = nMerged - 1; i >= 0; --i) {
     final CellRangeAddress mergedRegion = poiSheet.getMergedRegion(i);
     // ZSS-1114: any new merged region that overlapped with previous merged region is thrown away
     final CellRegion r =
         new CellRegion(
             mergedRegion.getFirstRow(),
             mergedRegion.getFirstColumn(),
             mergedRegion.getLastRow(),
             mergedRegion.getLastColumn());
     final CellRegion overlapped = sheetImpl.checkMergedRegion(r);
     if (overlapped != null) {
       _logger.warning(
           "Drop the region "
               + r
               + " which is overlapped with existing merged area "
               + overlapped
               + ".");
       continue;
     }
     sheetImpl.addDirectlyMergedRegion(r);
   }
 }
Esempio n. 2
0
  /** @param wapp the Web application (or null if not available yet) */
  private void sessionTimeout(
      HttpServletRequest request, HttpServletResponse response, WebApp wapp, String dtid)
      throws ServletException, IOException {
    final String sid = request.getHeader("ZK-SID");
    if (sid != null) response.setHeader("ZK-SID", sid);

    final AuWriter out = AuWriters.newInstance().open(request, response, 0);

    if (!getAuDecoder(wapp).isIgnorable(request, wapp)) {
      final String deviceType = getDeviceType(request);
      URIInfo ui =
          wapp != null ? (URIInfo) wapp.getConfiguration().getTimeoutURI(deviceType) : null;
      String uri = ui != null ? ui.uri : null;
      out.write(new AuConfirmClose(null)); // Bug: B50-3147382
      final AuResponse resp;
      if (uri != null) {
        if (uri.length() != 0) uri = Encodes.encodeURL(getServletContext(), request, response, uri);
        resp = new AuSendRedirect(uri, null);
      } else {
        String msg = wapp.getConfiguration().getTimeoutMessage(deviceType);
        if (msg != null && msg.startsWith("label:")) {
          final String key;
          msg = Labels.getLabel(key = msg.substring(6), new Object[] {dtid});
          if (msg == null) log.warning("Label not found, " + key);
        }
        if (msg == null) msg = Messages.get(MZk.UPDATE_OBSOLETE_PAGE, dtid);
        resp = new AuObsolete(dtid, msg);
      }
      out.write(resp);
    }

    out.close(request, response);
  }
Esempio n. 3
0
  private static final boolean load(String flnm) {
    final InputStream strm = ContentTypes.class.getResourceAsStream(flnm);
    if (strm == null) return false;

    BufferedReader in = null;
    // NOTE: we cannot use Properties.load because there might be replicated
    // mapping (e.g., jpg=images/jpg, jpg=images/jpeg)
    try {
      in = new BufferedReader(new InputStreamReader(strm));
      String line;
      while ((line = in.readLine()) != null) {
        final int j = line.indexOf('=');
        if (j < 0) {
          final int k = Strings.skipWhitespaces(line, 0);
          if (k < line.length() && line.charAt(k) != '#')
            log.warning("Ignored error;  illgal format: " + line);
          continue;
        }

        final String format = line.substring(0, j).trim();
        final String ctype = line.substring(j + 1).trim();
        if (format.length() == 0 || ctype.length() == 0) {
          log.warning("Ignored error;  illgal format: " + line);
          continue;
        }

        _fmt2ct.put(format, ctype);
        _ct2fmt.put(ctype, format);
      }
    } catch (IOException ex) {
      log.warning("Ingored error: Unable to read " + flnm, ex);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
        }
      }
      try {
        strm.close();
      } catch (Throwable ex) {
      }
    }
    return true;
  }
Esempio n. 4
0
  private void register0(Object locator) {
    if (locator == null) throw new NullPointerException("locator");

    synchronized (_locators) {
      if (!_locators.add(locator))
        log.warning("Replace the old one, because it is replicated: " + locator);
    }

    reset(); // Labels might be loaded before, so...
  }
Esempio n. 5
0
 private static String getDeviceType(HttpServletRequest request) {
   final String agt = request.getHeader("user-agent");
   if (agt != null && agt.length() > 0) {
     try {
       return Devices.getDeviceByClient(agt).getType();
     } catch (Throwable ex) {
       log.warning("Unknown device for " + agt);
     }
   }
   return "ajax";
 }
Esempio n. 6
0
 /**
  * Eliminates single and double quotations to avoid JavaScript injection. It eliminates all
  * quotations. In other words, the specified string shall NOT contain any quotations.
  *
  * <p>It is used to avoid JavaScript injection. For exmple, in DSP or JSP pages, the following
  * codes is better to escape with this method. <code><input value="${c:eatQuot(param.some)}"/>
  * </code>
  *
  * @since 3.5.2
  */
 public static String eatQuot(String s) {
   final int len = s != null ? s.length() : 0;
   StringBuffer sb = null;
   for (int j = 0; j < len; ++j) {
     final char cc = s.charAt(j);
     if (cc == '\'' || cc == '"') {
       if (sb == null) {
         log.warning("JavaScript Injection? Unexpected string detected: " + s);
         sb = new StringBuffer(len);
         if (j > 0) sb.append(s.substring(0, j));
       }
     } else if (sb != null) sb.append(cc);
   }
   return sb != null ? sb.toString() : s;
 }
Esempio n. 7
0
 static {
   final String flnm = "/metainfo/org/zkoss/util/media/contentTypes.properties";
   if (!load(flnm)) log.warning(MCommon.FILE_NOT_FOUND, flnm);
   load("/contentTypes.properties"); // override!
 }
Esempio n. 8
0
  /**
   * Process asynchronous update requests from the client.
   *
   * @since 3.0.0
   */
  protected void process(Session sess, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    final String errClient = request.getHeader("ZK-Error-Report");
    if (errClient != null)
      if (log.debugable())
        log.debug("Error found at client: " + errClient + "\n" + Servlets.getDetail(request));

    // parse desktop ID
    final WebApp wapp = sess.getWebApp();
    final WebAppCtrl wappc = (WebAppCtrl) wapp;
    final AuDecoder audec = getAuDecoder(wapp);
    final String dtid = audec.getDesktopId(request);
    if (dtid == null) {
      // Bug 1929139: incomplete request (IE only)
      if (log.debugable()) {
        final String msg = "Incomplete request\n" + Servlets.getDetail(request);
        log.debug(msg);
      }

      response.sendError(467, "Incomplete request");
      return;
    }

    Desktop desktop = getDesktop(sess, dtid);
    if (desktop == null) {
      final String cmdId = audec.getFirstCommand(request);
      if (!"rmDesktop".equals(cmdId))
        desktop = recoverDesktop(sess, request, response, wappc, dtid);

      if (desktop == null) {
        response.setIntHeader("ZK-Error", response.SC_GONE); // denote timeout
        sessionTimeout(request, response, wapp, dtid);
        return;
      }
    }
    WebManager.setDesktop(request, desktop);
    // reason: a new page might be created (such as include)

    final String sid = request.getHeader("ZK-SID");
    if (sid != null) // Some client might not have ZK-SID
    response.setHeader("ZK-SID", sid);

    // parse commands
    final Configuration config = wapp.getConfiguration();
    final List aureqs;
    boolean keepAlive = false;
    try {
      final boolean timerKeepAlive = config.isTimerKeepAlive();
      aureqs = audec.decode(request, desktop);
      for (Iterator it = aureqs.iterator(); it.hasNext(); ) {
        final String cmdId = ((AuRequest) it.next()).getCommand();
        keepAlive = !(!timerKeepAlive && Events.ON_TIMER.equals(cmdId)) && !"dummy".equals(cmdId);
        // dummy is used for PollingServerPush for piggyback
        if (keepAlive) break; // done
      }
    } catch (Throwable ex) {
      log.warningBriefly(ex);
      responseError(request, response, Exceptions.getMessage(ex));
      return;
    }

    if (aureqs.isEmpty()) {
      final String errmsg = "Illegal request: cmd required";
      log.debug(errmsg);
      responseError(request, response, errmsg);
      return;
    }

    ((SessionCtrl) sess).notifyClientRequest(keepAlive);

    //		if (log.debugable()) log.debug("AU request: "+aureqs);
    final DesktopCtrl desktopCtrl = (DesktopCtrl) desktop;
    final Execution exec = new ExecutionImpl(getServletContext(), request, response, desktop, null);
    if (sid != null) ((ExecutionCtrl) exec).setRequestId(sid);

    final AuWriter out = AuWriters.newInstance();
    out.setCompress(_compress);
    out.open(
        request,
        response,
        desktop.getDevice().isSupported(Device.RESEND)
            ? getProcessTimeout(config.getResendDelay())
            : 0);
    // Note: getResendDelay() might return nonpositive
    try {
      wappc.getUiEngine().execUpdate(exec, aureqs, out);
    } catch (RequestOutOfSequenceException ex) {
      log.warning(ex.getMessage());
      response.setHeader("ZK-SID", sid);
      response.setIntHeader("ZK-Error", AuResponse.SC_OUT_OF_SEQUENCE);
    }
    out.close(request, response);
  }
Esempio n. 9
0
  // Servlet//
  public void init() throws ServletException {
    final ServletConfig config = getServletConfig();
    final ServletContext ctx = getServletContext();
    ctx.setAttribute(ATTR_UPDATE_SERVLET, this);

    final WebManager webman = WebManager.getWebManager(ctx);
    String param = config.getInitParameter("compress");
    _compress = param == null || param.length() == 0 || "true".equals(param);
    if (!_compress) webman.getClassWebResource().setCompress(null); // disable all

    // Copies au extensions defined before DHtmlUpdateServlet is started
    final WebApp wapp = webman.getWebApp();
    final Map aues = (Map) wapp.getAttribute(ATTR_AU_PROCESSORS);
    if (aues != null) {
      for (Iterator it = aues.entrySet().iterator(); it.hasNext(); ) {
        final Map.Entry me = (Map.Entry) it.next();
        addAuExtension((String) me.getKey(), (AuExtension) me.getValue());
      }
      wapp.removeAttribute(ATTR_AU_PROCESSORS);
    }

    // ZK 5: extension defined in init-param has the higher priority
    for (int j = 0; ; ++j) {
      param = config.getInitParameter("extension" + j);
      if (param == null) {
        param = config.getInitParameter("processor" + j); // backward compatible
        if (param == null) break;
      }
      final int k = param.indexOf('=');
      if (k < 0) {
        log.warning("Ignore init-param: illegal format, " + param);
        continue;
      }

      final String prefix = param.substring(0, k).trim();
      final String clsnm = param.substring(k + 1).trim();
      try {
        addAuExtension(prefix, (AuExtension) Classes.newInstanceByThread(clsnm));
      } catch (ClassNotFoundException ex) {
        log.warning("Ignore init-param: class not found, " + clsnm);
      } catch (ClassCastException ex) {
        log.warning("Ignore: " + clsnm + " not implement " + AuExtension.class);
      } catch (Throwable ex) {
        log.warning("Ignore init-param: failed to add an AU extension, " + param, ex);
      }
    }

    if (getAuExtension("/upload") == null) {
      try {
        addAuExtension("/upload", new AuUploader());
      } catch (Throwable ex) {
        final String msg = "Make sure commons-fileupload.jar is installed.";
        log.warningBriefly("Failed to configure fileupload. " + msg, ex);

        // still add /upload to generate exception when fileupload is used
        addAuExtension(
            "/upload",
            new AuExtension() {
              public void init(DHtmlUpdateServlet servlet) {}

              public void destroy() {}

              public void service(
                  HttpServletRequest request, HttpServletResponse response, String pi)
                  throws ServletException, IOException {
                if (Sessions.getCurrent(false) != null)
                  throw new ServletException("Failed to upload. " + msg);
              }
            });
      }
    }

    if (getAuExtension("/view") == null) addAuExtension("/view", new AuDynaMediar());
  }
Esempio n. 10
0
  // -- private utilities --//
  private final Map loadLabels(Locale locale) {
    WaitLock lock = null;
    for (; ; ) {
      final Object o;
      synchronized (_syncLabels) {
        o = _syncLabels.get(locale);
        if (o == null) _syncLabels.put(locale, lock = new WaitLock()); // lock it
      }

      if (o instanceof Map) return (Map) o;
      if (o == null) break; // go to load the page

      // wait because some one is creating the servlet
      if (!((WaitLock) o).waitUntilUnlock(5 * 60 * 1000))
        log.warning(
            "Take too long to wait loading labels: "
                + locale
                + "\nTry to load again automatically...");
    } // for(;;)

    if (_jarcharset == null)
      _jarcharset = Library.getProperty("org.zkoss.util.label.classpath.charset", "UTF-8");
    if (_warcharset == null) {
      _warcharset = Library.getProperty("org.zkoss.util.label.web.charset", null);
      if (_warcharset == null)
        _warcharset =
            Library.getProperty(
                "org.zkoss.util.label.WEB-INF.charset", "UTF-8"); // backward compatible
    }

    try {
      // get the class name
      if (locale != null) log.info("Loading labels for " + locale);
      Map labels = new HashMap(512);

      // 1. load from modules
      final ClassLocator locator = new ClassLocator();
      for (Enumeration en =
              locator.getResources(
                  locale == null
                      ? "metainfo/i3-label.properties"
                      : "metainfo/i3-label_" + locale + ".properties");
          en.hasMoreElements(); ) {
        final URL url = (URL) en.nextElement();
        load(labels, url, _jarcharset);
      }

      // 2. load from extra resource
      final List locators;
      synchronized (_locators) {
        locators = new LinkedList(_locators);
      }
      for (Iterator it = locators.iterator(); it.hasNext(); ) {
        Object o = it.next();
        if (o instanceof LabelLocator) {
          final URL url = ((LabelLocator) o).locate(locale);
          if (url != null) load(labels, url, _warcharset);
        } else {
          final LabelLocator2 loc = (LabelLocator2) o;
          final InputStream is = loc.locate(locale);
          if (is != null) {
            final String cs = loc.getCharset();
            load(labels, is, cs != null ? cs : _warcharset);
          }
        }
      }

      // Convert values to ExValue
      toExValue(labels);

      // merge with labels from 'super' locale
      if (locale != null) {
        final String lang = locale.getLanguage();
        final String cnty = locale.getCountry();
        final String var = locale.getVariant();
        final Map superlabels =
            loadLabels(
                var != null && var.length() > 0
                    ? new Locale(lang, cnty)
                    : cnty != null && cnty.length() > 0 ? new Locale(lang, "") : null);
        if (labels.isEmpty()) {
          labels = superlabels.isEmpty() ? Collections.EMPTY_MAP : superlabels;
        } else if (!superlabels.isEmpty()) {
          Map combined = new HashMap(superlabels);
          combined.putAll(labels);
          labels = combined;
        }
      }

      // add to map
      synchronized (_syncLabels) {
        _syncLabels.put(locale, labels);
        cloneLables();
      }
      return labels;
    } catch (Throwable ex) {
      synchronized (_syncLabels) {
        _syncLabels.remove(locale);
        cloneLables();
      }
      throw SystemException.Aide.wrap(ex);
    } finally {
      lock.unlock(); // unlock (always unlock to avoid deadlock)
    }
  }