public List makeRow(String pDataString) {
   ArrayList row;
   if (mFormat != null) {
     // we have a format
     row = new ArrayList(mFormat.getNumFields());
     dbgMsg("makeRow(" + pDataString + "," + mFormat + ")");
     int[] groups = mFormat.getNumFieldsArray();
     dbgMsg(
         "Groups of the format: "
             + StringUtils.collectionToString(ConversionUtils.asList(groups), " "));
     dbgMsg("Row(" + pDataString + "," + mFormat + ")");
     String[] tokens = StringUtils.split(pDataString, columnSeparatorRegex, groups);
     dbgMsg("Tokens: " + StringUtils.arrayToString(tokens, "\n"));
     for (int i = 0; i < tokens.length; i++) {
       row.add(mFormat.makeFieldRep(i, tokens[i]));
     }
   } else {
     // we do not have a format
     String[] tokens = pDataString.split(columnSeparatorRegex);
     // note: -1 indicates that the number of fields is not fixed!
     if (mNumFields != -1 && tokens.length != mNumFields) {
       throw new RuntimeException(
           "Cannot make row: numFieds = " + mNumFields + " != numTokens = " + tokens.length);
     } else {
       row = new ArrayList(Arrays.asList(tokens));
     }
   }
   return row;
 }
  /**
   * Try to make a database connection to the given URL. The driver should return "null" if it
   * realizes it is the wrong kind of driver to connect to the given URL. This will be common, as
   * when the JDBC driverManager is asked to connect to a given URL, it passes the URL to each
   * loaded driver in turn.
   *
   * <p>The driver should raise an SQLException if it is the right driver to connect to the given
   * URL, but has trouble connecting to the database.
   *
   * <p>The java.util.Properties argument can be used to pass arbitrary string tag/value pairs as
   * connection arguments.
   *
   * <p>My protocol takes the form:
   *
   * <PRE>
   *
   * jdbc:mysql://host:port/database
   *
   * </PRE>
   *
   * @param url the URL of the database to connect to
   * @param info a list of arbitrary tag/value pairs as connection arguments
   * @return a connection to the URL or null if it isnt us
   * @exception SQLException if a database access error occurs
   * @see java.sql.Driver#connect
   */
  public java.sql.Connection connect(String url, Properties info) throws SQLException {
    if (url != null) {
      if (StringUtils.startsWithIgnoreCase(url, LOADBALANCE_URL_PREFIX)) {
        return connectLoadBalanced(url, info);
      } else if (StringUtils.startsWithIgnoreCase(url, REPLICATION_URL_PREFIX)) {
        return connectReplicationConnection(url, info);
      }
    }

    Properties props = null;

    if ((props = parseURL(url, info)) == null) {
      return null;
    }

    try {
      Connection newConn =
          new com.mysql.jdbc.Connection(host(props), port(props), props, database(props), url);

      return newConn;
    } catch (SQLException sqlEx) {
      // Don't wrap SQLExceptions, throw
      // them un-changed.
      throw sqlEx;
    } catch (Exception ex) {
      throw SQLError.createSQLException(
          Messages.getString("NonRegisteringDriver.17") // $NON-NLS-1$
              + ex.toString()
              + Messages.getString("NonRegisteringDriver.18"), // $NON-NLS-1$
          SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE);
    }
  }
Esempio n. 3
0
 @Override
 @SuppressWarnings({"unchecked", "rawtypes"})
 public void execute(
     Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
     throws TemplateException, IOException {
   Site site = FrontUtils.getSite(env);
   List<Content> list = getList(params, env);
   Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
   paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list));
   Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
   InvokeType type = DirectiveUtils.getInvokeType(params);
   String listStyle = DirectiveUtils.getString(PARAM_STYLE_LIST, params);
   if (InvokeType.sysDefined == type) {
     if (StringUtils.isBlank(listStyle)) {
       throw new ParamsRequiredException(PARAM_STYLE_LIST);
     }
     env.include(TPL_STYLE_LIST + listStyle + TPL_SUFFIX, UTF8, true);
   } else if (InvokeType.userDefined == type) {
     if (StringUtils.isBlank(listStyle)) {
       throw new ParamsRequiredException(PARAM_STYLE_LIST);
     }
     FrontUtils.includeTpl(TPL_STYLE_LIST, site, env);
   } else if (InvokeType.custom == type) {
     FrontUtils.includeTpl(TPL_NAME, site, params, env);
   } else if (InvokeType.body == type) {
     body.render(env.getOut());
   } else {
     throw new RuntimeException("invoke type not handled: " + type);
   }
   DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
 }
Esempio n. 4
0
    /**
     * Parse the parameters of a connection into a CoreNLP properties file that can be passed into
     * {@link StanfordCoreNLP}, and used in the I/O stages.
     *
     * @param httpExchange The http exchange; effectively, the request information.
     * @return A {@link Properties} object corresponding to a combination of default and passed
     *     properties.
     * @throws UnsupportedEncodingException Thrown if we could not decode the key/value pairs with
     *     UTF-8.
     */
    private Properties getProperties(HttpExchange httpExchange)
        throws UnsupportedEncodingException {
      // Load the default properties
      Properties props = new Properties();
      defaultProps
          .entrySet()
          .stream()
          .forEach(
              entry -> props.setProperty(entry.getKey().toString(), entry.getValue().toString()));

      // Try to get more properties from query string.
      Map<String, String> urlParams = getURLParams(httpExchange.getRequestURI());
      if (urlParams.containsKey("properties")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      } else if (urlParams.containsKey("props")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      }

      // Make sure the properties compile
      props.setProperty(
          "annotators",
          StanfordCoreNLP.ensurePrerequisiteAnnotators(
              props.getProperty("annotators").split("[, \t]+")));

      return props;
    }
  private void annotateMatched(List<CoreLabel> tokens) {
    List<SequenceMatchResult<CoreMap>> matched = multiPatternMatcher.findNonOverlapping(tokens);
    for (SequenceMatchResult<CoreMap> m : matched) {
      Entry entry = patternToEntry.get(m.pattern());

      // Check if we will overwrite the existing annotation with this annotation
      int g = entry.annotateGroup;
      int start = m.start(g);
      int end = m.end(g);

      boolean overwriteOriginalNer = checkPosTags(tokens, start, end);
      if (overwriteOriginalNer) {
        overwriteOriginalNer = checkOrigNerTags(entry, tokens, start, end);
      }
      if (overwriteOriginalNer) {
        for (int i = start; i < end; i++) {
          tokens.get(i).set(CoreAnnotations.NamedEntityTagAnnotation.class, entry.type);
        }
      } else {
        if (verbose) {
          System.err.println(
              "Not annotating  '"
                  + m.group(g)
                  + "': "
                  + StringUtils.joinFields(
                      m.groupNodes(g), CoreAnnotations.NamedEntityTagAnnotation.class)
                  + " with "
                  + entry.type
                  + ", sentence is '"
                  + StringUtils.joinWords(tokens, " ")
                  + '\'');
        }
      }
    }
  }
Esempio n. 6
0
  public void replacePointMarkersOnLine() {
    int width = getWidth();
    int height = getHeight();
    for (int yi = 0; yi < height; yi++) {
      for (int xi = 0; xi < width; xi++) {
        char c = get(xi, yi);
        Cell cell = new Cell(xi, yi);
        if (StringUtils.isOneOf(c, pointMarkers) && isStarOnLine(cell)) {

          boolean isOnHorizontalLine = false;
          if (StringUtils.isOneOf(get(cell.getEast()), horizontalLines)) isOnHorizontalLine = true;
          if (StringUtils.isOneOf(get(cell.getWest()), horizontalLines)) isOnHorizontalLine = true;

          boolean isOnVerticalLine = false;
          if (StringUtils.isOneOf(get(cell.getNorth()), verticalLines)) isOnVerticalLine = true;
          if (StringUtils.isOneOf(get(cell.getSouth()), verticalLines)) isOnVerticalLine = true;

          if (isOnHorizontalLine && isOnVerticalLine) {
            set(xi, yi, '+');
            if (DEBUG) System.out.println("replaced marker on line '" + c + "' with +");
          } else if (isOnHorizontalLine) {
            set(xi, yi, '-');
            if (DEBUG) System.out.println("replaced marker on line '" + c + "' with -");
          } else if (isOnVerticalLine) {
            set(xi, yi, '|');
            if (DEBUG) System.out.println("replaced marker on line '" + c + "' with |");
          }
        }
      }
    }
  }
Esempio n. 7
0
  public Collection<User> findUsers(Set<String> fields, String query)
      throws UnsupportedOperationException {
    if (fields.isEmpty()) {
      return Collections.emptyList();
    }
    if (!getSearchFields().containsAll(fields)) {
      throw new IllegalArgumentException("Search fields " + fields + " are not valid.");
    }
    if (query == null || "".equals(query)) {
      return Collections.emptyList();
    }
    // SQL LIKE queries don't map directly into a keyword/wildcard search like we want.
    // Therefore, we do a best approximiation by replacing '*' with '%' and then
    // surrounding the whole query with two '%'. This will return more data than desired,
    // but is better than returning less data than desired.
    query = "%" + query.replace('*', '%') + "%";
    if (query.endsWith("%%")) {
      query = query.substring(0, query.length() - 1);
    }

    List<String> usernames = new ArrayList<String>(50);
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      con = DbConnectionManager.getConnection();
      stmt = con.createStatement();
      StringBuilder sql = new StringBuilder();
      sql.append("SELECT username FROM jiveUser WHERE");
      boolean first = true;
      if (fields.contains("Username")) {
        sql.append(" username LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
        first = false;
      }
      if (fields.contains("Name")) {
        if (!first) {
          sql.append(" AND");
        }
        sql.append(" name LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
        first = false;
      }
      if (fields.contains("Email")) {
        if (!first) {
          sql.append(" AND");
        }
        sql.append(" email LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
      }
      rs = stmt.executeQuery(sql.toString());
      while (rs.next()) {
        usernames.add(rs.getString(1));
      }
    } catch (SQLException e) {
      Log.error(e);
    } finally {
      DbConnectionManager.closeConnection(rs, stmt, con);
    }
    return new UserCollection(usernames.toArray(new String[usernames.size()]));
  }
 /** 保存添加和修改,对象的id不为空时,为修改,否则为添加 */
 @PageType(EnumPageType.JSONPAGE)
 @RequestMapping(value = "/save/json", method = RequestMethod.POST)
 @ResponseBody
 public DwzJson settlementSave(
     UserAgent userAgent,
     @RequestParam(required = false) String dwzId,
     @ModelAttribute("settlement") Settlement settlement,
     @RequestParam(required = false) String dwzId,
     ModelMap model) {
   DwzJson dwzJson;
   if (settlement == null) {
     dwzJson =
         new DwzJson(
             "300", this.messageSource.getMessage("operation.failed", null, this.getThisLocale()));
     return dwzJson;
   }
   if (settlement.getId() != null && settlement.getId() >= 0) {
     // 保存修改
     ServiceResult<Integer> result =
         settlementService.update(new ServiceRequest(settlement, userAgent));
     if (result.getErrorNO() != null) {
       dwzJson =
           new DwzJson(
               "300",
               this.messageSource.getMessage(
                   result.getErrorInfo(), result.getMsgArgs(), this.getThisLocale()));
     } else {
       dwzJson =
           new DwzJson(
               "200",
               this.messageSource.getMessage(
                   "operation.success", result.getMsgArgs(), this.getThisLocale()),
               StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId,
               "closeCurrent");
     }
   } else {
     // 保存新增
     ServiceResult<Settlement> result =
         settlementService.save(new ServiceRequest(settlement, userAgent));
     if (result.getErrorNO() != null) {
       dwzJson =
           new DwzJson(
               "300",
               this.messageSource.getMessage(
                   result.getErrorInfo(), result.getMsgArgs(), this.getThisLocale()));
     } else {
       dwzJson =
           new DwzJson(
               "200",
               this.messageSource.getMessage(
                   "operation.success", result.getMsgArgs(), this.getThisLocale()),
               StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId,
               "closeCurrent");
     }
   }
   return dwzJson;
 }
  /** 根据查询条件,批量删除 */
  @PageType(EnumPageType.JSONPAGE)
  @RequestMapping(value = "/delJson", method = RequestMethod.POST)
  public @ResponseBody DwzJson settlementDelBatch(
      @ModelAttribute("query") SettlementQuery query,
      @RequestParam(required = false) String dwzId,
      UserAgent userAgent,
      ModelMap model) {
    DwzJson dwzJson;
    // 将query.ids的条件合并到query.id_in中
    if (query != null && StringUtils.isNotBlank(query.getIds())) {
      List<Long> id_in = query.getIdsList();
      if (query.getId_in() == null) {
        query.setId_in(id_in);
      } else {
        query.getId_in().addAll(id_in);
      }
    }
    // 如果没有条件,就拒绝删除操作,以免所有数据被删掉.
    if (query == null || (query.getId_in() == null || query.getId_in().size() <= 0)) {
      dwzJson =
          new DwzJson(
              "300",
              this.getMessageSource()
                  .getMessage("delete.error.parameter.ids.null", null, this.getThisLocale()));
      return dwzJson;
    }

    ServiceResult<Integer> result = settlementService.remove(new ServiceRequest(query, userAgent));
    if (result.getErrorNO() != null) {
      dwzJson =
          new DwzJson(
              "300",
              this.messageSource.getMessage(
                  result.getErrorInfo(), result.getMsgArgs(), this.getThisLocale()));
    } else {
      if (result.getDataObj() > 0) {
        dwzJson =
            new DwzJson(
                "200",
                this.messageSource.getMessage(
                    "operation.success", result.getMsgArgs(), this.getThisLocale()),
                StringUtils.isBlank(dwzId) ? "dwz_tab_settlement" : dwzId);
      } else {
        dwzJson =
            new DwzJson(
                "300",
                this.getMessageSource()
                    .getMessage("delete.error", result.getMsgArgs(), this.getThisLocale()));
      }
    }

    return dwzJson;
  }
Esempio n. 10
0
  /**
   * Initializes this object.
   *
   * @param key Property-key to use for locating initialization properties.
   * @param type Property-type to use for locating initialization properties.
   * @exception ProcessingException when initialization fails
   */
  public void initialize(String key, String type) throws ProcessingException {
    super.initialize(key, type);

    StringBuffer errorBuf = new StringBuffer();

    // serverName = getRequiredProperty(SERVER_NAME_PROP, errorBuf);

    headerLocation = getPropertyValue(NF_HEADER_LOCATION_PROP);

    isAsyncLocation = getPropertyValue(IS_ASYNCHRONOUS_LOCATION_PROP);

    orbAgentAddr = getPropertyValue(ORB_AGENT_ADDR_PROP);

    orbAgentPort = getPropertyValue(ORB_AGENT_PORT_PROP);

    orbAgentAddrLocation = getPropertyValue(ORB_AGENT_ADDR_PROP_LOCATION);

    orbAgentPortLocation = getPropertyValue(ORB_AGENT_PORT_PROP_LOCATION);

    if (!StringUtils.hasValue(isAsyncLocation)) {
      try {
        isAsync =
            StringUtils.getBoolean(
                (String) getRequiredPropertyValue(DEFAULT_IS_ASYNCHRONOUS_PROP, errorBuf));
      } catch (FrameworkException fe) {
        errorBuf.append(
            "No value is specified for either "
                + IS_ASYNCHRONOUS_LOCATION_PROP
                + "or"
                + DEFAULT_IS_ASYNCHRONOUS_PROP
                + ". One of the values should be present"
                + fe.getMessage());
      }
    }

    if (!StringUtils.hasValue(headerLocation)) {
      try {
        header = getRequiredPropertyValue(DEFAULT_HEADER_PROP, errorBuf);
      } catch (Exception e) {
        errorBuf.append(
            "No value is specified for "
                + NF_HEADER_LOCATION_PROP
                + "or"
                + DEFAULT_HEADER_PROP
                + ". One of the values should be present"
                + e.getMessage());
      }
    }

    if (errorBuf.length() > 0) throw new ProcessingException(errorBuf.toString());
  }
Esempio n. 11
0
  /**
   * Initialize the event queue.
   *
   * @param props A container of configuration properties.
   * @exception FrameworkException Thrown if configuration is invalid.
   */
  public void initialize(Map props) throws FrameworkException {
    String temp = (String) props.get(LOAD_EVENT_BATCH_SIZE_PROP);

    if (StringUtils.hasValue(temp)) {
      maxDatabaseEventLoadSize = StringUtils.getInteger(temp);

      if (Debug.isLevelEnabled(Debug.SYSTEM_CONFIG))
        Debug.log(
            Debug.SYSTEM_CONFIG,
            "QUEUE OPERATION: Initializing: Maximum-database-event-batch-load-size is ["
                + maxDatabaseEventLoadSize
                + "] rows.");
    }
  }
Esempio n. 12
0
  /**
   * This is done in a bit of a messy way, should be impossible to go out of sync with corresponding
   * GridPatternGroup.
   */
  public boolean hasEntryPoint(Cell cell, int entryPointId) {
    char c = get(cell);
    if (entryPointId == 1) {
      return StringUtils.isOneOf(c, entryPoints1);

    } else if (entryPointId == 2) {
      return StringUtils.isOneOf(c, entryPoints2);

    } else if (entryPointId == 3) {
      return StringUtils.isOneOf(c, entryPoints3);

    } else if (entryPointId == 4) {
      return StringUtils.isOneOf(c, entryPoints4);

    } else if (entryPointId == 5) {
      return StringUtils.isOneOf(c, entryPoints5);

    } else if (entryPointId == 6) {
      return StringUtils.isOneOf(c, entryPoints6);

    } else if (entryPointId == 7) {
      return StringUtils.isOneOf(c, entryPoints7);

    } else if (entryPointId == 8) {
      return StringUtils.isOneOf(c, entryPoints8);
    }
    return false;
  }
Esempio n. 13
0
  /**
   * Represents this <tt>FileElement</tt> in an XML.
   *
   * @see File#toXML()
   */
  @Override
  public String toXML() {
    StringBuilder buffer = new StringBuilder();

    buffer
        .append("<")
        .append(getElementName())
        .append(" xmlns=\"")
        .append(getNamespace())
        .append("\" ");

    if (getName() != null) {
      buffer.append("name=\"").append(StringUtils.escapeForXML(getName())).append("\" ");
    }

    if (getSize() > 0) {
      buffer.append("size=\"").append(getSize()).append("\" ");
    }

    if (getDate() != null) {
      buffer.append("date=\"").append(StringUtils.formatXEP0082Date(this.getDate())).append("\" ");
    }

    if (getHash() != null) {
      buffer.append("hash=\"").append(getHash()).append("\" ");
    }

    if ((this.getDesc() != null && getDesc().length() > 0) || isRanged() || thumbnail != null) {
      buffer.append(">");

      if (getDesc() != null && getDesc().length() > 0) {
        buffer.append("<desc>").append(StringUtils.escapeForXML(getDesc())).append("</desc>");
      }

      if (isRanged()) {
        buffer.append("<range/>");
      }

      if (thumbnail != null) {
        buffer.append(thumbnail.toXML());
      }

      buffer.append("</").append(getElementName()).append(">");
    } else {
      buffer.append("/>");
    }

    return buffer.toString();
  }
Esempio n. 14
0
  /**
   * Validate message payloads by comparing to a control message.
   *
   * @param receivedMessage
   * @param validationContext
   * @param context
   */
  protected void validateMessageContent(
      Message receivedMessage,
      Message controlMessage,
      XmlMessageValidationContext validationContext,
      TestContext context) {
    if (controlMessage == null || controlMessage.getPayload() == null) {
      log.info("Skip message payload validation as no control message was defined");
      return;
    }

    if (!(controlMessage.getPayload() instanceof String)) {
      throw new IllegalArgumentException(
          "DomXmlMessageValidator does only support message payload of type String, "
              + "but was "
              + controlMessage.getPayload().getClass());
    }

    String controlMessagePayload = controlMessage.getPayload(String.class);

    if (receivedMessage.getPayload() == null
        || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {
      Assert.isTrue(
          !StringUtils.hasText(controlMessagePayload),
          "Unable to validate message payload - received message payload was empty, control message payload is not");
      return;
    } else if (!StringUtils.hasText(controlMessagePayload)) {
      return;
    }

    log.info("Start XML tree validation ...");

    Document received = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));
    Document source = XMLUtils.parseMessagePayload(controlMessagePayload);

    XMLUtils.stripWhitespaceNodes(received);
    XMLUtils.stripWhitespaceNodes(source);

    if (log.isDebugEnabled()) {
      log.debug("Received message:\n" + XMLUtils.serialize(received));
      log.debug("Control message:\n" + XMLUtils.serialize(source));
    }

    validateXmlTree(
        received,
        source,
        validationContext,
        namespaceContextBuilder.buildContext(receivedMessage, validationContext.getNamespaces()),
        context);
  }
Esempio n. 15
0
  private void handleMuteIq(MuteIq muteIq) {
    Boolean doMute = muteIq.getMute();
    String jid = muteIq.getJid();

    if (doMute == null || StringUtils.isNullOrEmpty(jid)) return;

    String from = muteIq.getFrom();
    JitsiMeetConference conference = getConferenceForMucJid(from);
    if (conference == null) {
      logger.debug("Mute error: room not found for JID: " + from);
      return;
    }

    IQ result;

    if (conference.handleMuteRequest(muteIq.getFrom(), jid, doMute)) {
      result = IQ.createResultIQ(muteIq);

      if (!muteIq.getFrom().equals(jid)) {
        MuteIq muteStatusUpdate = new MuteIq();
        muteStatusUpdate.setType(IQ.Type.SET);
        muteStatusUpdate.setTo(jid);

        muteStatusUpdate.setMute(doMute);

        smackXmpp.getXmppConnection().sendPacket(muteStatusUpdate);
      }
    } else {
      result =
          IQ.createErrorResponse(muteIq, new XMPPError(XMPPError.Condition.interna_server_error));
    }

    smackXmpp.getXmppConnection().sendPacket(result);
  }
Esempio n. 16
0
  private void fixTabs(int tabSize) {

    int rowIndex = 0;

    for (StringBuilder row1 : rows) {
      String row = row1.toString();
      StringBuilder newRow = new StringBuilder();

      char[] chars = row.toCharArray();
      for (char c : chars) {
        if (c == '\t') {
          int spacesLeft = tabSize - newRow.length() % tabSize;
          if (DEBUG) {
            System.out.println("Found tab. Spaces left: " + spacesLeft);
          }
          String spaces = StringUtils.repeatString(" ", spacesLeft);
          newRow.append(spaces);
        } else {
          String character = Character.toString(c);
          newRow.append(character);
        }
      }
      rows.set(rowIndex, newRow);
      rowIndex++;
    }
  }
Esempio n. 17
0
 private static int compareNodes(Sortable node1, Sortable node2) {
   int result = node1.getNodeWeight() - node2.getNodeWeight();
   if (0 == result) {
     result = StringUtils.stringCompare(node1.getText(), node2.getText());
   }
   return result;
 }
 @Override
 public void init() {
   String rolesPropertyValue = getContext().getProperty(ROLES);
   if (rolesPropertyValue != null) {
     this.roles = StringUtils.commaDelimitedListToStringArray(rolesPropertyValue);
   }
 }
Esempio n. 19
0
  /**
   * Checks whether the given node contains a validation matcher
   *
   * @param node
   * @return true if node value contains validation matcher, false if not
   */
  private boolean isValidationMatcherExpression(Node node) {
    switch (node.getNodeType()) {
      case Node.ELEMENT_NODE:
        return node.getFirstChild() != null
            && StringUtils.hasText(node.getFirstChild().getNodeValue())
            && ValidationMatcherUtils.isValidationMatcherExpression(
                node.getFirstChild().getNodeValue().trim());

      case Node.ATTRIBUTE_NODE:
        return StringUtils.hasText(node.getNodeValue())
            && ValidationMatcherUtils.isValidationMatcherExpression(node.getNodeValue().trim());

      default:
        return false; // validation matchers makes no sense
    }
  }
Esempio n. 20
0
 public String toString() {
   if (mAtomicParts == null) {
     return super.toString();
   } else {
     return StringUtils.collectionToString(mAtomicParts, " ");
   }
 }
Esempio n. 21
0
  /**
   * @param queryString a query string of the form n1=v1&n2=v2&... to decode. May be null.
   * @param acceptAmp -> "&amp;" if true, "&" if false
   * @return a Map of String[] indexed by name, an empty Map if the query string was null
   */
  public static Map<String, String[]> decodeQueryString(
      final CharSequence queryString, final boolean acceptAmp) {

    final Map<String, String[]> result = new TreeMap<String, String[]>();
    if (queryString != null) {
      final Matcher matcher =
          acceptAmp ? PATTERN_AMP.matcher(queryString) : PATTERN_NO_AMP.matcher(queryString);
      int matcherEnd = 0;
      while (matcher.find()) {
        matcherEnd = matcher.end();
        try {
          // Group 0 is the whole match, e.g. a=b, while group 1 is the first group
          // denoted ( with parens ) in the expression.  Hence we start with group 1.
          final String name =
              URLDecoder.decode(matcher.group(1), NetUtils.STANDARD_PARAMETER_ENCODING);
          final String value =
              URLDecoder.decode(matcher.group(2), NetUtils.STANDARD_PARAMETER_ENCODING);

          StringUtils.addValueToStringArrayMap(result, name, value);
        } catch (UnsupportedEncodingException e) {
          // Should not happen as we are using a required encoding
          throw new OXFException(e);
        }
      }
      if (queryString.length() != matcherEnd) {
        // There was garbage at the end of the query.
        throw new OXFException("Malformed URL: " + queryString);
      }
    }
    return result;
  }
Esempio n. 22
0
  @RequestMapping(value = "/user", method = RequestMethod.PUT)
  @Transactional
  public ResponseEntity<Client> doIt(@RequestBody Client client, Authentication authentication) {

    List<String> errors = DomainValidator.checkForErrors(client);
    if (!errors.isEmpty()) {
      return new ResponseEntity<Client>(new Client(client, errors), HttpStatus.BAD_REQUEST);
    }
    HttpStatus status = null;

    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("USER"));

    if (ApplicationSecurity.isRoot(authentication)) {
      if (ApplicationSecurity.isRoot(client.getUsername())) {
        return new ResponseEntity<Client>(
            new Client(client, cannotChangeRootPassword), HttpStatus.BAD_REQUEST);
      }
      status = upsert(client, authorities);

    } else if (StringUtils.equals(client.getUsername(), authentication.getName())) {
      if (!userDetailsManager.userExists(client.getUsername())) {
        return new ResponseEntity<Client>(new Client(client, mustBeRoot), HttpStatus.BAD_REQUEST);
      }
      User user = new User(client.getUsername(), client.getPassword(), authorities);
      userDetailsManager.updateUser(user);
      status = HttpStatus.OK;

    } else {
      return new ResponseEntity<Client>(HttpStatus.FORBIDDEN);
    }

    return new ResponseEntity<Client>(new Client(client), status);
  }
Esempio n. 23
0
  public boolean moveToGroup(String group) {
    String currentParent = Group.substractParentName(getName());
    if (group.equals(currentParent)) return false;

    // String oldName = getName();
    String newName;
    if (group.equals(nullString)) newName = Group.substractObjectName(getName());
    else newName = group + Constants.GROUP_SEPARATOR + Group.substractObjectName(getName());

    // object with new name already exists, add suffix // !!!
    Object obj;
    boolean renameNeeded = false;
    while ((obj = Group.getRoot().findObject(newName, true)) != null) {
      if (obj == this) // it's me :) already moved, fix data
      {
        name = newName;
        return true;
      } else {
        renameNeeded = true;
        newName = StringUtils.incrementName(newName, Constants.MOVE_SUFFIX);
      }
    }

    if (renameNeeded) return rename(newName);

    getParent().removeObject(Group.substractObjectName(getName()));
    setParent(null);
    Group.getRoot().addSubObject(newName, this, true);

    name = newName;
    unconditionalValidation();

    return true;
  }
Esempio n. 24
0
  public Flexible copyToGroup(String group) {

    String newName;
    if (group.equals(nullString)) newName = Group.substractObjectName(getName());
    else newName = group + Constants.GROUP_SEPARATOR + Group.substractObjectName(getName());

    // object with new name already exists, add suffix ///!!!
    while (Group.getRoot().findObject(newName, true) != null)
      newName = StringUtils.incrementName(newName, Constants.COPY_SUFFIX);

    Box grBox =
        new Box(
            newName,
            null,
            startVertex.getX(),
            startVertex.getY(),
            endVertex.getX(),
            endVertex.getY());
    grBox.setColor(getColor());
    Group.getRoot().addSubObject(newName, grBox, true);

    // ViewState view = ViewState.getInstance();
    // grBox.move(20 - view.getRx(), 20 - view.getRy());

    unconditionalValidation();
    return grBox;
  }
  private java.sql.Connection connectLoadBalanced(String url, Properties info) throws SQLException {
    Properties parsedProps = parseURL(url, info);

    if (parsedProps == null) {
      return null;
    }

    String hostValues = parsedProps.getProperty(HOST_PROPERTY_KEY);

    List hostList = null;

    if (hostValues != null) {
      hostList = StringUtils.split(hostValues, ",", true);
    }

    if (hostList == null) {
      hostList = new ArrayList();
      hostList.add("localhost:3306");
    }

    LoadBalancingConnectionProxy proxyBal = new LoadBalancingConnectionProxy(hostList, parsedProps);

    return (java.sql.Connection)
        java.lang.reflect.Proxy.newProxyInstance(
            this.getClass().getClassLoader(), new Class[] {java.sql.Connection.class}, proxyBal);
  }
Esempio n. 26
0
  private void handleRayoIQ(RayoIqProvider.DialIq dialIq) {
    String from = dialIq.getFrom();

    JitsiMeetConference conference = getConferenceForMucJid(from);

    if (conference == null) {
      logger.debug("Mute error: room not found for JID: " + from);
      return;
    }

    ChatRoomMemberRole role = conference.getRoleForMucJid(from);

    if (role == null) {
      // Only room members are allowed to send requests
      IQ error = createErrorResponse(dialIq, new XMPPError(XMPPError.Condition.forbidden));

      smackXmpp.getXmppConnection().sendPacket(error);

      return;
    }

    if (ChatRoomMemberRole.MODERATOR.compareTo(role) < 0) {
      // Moderator permission is required
      IQ error = createErrorResponse(dialIq, new XMPPError(XMPPError.Condition.not_allowed));

      smackXmpp.getXmppConnection().sendPacket(error);

      return;
    }

    // Check if Jigasi is available
    String jigasiJid = conference.getServices().getSipGateway();

    if (StringUtils.isNullOrEmpty(jigasiJid)) {
      // Not available
      IQ error =
          createErrorResponse(dialIq, new XMPPError(XMPPError.Condition.service_unavailable));

      smackXmpp.getXmppConnection().sendPacket(error);

      return;
    }

    // Redirect original request to Jigasi component
    String originalPacketId = dialIq.getPacketID();

    dialIq.setFrom(null);
    dialIq.setTo(jigasiJid);
    dialIq.setPacketID(IQ.nextID());

    IQ reply = (IQ) smackXmpp.getXmppConnection().sendPacketAndGetReply(dialIq);

    // Send Jigasi response back to the client
    reply.setFrom(null);
    reply.setTo(from);
    reply.setPacketID(originalPacketId);

    smackXmpp.getXmppConnection().sendPacket(reply);
  }
Esempio n. 27
0
  /**
   * Initializes the Splitter.
   *
   * @param key Property-key to use for locating initialization properties.
   * @param type Property-type to use for locating initialization properties.
   * @exception ProcessingException when initialization fails
   */
  public void initialize(String key, String type) throws ProcessingException {

    // Call the abstract super class's initialize method. This initializes
    // the adapterProperties hashtable defined in the super class and
    // retrieves the name and toProcessorNames values from the properties.
    super.initialize(key, type);

    if (Debug.isLevelEnabled(Debug.OBJECT_LIFECYCLE))
      Debug.log(Debug.OBJECT_LIFECYCLE, "Splitter: Initializing.....");

    StringBuffer errorBuffer = new StringBuffer();
    truncHeaderFooter = getRequiredPropertyValue(TRUNCATE_HEADER_FOOTER_PROP, errorBuffer);

    if (Debug.isLevelEnabled(Debug.MSG_DATA))
      Debug.log(Debug.MSG_DATA, "Splitter: truncHeaderFooter? ---->" + truncHeaderFooter);

    String temp = getPropertyValue(FILE_SEPARATOR_PROP);
    if (StringUtils.hasValue(temp)) {
      fileSeparator = StringUtils.replaceSubstrings(temp, "\\r", "\r");
      fileSeparator = StringUtils.replaceSubstrings(fileSeparator, "\\n", "\n");
      if (Debug.isLevelEnabled(Debug.MSG_DATA))
        Debug.log(Debug.MSG_DATA, "Splitter: fileSeparator---->" + fileSeparator);
    }

    try {
      splitLength = Integer.parseInt(getRequiredPropertyValue(SPLIT_LENGTH_PROP, errorBuffer));

      if (Debug.isLevelEnabled(Debug.MSG_DATA))
        Debug.log(Debug.MSG_DATA, "Splitter: splitLength---->" + splitLength);
    } catch (NumberFormatException nx) {
      throw new ProcessingException("ERROR: Splitter: The SPLIT_LENGTH " + "must be a number.");
    }

    if (splitLength <= 0) {
      throw new ProcessingException(
          "ERROR: Splitter: The SPLIT_LENGTH " + "must be greater than zero.");
    }

    if (errorBuffer.length() > 0) {
      String errMsg = errorBuffer.toString();

      Debug.log(Debug.ALL_ERRORS, errMsg);

      throw new ProcessingException(errMsg);
    }
  }
Esempio n. 28
0
  /**
   * Creates query for the given <tt>searchString</tt>.
   *
   * @param queryString the string to search for
   * @param contactCount the maximum count of result contacts
   * @return the created query
   */
  @Override
  public ContactQuery createContactQuery(String queryString, int contactCount) {
    if (!StringUtils.isNullOrEmpty(queryString)) return null;

    recentQuery = new MessageSourceContactQuery(MessageSourceService.this);

    return recentQuery;
  }
Esempio n. 29
0
 public boolean isBoundary(Cell cell) {
   char c = get(cell.x, cell.y);
   if (0 == c) return false;
   if ('+' == c || '\\' == c || '/' == c) {
     return isIntersection(cell) || isCorner(cell) || isStub(cell) || isCrossOnLine(cell);
   }
   return StringUtils.isOneOf(c, boundaries) && !isLoneDiagonal(cell);
 }
Esempio n. 30
0
 public void removeMarkupTags() {
   for (CellTagPair pair : findMarkupTags()) {
     String tagName = pair.tag;
     if (tagName == null) continue;
     int length = 2 + tagName.length();
     writeStringTo(pair.cell, StringUtils.repeatString(" ", length));
   }
 }