/**
   * The parameter must follow the syntax "page:nr" where nr is the number of the page to be
   * displayed.
   *
   * <p>
   *
   * @see org.opencms.file.collectors.I_CmsResourceCollector#getResults(org.opencms.file.CmsObject,
   *     java.lang.String, java.lang.String)
   */
  public List<CmsResource> getResults(CmsObject cms, String collectorName, String parameter)
      throws CmsException {

    synchronized (this) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_COLLECTOR_GET_RESULTS_START_0));
      }
      if (parameter == null) {
        parameter = m_collectorParameter;
      }
      List<CmsResource> resources = new ArrayList<CmsResource>();
      if (getWp().getList() != null) {
        Iterator<CmsListItem> itItems = getListItems(parameter).iterator();
        while (itItems.hasNext()) {
          CmsListItem item = itItems.next();
          resources.add(getResource(cms, item));
        }
      } else {
        Map<String, String> params =
            CmsStringUtil.splitAsMap(
                parameter,
                I_CmsListResourceCollector.SEP_PARAM,
                I_CmsListResourceCollector.SEP_KEYVAL);
        resources = getInternalResources(cms, params);
      }
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            Messages.get()
                .getBundle()
                .key(Messages.LOG_COLLECTOR_GET_RESULTS_END_1, new Integer(resources.size())));
      }
      return resources;
    }
  }
Beispiel #2
0
  /**
   * Test batched prepared statement concurrency. Batch prepares must not disappear between the
   * moment when they were created and when they are executed.
   */
  public void testConcurrentBatching() throws Exception {
    // Create a connection with a batch size of 1. This should cause prepares and actual batch
    // execution to become
    // interspersed (if correct synchronization is not in place) and greatly increase the chance of
    // prepares
    // being rolled back before getting executed.
    Properties props = new Properties();
    props.setProperty(Messages.get(net.sourceforge.jtds.jdbc.Driver.BATCHSIZE), "1");
    props.setProperty(
        Messages.get(net.sourceforge.jtds.jdbc.Driver.PREPARESQL),
        String.valueOf(TdsCore.TEMPORARY_STORED_PROCEDURES));
    Connection con = getConnection(props);

    try {
      Statement stmt = con.createStatement();
      stmt.execute(
          "create table #testConcurrentBatch (v1 int, v2 int, v3 int, v4 int, v5 int, v6 int)");
      stmt.close();

      Vector exceptions = new Vector();
      con.setAutoCommit(false);

      Thread t1 = new ConcurrentBatchingHelper(con, exceptions);
      Thread t2 = new ConcurrentBatchingHelper(con, exceptions);
      t1.start();
      t2.start();
      t1.join();
      t2.join();

      assertEquals(0, exceptions.size());
    } finally {
      con.close();
    }
  }
Beispiel #3
0
  /**
   * Substitute actual data for the parameter markers to simulate parameter substitution in a
   * PreparedStatement.
   *
   * @param sql The SQL containing parameter markers to substitute.
   * @param list The parameter descriptors.
   * @param connection The current connection.
   * @return The modified SQL statement.
   */
  static String substituteParameters(String sql, ParamInfo[] list, ConnectionJDBC2 connection)
      throws SQLException {
    int len = sql.length();

    for (int i = 0; i < list.length; i++) {
      if (!list[i].isRetVal && !list[i].isSet && !list[i].isOutput) {
        throw new SQLException(
            Messages.get("error.prepare.paramnotset", Integer.toString(i + 1)), "07000");
      }

      Object value = list[i].value;

      if (value instanceof java.io.InputStream || value instanceof java.io.Reader) {
        try {
          if (list[i].jdbcType == java.sql.Types.LONGVARCHAR
              || list[i].jdbcType == java.sql.Types.CLOB
              || list[i].jdbcType == java.sql.Types.VARCHAR) {
            // TODO: Should improve the character set handling here
            value = list[i].getString("US-ASCII");
          } else {
            value = list[i].getBytes("US-ASCII");
          }
          // Replace the stream/reader with the String/byte[]
          list[i].value = value;
        } catch (java.io.IOException e) {
          throw new SQLException(Messages.get("error.generic.ioerror", e.getMessage()), "HY000");
        }
      }

      if (value instanceof String) {
        len += ((String) value).length() + 5;
      } else if (value instanceof byte[]) {
        len += ((byte[]) value).length * 2 + 4;
      } else {
        len += 32; // Default size
      }
    }

    StringBuffer buf = new StringBuffer(len + 16);
    int start = 0;

    for (int i = 0; i < list.length; i++) {
      int pos = list[i].markerPos;

      if (pos > 0) {
        buf.append(sql.substring(start, list[i].markerPos));
        start = pos + 1;
        final boolean isUnicode = connection.getTdsVersion() >= Driver.TDS70 && list[i].isUnicode;
        Support.embedData(buf, list[i].value, isUnicode, connection);
      }
    }

    if (start < sql.length()) {
      buf.append(sql.substring(start));
    }

    return buf.toString();
  }
  public boolean execute(String sql, String[] columnNames) throws SQLException {
    if (columnNames == null) {
      throw new SQLException(Messages.get("error.generic.nullparam", "execute"), "HY092");
    } else if (columnNames.length != 1) {
      throw new SQLException(Messages.get("error.generic.needcolname", "execute"), "HY092");
    }

    return execute(sql, RETURN_GENERATED_KEYS);
  }
  public void deleteRow() throws SQLException {
    checkOpen();
    checkUpdateable();

    if (currentRow == null) {
      throw new SQLException(Messages.get("error.resultset.norow"), "24000");
    }

    if (onInsertRow) {
      throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
    }

    //
    // Construct an SQL DELETE statement
    //
    StringBuffer sql = new StringBuffer(128);
    ArrayList params = new ArrayList();
    sql.append("DELETE FROM ");
    sql.append(tableName);
    //
    // Create the WHERE clause
    //
    ParamInfo parameters[] = buildWhereClause(sql, params, false);
    //
    // Execute the delete statement
    //
    updateTds.executeSQL(
        sql.toString(),
        null,
        parameters,
        false,
        0,
        statement.getMaxRows(),
        statement.getMaxFieldSize(),
        true);
    int updateCount = 0;
    while (!updateTds.isEndOfResponse()) {
      if (!updateTds.getMoreResults()) {
        if (updateTds.isUpdateCount()) {
          updateCount = updateTds.getUpdateCount();
        }
      }
    }
    updateTds.clearResponseQueue();
    statement.getMessages().checkErrors();
    if (updateCount == 0) {
      // No delete. Possibly row was changed on database by another user?
      throw new SQLException(Messages.get("error.resultset.deletefail"), "24000");
    }
    rowDeleted = true;
    currentRow = null;
    if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) {
      // Leave a 'hole' in the result set array.
      rowData.set(pos - 1, null);
    }
  }
  public boolean execute(String sql, int[] columnIndexes) throws SQLException {
    checkOpen();

    if (columnIndexes == null) {
      throw new SQLException(Messages.get("error.generic.nullparam", "execute"), "HY092");
    } else if (columnIndexes.length != 1) {
      throw new SQLException(Messages.get("error.generic.needcolindex", "execute"), "HY092");
    }

    return execute(sql, RETURN_GENERATED_KEYS);
  }
  /**
   * @see
   *     org.opencms.workplace.list.A_CmsListDialog#setMultiActions(org.opencms.workplace.list.CmsListMetadata)
   */
  @Override
  protected void setMultiActions(final CmsListMetadata metadata) {

    // add copy multi action
    CmsListMultiAction deleteMultiAction = new CmsListMultiAction(LIST_MACTION_COPY);
    deleteMultiAction.setName(
        Messages.get().container(Messages.GUI_LIST_SEARCHINDEX_MACTION_COPY_NAME_0));
    deleteMultiAction.setHelpText(
        Messages.get().container(Messages.GUI_LIST_SEARCHINDEX_MACTION_COPY_HELP_0));
    deleteMultiAction.setIconPath(ICON_MULTI_ADD);
    metadata.addMultiAction(deleteMultiAction);
  }
  public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
    checkOpen();

    if (sql == null || sql.length() == 0) {
      throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
    }

    closeCurrentResultSet();
    boolean returnKeys;
    String sqlWord = "";
    if (escapeProcessing) {
      ArrayList params = new ArrayList();
      String tmp[] = new SQLParser(sql, params, connection).parse(false);

      if (tmp[1].length() != 0 || params.size() > 0) {
        throw new SQLException(Messages.get("error.statement.badsql"), "07000");
      }

      sql = tmp[0];
      sqlWord = tmp[2];
    } else {
      // Escape processing turned off so
      // see if we can extract "insert" from start of statement
      sql = sql.trim();
      if (sql.length() > 5) {
        sqlWord = sql.substring(0, 6).toLowerCase();
      }
    }
    if (autoGeneratedKeys == RETURN_GENERATED_KEYS) {
      returnKeys = sqlWord.equals("insert");
    } else if (autoGeneratedKeys == NO_GENERATED_KEYS) {
      returnKeys = false;
    } else {
      throw new SQLException(
          Messages.get(
              "error.generic.badoption", Integer.toString(autoGeneratedKeys), "executeUpate"),
          "HY092");
    }

    if (returnKeys) {
      if (connection.getServerType() == Driver.SQLSERVER
          && connection.getDatabaseMajorVersion() >= 8) {
        sql += " SELECT SCOPE_IDENTITY() AS ID";
      } else {
        sql += " SELECT @@IDENTITY AS ID";
      }
    }

    executeSQL(sql, null, sqlWord, null, returnKeys, true);

    return getUpdateCount(0);
  }
Beispiel #9
0
  /**
   * Sets the name of the menu rule set.
   *
   * <p>
   *
   * @param name the name of the menu rule set
   */
  public void setName(String name) {

    if (m_frozen) {
      throw new CmsRuntimeException(Messages.get().container(Messages.ERR_MENURULE_FROZEN_0));
    }
    m_name = name;
  }
  public void refreshRow() throws SQLException {
    checkOpen();

    if (onInsertRow) {
      throw new SQLException(Messages.get("error.resultset.insrow"), "24000");
    }

    //
    // If row is being updated discard updates now
    //
    if (concurrency == CONCUR_UPDATABLE) {
      cancelRowUpdates();
      rowUpdated = false;
    }
    if (resultSetType == ResultSet.TYPE_FORWARD_ONLY || currentRow == null) {
      // Do not try and refresh the row in these cases.
      return;
    }
    //
    // If result set is keyed we can refresh the row data from the
    // database using the key.
    // NB. MS SQL Server #Temporary tables with keys are not identified correctly
    // in the column meta data sent after 'for browse'. This means that
    // temporary tables can not be used with this logic.
    //
    if (isKeyed) {
      // OK all tables are keyed
      refreshKeyedRows();
    } else {
      // No good have to use brute force approach
      refreshReRead();
    }
  }
  /** @see org.opencms.workplace.CmsWorkplace#initMessages() */
  protected void initMessages() {

    // add specific dialog resource bundle
    addMessages(Messages.get().getBundleName());
    // add default resource bundles
    super.initMessages();
  }
  public MSSqlServerInfo(String host) throws SQLException {
    try {
      InetAddress addr = InetAddress.getByName(host);
      DatagramSocket socket = new DatagramSocket();
      byte[] msg = new byte[] {0x02};
      DatagramPacket p = new DatagramPacket(msg, msg.length, addr, 1434);

      socket.send(p);

      byte[] buf = new byte[4096];

      p = new DatagramPacket(buf, buf.length);
      socket.setSoTimeout(m_timeout);

      for (int i = 0; i < m_numRetries; i++) {
        try {
          socket.receive(p);
          String infoString = extractString(buf, p.getLength());
          m_serverInfoStrings = split(infoString, ';');

          return;
        } catch (InterruptedIOException toEx) {
        }
      }
    } catch (Exception e) {
      // Ignore...
    }

    throw new SQLException(Messages.get("error.msinfo.badinfo", host), "HY000");
  }
  /**
   * Checks if this job info configuration is frozen.
   *
   * <p>
   *
   * @throws CmsRuntimeException in case the configuration is already frozen
   */
  protected void checkFrozen() throws CmsRuntimeException {

    if (m_frozen) {
      throw new CmsRuntimeException(
          Messages.get().container(Messages.ERR_JOB_INFO_FROZEN_1, getJobName()));
    }
  }
  /** @see org.opencms.workplace.CmsWorkplace#initMessages() */
  @Override
  protected void initMessages() {

    // add specific dialog resource bundle
    addMessages(Messages.get().getBundleName());
    super.initMessages();
  }
  /**
   * @return SKIP_BODY
   * @see javax.servlet.jsp.tagext.Tag#doStartTag()
   */
  @Override
  public int doStartTag() throws JspException {

    ServletRequest req = pageContext.getRequest();

    // This will always be true if the page is called through OpenCms
    if (CmsFlexController.isCmsRequest(req)) {

      try {
        String setting = elementSettingTagAction(getName(), m_defaultValue, m_escapeHtml, req);
        // Make sure that no null String is returned
        if (setting == null) {
          setting = "";
        }
        pageContext.getOut().print(setting);

      } catch (Exception ex) {
        if (LOG.isErrorEnabled()) {
          LOG.error(
              Messages.get().getBundle().key(Messages.ERR_PROCESS_TAG_1, "elementSetting"), ex);
        }
        throw new javax.servlet.jsp.JspException(ex);
      }
    }
    return SKIP_BODY;
  }
  /**
   * Reads the resources available for processing based on the path parameters.
   *
   * <p>
   *
   * @return the resources available for processing based on the path parameters.
   */
  @SuppressWarnings("unchecked")
  private List<CmsResource> getResources() {

    List<CmsResource> result = new LinkedList<CmsResource>();
    CmsObject cms = this.getCms();
    CmsResourceFilter filter = CmsResourceFilter.ALL;
    try {
      for (String path : this.m_paths) {
        List<CmsResource> resources = cms.readResources(path, filter, true);
        // filter out any resource that is no XML content:
        for (CmsResource resource : resources) {
          if (resource.isFile()) {
            if (CmsResourceTypeXmlContent.isXmlContent(resource)) {
              result.add(resource);
            } else if (CmsResourceTypeXmlPage.isXmlPage(resource)) {
              result.add(resource);
            }
          }
        }
      }
    } catch (CmsException e) {
      LOG.error(Messages.get().getBundle().key(Messages.LOG_ERR_LANGUAGECOPY_READRESOURCES_0), e);
      result = Collections.emptyList();
    }

    return result;
  }
  /** @see org.opencms.cache.I_CmsLruCacheObject#addToLruCache() */
  public void addToLruCache() {

    // do nothing here...
    if (LOG.isDebugEnabled()) {
      LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXCACHEENTRY_ADDED_ENTRY_1, this));
    }
  }
  /** @see org.opencms.workplace.CmsWorkplace#initMessages() */
  protected void initMessages() {

    // add specific dialog resource bundle
    addMessages(Messages.get().getBundleName());
    // add default resource bundles
    addMessages(org.opencms.workplace.Messages.get().getBundleName());
    addMessages(org.opencms.workplace.tools.Messages.get().getBundleName());
  }
  /**
   * Sets the name of the class to schedule.
   *
   * <p>
   *
   * @param className the class name to set
   */
  public void setClassName(String className) {

    checkFrozen();
    if (!CmsStringUtil.isValidJavaClassName(className)) {
      CmsMessageContainer message =
          Messages.get().container(Messages.ERR_BAD_JOB_CLASS_NAME_1, className);
      if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) {
        throw new CmsIllegalArgumentException(message);
      } else {
        LOG.warn(message.key());
      }
    } else {
      Class<?> jobClass;
      try {
        jobClass = Class.forName(className);
        if (!I_CmsScheduledJob.class.isAssignableFrom(jobClass)) {
          CmsMessageContainer message =
              Messages.get()
                  .container(
                      Messages.ERR_JOB_CLASS_BAD_INTERFACE_2,
                      className,
                      I_CmsScheduledJob.class.getName());

          if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) {
            throw new CmsIllegalArgumentException(message);
          } else {
            LOG.warn(message.key());
          }
        }
      } catch (ClassNotFoundException e) {
        CmsMessageContainer message =
            Messages.get().container(Messages.ERR_JOB_CLASS_NOT_FOUND_1, className);
        if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) {
          throw new CmsIllegalArgumentException(message);
        } else {
          LOG.warn(message.key());
        }
      }
    }
    m_className = className;
    if (getJobName() == null) {
      // initialize job name with class name as default
      setJobName(className);
    }
  }
  /**
   * @see
   *     org.opencms.workplace.list.A_CmsListDialog#setColumns(org.opencms.workplace.list.CmsListMetadata)
   */
  @SuppressWarnings("unchecked")
  @Override
  protected void setColumns(final CmsListMetadata metadata) {

    // enforce re-invocation of this method because columns are varying and must not be cached:
    metadata.setVolatile(true);

    // add column for icon
    CmsListColumnDefinition iconCol = new CmsListColumnDefinition(LIST_COLUMN_ICON);
    iconCol.setName(Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_ICON_NAME_0));
    iconCol.setHelpText(Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_ICON_HELP_0));
    iconCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT);
    iconCol.setWidth("16");
    iconCol.setSorteable(false);
    metadata.addColumn(iconCol);
    iconCol.setPrintable(true);

    // add column for name
    CmsListColumnDefinition nameCol = new CmsListColumnDefinition(LIST_COLUMN_PATH);
    nameCol.setName(Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_PATH_NAME_0));
    nameCol.setHelpText(Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_PATH_HELP_0));
    nameCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT);
    nameCol.setSorteable(true);
    metadata.addColumn(nameCol);
    nameCol.setPrintable(true);

    // add column for resource type
    CmsListColumnDefinition typeCol = new CmsListColumnDefinition(LIST_COLUMN_RESOURCETYPE);
    typeCol.setName(
        Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_RESOURCETYPE_NAME_0));
    typeCol.setHelpText(
        Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_RESOURCETYPE_HELP_0));
    typeCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT);
    typeCol.setSorteable(true);
    metadata.addColumn(typeCol);
    typeCol.setPrintable(true);

    // add columns for languages:
    List<Locale> sysLocales = OpenCms.getLocaleManager().getAvailableLocales();
    CmsListColumnDefinition langCol;
    for (Locale locale : sysLocales) {
      langCol = new CmsListColumnDefinition(locale.toString());
      langCol.setName(
          Messages.get()
              .container(
                  Messages.GUI_LIST_LANGUAGECOPY_COL_LANGUAGE_NAME_1,
                  new Object[] {locale.toString()}));
      langCol.setHelpText(
          Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_LANGUAGE_HELP_0));
      langCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT);
      langCol.setSorteable(false);
      metadata.addColumn(langCol);
      langCol.setPrintable(true);
    }
  }
  public void setQueryTimeout(int seconds) throws SQLException {
    checkOpen();

    if (seconds < 0) {
      throw new SQLException(Messages.get("error.generic.optltzero", "setQueryTimeout"), "HY092");
    }

    this.queryTimeout = seconds;
  }
  /**
   * Sets the context information for the user executing the job.
   *
   * <p>This will also "freeze" the context information that is set.
   *
   * <p>
   *
   * @param contextInfo the context information for the user executing the job
   * @see CmsContextInfo#freeze()
   */
  public void setContextInfo(CmsContextInfo contextInfo) {

    checkFrozen();
    if (contextInfo == null) {
      throw new CmsIllegalArgumentException(
          Messages.get().container(Messages.ERR_BAD_CONTEXT_INFO_0));
    }
    m_context = contextInfo;
  }
  public void setFetchSize(int rows) throws SQLException {
    checkOpen();

    if (rows < 0 || (maxRows > 0 && rows > maxRows)) {
      throw new SQLException(Messages.get("error.generic.optltzero", "setFetchSize"), "HY092");
    }

    this.fetchSize = rows;
  }
  public void setMaxRows(int max) throws SQLException {
    checkOpen();

    if (max < 0) {
      throw new SQLException(Messages.get("error.generic.optltzero", "setMaxRows"), "HY092");
    }

    this.maxRows = max;
  }
Beispiel #25
0
    public void dataReceived(List<JSOModel> models) {
      ConfirmDialog saved = new ConfirmDialog("Survey Cancelled!");
      saved.show();
      saved.center();

      // assume that the cancellation is
      // done to a bcast in the first page
      Messages.get().loadBroadcasts(0);
    }
  /**
   * Sets the job name.
   *
   * <p>
   *
   * @param jobName the job name to set
   */
  public void setJobName(String jobName) {

    checkFrozen();
    if (CmsStringUtil.isEmpty(jobName) || !jobName.trim().equals(jobName)) {
      throw new CmsIllegalArgumentException(
          Messages.get().container(Messages.ERR_BAD_JOB_NAME_1, jobName));
    }
    m_jobName = jobName;
  }
  public ResultSet executeQuery(String sql) throws SQLException {
    checkOpen();

    if (sql == null || sql.length() == 0) {
      throw new SQLException(Messages.get("error.generic.nosql"), "HY000");
    }
    if (escapeProcessing) {
      ArrayList params = new ArrayList();
      String tmp[] = new SQLParser(sql, params, connection).parse(false);

      if (tmp[1].length() != 0 || params.size() > 0) {
        throw new SQLException(Messages.get("error.statement.badsql"), "07000");
      }

      sql = tmp[0];
    }

    return this.executeSQLQuery(sql, null, null, false);
  }
  /**
   * Sets the job parameters.
   *
   * <p>
   *
   * @param parameters the parameters to set
   */
  public void setParameters(SortedMap<String, String> parameters) {

    checkFrozen();
    if (parameters == null) {
      throw new CmsIllegalArgumentException(
          Messages.get().container(Messages.ERR_BAD_JOB_PARAMS_0));
    }
    // make sure the parameters are a sorted map
    m_parameters = new TreeMap<String, String>(parameters);
  }
 /** Get the string searching in the chain */
 public String get(String key) {
   for (Iterator iter = chain.iterator(); iter.hasNext(); ) {
     Messages msgs = (Messages) iter.next();
     String str = msgs.get(key);
     if (!str.startsWith("???")) {
       return str;
     }
   }
   return "???" + key + "???";
 }
 /**
  * Retrieve the value of an output parameter.
  *
  * @param parameterIndex the ordinal position of the parameter
  * @return the parameter value as an <code>Object</code>
  * @throws SQLException if the parameter has not been set
  */
 protected Object getOutputValue(int parameterIndex) throws SQLException {
   ParamInfo parameter = getParameter(parameterIndex);
   if (!parameter.isOutput) {
     throw new SQLException(
         Messages.get("error.callable.notoutput", new Integer(parameterIndex)), "07000");
   }
   Object value = parameter.getOutValue();
   paramWasNull = (value == null);
   return value;
 }