Beispiel #1
1
 /** @param defaultpath The path to change the working directory to upon connecting */
 public void setDefaultPath(String defaultpath) {
   this.defaultpath =
       StringUtils.isBlank(defaultpath)
           ? null
           : StringUtils.remove(StringUtils.remove(defaultpath, CharUtils.LF), CharUtils.CR)
               .trim();
 }
Beispiel #2
0
 private String removeNewLineCharacters(String text) {
   String removedCRLF = StringUtils.remove(text, "\n");
   removedCRLF = StringUtils.remove(removedCRLF, "\r");
   removedCRLF = StringUtils.remove(removedCRLF, "\n\r");
   removedCRLF = StringUtils.remove(removedCRLF, "\r\n");
   return removedCRLF;
 }
  public static void onChat(AsyncPlayerChatEvent e) {
    Player p = e.getPlayer();
    if (gunBuilder.get(p) == true) {
      if (gunBuilderStep.get(p) == 3) {
        e.setCancelled(true);
        // String Name = StringUtils.remove(e.getMessage(), ' ');
        GName.put(p, e.getMessage());
        p.sendMessage(" §f» §8Set gun name to§7 " + e.getMessage());
        p.sendMessage("§24. §aNow type the name of the ammo in the chat");
        gunBuilderStep.put(p, 4);
      } else if (gunBuilderStep.get(p) == 4) {
        e.setCancelled(true);
        // String Name = StringUtils.remove(e.getMessage(), ' ');
        AName.put(p, e.getMessage());
        p.sendMessage(" §f» §8Set ammo name to§7 " + e.getMessage());
        p.sendMessage("§25. §aNow type the cost of the gun in the chat");
        gunBuilderStep.put(p, 5);
      } else if (gunBuilderStep.get(p) == 5) {
        e.setCancelled(true);
        Integer cost = 0;
        try {
          String message = StringUtils.remove(e.getMessage(), ' ');
          cost = Integer.parseInt(message);
        } catch (NumberFormatException exeption) {
          p.sendMessage("§cGun cost must be a valid number. Try again");
          return;
        }

        gunCost.put(p, cost);
        p.sendMessage(" §f» §8Set gun cost to§7 " + cost);
        p.sendMessage("§26. §aNow type the level at which the gun will be unlocked in the chat");
        gunBuilderStep.put(p, 6);
      } else if (gunBuilderStep.get(p) == 6) {
        e.setCancelled(true);
        Integer level = 0;
        try {
          String message = StringUtils.remove(e.getMessage(), ' ');
          level = Integer.parseInt(message);
        } catch (NumberFormatException exception) {
          p.sendMessage("§cUnlock level must be a valid number. Try again");
          return;
        }

        LevelUnlock.put(p, level);
        p.sendMessage(" §f» §8Set gun level unlock to §7 " + level);
        p.sendMessage(
            "§27. §aNow right-click the red wool in your inventory to make the gun primary, or right-click the green wool in you inventory to make the gun secondary");
        gunBuilderStep.put(p, 7);

        inventory.put(p, p.getInventory().getContents());
        p.getInventory().clear();
        p.getInventory().setItem(1, primary);
        p.getInventory().setItem(7, secondary);
        p.getInventory().setHeldItemSlot(4);
      }
    }
  }
Beispiel #4
0
  /**
   * @see
   *     org.kuali.ole.sys.batch.BatchInputFileType#getFileName(org.kuali.rice.kim.api.identity.Person,
   *     java.lang.Object, java.lang.String)
   */
  public String getFileName(
      String principalName, Object parsedFileContents, String fileUserIdentifer) {
    Timestamp currentTimestamp = dateTimeService.getCurrentTimestamp();

    String fileName = PdpConstants.PDP_FILE_UPLOAD_FILE_PREFIX + "_" + principalName;
    if (StringUtils.isNotBlank(fileUserIdentifer)) {
      fileName += "_" + StringUtils.remove(fileUserIdentifer, " ");
    }
    fileName += "_" + dateTimeService.toString(currentTimestamp, "yyyyMMdd_HHmmss");

    // remove spaces in filename
    fileName = StringUtils.remove(fileName, " ");

    return fileName;
  }
  @EventHandler
  public void onAsyncChat(AsyncPlayerChatEvent event) {
    String message = event.getMessage();
    Player player = event.getPlayer();
    // Chat commands start with a '!' delimiter, so check if it's a chat command
    if (message.startsWith("!")) {
      event.setCancelled(true);
      String command = message;
      String[] args = PATTERN_ON_SPACE.split(message);
      if (args.length > 0) {
        command = args[0];
        try {
          args = Arrays_copyOfRange(args, 1, args.length);
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }

      command = StringUtils.remove(command, "!");
      if (ChatCommand.isValidCommand(command)) {
        ChatCommand chatCommand = ChatCommand.getCommand(command);
        int argsRequired = chatCommand.getMinArgs();
        if (args.length >= argsRequired) {
          chatCommand.doCommand(player, args);
        } else {
          Players.sendMessage(
              player, GameMessages.INSUFFICIENT_CHAT_COMMAND_ARGUMENTS(command, argsRequired));
        }
      } else {
        Players.sendMessage(player, GameMessages.INVALID_CHAT_COMMAND(command));
      }
    }
  }
 public static String stripMobilePhoneNumber(String phone) {
   phone = StringUtils.trimToEmpty(phone);
   phone = StringUtils.remove(phone, " ");
   return phone.length() > MOBILE_PHONE_NUMBER_LENGTH
       ? StringUtils.right(phone, MOBILE_PHONE_NUMBER_LENGTH)
       : phone;
 }
Beispiel #7
0
 public static String getKeyword(String url) {
   String keywordReg =
       "(?:yahoo.+?[\\?|&]q=|openfind.+?q=|google.+?q=|lycos.+?query=|onseek.+?keyword=|search\\.tom.+?word=|search\\.qq\\.com.+?word=|zhongsou\\.com.+?word=|search\\.msn\\.com.+?q=|yisou\\.com.+?p=|sina.+?word=|sina.+?query=|sina.+?_searchkey=|sohu.+?word=|sohu.+?key_word=|sohu.+?query=|163.+?q=|baidu.+?wd=|soso.+?w=|3721\\.com.+?p=|Alltheweb.+?q=)([^&]*)";
   String encodeReg =
       "^(?:[\\x00-\\x7f]|[\\xfc-\\xff][\\x80-\\xbf]{5}|[\\xf8-\\xfb][\\x80-\\xbf]{4}|[\\xf0-\\xf7][\\x80-\\xbf]{3}|[\\xe0-\\xef][\\x80-\\xbf]{2}|[\\xc0-\\xdf][\\x80-\\xbf])+$";
   Pattern keywordPattern = Pattern.compile(keywordReg);
   StringBuffer keywordBuff = new StringBuffer(20);
   Matcher keywordMat = keywordPattern.matcher(url);
   while (keywordMat.find()) {
     keywordMat.appendReplacement(keywordBuff, "$1");
   }
   String keyword = keywordBuff.toString();
   if (StringUtils.isNotBlank(keyword.toString())) {
     keyword = StringUtils.remove(keyword, keyword.substring(0, keyword.indexOf(".") + 1));
     Pattern encodePatt = Pattern.compile(encodeReg);
     String unescapeString = ParseURLKeyword.unescape(keyword);
     Matcher encodeMat = encodePatt.matcher(unescapeString);
     String encode = "gbk";
     if (encodeMat.matches()) encode = "utf-8";
     try {
       return URLDecoder.decode(keyword, encode);
     } catch (UnsupportedEncodingException e) {
       return "";
     }
   }
   return "";
 }
  /**
   * Changes from/to dates into the range operators the lookupable dao expects ("..",">" etc) this
   * method modifies the passed in map and returns an updated search criteria map
   *
   * @param searchCriteria - map of criteria currently set for which the date criteria will be
   *     adjusted
   * @return map updated search criteria
   */
  public static Map<String, String> preprocessDateFields(Map<String, String> searchCriteria) {
    Map<String, String> fieldsToUpdate = new HashMap<String, String>();
    Map<String, String> searchCriteriaUpdated = new HashMap<String, String>(searchCriteria);
    Set<String> fieldsForLookup = searchCriteria.keySet();
    for (String propName : fieldsForLookup) {
      if (propName.startsWith(KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX)) {
        String from_DateValue = searchCriteria.get(propName);
        String dateFieldName =
            StringUtils.remove(propName, KRADConstants.LOOKUP_RANGE_LOWER_BOUND_PROPERTY_PREFIX);
        String to_DateValue = searchCriteria.get(dateFieldName);
        String newPropValue = to_DateValue; // maybe clean above with
        // ObjectUtils.clean(propertyValue)
        if (StringUtils.isNotEmpty(from_DateValue) && StringUtils.isNotEmpty(to_DateValue)) {
          newPropValue = from_DateValue + SearchOperator.BETWEEN + to_DateValue;
        } else if (StringUtils.isNotEmpty(from_DateValue) && StringUtils.isEmpty(to_DateValue)) {
          newPropValue = SearchOperator.GREATER_THAN_EQUAL.op() + from_DateValue;
        } else if (StringUtils.isNotEmpty(to_DateValue) && StringUtils.isEmpty(from_DateValue)) {
          newPropValue = SearchOperator.LESS_THAN_EQUAL.op() + to_DateValue;
        } // could optionally continue on else here

        fieldsToUpdate.put(dateFieldName, newPropValue);
      }
    }

    // update lookup values from found date values to update
    Set<String> keysToUpdate = fieldsToUpdate.keySet();
    for (String updateKey : keysToUpdate) {
      searchCriteriaUpdated.put(updateKey, fieldsToUpdate.get(updateKey));
    }

    return searchCriteriaUpdated;
  }
  /**
   * Returns the display string for the supplied uid
   *
   * @param uid
   * @return a user friendly display name for this UID
   */
  public String getUidDisplayString(String fieldName, String uid, boolean includeField) {

    uid = stripEscapedQuotes(uid);

    // get the information from the collections cache
    if (uid.startsWith("in") && collectionCache.getInstitutions().containsKey(uid)) {
      if (includeField) return "Institution: " + collectionCache.getInstitutions().get(uid);
      else return collectionCache.getInstitutions().get(uid);
    } else if (uid.startsWith("co") && collectionCache.getCollections().containsKey(uid)) {
      if (includeField) return "Collection: " + collectionCache.getCollections().get(uid);
      else return collectionCache.getCollections().get(uid);
    } else if (uid.startsWith("drt") && collectionCache.getTempDataResources().containsKey(uid)) {
      if (includeField)
        return "Temporary Data resource: " + collectionCache.getTempDataResources().get(uid);
      else return collectionCache.getTempDataResources().get(uid);
    } else if (uid.startsWith("dr") && collectionCache.getDataResources().containsKey(uid)) {
      if (includeField) return "Data resource: " + collectionCache.getDataResources().get(uid);
      else return collectionCache.getDataResources().get(uid);
    } else if (uid.startsWith("dp") && collectionCache.getDataProviders().containsKey(uid)) {
      if (includeField) return "Data provider: " + collectionCache.getDataProviders().get(uid);
      else return collectionCache.getDataProviders().get(uid);
    } else if (uid.startsWith("dh") && collectionCache.getDataHubs().containsKey(uid)) {
      if (includeField) return "Data hub: " + collectionCache.getDataHubs().get(uid);
      else return collectionCache.getDataHubs().get(uid);
    }
    return messageSource.getMessage(
        fieldName + "." + StringUtils.remove(uid, "\""), null, uid, null);
  }
Beispiel #10
0
  /**
   * Parses a {@link SimpleConcept} from a String
   *
   * @param concept
   * @return
   * @author jmayaalv
   */
  public static SimpleConcept parse(String concept) {
    if (StringUtils.isBlank(concept)) {
      return null;
    }

    concept = StringUtils.trim(concept);
    if ((StringUtils.countMatches(concept, "(") == (StringUtils.countMatches(concept, ")")))
        && StringUtils.startsWith(concept, "(")
        && StringUtils.endsWith(concept, ")")) {
      concept = StringUtils.substring(concept, 1, concept.length() - 1);
    }

    boolean negated = false;
    if (concept.startsWith(".NO")) {
      negated = true;
      concept = StringUtils.remove(concept, ".NO");
      concept = StringUtils.trim(concept);
    }

    if (StringUtils.isBlank(concept)) {
      throw new RuntimeException("Concept can't be parsed: " + concept);
    }

    if ((StringUtils.countMatches(concept, "(") == (StringUtils.countMatches(concept, ")")))
        && StringUtils.startsWith(concept, "(")
        && StringUtils.endsWith(concept, ")")) {
      concept = StringUtils.substring(concept, 1, concept.length() - 1);
    }

    if (StringUtils.contains(concept, " ")) {
      return null; // not a SimpleConcep
    }

    return new SimpleConcept(Integer.parseInt(concept), negated);
  }
  public static Fqn<String> constructJcrQueryFQN(String jcrQuery, CacheRegion cacheRegion) {

    // replace all '/'  and spaces with empty string
    String jcrQueryWithoutForwardSlashes = StringUtils.remove(jcrQuery, CmsConstants.FORWARD_SLASH);

    if (cacheRegion == null) {
      cacheRegion = CmsCriteria.DEFAULT_CACHE_REGION;
    }

    // Create  Cache Region FQN
    Fqn<String> cacheRegionFqn =
        Fqn.fromRelativeElements(JCR_QUERY_NODE_FQN, cacheRegion.getRegionName());

    // Create FQN for authentication token
    String authenticationToken = AstroboaClientContextHolder.getActiveAuthenticationToken();

    if (authenticationToken == null) {
      throw new CmsException(
          "No active authenticationToken found. Could not construct appropriate FQN for query "
              + jcrQuery);
    }

    Fqn<String> autheticationTokenFqn =
        Fqn.fromRelativeElements(cacheRegionFqn, authenticationToken);

    return Fqn.fromRelativeElements(
        autheticationTokenFqn, StringUtils.deleteWhitespace(jcrQueryWithoutForwardSlashes));
  }
  private void assertCodecConfigurationForModel(CodecGroupType codecGroup, String phoneModelId)
      throws Exception {

    // Initialize the phone.
    m_phone = new PolycomPhone();
    m_phone.setModel(phoneModelBuilder(phoneModelId, getClass()));
    PhoneTestDriver.supplyTestData(m_phone, new LinkedList<User>());

    // Each model belongs to exactly one codec group.
    Collection<Setting> codecPref = m_phone.getSettings().getSetting("voice/codecPref").getValues();
    assertTrue(
        String.format("The '%s' model does not have a codec group.", phoneModelId),
        0 != codecPref.size());
    String str_groups = "";
    for (Setting s : codecPref) {
      str_groups += "-" + s.getName();
    }
    assertEquals(
        String.format(
            "The '%s' model has more than one codec group ('%s'):", phoneModelId, str_groups),
        1,
        codecPref.size());

    // Make sure it's the correct codec group.
    Setting codec_adaptor = codecPref.iterator().next();
    assertEquals(
        String.format("The '%s' model has the wrong codec group:", phoneModelId),
        codecGroup.toString(),
        codec_adaptor.getName());

    // Collect the major types of the supported codec options.  (Remove the minor bit/sample rates.)
    HashSet<String> major_supported_codecs = new HashSet<String>();
    Collection<String> options = ((MultiEnumSetting) codec_adaptor.getType()).getEnums().values();
    for (String option : options) {
      int i = option.indexOf('.');
      if (-1 != i) {
        option = option.substring(0, i);
      }
      major_supported_codecs.add(StringUtils.remove(option, "_"));
    }

    // Loop though the audioProfiles for the model.  There should be one for major supported codec
    // type.
    Collection<Setting> audioProfile =
        m_phone.getSettings().getSetting("voice/audioProfile").getValues();
    for (Setting s : audioProfile) {
      assertTrue(
          String.format(
              "The '%s' model has an audioProfile for unsupported codec type '%s'.",
              phoneModelId, s.getName()),
          major_supported_codecs.remove(s.getName()));
    }
    assertEquals(
        String.format(
            "The '%s' model is missing an audioProfile for the following supported code type(s): %s.",
            phoneModelId, major_supported_codecs),
        0,
        major_supported_codecs.size());
  }
Beispiel #13
0
 /** Clean up HTML tags to make them XHTML compliant (lowercase, no unnecessary spaces). */
 protected static String sanitizeHtmlTag(String tag) {
   String result = tag.trim();
   result = StringUtils.remove(result, " ").toLowerCase();
   if (result.endsWith("/>")) {
     // spaces were stripped, so make sure tag is of the form "<br />"
     result = result.substring(0, result.length() - 2) + " />";
   }
   return result;
 }
 @Override
 public void visitNode(Tree tree) {
   ClassPropertyDeclarationTree property = (ClassPropertyDeclarationTree) tree;
   for (VariableDeclarationTree variableDeclarationTree : property.declarations()) {
     String propertyName = variableDeclarationTree.identifier().text();
     if (!pattern.matcher(StringUtils.remove(propertyName, "$")).matches()) {
       context().newIssue(this, String.format(MESSAGE, propertyName, format)).tree(property);
     }
   }
 }
  @Override
  public String getRequestURI() {
    final String originalRequestURI = super.getRequestURI();
    final String tempRequestURI = StringUtils.remove(originalRequestURI, super.getContextPath());

    if (StringUtils.isEmpty(tempRequestURI) || StringUtils.containsOnly(tempRequestURI, "/")) {
      return "/";
    }
    return originalRequestURI;
  }
  int calculateNextStart(
      final String oldOutputID, final String newOutputID, final int start, final String[] outputs) {

    if (outputs == null || outputs.length == 0) {
      // Use OutputID change to determine if logger changed, and reset start line if needed.
      if (newOutputID == null || newOutputID.equals(oldOutputID)) {
        return start;
      } else {
        return 0;
      }
    }
    final String firstLine = outputs[0];
    if (firstLine.startsWith("Skipped") && firstLine.endsWith("lines")) {
      final String skippedLines =
          StringUtils.remove(StringUtils.remove(firstLine, "Skipped"), "lines").trim();
      return start + Integer.parseInt(skippedLines) + outputs.length - 1;
    }
    return start + outputs.length;
  }
Beispiel #17
0
 public static String getDefaultDialect(String propPrefix, String driver) {
   String dialect = null;
   if (propPrefix.isEmpty()) {
     dialect = Play.configuration.getProperty("db.jpa.dialect");
   } else {
     propPrefix = StringUtils.remove(propPrefix, '.');
     dialect = Play.configuration.getProperty(propPrefix + ".jpa.dialect");
   }
   if (dialect != null) {
     return dialect;
   } else if ("org.h2.Driver".equals(driver)) {
     return "org.hibernate.dialect.H2Dialect";
   } else if ("org.hsqldb.jdbcDriver".equals(driver)) {
     return "org.hibernate.dialect.HSQLDialect";
   } else if ("com.mysql.jdbc.Driver".equals(driver)) {
     return "play.db.jpa.MySQLDialect";
   } else if ("org.postgresql.Driver".equals(driver)) {
     return "org.hibernate.dialect.PostgreSQLDialect";
   } else if ("com.ibm.db2.jdbc.app.DB2Driver".equals(driver)) {
     return "org.hibernate.dialect.DB2Dialect";
   } else if ("com.ibm.as400.access.AS400JDBCDriver".equals(driver)) {
     return "org.hibernate.dialect.DB2400Dialect";
   } else if ("com.ibm.as400.access.AS390JDBCDriver".equals(driver)) {
     return "org.hibernate.dialect.DB2390Dialect";
   } else if ("oracle.jdbc.OracleDriver".equals(driver)) {
     return "org.hibernate.dialect.Oracle10gDialect";
   } else if ("com.sybase.jdbc2.jdbc.SybDriver".equals(driver)) {
     return "org.hibernate.dialect.SybaseAnywhereDialect";
   } else if ("com.microsoft.jdbc.sqlserver.SQLServerDriver".equals(driver)) {
     return "org.hibernate.dialect.SQLServerDialect";
   } else if ("com.sap.dbtech.jdbc.DriverSapDB".equals(driver)) {
     return "org.hibernate.dialect.SAPDBDialect";
   } else if ("com.informix.jdbc.IfxDriver".equals(driver)) {
     return "org.hibernate.dialect.InformixDialect";
   } else if ("com.ingres.jdbc.IngresDriver".equals(driver)) {
     return "org.hibernate.dialect.IngresDialect";
   } else if ("progress.sql.jdbc.JdbcProgressDriver".equals(driver)) {
     return "org.hibernate.dialect.ProgressDialect";
   } else if ("com.mckoi.JDBCDriver".equals(driver)) {
     return "org.hibernate.dialect.MckoiDialect";
   } else if ("InterBase.interclient.Driver".equals(driver)) {
     return "org.hibernate.dialect.InterbaseDialect";
   } else if ("com.pointbase.jdbc.jdbcUniversalDriver".equals(driver)) {
     return "org.hibernate.dialect.PointbaseDialect";
   } else if ("com.frontbase.jdbc.FBJDriver".equals(driver)) {
     return "org.hibernate.dialect.FrontbaseDialect";
   } else if ("org.firebirdsql.jdbc.FBDriver".equals(driver)) {
     return "org.hibernate.dialect.FirebirdDialect";
   } else {
     throw new UnsupportedOperationException(
         "I do not know which hibernate dialect to use with "
             + driver
             + " and I cannot guess it, use the property jpa.dialect in config file");
   }
 }
  protected void collectExpectedIssues(String comment, int line) {
    String expectedStart = getExpectedIssueTrigger();
    if (comment.startsWith(expectedStart)) {
      String cleanedComment = StringUtils.remove(comment, expectedStart);

      EnumMap<IssueAttribute, String> attr = new EnumMap<>(IssueAttribute.class);
      String expectedMessage = StringUtils.substringBetween(cleanedComment, "{{", "}}");
      if (StringUtils.isNotEmpty(expectedMessage)) {
        attr.put(IssueAttribute.MESSAGE, expectedMessage);
      }
      int expectedLine = line;
      String attributesSubstr = extractAttributes(comment, attr);

      cleanedComment =
          StringUtils.stripEnd(
              StringUtils.remove(
                  StringUtils.remove(cleanedComment, "[[" + attributesSubstr + "]]"),
                  "{{" + expectedMessage + "}}"),
              " \t");
      if (StringUtils.startsWith(cleanedComment, "@")) {
        final int lineAdjustment;
        final char firstChar = cleanedComment.charAt(1);
        final int endIndex = cleanedComment.indexOf(' ');
        if (endIndex == -1) {
          lineAdjustment = Integer.parseInt(cleanedComment.substring(2));
        } else {
          lineAdjustment = Integer.parseInt(cleanedComment.substring(2, endIndex));
        }
        if (firstChar == '+') {
          expectedLine += lineAdjustment;
        } else if (firstChar == '-') {
          expectedLine -= lineAdjustment;
        } else {
          Fail.fail("Use only '@+N' or '@-N' to shifts messages.");
        }
      }
      updateEndLine(expectedLine, attr);
      expected.put(expectedLine, attr);
    }
  }
Beispiel #19
0
 /**
  * Return a list of WikiDiff objects that can be used to create a display of the diff content.
  *
  * @param newVersion The String that is to be compared to, ie the later version of a topic.
  * @param oldVersion The String that is to be considered as having changed, ie the earlier version
  *     of a topic.
  * @return Returns a list of WikiDiff objects that correspond to the changed text.
  */
 public static List<WikiDiff> diff(String newVersion, String oldVersion)
     throws DataAccessException {
   List<WikiDiff> result = DiffUtil.retrieveFromCache(newVersion, oldVersion);
   if (result != null) {
     return result;
   }
   String version1 = newVersion;
   String version2 = oldVersion;
   if (version2 == null) {
     version2 = "";
   }
   if (version1 == null) {
     version1 = "";
   }
   // remove line-feeds to avoid unnecessary noise in the diff due to
   // cut & paste or other issues
   version2 = StringUtils.remove(version2, '\r');
   version1 = StringUtils.remove(version1, '\r');
   result = DiffUtil.process(version1, version2);
   DiffUtil.addToCache(newVersion, oldVersion, result);
   return result;
 }
Beispiel #20
0
  // based on old XDR stuff
  public static List<String> parseRecipients(DirectDocuments documents) {

    List<String> ret = new ArrayList();
    for (String recipient : documents.getSubmissionSet().getIntendedRecipient()) {
      if (recipient.startsWith("|")) {
        String address = StringUtils.remove(recipient, "|");
        ret.add(StringUtils.splitPreserveAllTokens(address, "^")[0]);
      } else {
        String id = getId(recipient);
        ret.add(id);
      }
    }
    return ret;
  }
Beispiel #21
0
  @RequestMapping(value = "/vote.jspx", method = RequestMethod.POST)
  public String submit(
      Integer voteId,
      Integer[] subIds,
      String[] reply,
      HttpServletRequest request,
      HttpServletResponse response,
      ModelMap model) {
    CmsSite site = CmsUtils.getSite(request);
    CmsUser user = CmsUtils.getUser(request);
    String ip = RequestUtils.getIpAddr(request);
    String cookieName = VOTE_COOKIE_PREFIX + voteId;
    Cookie cookie = CookieUtils.getCookie(request, cookieName);
    String cookieValue;
    if (cookie != null && !StringUtils.isBlank(cookie.getValue())) {
      cookieValue = cookie.getValue();
    } else {
      cookieValue = null;
    }
    List<Integer[]> itemIds = getItemIdsParam(request, subIds);
    Integer[] subTxtIds = null;
    if (reply != null && reply.length > 0) {
      subTxtIds = new Integer[reply.length];
      List<Integer> subTxtIdList = new ArrayList<Integer>();
      for (int i = 0; i < itemIds.size(); i++) {
        if (itemIds.get(i) == null) {
          subTxtIdList.add(subIds[i]);
        }
      }
      // 投票文本选项和题目id数组对应相同大小
      subTxtIds = (Integer[]) subTxtIdList.toArray(subTxtIds);
    }
    if (!validateSubmit(voteId, subIds, itemIds, user, ip, cookieValue, model)) {
      if (cookieValue == null) {
        // 随机cookie
        cookieValue = StringUtils.remove(UUID.randomUUID().toString(), "-");
        // 写cookie
        CookieUtils.addCookie(request, response, cookieName, cookieValue, Integer.MAX_VALUE, null);
      }
      CmsVoteTopic vote =
          cmsVoteTopicMng.vote(voteId, subTxtIds, itemIds, reply, user, ip, cookieValue);
      model.addAttribute("status", 0);
      model.addAttribute("vote", vote);

      log.info("vote CmsVote id={}, name={}", vote.getId(), vote.getTitle());
    }
    FrontUtils.frontData(request, model, site);
    return FrontUtils.getTplPath(request, site.getSolutionPath(), TPLDIR_SPECIAL, VOTE_RESULT);
  }
Beispiel #22
0
 public static List<User> find(
     Long id, String name, String screenName, Long uid, String accessToken, int begin, int max) {
   if (max <= 0) {
     max = 50;
   }
   if (begin <= 1) {
     begin = 1;
   }
   MorphiaQuery query = createQuery();
   query.offset((begin - 1) * max);
   query.limit(max);
   if (id != null && id > 0) {
     query.field("_id").equal(id);
   }
   if (!StringUtils.isEmpty(name)) {
     if (!StringUtils.contains(name, "*")) {
       query.field("name").contains(StringUtils.remove(name, "*"));
     } else {
       query.field("name").equal(name);
     }
   }
   if (!StringUtils.isEmpty(screenName)) {
     if (!StringUtils.contains(screenName, "*")) {
       query.field("screenName").contains(StringUtils.remove(screenName, "*"));
     } else {
       query.field("screenName").equal(screenName);
     }
   }
   if (uid != null && uid > 0) {
     query.field("uid").equal(uid);
   }
   if (!StringUtils.isEmpty(accessToken)) {
     query.field("accessToken").equal(accessToken);
   }
   return query.asList();
 }
  public void cancelar(String uuid) throws Exception {
    String[] uuidList = new String[] {uuid};
    System.out.println("Mandando canclera CFDIS: " + ArrayUtils.toString(uuidList));

    String dirPath = "Z:\\CFDI\\cancelaciones";
    File dir = new File(dirPath);
    Assert.isTrue(dir.exists(), "No existe el directorio para cancelaciones: " + dirPath);
    Assert.isTrue(
        dir.isDirectory(), "La ruta para las cancelaciones no es un directorio " + dirPath);

    CancelaResponse res =
        client.cancelCfdi(
            "PAP830101CR3",
            "yqjvqfofb",
            empresa.getRfc(),
            uuidList,
            empresa.getCertificadoDigitalPfx(),
            pfxPassword);
    String msg = res.getText();
    String aka = res.getAck();
    // String[] uuids=res.getUuids();
    CFDI cfdi = ServiceLocator2.getCFDIManager().buscarPorUUID(uuid);
    Assert.notNull(cfdi, "No eixste el CFDI con UUID:" + uuid);

    try {
      // byte[] d1=Base64.decode(msg.getBytes());
      String xmlFile = StringUtils.remove(cfdi.getXmlFilePath(), "xml");
      byte[] d1 = msg.getBytes();
      File msgFile = new File(dir, xmlFile + "_MSG.xml");
      FileOutputStream out1 = new FileOutputStream(msgFile);
      out1.write(d1);
      out1.close();

      // byte[] d2=Base64.decode(aka.getBytes());
      byte[] d2 = aka.getBytes();
      File akaFile = new File(dir, xmlFile + "_AKA.xml");
      FileOutputStream out2 = new FileOutputStream(akaFile);
      out2.write(d2);
      out2.close();

    } catch (Exception e) {
      e.printStackTrace();
      System.out.println(
          "Error salvando archivos de cancelacion: " + ExceptionUtils.getRootCauseMessage(e));
    }
    cfdi.setCancelacion(new Date());
    ServiceLocator2.getHibernateTemplate().merge(cfdi);
  }
Beispiel #24
0
 /**
  * parse IPV6 ARPA domain to IP bytes.
  *
  * @param name an ARPA string.
  * @return ARPA.
  */
 private static NetworkInBytes parseIpV6Arpa(String name) {
   LOGGER.debug("parseIp6Arpa, name:" + name);
   String arpa = StringUtils.removeEndIgnoreCase(name, CHAR_DOT + DomainUtil.IPV6_ARPA_SUFFIX);
   arpa = StringUtils.remove(arpa, CHAR_DOT);
   String ip = StringUtils.reverse(arpa);
   String fullIp = StringUtils.rightPad(ip, 32, '0');
   byte[] startIpBytes = DatatypeConverter.parseHexBinary(fullIp);
   int networkMask = StringUtils.length(arpa) * 4;
   IPv6Address fromByteArray = IPv6Address.fromByteArray(startIpBytes);
   IPv6Network network =
       IPv6Network.fromAddressAndMask(
           fromByteArray, IPv6NetworkMask.fromPrefixLength(networkMask));
   NetworkInBytes result =
       new NetworkInBytes(
           IpVersion.V6, network.getFirst().toByteArray(), network.getLast().toByteArray());
   return result;
 }
  /**
   * @see org.kuali.kfs.sys.batch.BatchInputFileType#getFileName(java.lang.String, java.lang.Object,
   *     java.lang.String)
   */
  @Override
  public String getFileName(
      String principalName, Object parsedFileContents, String fileUserIdentifier) {
    StringBuilder fileName = new StringBuilder();

    fileUserIdentifier = StringUtils.deleteWhitespace(fileUserIdentifier);
    fileUserIdentifier =
        StringUtils.remove(fileUserIdentifier, TemConstants.FILE_NAME_PART_DELIMITER);

    fileName.append(this.getFileNamePrefix()).append(TemConstants.FILE_NAME_PART_DELIMITER);
    fileName.append(principalName).append(TemConstants.FILE_NAME_PART_DELIMITER);
    fileName.append(fileUserIdentifier).append(TemConstants.FILE_NAME_PART_DELIMITER);

    fileName.append(dateTimeService.toDateTimeStringForFilename(dateTimeService.getCurrentDate()));

    return fileName.toString();
  }
  /**
   * Converts the folderName to comply with java naming convention
   *
   * @param importFolderName
   * @return String
   */
  private String convertToJavaCompliantName(String importFolderName) {
    // do not use upper case
    importFolderName = importFolderName.toLowerCase();

    // remove blank space
    importFolderName = importFolderName.replaceAll("\\s", "");
    importFolderName = importFolderName.replaceAll("-", "_");
    importFolderName = importFolderName.replaceAll("^\\d", "");

    // remove special chars
    Set<Character> barredChars = new HashSet<Character>();
    for (int i = 0; i < importFolderName.length(); i++) {
      char c = importFolderName.charAt(i);
      if (!(Character.isJavaIdentifierPart(c))) {
        barredChars.add(c);
      }
    }
    for (char c : barredChars) {
      importFolderName = StringUtils.remove(importFolderName, c);
    }
    return StringUtils.uncapitalize(importFolderName);
  }
 protected String calculateRelativeRedirectUrl(final String contextPath, final String url) {
   if (UrlUtils.isAbsoluteUrl(url)) {
     String relUrl = url.substring(url.indexOf("://") + 3);
     String modifiedContextPath = contextPath;
     final String urlEncodingAttributes =
         getSessionService().getAttribute(WebConstants.URL_ENCODING_ATTRIBUTES);
     if (urlEncodingAttributes != null
         && !url.contains(urlEncodingAttributes)
         && modifiedContextPath.contains(urlEncodingAttributes)) {
       modifiedContextPath = StringUtils.remove(modifiedContextPath, urlEncodingAttributes);
     }
     if (StringUtils.isEmpty(relUrl) || StringUtils.isEmpty(modifiedContextPath)) {
       relUrl = "/";
     } else {
       relUrl =
           relUrl.substring(relUrl.indexOf(modifiedContextPath) + modifiedContextPath.length());
     }
     return relUrl;
   } else {
     return url;
   }
 }
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws ServletException, IOException {
    try {
      // 示例为一个固定的登陆用户,请直接修改代码
      MDC.put("loginUserId", "demo-loginUsername");

      MDC.put("req.requestURI", StringUtils.defaultString(request.getRequestURI()));
      MDC.put("req.queryString", StringUtils.defaultString(request.getQueryString()));
      MDC.put(
          "req.requestURIWithQueryString",
          request.getRequestURI()
              + (request.getQueryString() == null ? "" : "?" + request.getQueryString()));
      MDC.put("req.remoteAddr", StringUtils.defaultString(request.getRemoteAddr()));

      // 为每一个请求创建一个ID,方便查找日志时可以根据ID查找出一个http请求所有相关日志
      MDC.put("req.id", StringUtils.remove(UUID.randomUUID().toString(), "-"));
      chain.doFilter(request, response);
    } finally {
      clearMDC();
    }
  }
Beispiel #29
0
 @Test
 public void testCRC32File1() throws IOException {
   File file = new File("C:/test/222/pai2_user.csv");
   List<String> lines = FileUtils.readLines(file);
   HashMap<Integer, Integer> map = new HashMap<>();
   Integer key;
   String[] array;
   String str;
   for (String line : lines) {
     array = StringUtils.split(line, ',');
     str = array[2];
     str = StringUtils.trimToNull(StringUtils.remove(str, '\"'));
     if (null == str || str.length() < 5) {
       continue;
     }
     System.out.println(str);
     key = newCompatHashingAlg(str);
     // hash
     hashStat(map, key.intValue());
   }
   System.out.println(map);
 }
  @Override
  public void doFilterInternal(
      final HttpServletRequest request,
      final HttpServletResponse response,
      final FilterChain filterChain)
      throws ServletException, IOException {
    if (getCustomerLocationFacade().getUserLocationData() == null) {
      final Cookie[] cookies = request.getCookies();

      if (cookies != null) {
        for (final Cookie cookie : cookies) {
          if (getCustomerLocationCookieGenerator().getCookieName().equals(cookie.getName())) {
            final UserLocationData cookieUserLocationData =
                decipherUserLocationData(StringUtils.remove(cookie.getValue(), "\""));
            getCustomerLocationFacade().setUserLocationData(cookieUserLocationData);
            break;
          }
        }
      }
    }

    filterChain.doFilter(request, response);
  }